Instructions.cpp 176 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813
  1. //===- Instructions.cpp - Implement the LLVM instructions -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements all of the non-inline methods for the LLVM instruction
  10. // classes.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/IR/Instructions.h"
  14. #include "LLVMContextImpl.h"
  15. #include "llvm/ADT/None.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/Twine.h"
  18. #include "llvm/IR/Attributes.h"
  19. #include "llvm/IR/BasicBlock.h"
  20. #include "llvm/IR/Constant.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/DataLayout.h"
  23. #include "llvm/IR/DerivedTypes.h"
  24. #include "llvm/IR/Function.h"
  25. #include "llvm/IR/InstrTypes.h"
  26. #include "llvm/IR/Instruction.h"
  27. #include "llvm/IR/Intrinsics.h"
  28. #include "llvm/IR/LLVMContext.h"
  29. #include "llvm/IR/MDBuilder.h"
  30. #include "llvm/IR/Metadata.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/IR/Operator.h"
  33. #include "llvm/IR/Type.h"
  34. #include "llvm/IR/Value.h"
  35. #include "llvm/Support/AtomicOrdering.h"
  36. #include "llvm/Support/Casting.h"
  37. #include "llvm/Support/ErrorHandling.h"
  38. #include "llvm/Support/MathExtras.h"
  39. #include "llvm/Support/TypeSize.h"
  40. #include <algorithm>
  41. #include <cassert>
  42. #include <cstdint>
  43. #include <vector>
  44. using namespace llvm;
  45. static cl::opt<bool> DisableI2pP2iOpt(
  46. "disable-i2p-p2i-opt", cl::init(false),
  47. cl::desc("Disables inttoptr/ptrtoint roundtrip optimization"));
  48. //===----------------------------------------------------------------------===//
  49. // AllocaInst Class
  50. //===----------------------------------------------------------------------===//
  51. Optional<TypeSize>
  52. AllocaInst::getAllocationSizeInBits(const DataLayout &DL) const {
  53. TypeSize Size = DL.getTypeAllocSizeInBits(getAllocatedType());
  54. if (isArrayAllocation()) {
  55. auto *C = dyn_cast<ConstantInt>(getArraySize());
  56. if (!C)
  57. return None;
  58. assert(!Size.isScalable() && "Array elements cannot have a scalable size");
  59. Size *= C->getZExtValue();
  60. }
  61. return Size;
  62. }
  63. //===----------------------------------------------------------------------===//
  64. // SelectInst Class
  65. //===----------------------------------------------------------------------===//
  66. /// areInvalidOperands - Return a string if the specified operands are invalid
  67. /// for a select operation, otherwise return null.
  68. const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
  69. if (Op1->getType() != Op2->getType())
  70. return "both values to select must have same type";
  71. if (Op1->getType()->isTokenTy())
  72. return "select values cannot have token type";
  73. if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
  74. // Vector select.
  75. if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
  76. return "vector select condition element type must be i1";
  77. VectorType *ET = dyn_cast<VectorType>(Op1->getType());
  78. if (!ET)
  79. return "selected values for vector select must be vectors";
  80. if (ET->getElementCount() != VT->getElementCount())
  81. return "vector select requires selected vectors to have "
  82. "the same vector length as select condition";
  83. } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
  84. return "select condition must be i1 or <n x i1>";
  85. }
  86. return nullptr;
  87. }
  88. //===----------------------------------------------------------------------===//
  89. // PHINode Class
  90. //===----------------------------------------------------------------------===//
  91. PHINode::PHINode(const PHINode &PN)
  92. : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()),
  93. ReservedSpace(PN.getNumOperands()) {
  94. allocHungoffUses(PN.getNumOperands());
  95. std::copy(PN.op_begin(), PN.op_end(), op_begin());
  96. std::copy(PN.block_begin(), PN.block_end(), block_begin());
  97. SubclassOptionalData = PN.SubclassOptionalData;
  98. }
  99. // removeIncomingValue - Remove an incoming value. This is useful if a
  100. // predecessor basic block is deleted.
  101. Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
  102. Value *Removed = getIncomingValue(Idx);
  103. // Move everything after this operand down.
  104. //
  105. // FIXME: we could just swap with the end of the list, then erase. However,
  106. // clients might not expect this to happen. The code as it is thrashes the
  107. // use/def lists, which is kinda lame.
  108. std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
  109. std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
  110. // Nuke the last value.
  111. Op<-1>().set(nullptr);
  112. setNumHungOffUseOperands(getNumOperands() - 1);
  113. // If the PHI node is dead, because it has zero entries, nuke it now.
  114. if (getNumOperands() == 0 && DeletePHIIfEmpty) {
  115. // If anyone is using this PHI, make them use a dummy value instead...
  116. replaceAllUsesWith(UndefValue::get(getType()));
  117. eraseFromParent();
  118. }
  119. return Removed;
  120. }
  121. /// growOperands - grow operands - This grows the operand list in response
  122. /// to a push_back style of operation. This grows the number of ops by 1.5
  123. /// times.
  124. ///
  125. void PHINode::growOperands() {
  126. unsigned e = getNumOperands();
  127. unsigned NumOps = e + e / 2;
  128. if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
  129. ReservedSpace = NumOps;
  130. growHungoffUses(ReservedSpace, /* IsPhi */ true);
  131. }
  132. /// hasConstantValue - If the specified PHI node always merges together the same
  133. /// value, return the value, otherwise return null.
  134. Value *PHINode::hasConstantValue() const {
  135. // Exploit the fact that phi nodes always have at least one entry.
  136. Value *ConstantValue = getIncomingValue(0);
  137. for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
  138. if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
  139. if (ConstantValue != this)
  140. return nullptr; // Incoming values not all the same.
  141. // The case where the first value is this PHI.
  142. ConstantValue = getIncomingValue(i);
  143. }
  144. if (ConstantValue == this)
  145. return UndefValue::get(getType());
  146. return ConstantValue;
  147. }
  148. /// hasConstantOrUndefValue - Whether the specified PHI node always merges
  149. /// together the same value, assuming that undefs result in the same value as
  150. /// non-undefs.
  151. /// Unlike \ref hasConstantValue, this does not return a value because the
  152. /// unique non-undef incoming value need not dominate the PHI node.
  153. bool PHINode::hasConstantOrUndefValue() const {
  154. Value *ConstantValue = nullptr;
  155. for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) {
  156. Value *Incoming = getIncomingValue(i);
  157. if (Incoming != this && !isa<UndefValue>(Incoming)) {
  158. if (ConstantValue && ConstantValue != Incoming)
  159. return false;
  160. ConstantValue = Incoming;
  161. }
  162. }
  163. return true;
  164. }
  165. //===----------------------------------------------------------------------===//
  166. // LandingPadInst Implementation
  167. //===----------------------------------------------------------------------===//
  168. LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
  169. const Twine &NameStr, Instruction *InsertBefore)
  170. : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
  171. init(NumReservedValues, NameStr);
  172. }
  173. LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
  174. const Twine &NameStr, BasicBlock *InsertAtEnd)
  175. : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
  176. init(NumReservedValues, NameStr);
  177. }
  178. LandingPadInst::LandingPadInst(const LandingPadInst &LP)
  179. : Instruction(LP.getType(), Instruction::LandingPad, nullptr,
  180. LP.getNumOperands()),
  181. ReservedSpace(LP.getNumOperands()) {
  182. allocHungoffUses(LP.getNumOperands());
  183. Use *OL = getOperandList();
  184. const Use *InOL = LP.getOperandList();
  185. for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
  186. OL[I] = InOL[I];
  187. setCleanup(LP.isCleanup());
  188. }
  189. LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
  190. const Twine &NameStr,
  191. Instruction *InsertBefore) {
  192. return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
  193. }
  194. LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
  195. const Twine &NameStr,
  196. BasicBlock *InsertAtEnd) {
  197. return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd);
  198. }
  199. void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
  200. ReservedSpace = NumReservedValues;
  201. setNumHungOffUseOperands(0);
  202. allocHungoffUses(ReservedSpace);
  203. setName(NameStr);
  204. setCleanup(false);
  205. }
  206. /// growOperands - grow operands - This grows the operand list in response to a
  207. /// push_back style of operation. This grows the number of ops by 2 times.
  208. void LandingPadInst::growOperands(unsigned Size) {
  209. unsigned e = getNumOperands();
  210. if (ReservedSpace >= e + Size) return;
  211. ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
  212. growHungoffUses(ReservedSpace);
  213. }
  214. void LandingPadInst::addClause(Constant *Val) {
  215. unsigned OpNo = getNumOperands();
  216. growOperands(1);
  217. assert(OpNo < ReservedSpace && "Growing didn't work!");
  218. setNumHungOffUseOperands(getNumOperands() + 1);
  219. getOperandList()[OpNo] = Val;
  220. }
  221. //===----------------------------------------------------------------------===//
  222. // CallBase Implementation
  223. //===----------------------------------------------------------------------===//
  224. CallBase *CallBase::Create(CallBase *CB, ArrayRef<OperandBundleDef> Bundles,
  225. Instruction *InsertPt) {
  226. switch (CB->getOpcode()) {
  227. case Instruction::Call:
  228. return CallInst::Create(cast<CallInst>(CB), Bundles, InsertPt);
  229. case Instruction::Invoke:
  230. return InvokeInst::Create(cast<InvokeInst>(CB), Bundles, InsertPt);
  231. case Instruction::CallBr:
  232. return CallBrInst::Create(cast<CallBrInst>(CB), Bundles, InsertPt);
  233. default:
  234. llvm_unreachable("Unknown CallBase sub-class!");
  235. }
  236. }
  237. CallBase *CallBase::Create(CallBase *CI, OperandBundleDef OpB,
  238. Instruction *InsertPt) {
  239. SmallVector<OperandBundleDef, 2> OpDefs;
  240. for (unsigned i = 0, e = CI->getNumOperandBundles(); i < e; ++i) {
  241. auto ChildOB = CI->getOperandBundleAt(i);
  242. if (ChildOB.getTagName() != OpB.getTag())
  243. OpDefs.emplace_back(ChildOB);
  244. }
  245. OpDefs.emplace_back(OpB);
  246. return CallBase::Create(CI, OpDefs, InsertPt);
  247. }
  248. Function *CallBase::getCaller() { return getParent()->getParent(); }
  249. unsigned CallBase::getNumSubclassExtraOperandsDynamic() const {
  250. assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!");
  251. return cast<CallBrInst>(this)->getNumIndirectDests() + 1;
  252. }
  253. bool CallBase::isIndirectCall() const {
  254. const Value *V = getCalledOperand();
  255. if (isa<Function>(V) || isa<Constant>(V))
  256. return false;
  257. return !isInlineAsm();
  258. }
  259. /// Tests if this call site must be tail call optimized. Only a CallInst can
  260. /// be tail call optimized.
  261. bool CallBase::isMustTailCall() const {
  262. if (auto *CI = dyn_cast<CallInst>(this))
  263. return CI->isMustTailCall();
  264. return false;
  265. }
  266. /// Tests if this call site is marked as a tail call.
  267. bool CallBase::isTailCall() const {
  268. if (auto *CI = dyn_cast<CallInst>(this))
  269. return CI->isTailCall();
  270. return false;
  271. }
  272. Intrinsic::ID CallBase::getIntrinsicID() const {
  273. if (auto *F = getCalledFunction())
  274. return F->getIntrinsicID();
  275. return Intrinsic::not_intrinsic;
  276. }
  277. bool CallBase::isReturnNonNull() const {
  278. if (hasRetAttr(Attribute::NonNull))
  279. return true;
  280. if (getRetDereferenceableBytes() > 0 &&
  281. !NullPointerIsDefined(getCaller(), getType()->getPointerAddressSpace()))
  282. return true;
  283. return false;
  284. }
  285. Value *CallBase::getReturnedArgOperand() const {
  286. unsigned Index;
  287. if (Attrs.hasAttrSomewhere(Attribute::Returned, &Index))
  288. return getArgOperand(Index - AttributeList::FirstArgIndex);
  289. if (const Function *F = getCalledFunction())
  290. if (F->getAttributes().hasAttrSomewhere(Attribute::Returned, &Index))
  291. return getArgOperand(Index - AttributeList::FirstArgIndex);
  292. return nullptr;
  293. }
  294. /// Determine whether the argument or parameter has the given attribute.
  295. bool CallBase::paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
  296. assert(ArgNo < arg_size() && "Param index out of bounds!");
  297. if (Attrs.hasParamAttr(ArgNo, Kind))
  298. return true;
  299. if (const Function *F = getCalledFunction())
  300. return F->getAttributes().hasParamAttr(ArgNo, Kind);
  301. return false;
  302. }
  303. bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const {
  304. Value *V = getCalledOperand();
  305. if (auto *CE = dyn_cast<ConstantExpr>(V))
  306. if (CE->getOpcode() == BitCast)
  307. V = CE->getOperand(0);
  308. if (auto *F = dyn_cast<Function>(V))
  309. return F->getAttributes().hasFnAttr(Kind);
  310. return false;
  311. }
  312. bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const {
  313. Value *V = getCalledOperand();
  314. if (auto *CE = dyn_cast<ConstantExpr>(V))
  315. if (CE->getOpcode() == BitCast)
  316. V = CE->getOperand(0);
  317. if (auto *F = dyn_cast<Function>(V))
  318. return F->getAttributes().hasFnAttr(Kind);
  319. return false;
  320. }
  321. void CallBase::getOperandBundlesAsDefs(
  322. SmallVectorImpl<OperandBundleDef> &Defs) const {
  323. for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
  324. Defs.emplace_back(getOperandBundleAt(i));
  325. }
  326. CallBase::op_iterator
  327. CallBase::populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
  328. const unsigned BeginIndex) {
  329. auto It = op_begin() + BeginIndex;
  330. for (auto &B : Bundles)
  331. It = std::copy(B.input_begin(), B.input_end(), It);
  332. auto *ContextImpl = getContext().pImpl;
  333. auto BI = Bundles.begin();
  334. unsigned CurrentIndex = BeginIndex;
  335. for (auto &BOI : bundle_op_infos()) {
  336. assert(BI != Bundles.end() && "Incorrect allocation?");
  337. BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
  338. BOI.Begin = CurrentIndex;
  339. BOI.End = CurrentIndex + BI->input_size();
  340. CurrentIndex = BOI.End;
  341. BI++;
  342. }
  343. assert(BI == Bundles.end() && "Incorrect allocation?");
  344. return It;
  345. }
  346. CallBase::BundleOpInfo &CallBase::getBundleOpInfoForOperand(unsigned OpIdx) {
  347. /// When there isn't many bundles, we do a simple linear search.
  348. /// Else fallback to a binary-search that use the fact that bundles usually
  349. /// have similar number of argument to get faster convergence.
  350. if (bundle_op_info_end() - bundle_op_info_begin() < 8) {
  351. for (auto &BOI : bundle_op_infos())
  352. if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
  353. return BOI;
  354. llvm_unreachable("Did not find operand bundle for operand!");
  355. }
  356. assert(OpIdx >= arg_size() && "the Idx is not in the operand bundles");
  357. assert(bundle_op_info_end() - bundle_op_info_begin() > 0 &&
  358. OpIdx < std::prev(bundle_op_info_end())->End &&
  359. "The Idx isn't in the operand bundle");
  360. /// We need a decimal number below and to prevent using floating point numbers
  361. /// we use an intergal value multiplied by this constant.
  362. constexpr unsigned NumberScaling = 1024;
  363. bundle_op_iterator Begin = bundle_op_info_begin();
  364. bundle_op_iterator End = bundle_op_info_end();
  365. bundle_op_iterator Current = Begin;
  366. while (Begin != End) {
  367. unsigned ScaledOperandPerBundle =
  368. NumberScaling * (std::prev(End)->End - Begin->Begin) / (End - Begin);
  369. Current = Begin + (((OpIdx - Begin->Begin) * NumberScaling) /
  370. ScaledOperandPerBundle);
  371. if (Current >= End)
  372. Current = std::prev(End);
  373. assert(Current < End && Current >= Begin &&
  374. "the operand bundle doesn't cover every value in the range");
  375. if (OpIdx >= Current->Begin && OpIdx < Current->End)
  376. break;
  377. if (OpIdx >= Current->End)
  378. Begin = Current + 1;
  379. else
  380. End = Current;
  381. }
  382. assert(OpIdx >= Current->Begin && OpIdx < Current->End &&
  383. "the operand bundle doesn't cover every value in the range");
  384. return *Current;
  385. }
  386. CallBase *CallBase::addOperandBundle(CallBase *CB, uint32_t ID,
  387. OperandBundleDef OB,
  388. Instruction *InsertPt) {
  389. if (CB->getOperandBundle(ID))
  390. return CB;
  391. SmallVector<OperandBundleDef, 1> Bundles;
  392. CB->getOperandBundlesAsDefs(Bundles);
  393. Bundles.push_back(OB);
  394. return Create(CB, Bundles, InsertPt);
  395. }
  396. CallBase *CallBase::removeOperandBundle(CallBase *CB, uint32_t ID,
  397. Instruction *InsertPt) {
  398. SmallVector<OperandBundleDef, 1> Bundles;
  399. bool CreateNew = false;
  400. for (unsigned I = 0, E = CB->getNumOperandBundles(); I != E; ++I) {
  401. auto Bundle = CB->getOperandBundleAt(I);
  402. if (Bundle.getTagID() == ID) {
  403. CreateNew = true;
  404. continue;
  405. }
  406. Bundles.emplace_back(Bundle);
  407. }
  408. return CreateNew ? Create(CB, Bundles, InsertPt) : CB;
  409. }
  410. bool CallBase::hasReadingOperandBundles() const {
  411. // Implementation note: this is a conservative implementation of operand
  412. // bundle semantics, where *any* non-assume operand bundle forces a callsite
  413. // to be at least readonly.
  414. return hasOperandBundles() && getIntrinsicID() != Intrinsic::assume;
  415. }
  416. //===----------------------------------------------------------------------===//
  417. // CallInst Implementation
  418. //===----------------------------------------------------------------------===//
  419. void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
  420. ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
  421. this->FTy = FTy;
  422. assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
  423. "NumOperands not set up?");
  424. #ifndef NDEBUG
  425. assert((Args.size() == FTy->getNumParams() ||
  426. (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
  427. "Calling a function with bad signature!");
  428. for (unsigned i = 0; i != Args.size(); ++i)
  429. assert((i >= FTy->getNumParams() ||
  430. FTy->getParamType(i) == Args[i]->getType()) &&
  431. "Calling a function with a bad signature!");
  432. #endif
  433. // Set operands in order of their index to match use-list-order
  434. // prediction.
  435. llvm::copy(Args, op_begin());
  436. setCalledOperand(Func);
  437. auto It = populateBundleOperandInfos(Bundles, Args.size());
  438. (void)It;
  439. assert(It + 1 == op_end() && "Should add up!");
  440. setName(NameStr);
  441. }
  442. void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) {
  443. this->FTy = FTy;
  444. assert(getNumOperands() == 1 && "NumOperands not set up?");
  445. setCalledOperand(Func);
  446. assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
  447. setName(NameStr);
  448. }
  449. CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
  450. Instruction *InsertBefore)
  451. : CallBase(Ty->getReturnType(), Instruction::Call,
  452. OperandTraits<CallBase>::op_end(this) - 1, 1, InsertBefore) {
  453. init(Ty, Func, Name);
  454. }
  455. CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
  456. BasicBlock *InsertAtEnd)
  457. : CallBase(Ty->getReturnType(), Instruction::Call,
  458. OperandTraits<CallBase>::op_end(this) - 1, 1, InsertAtEnd) {
  459. init(Ty, Func, Name);
  460. }
  461. CallInst::CallInst(const CallInst &CI)
  462. : CallBase(CI.Attrs, CI.FTy, CI.getType(), Instruction::Call,
  463. OperandTraits<CallBase>::op_end(this) - CI.getNumOperands(),
  464. CI.getNumOperands()) {
  465. setTailCallKind(CI.getTailCallKind());
  466. setCallingConv(CI.getCallingConv());
  467. std::copy(CI.op_begin(), CI.op_end(), op_begin());
  468. std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(),
  469. bundle_op_info_begin());
  470. SubclassOptionalData = CI.SubclassOptionalData;
  471. }
  472. CallInst *CallInst::Create(CallInst *CI, ArrayRef<OperandBundleDef> OpB,
  473. Instruction *InsertPt) {
  474. std::vector<Value *> Args(CI->arg_begin(), CI->arg_end());
  475. auto *NewCI = CallInst::Create(CI->getFunctionType(), CI->getCalledOperand(),
  476. Args, OpB, CI->getName(), InsertPt);
  477. NewCI->setTailCallKind(CI->getTailCallKind());
  478. NewCI->setCallingConv(CI->getCallingConv());
  479. NewCI->SubclassOptionalData = CI->SubclassOptionalData;
  480. NewCI->setAttributes(CI->getAttributes());
  481. NewCI->setDebugLoc(CI->getDebugLoc());
  482. return NewCI;
  483. }
  484. // Update profile weight for call instruction by scaling it using the ratio
  485. // of S/T. The meaning of "branch_weights" meta data for call instruction is
  486. // transfered to represent call count.
  487. void CallInst::updateProfWeight(uint64_t S, uint64_t T) {
  488. auto *ProfileData = getMetadata(LLVMContext::MD_prof);
  489. if (ProfileData == nullptr)
  490. return;
  491. auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
  492. if (!ProfDataName || (!ProfDataName->getString().equals("branch_weights") &&
  493. !ProfDataName->getString().equals("VP")))
  494. return;
  495. if (T == 0) {
  496. LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
  497. "div by 0. Ignoring. Likely the function "
  498. << getParent()->getParent()->getName()
  499. << " has 0 entry count, and contains call instructions "
  500. "with non-zero prof info.");
  501. return;
  502. }
  503. MDBuilder MDB(getContext());
  504. SmallVector<Metadata *, 3> Vals;
  505. Vals.push_back(ProfileData->getOperand(0));
  506. APInt APS(128, S), APT(128, T);
  507. if (ProfDataName->getString().equals("branch_weights") &&
  508. ProfileData->getNumOperands() > 0) {
  509. // Using APInt::div may be expensive, but most cases should fit 64 bits.
  510. APInt Val(128, mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1))
  511. ->getValue()
  512. .getZExtValue());
  513. Val *= APS;
  514. Vals.push_back(MDB.createConstant(
  515. ConstantInt::get(Type::getInt32Ty(getContext()),
  516. Val.udiv(APT).getLimitedValue(UINT32_MAX))));
  517. } else if (ProfDataName->getString().equals("VP"))
  518. for (unsigned i = 1; i < ProfileData->getNumOperands(); i += 2) {
  519. // The first value is the key of the value profile, which will not change.
  520. Vals.push_back(ProfileData->getOperand(i));
  521. uint64_t Count =
  522. mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i + 1))
  523. ->getValue()
  524. .getZExtValue();
  525. // Don't scale the magic number.
  526. if (Count == NOMORE_ICP_MAGICNUM) {
  527. Vals.push_back(ProfileData->getOperand(i + 1));
  528. continue;
  529. }
  530. // Using APInt::div may be expensive, but most cases should fit 64 bits.
  531. APInt Val(128, Count);
  532. Val *= APS;
  533. Vals.push_back(MDB.createConstant(
  534. ConstantInt::get(Type::getInt64Ty(getContext()),
  535. Val.udiv(APT).getLimitedValue())));
  536. }
  537. setMetadata(LLVMContext::MD_prof, MDNode::get(getContext(), Vals));
  538. }
  539. /// IsConstantOne - Return true only if val is constant int 1
  540. static bool IsConstantOne(Value *val) {
  541. assert(val && "IsConstantOne does not work with nullptr val");
  542. const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
  543. return CVal && CVal->isOne();
  544. }
  545. static Instruction *createMalloc(Instruction *InsertBefore,
  546. BasicBlock *InsertAtEnd, Type *IntPtrTy,
  547. Type *AllocTy, Value *AllocSize,
  548. Value *ArraySize,
  549. ArrayRef<OperandBundleDef> OpB,
  550. Function *MallocF, const Twine &Name) {
  551. assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
  552. "createMalloc needs either InsertBefore or InsertAtEnd");
  553. // malloc(type) becomes:
  554. // bitcast (i8* malloc(typeSize)) to type*
  555. // malloc(type, arraySize) becomes:
  556. // bitcast (i8* malloc(typeSize*arraySize)) to type*
  557. if (!ArraySize)
  558. ArraySize = ConstantInt::get(IntPtrTy, 1);
  559. else if (ArraySize->getType() != IntPtrTy) {
  560. if (InsertBefore)
  561. ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
  562. "", InsertBefore);
  563. else
  564. ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
  565. "", InsertAtEnd);
  566. }
  567. if (!IsConstantOne(ArraySize)) {
  568. if (IsConstantOne(AllocSize)) {
  569. AllocSize = ArraySize; // Operand * 1 = Operand
  570. } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
  571. Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
  572. false /*ZExt*/);
  573. // Malloc arg is constant product of type size and array size
  574. AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
  575. } else {
  576. // Multiply type size by the array size...
  577. if (InsertBefore)
  578. AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
  579. "mallocsize", InsertBefore);
  580. else
  581. AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
  582. "mallocsize", InsertAtEnd);
  583. }
  584. }
  585. assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
  586. // Create the call to Malloc.
  587. BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
  588. Module *M = BB->getParent()->getParent();
  589. Type *BPTy = Type::getInt8PtrTy(BB->getContext());
  590. FunctionCallee MallocFunc = MallocF;
  591. if (!MallocFunc)
  592. // prototype malloc as "void *malloc(size_t)"
  593. MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy);
  594. PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
  595. CallInst *MCall = nullptr;
  596. Instruction *Result = nullptr;
  597. if (InsertBefore) {
  598. MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall",
  599. InsertBefore);
  600. Result = MCall;
  601. if (Result->getType() != AllocPtrType)
  602. // Create a cast instruction to convert to the right type...
  603. Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
  604. } else {
  605. MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall");
  606. Result = MCall;
  607. if (Result->getType() != AllocPtrType) {
  608. InsertAtEnd->getInstList().push_back(MCall);
  609. // Create a cast instruction to convert to the right type...
  610. Result = new BitCastInst(MCall, AllocPtrType, Name);
  611. }
  612. }
  613. MCall->setTailCall();
  614. if (Function *F = dyn_cast<Function>(MallocFunc.getCallee())) {
  615. MCall->setCallingConv(F->getCallingConv());
  616. if (!F->returnDoesNotAlias())
  617. F->setReturnDoesNotAlias();
  618. }
  619. assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
  620. return Result;
  621. }
  622. /// CreateMalloc - Generate the IR for a call to malloc:
  623. /// 1. Compute the malloc call's argument as the specified type's size,
  624. /// possibly multiplied by the array size if the array size is not
  625. /// constant 1.
  626. /// 2. Call malloc with that argument.
  627. /// 3. Bitcast the result of the malloc call to the specified type.
  628. Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
  629. Type *IntPtrTy, Type *AllocTy,
  630. Value *AllocSize, Value *ArraySize,
  631. Function *MallocF,
  632. const Twine &Name) {
  633. return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
  634. ArraySize, None, MallocF, Name);
  635. }
  636. Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
  637. Type *IntPtrTy, Type *AllocTy,
  638. Value *AllocSize, Value *ArraySize,
  639. ArrayRef<OperandBundleDef> OpB,
  640. Function *MallocF,
  641. const Twine &Name) {
  642. return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
  643. ArraySize, OpB, MallocF, Name);
  644. }
  645. /// CreateMalloc - Generate the IR for a call to malloc:
  646. /// 1. Compute the malloc call's argument as the specified type's size,
  647. /// possibly multiplied by the array size if the array size is not
  648. /// constant 1.
  649. /// 2. Call malloc with that argument.
  650. /// 3. Bitcast the result of the malloc call to the specified type.
  651. /// Note: This function does not add the bitcast to the basic block, that is the
  652. /// responsibility of the caller.
  653. Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
  654. Type *IntPtrTy, Type *AllocTy,
  655. Value *AllocSize, Value *ArraySize,
  656. Function *MallocF, const Twine &Name) {
  657. return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
  658. ArraySize, None, MallocF, Name);
  659. }
  660. Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
  661. Type *IntPtrTy, Type *AllocTy,
  662. Value *AllocSize, Value *ArraySize,
  663. ArrayRef<OperandBundleDef> OpB,
  664. Function *MallocF, const Twine &Name) {
  665. return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
  666. ArraySize, OpB, MallocF, Name);
  667. }
  668. static Instruction *createFree(Value *Source,
  669. ArrayRef<OperandBundleDef> Bundles,
  670. Instruction *InsertBefore,
  671. BasicBlock *InsertAtEnd) {
  672. assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
  673. "createFree needs either InsertBefore or InsertAtEnd");
  674. assert(Source->getType()->isPointerTy() &&
  675. "Can not free something of nonpointer type!");
  676. BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
  677. Module *M = BB->getParent()->getParent();
  678. Type *VoidTy = Type::getVoidTy(M->getContext());
  679. Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
  680. // prototype free as "void free(void*)"
  681. FunctionCallee FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy);
  682. CallInst *Result = nullptr;
  683. Value *PtrCast = Source;
  684. if (InsertBefore) {
  685. if (Source->getType() != IntPtrTy)
  686. PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
  687. Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "", InsertBefore);
  688. } else {
  689. if (Source->getType() != IntPtrTy)
  690. PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
  691. Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "");
  692. }
  693. Result->setTailCall();
  694. if (Function *F = dyn_cast<Function>(FreeFunc.getCallee()))
  695. Result->setCallingConv(F->getCallingConv());
  696. return Result;
  697. }
  698. /// CreateFree - Generate the IR for a call to the builtin free function.
  699. Instruction *CallInst::CreateFree(Value *Source, Instruction *InsertBefore) {
  700. return createFree(Source, None, InsertBefore, nullptr);
  701. }
  702. Instruction *CallInst::CreateFree(Value *Source,
  703. ArrayRef<OperandBundleDef> Bundles,
  704. Instruction *InsertBefore) {
  705. return createFree(Source, Bundles, InsertBefore, nullptr);
  706. }
  707. /// CreateFree - Generate the IR for a call to the builtin free function.
  708. /// Note: This function does not add the call to the basic block, that is the
  709. /// responsibility of the caller.
  710. Instruction *CallInst::CreateFree(Value *Source, BasicBlock *InsertAtEnd) {
  711. Instruction *FreeCall = createFree(Source, None, nullptr, InsertAtEnd);
  712. assert(FreeCall && "CreateFree did not create a CallInst");
  713. return FreeCall;
  714. }
  715. Instruction *CallInst::CreateFree(Value *Source,
  716. ArrayRef<OperandBundleDef> Bundles,
  717. BasicBlock *InsertAtEnd) {
  718. Instruction *FreeCall = createFree(Source, Bundles, nullptr, InsertAtEnd);
  719. assert(FreeCall && "CreateFree did not create a CallInst");
  720. return FreeCall;
  721. }
  722. //===----------------------------------------------------------------------===//
  723. // InvokeInst Implementation
  724. //===----------------------------------------------------------------------===//
  725. void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
  726. BasicBlock *IfException, ArrayRef<Value *> Args,
  727. ArrayRef<OperandBundleDef> Bundles,
  728. const Twine &NameStr) {
  729. this->FTy = FTy;
  730. assert((int)getNumOperands() ==
  731. ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) &&
  732. "NumOperands not set up?");
  733. #ifndef NDEBUG
  734. assert(((Args.size() == FTy->getNumParams()) ||
  735. (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
  736. "Invoking a function with bad signature");
  737. for (unsigned i = 0, e = Args.size(); i != e; i++)
  738. assert((i >= FTy->getNumParams() ||
  739. FTy->getParamType(i) == Args[i]->getType()) &&
  740. "Invoking a function with a bad signature!");
  741. #endif
  742. // Set operands in order of their index to match use-list-order
  743. // prediction.
  744. llvm::copy(Args, op_begin());
  745. setNormalDest(IfNormal);
  746. setUnwindDest(IfException);
  747. setCalledOperand(Fn);
  748. auto It = populateBundleOperandInfos(Bundles, Args.size());
  749. (void)It;
  750. assert(It + 3 == op_end() && "Should add up!");
  751. setName(NameStr);
  752. }
  753. InvokeInst::InvokeInst(const InvokeInst &II)
  754. : CallBase(II.Attrs, II.FTy, II.getType(), Instruction::Invoke,
  755. OperandTraits<CallBase>::op_end(this) - II.getNumOperands(),
  756. II.getNumOperands()) {
  757. setCallingConv(II.getCallingConv());
  758. std::copy(II.op_begin(), II.op_end(), op_begin());
  759. std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(),
  760. bundle_op_info_begin());
  761. SubclassOptionalData = II.SubclassOptionalData;
  762. }
  763. InvokeInst *InvokeInst::Create(InvokeInst *II, ArrayRef<OperandBundleDef> OpB,
  764. Instruction *InsertPt) {
  765. std::vector<Value *> Args(II->arg_begin(), II->arg_end());
  766. auto *NewII = InvokeInst::Create(
  767. II->getFunctionType(), II->getCalledOperand(), II->getNormalDest(),
  768. II->getUnwindDest(), Args, OpB, II->getName(), InsertPt);
  769. NewII->setCallingConv(II->getCallingConv());
  770. NewII->SubclassOptionalData = II->SubclassOptionalData;
  771. NewII->setAttributes(II->getAttributes());
  772. NewII->setDebugLoc(II->getDebugLoc());
  773. return NewII;
  774. }
  775. LandingPadInst *InvokeInst::getLandingPadInst() const {
  776. return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
  777. }
  778. //===----------------------------------------------------------------------===//
  779. // CallBrInst Implementation
  780. //===----------------------------------------------------------------------===//
  781. void CallBrInst::init(FunctionType *FTy, Value *Fn, BasicBlock *Fallthrough,
  782. ArrayRef<BasicBlock *> IndirectDests,
  783. ArrayRef<Value *> Args,
  784. ArrayRef<OperandBundleDef> Bundles,
  785. const Twine &NameStr) {
  786. this->FTy = FTy;
  787. assert((int)getNumOperands() ==
  788. ComputeNumOperands(Args.size(), IndirectDests.size(),
  789. CountBundleInputs(Bundles)) &&
  790. "NumOperands not set up?");
  791. #ifndef NDEBUG
  792. assert(((Args.size() == FTy->getNumParams()) ||
  793. (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
  794. "Calling a function with bad signature");
  795. for (unsigned i = 0, e = Args.size(); i != e; i++)
  796. assert((i >= FTy->getNumParams() ||
  797. FTy->getParamType(i) == Args[i]->getType()) &&
  798. "Calling a function with a bad signature!");
  799. #endif
  800. // Set operands in order of their index to match use-list-order
  801. // prediction.
  802. std::copy(Args.begin(), Args.end(), op_begin());
  803. NumIndirectDests = IndirectDests.size();
  804. setDefaultDest(Fallthrough);
  805. for (unsigned i = 0; i != NumIndirectDests; ++i)
  806. setIndirectDest(i, IndirectDests[i]);
  807. setCalledOperand(Fn);
  808. auto It = populateBundleOperandInfos(Bundles, Args.size());
  809. (void)It;
  810. assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!");
  811. setName(NameStr);
  812. }
  813. void CallBrInst::updateArgBlockAddresses(unsigned i, BasicBlock *B) {
  814. assert(getNumIndirectDests() > i && "IndirectDest # out of range for callbr");
  815. if (BasicBlock *OldBB = getIndirectDest(i)) {
  816. BlockAddress *Old = BlockAddress::get(OldBB);
  817. BlockAddress *New = BlockAddress::get(B);
  818. for (unsigned ArgNo = 0, e = arg_size(); ArgNo != e; ++ArgNo)
  819. if (dyn_cast<BlockAddress>(getArgOperand(ArgNo)) == Old)
  820. setArgOperand(ArgNo, New);
  821. }
  822. }
  823. CallBrInst::CallBrInst(const CallBrInst &CBI)
  824. : CallBase(CBI.Attrs, CBI.FTy, CBI.getType(), Instruction::CallBr,
  825. OperandTraits<CallBase>::op_end(this) - CBI.getNumOperands(),
  826. CBI.getNumOperands()) {
  827. setCallingConv(CBI.getCallingConv());
  828. std::copy(CBI.op_begin(), CBI.op_end(), op_begin());
  829. std::copy(CBI.bundle_op_info_begin(), CBI.bundle_op_info_end(),
  830. bundle_op_info_begin());
  831. SubclassOptionalData = CBI.SubclassOptionalData;
  832. NumIndirectDests = CBI.NumIndirectDests;
  833. }
  834. CallBrInst *CallBrInst::Create(CallBrInst *CBI, ArrayRef<OperandBundleDef> OpB,
  835. Instruction *InsertPt) {
  836. std::vector<Value *> Args(CBI->arg_begin(), CBI->arg_end());
  837. auto *NewCBI = CallBrInst::Create(
  838. CBI->getFunctionType(), CBI->getCalledOperand(), CBI->getDefaultDest(),
  839. CBI->getIndirectDests(), Args, OpB, CBI->getName(), InsertPt);
  840. NewCBI->setCallingConv(CBI->getCallingConv());
  841. NewCBI->SubclassOptionalData = CBI->SubclassOptionalData;
  842. NewCBI->setAttributes(CBI->getAttributes());
  843. NewCBI->setDebugLoc(CBI->getDebugLoc());
  844. NewCBI->NumIndirectDests = CBI->NumIndirectDests;
  845. return NewCBI;
  846. }
  847. //===----------------------------------------------------------------------===//
  848. // ReturnInst Implementation
  849. //===----------------------------------------------------------------------===//
  850. ReturnInst::ReturnInst(const ReturnInst &RI)
  851. : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Ret,
  852. OperandTraits<ReturnInst>::op_end(this) - RI.getNumOperands(),
  853. RI.getNumOperands()) {
  854. if (RI.getNumOperands())
  855. Op<0>() = RI.Op<0>();
  856. SubclassOptionalData = RI.SubclassOptionalData;
  857. }
  858. ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
  859. : Instruction(Type::getVoidTy(C), Instruction::Ret,
  860. OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
  861. InsertBefore) {
  862. if (retVal)
  863. Op<0>() = retVal;
  864. }
  865. ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
  866. : Instruction(Type::getVoidTy(C), Instruction::Ret,
  867. OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
  868. InsertAtEnd) {
  869. if (retVal)
  870. Op<0>() = retVal;
  871. }
  872. ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
  873. : Instruction(Type::getVoidTy(Context), Instruction::Ret,
  874. OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {}
  875. //===----------------------------------------------------------------------===//
  876. // ResumeInst Implementation
  877. //===----------------------------------------------------------------------===//
  878. ResumeInst::ResumeInst(const ResumeInst &RI)
  879. : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Resume,
  880. OperandTraits<ResumeInst>::op_begin(this), 1) {
  881. Op<0>() = RI.Op<0>();
  882. }
  883. ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
  884. : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
  885. OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
  886. Op<0>() = Exn;
  887. }
  888. ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
  889. : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
  890. OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
  891. Op<0>() = Exn;
  892. }
  893. //===----------------------------------------------------------------------===//
  894. // CleanupReturnInst Implementation
  895. //===----------------------------------------------------------------------===//
  896. CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI)
  897. : Instruction(CRI.getType(), Instruction::CleanupRet,
  898. OperandTraits<CleanupReturnInst>::op_end(this) -
  899. CRI.getNumOperands(),
  900. CRI.getNumOperands()) {
  901. setSubclassData<Instruction::OpaqueField>(
  902. CRI.getSubclassData<Instruction::OpaqueField>());
  903. Op<0>() = CRI.Op<0>();
  904. if (CRI.hasUnwindDest())
  905. Op<1>() = CRI.Op<1>();
  906. }
  907. void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) {
  908. if (UnwindBB)
  909. setSubclassData<UnwindDestField>(true);
  910. Op<0>() = CleanupPad;
  911. if (UnwindBB)
  912. Op<1>() = UnwindBB;
  913. }
  914. CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
  915. unsigned Values, Instruction *InsertBefore)
  916. : Instruction(Type::getVoidTy(CleanupPad->getContext()),
  917. Instruction::CleanupRet,
  918. OperandTraits<CleanupReturnInst>::op_end(this) - Values,
  919. Values, InsertBefore) {
  920. init(CleanupPad, UnwindBB);
  921. }
  922. CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
  923. unsigned Values, BasicBlock *InsertAtEnd)
  924. : Instruction(Type::getVoidTy(CleanupPad->getContext()),
  925. Instruction::CleanupRet,
  926. OperandTraits<CleanupReturnInst>::op_end(this) - Values,
  927. Values, InsertAtEnd) {
  928. init(CleanupPad, UnwindBB);
  929. }
  930. //===----------------------------------------------------------------------===//
  931. // CatchReturnInst Implementation
  932. //===----------------------------------------------------------------------===//
  933. void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) {
  934. Op<0>() = CatchPad;
  935. Op<1>() = BB;
  936. }
  937. CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI)
  938. : Instruction(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet,
  939. OperandTraits<CatchReturnInst>::op_begin(this), 2) {
  940. Op<0>() = CRI.Op<0>();
  941. Op<1>() = CRI.Op<1>();
  942. }
  943. CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
  944. Instruction *InsertBefore)
  945. : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
  946. OperandTraits<CatchReturnInst>::op_begin(this), 2,
  947. InsertBefore) {
  948. init(CatchPad, BB);
  949. }
  950. CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
  951. BasicBlock *InsertAtEnd)
  952. : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
  953. OperandTraits<CatchReturnInst>::op_begin(this), 2,
  954. InsertAtEnd) {
  955. init(CatchPad, BB);
  956. }
  957. //===----------------------------------------------------------------------===//
  958. // CatchSwitchInst Implementation
  959. //===----------------------------------------------------------------------===//
  960. CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
  961. unsigned NumReservedValues,
  962. const Twine &NameStr,
  963. Instruction *InsertBefore)
  964. : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
  965. InsertBefore) {
  966. if (UnwindDest)
  967. ++NumReservedValues;
  968. init(ParentPad, UnwindDest, NumReservedValues + 1);
  969. setName(NameStr);
  970. }
  971. CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
  972. unsigned NumReservedValues,
  973. const Twine &NameStr, BasicBlock *InsertAtEnd)
  974. : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
  975. InsertAtEnd) {
  976. if (UnwindDest)
  977. ++NumReservedValues;
  978. init(ParentPad, UnwindDest, NumReservedValues + 1);
  979. setName(NameStr);
  980. }
  981. CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI)
  982. : Instruction(CSI.getType(), Instruction::CatchSwitch, nullptr,
  983. CSI.getNumOperands()) {
  984. init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands());
  985. setNumHungOffUseOperands(ReservedSpace);
  986. Use *OL = getOperandList();
  987. const Use *InOL = CSI.getOperandList();
  988. for (unsigned I = 1, E = ReservedSpace; I != E; ++I)
  989. OL[I] = InOL[I];
  990. }
  991. void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest,
  992. unsigned NumReservedValues) {
  993. assert(ParentPad && NumReservedValues);
  994. ReservedSpace = NumReservedValues;
  995. setNumHungOffUseOperands(UnwindDest ? 2 : 1);
  996. allocHungoffUses(ReservedSpace);
  997. Op<0>() = ParentPad;
  998. if (UnwindDest) {
  999. setSubclassData<UnwindDestField>(true);
  1000. setUnwindDest(UnwindDest);
  1001. }
  1002. }
  1003. /// growOperands - grow operands - This grows the operand list in response to a
  1004. /// push_back style of operation. This grows the number of ops by 2 times.
  1005. void CatchSwitchInst::growOperands(unsigned Size) {
  1006. unsigned NumOperands = getNumOperands();
  1007. assert(NumOperands >= 1);
  1008. if (ReservedSpace >= NumOperands + Size)
  1009. return;
  1010. ReservedSpace = (NumOperands + Size / 2) * 2;
  1011. growHungoffUses(ReservedSpace);
  1012. }
  1013. void CatchSwitchInst::addHandler(BasicBlock *Handler) {
  1014. unsigned OpNo = getNumOperands();
  1015. growOperands(1);
  1016. assert(OpNo < ReservedSpace && "Growing didn't work!");
  1017. setNumHungOffUseOperands(getNumOperands() + 1);
  1018. getOperandList()[OpNo] = Handler;
  1019. }
  1020. void CatchSwitchInst::removeHandler(handler_iterator HI) {
  1021. // Move all subsequent handlers up one.
  1022. Use *EndDst = op_end() - 1;
  1023. for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst)
  1024. *CurDst = *(CurDst + 1);
  1025. // Null out the last handler use.
  1026. *EndDst = nullptr;
  1027. setNumHungOffUseOperands(getNumOperands() - 1);
  1028. }
  1029. //===----------------------------------------------------------------------===//
  1030. // FuncletPadInst Implementation
  1031. //===----------------------------------------------------------------------===//
  1032. void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args,
  1033. const Twine &NameStr) {
  1034. assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?");
  1035. llvm::copy(Args, op_begin());
  1036. setParentPad(ParentPad);
  1037. setName(NameStr);
  1038. }
  1039. FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI)
  1040. : Instruction(FPI.getType(), FPI.getOpcode(),
  1041. OperandTraits<FuncletPadInst>::op_end(this) -
  1042. FPI.getNumOperands(),
  1043. FPI.getNumOperands()) {
  1044. std::copy(FPI.op_begin(), FPI.op_end(), op_begin());
  1045. setParentPad(FPI.getParentPad());
  1046. }
  1047. FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
  1048. ArrayRef<Value *> Args, unsigned Values,
  1049. const Twine &NameStr, Instruction *InsertBefore)
  1050. : Instruction(ParentPad->getType(), Op,
  1051. OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
  1052. InsertBefore) {
  1053. init(ParentPad, Args, NameStr);
  1054. }
  1055. FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
  1056. ArrayRef<Value *> Args, unsigned Values,
  1057. const Twine &NameStr, BasicBlock *InsertAtEnd)
  1058. : Instruction(ParentPad->getType(), Op,
  1059. OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
  1060. InsertAtEnd) {
  1061. init(ParentPad, Args, NameStr);
  1062. }
  1063. //===----------------------------------------------------------------------===//
  1064. // UnreachableInst Implementation
  1065. //===----------------------------------------------------------------------===//
  1066. UnreachableInst::UnreachableInst(LLVMContext &Context,
  1067. Instruction *InsertBefore)
  1068. : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
  1069. 0, InsertBefore) {}
  1070. UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
  1071. : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
  1072. 0, InsertAtEnd) {}
  1073. //===----------------------------------------------------------------------===//
  1074. // BranchInst Implementation
  1075. //===----------------------------------------------------------------------===//
  1076. void BranchInst::AssertOK() {
  1077. if (isConditional())
  1078. assert(getCondition()->getType()->isIntegerTy(1) &&
  1079. "May only branch on boolean predicates!");
  1080. }
  1081. BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
  1082. : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
  1083. OperandTraits<BranchInst>::op_end(this) - 1, 1,
  1084. InsertBefore) {
  1085. assert(IfTrue && "Branch destination may not be null!");
  1086. Op<-1>() = IfTrue;
  1087. }
  1088. BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
  1089. Instruction *InsertBefore)
  1090. : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
  1091. OperandTraits<BranchInst>::op_end(this) - 3, 3,
  1092. InsertBefore) {
  1093. // Assign in order of operand index to make use-list order predictable.
  1094. Op<-3>() = Cond;
  1095. Op<-2>() = IfFalse;
  1096. Op<-1>() = IfTrue;
  1097. #ifndef NDEBUG
  1098. AssertOK();
  1099. #endif
  1100. }
  1101. BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
  1102. : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
  1103. OperandTraits<BranchInst>::op_end(this) - 1, 1, InsertAtEnd) {
  1104. assert(IfTrue && "Branch destination may not be null!");
  1105. Op<-1>() = IfTrue;
  1106. }
  1107. BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
  1108. BasicBlock *InsertAtEnd)
  1109. : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
  1110. OperandTraits<BranchInst>::op_end(this) - 3, 3, InsertAtEnd) {
  1111. // Assign in order of operand index to make use-list order predictable.
  1112. Op<-3>() = Cond;
  1113. Op<-2>() = IfFalse;
  1114. Op<-1>() = IfTrue;
  1115. #ifndef NDEBUG
  1116. AssertOK();
  1117. #endif
  1118. }
  1119. BranchInst::BranchInst(const BranchInst &BI)
  1120. : Instruction(Type::getVoidTy(BI.getContext()), Instruction::Br,
  1121. OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
  1122. BI.getNumOperands()) {
  1123. // Assign in order of operand index to make use-list order predictable.
  1124. if (BI.getNumOperands() != 1) {
  1125. assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
  1126. Op<-3>() = BI.Op<-3>();
  1127. Op<-2>() = BI.Op<-2>();
  1128. }
  1129. Op<-1>() = BI.Op<-1>();
  1130. SubclassOptionalData = BI.SubclassOptionalData;
  1131. }
  1132. void BranchInst::swapSuccessors() {
  1133. assert(isConditional() &&
  1134. "Cannot swap successors of an unconditional branch");
  1135. Op<-1>().swap(Op<-2>());
  1136. // Update profile metadata if present and it matches our structural
  1137. // expectations.
  1138. swapProfMetadata();
  1139. }
  1140. //===----------------------------------------------------------------------===//
  1141. // AllocaInst Implementation
  1142. //===----------------------------------------------------------------------===//
  1143. static Value *getAISize(LLVMContext &Context, Value *Amt) {
  1144. if (!Amt)
  1145. Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
  1146. else {
  1147. assert(!isa<BasicBlock>(Amt) &&
  1148. "Passed basic block into allocation size parameter! Use other ctor");
  1149. assert(Amt->getType()->isIntegerTy() &&
  1150. "Allocation array size is not an integer!");
  1151. }
  1152. return Amt;
  1153. }
  1154. static Align computeAllocaDefaultAlign(Type *Ty, BasicBlock *BB) {
  1155. assert(BB && "Insertion BB cannot be null when alignment not provided!");
  1156. assert(BB->getParent() &&
  1157. "BB must be in a Function when alignment not provided!");
  1158. const DataLayout &DL = BB->getModule()->getDataLayout();
  1159. return DL.getPrefTypeAlign(Ty);
  1160. }
  1161. static Align computeAllocaDefaultAlign(Type *Ty, Instruction *I) {
  1162. assert(I && "Insertion position cannot be null when alignment not provided!");
  1163. return computeAllocaDefaultAlign(Ty, I->getParent());
  1164. }
  1165. AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
  1166. Instruction *InsertBefore)
  1167. : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {}
  1168. AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
  1169. BasicBlock *InsertAtEnd)
  1170. : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertAtEnd) {}
  1171. AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
  1172. const Twine &Name, Instruction *InsertBefore)
  1173. : AllocaInst(Ty, AddrSpace, ArraySize,
  1174. computeAllocaDefaultAlign(Ty, InsertBefore), Name,
  1175. InsertBefore) {}
  1176. AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
  1177. const Twine &Name, BasicBlock *InsertAtEnd)
  1178. : AllocaInst(Ty, AddrSpace, ArraySize,
  1179. computeAllocaDefaultAlign(Ty, InsertAtEnd), Name,
  1180. InsertAtEnd) {}
  1181. AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
  1182. Align Align, const Twine &Name,
  1183. Instruction *InsertBefore)
  1184. : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
  1185. getAISize(Ty->getContext(), ArraySize), InsertBefore),
  1186. AllocatedType(Ty) {
  1187. setAlignment(Align);
  1188. assert(!Ty->isVoidTy() && "Cannot allocate void!");
  1189. setName(Name);
  1190. }
  1191. AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
  1192. Align Align, const Twine &Name, BasicBlock *InsertAtEnd)
  1193. : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
  1194. getAISize(Ty->getContext(), ArraySize), InsertAtEnd),
  1195. AllocatedType(Ty) {
  1196. setAlignment(Align);
  1197. assert(!Ty->isVoidTy() && "Cannot allocate void!");
  1198. setName(Name);
  1199. }
  1200. bool AllocaInst::isArrayAllocation() const {
  1201. if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
  1202. return !CI->isOne();
  1203. return true;
  1204. }
  1205. /// isStaticAlloca - Return true if this alloca is in the entry block of the
  1206. /// function and is a constant size. If so, the code generator will fold it
  1207. /// into the prolog/epilog code, so it is basically free.
  1208. bool AllocaInst::isStaticAlloca() const {
  1209. // Must be constant size.
  1210. if (!isa<ConstantInt>(getArraySize())) return false;
  1211. // Must be in the entry block.
  1212. const BasicBlock *Parent = getParent();
  1213. return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
  1214. }
  1215. //===----------------------------------------------------------------------===//
  1216. // LoadInst Implementation
  1217. //===----------------------------------------------------------------------===//
  1218. void LoadInst::AssertOK() {
  1219. assert(getOperand(0)->getType()->isPointerTy() &&
  1220. "Ptr must have pointer type.");
  1221. }
  1222. static Align computeLoadStoreDefaultAlign(Type *Ty, BasicBlock *BB) {
  1223. assert(BB && "Insertion BB cannot be null when alignment not provided!");
  1224. assert(BB->getParent() &&
  1225. "BB must be in a Function when alignment not provided!");
  1226. const DataLayout &DL = BB->getModule()->getDataLayout();
  1227. return DL.getABITypeAlign(Ty);
  1228. }
  1229. static Align computeLoadStoreDefaultAlign(Type *Ty, Instruction *I) {
  1230. assert(I && "Insertion position cannot be null when alignment not provided!");
  1231. return computeLoadStoreDefaultAlign(Ty, I->getParent());
  1232. }
  1233. LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
  1234. Instruction *InsertBef)
  1235. : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertBef) {}
  1236. LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
  1237. BasicBlock *InsertAE)
  1238. : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertAE) {}
  1239. LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
  1240. Instruction *InsertBef)
  1241. : LoadInst(Ty, Ptr, Name, isVolatile,
  1242. computeLoadStoreDefaultAlign(Ty, InsertBef), InsertBef) {}
  1243. LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
  1244. BasicBlock *InsertAE)
  1245. : LoadInst(Ty, Ptr, Name, isVolatile,
  1246. computeLoadStoreDefaultAlign(Ty, InsertAE), InsertAE) {}
  1247. LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
  1248. Align Align, Instruction *InsertBef)
  1249. : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
  1250. SyncScope::System, InsertBef) {}
  1251. LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
  1252. Align Align, BasicBlock *InsertAE)
  1253. : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
  1254. SyncScope::System, InsertAE) {}
  1255. LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
  1256. Align Align, AtomicOrdering Order, SyncScope::ID SSID,
  1257. Instruction *InsertBef)
  1258. : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
  1259. assert(cast<PointerType>(Ptr->getType())->isOpaqueOrPointeeTypeMatches(Ty));
  1260. setVolatile(isVolatile);
  1261. setAlignment(Align);
  1262. setAtomic(Order, SSID);
  1263. AssertOK();
  1264. setName(Name);
  1265. }
  1266. LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
  1267. Align Align, AtomicOrdering Order, SyncScope::ID SSID,
  1268. BasicBlock *InsertAE)
  1269. : UnaryInstruction(Ty, Load, Ptr, InsertAE) {
  1270. assert(cast<PointerType>(Ptr->getType())->isOpaqueOrPointeeTypeMatches(Ty));
  1271. setVolatile(isVolatile);
  1272. setAlignment(Align);
  1273. setAtomic(Order, SSID);
  1274. AssertOK();
  1275. setName(Name);
  1276. }
  1277. //===----------------------------------------------------------------------===//
  1278. // StoreInst Implementation
  1279. //===----------------------------------------------------------------------===//
  1280. void StoreInst::AssertOK() {
  1281. assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
  1282. assert(getOperand(1)->getType()->isPointerTy() &&
  1283. "Ptr must have pointer type!");
  1284. assert(cast<PointerType>(getOperand(1)->getType())
  1285. ->isOpaqueOrPointeeTypeMatches(getOperand(0)->getType()) &&
  1286. "Ptr must be a pointer to Val type!");
  1287. }
  1288. StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
  1289. : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
  1290. StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
  1291. : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {}
  1292. StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
  1293. Instruction *InsertBefore)
  1294. : StoreInst(val, addr, isVolatile,
  1295. computeLoadStoreDefaultAlign(val->getType(), InsertBefore),
  1296. InsertBefore) {}
  1297. StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
  1298. BasicBlock *InsertAtEnd)
  1299. : StoreInst(val, addr, isVolatile,
  1300. computeLoadStoreDefaultAlign(val->getType(), InsertAtEnd),
  1301. InsertAtEnd) {}
  1302. StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
  1303. Instruction *InsertBefore)
  1304. : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
  1305. SyncScope::System, InsertBefore) {}
  1306. StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
  1307. BasicBlock *InsertAtEnd)
  1308. : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
  1309. SyncScope::System, InsertAtEnd) {}
  1310. StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
  1311. AtomicOrdering Order, SyncScope::ID SSID,
  1312. Instruction *InsertBefore)
  1313. : Instruction(Type::getVoidTy(val->getContext()), Store,
  1314. OperandTraits<StoreInst>::op_begin(this),
  1315. OperandTraits<StoreInst>::operands(this), InsertBefore) {
  1316. Op<0>() = val;
  1317. Op<1>() = addr;
  1318. setVolatile(isVolatile);
  1319. setAlignment(Align);
  1320. setAtomic(Order, SSID);
  1321. AssertOK();
  1322. }
  1323. StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
  1324. AtomicOrdering Order, SyncScope::ID SSID,
  1325. BasicBlock *InsertAtEnd)
  1326. : Instruction(Type::getVoidTy(val->getContext()), Store,
  1327. OperandTraits<StoreInst>::op_begin(this),
  1328. OperandTraits<StoreInst>::operands(this), InsertAtEnd) {
  1329. Op<0>() = val;
  1330. Op<1>() = addr;
  1331. setVolatile(isVolatile);
  1332. setAlignment(Align);
  1333. setAtomic(Order, SSID);
  1334. AssertOK();
  1335. }
  1336. //===----------------------------------------------------------------------===//
  1337. // AtomicCmpXchgInst Implementation
  1338. //===----------------------------------------------------------------------===//
  1339. void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
  1340. Align Alignment, AtomicOrdering SuccessOrdering,
  1341. AtomicOrdering FailureOrdering,
  1342. SyncScope::ID SSID) {
  1343. Op<0>() = Ptr;
  1344. Op<1>() = Cmp;
  1345. Op<2>() = NewVal;
  1346. setSuccessOrdering(SuccessOrdering);
  1347. setFailureOrdering(FailureOrdering);
  1348. setSyncScopeID(SSID);
  1349. setAlignment(Alignment);
  1350. assert(getOperand(0) && getOperand(1) && getOperand(2) &&
  1351. "All operands must be non-null!");
  1352. assert(getOperand(0)->getType()->isPointerTy() &&
  1353. "Ptr must have pointer type!");
  1354. assert(cast<PointerType>(getOperand(0)->getType())
  1355. ->isOpaqueOrPointeeTypeMatches(getOperand(1)->getType()) &&
  1356. "Ptr must be a pointer to Cmp type!");
  1357. assert(cast<PointerType>(getOperand(0)->getType())
  1358. ->isOpaqueOrPointeeTypeMatches(getOperand(2)->getType()) &&
  1359. "Ptr must be a pointer to NewVal type!");
  1360. assert(getOperand(1)->getType() == getOperand(2)->getType() &&
  1361. "Cmp type and NewVal type must be same!");
  1362. }
  1363. AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
  1364. Align Alignment,
  1365. AtomicOrdering SuccessOrdering,
  1366. AtomicOrdering FailureOrdering,
  1367. SyncScope::ID SSID,
  1368. Instruction *InsertBefore)
  1369. : Instruction(
  1370. StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
  1371. AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
  1372. OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
  1373. Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID);
  1374. }
  1375. AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
  1376. Align Alignment,
  1377. AtomicOrdering SuccessOrdering,
  1378. AtomicOrdering FailureOrdering,
  1379. SyncScope::ID SSID,
  1380. BasicBlock *InsertAtEnd)
  1381. : Instruction(
  1382. StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
  1383. AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
  1384. OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
  1385. Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID);
  1386. }
  1387. //===----------------------------------------------------------------------===//
  1388. // AtomicRMWInst Implementation
  1389. //===----------------------------------------------------------------------===//
  1390. void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
  1391. Align Alignment, AtomicOrdering Ordering,
  1392. SyncScope::ID SSID) {
  1393. Op<0>() = Ptr;
  1394. Op<1>() = Val;
  1395. setOperation(Operation);
  1396. setOrdering(Ordering);
  1397. setSyncScopeID(SSID);
  1398. setAlignment(Alignment);
  1399. assert(getOperand(0) && getOperand(1) &&
  1400. "All operands must be non-null!");
  1401. assert(getOperand(0)->getType()->isPointerTy() &&
  1402. "Ptr must have pointer type!");
  1403. assert(cast<PointerType>(getOperand(0)->getType())
  1404. ->isOpaqueOrPointeeTypeMatches(getOperand(1)->getType()) &&
  1405. "Ptr must be a pointer to Val type!");
  1406. assert(Ordering != AtomicOrdering::NotAtomic &&
  1407. "AtomicRMW instructions must be atomic!");
  1408. }
  1409. AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
  1410. Align Alignment, AtomicOrdering Ordering,
  1411. SyncScope::ID SSID, Instruction *InsertBefore)
  1412. : Instruction(Val->getType(), AtomicRMW,
  1413. OperandTraits<AtomicRMWInst>::op_begin(this),
  1414. OperandTraits<AtomicRMWInst>::operands(this), InsertBefore) {
  1415. Init(Operation, Ptr, Val, Alignment, Ordering, SSID);
  1416. }
  1417. AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
  1418. Align Alignment, AtomicOrdering Ordering,
  1419. SyncScope::ID SSID, BasicBlock *InsertAtEnd)
  1420. : Instruction(Val->getType(), AtomicRMW,
  1421. OperandTraits<AtomicRMWInst>::op_begin(this),
  1422. OperandTraits<AtomicRMWInst>::operands(this), InsertAtEnd) {
  1423. Init(Operation, Ptr, Val, Alignment, Ordering, SSID);
  1424. }
  1425. StringRef AtomicRMWInst::getOperationName(BinOp Op) {
  1426. switch (Op) {
  1427. case AtomicRMWInst::Xchg:
  1428. return "xchg";
  1429. case AtomicRMWInst::Add:
  1430. return "add";
  1431. case AtomicRMWInst::Sub:
  1432. return "sub";
  1433. case AtomicRMWInst::And:
  1434. return "and";
  1435. case AtomicRMWInst::Nand:
  1436. return "nand";
  1437. case AtomicRMWInst::Or:
  1438. return "or";
  1439. case AtomicRMWInst::Xor:
  1440. return "xor";
  1441. case AtomicRMWInst::Max:
  1442. return "max";
  1443. case AtomicRMWInst::Min:
  1444. return "min";
  1445. case AtomicRMWInst::UMax:
  1446. return "umax";
  1447. case AtomicRMWInst::UMin:
  1448. return "umin";
  1449. case AtomicRMWInst::FAdd:
  1450. return "fadd";
  1451. case AtomicRMWInst::FSub:
  1452. return "fsub";
  1453. case AtomicRMWInst::BAD_BINOP:
  1454. return "<invalid operation>";
  1455. }
  1456. llvm_unreachable("invalid atomicrmw operation");
  1457. }
  1458. //===----------------------------------------------------------------------===//
  1459. // FenceInst Implementation
  1460. //===----------------------------------------------------------------------===//
  1461. FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
  1462. SyncScope::ID SSID,
  1463. Instruction *InsertBefore)
  1464. : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
  1465. setOrdering(Ordering);
  1466. setSyncScopeID(SSID);
  1467. }
  1468. FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
  1469. SyncScope::ID SSID,
  1470. BasicBlock *InsertAtEnd)
  1471. : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
  1472. setOrdering(Ordering);
  1473. setSyncScopeID(SSID);
  1474. }
  1475. //===----------------------------------------------------------------------===//
  1476. // GetElementPtrInst Implementation
  1477. //===----------------------------------------------------------------------===//
  1478. void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
  1479. const Twine &Name) {
  1480. assert(getNumOperands() == 1 + IdxList.size() &&
  1481. "NumOperands not initialized?");
  1482. Op<0>() = Ptr;
  1483. llvm::copy(IdxList, op_begin() + 1);
  1484. setName(Name);
  1485. }
  1486. GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
  1487. : Instruction(GEPI.getType(), GetElementPtr,
  1488. OperandTraits<GetElementPtrInst>::op_end(this) -
  1489. GEPI.getNumOperands(),
  1490. GEPI.getNumOperands()),
  1491. SourceElementType(GEPI.SourceElementType),
  1492. ResultElementType(GEPI.ResultElementType) {
  1493. std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
  1494. SubclassOptionalData = GEPI.SubclassOptionalData;
  1495. }
  1496. Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, Value *Idx) {
  1497. if (auto *Struct = dyn_cast<StructType>(Ty)) {
  1498. if (!Struct->indexValid(Idx))
  1499. return nullptr;
  1500. return Struct->getTypeAtIndex(Idx);
  1501. }
  1502. if (!Idx->getType()->isIntOrIntVectorTy())
  1503. return nullptr;
  1504. if (auto *Array = dyn_cast<ArrayType>(Ty))
  1505. return Array->getElementType();
  1506. if (auto *Vector = dyn_cast<VectorType>(Ty))
  1507. return Vector->getElementType();
  1508. return nullptr;
  1509. }
  1510. Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, uint64_t Idx) {
  1511. if (auto *Struct = dyn_cast<StructType>(Ty)) {
  1512. if (Idx >= Struct->getNumElements())
  1513. return nullptr;
  1514. return Struct->getElementType(Idx);
  1515. }
  1516. if (auto *Array = dyn_cast<ArrayType>(Ty))
  1517. return Array->getElementType();
  1518. if (auto *Vector = dyn_cast<VectorType>(Ty))
  1519. return Vector->getElementType();
  1520. return nullptr;
  1521. }
  1522. template <typename IndexTy>
  1523. static Type *getIndexedTypeInternal(Type *Ty, ArrayRef<IndexTy> IdxList) {
  1524. if (IdxList.empty())
  1525. return Ty;
  1526. for (IndexTy V : IdxList.slice(1)) {
  1527. Ty = GetElementPtrInst::getTypeAtIndex(Ty, V);
  1528. if (!Ty)
  1529. return Ty;
  1530. }
  1531. return Ty;
  1532. }
  1533. Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) {
  1534. return getIndexedTypeInternal(Ty, IdxList);
  1535. }
  1536. Type *GetElementPtrInst::getIndexedType(Type *Ty,
  1537. ArrayRef<Constant *> IdxList) {
  1538. return getIndexedTypeInternal(Ty, IdxList);
  1539. }
  1540. Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) {
  1541. return getIndexedTypeInternal(Ty, IdxList);
  1542. }
  1543. /// hasAllZeroIndices - Return true if all of the indices of this GEP are
  1544. /// zeros. If so, the result pointer and the first operand have the same
  1545. /// value, just potentially different types.
  1546. bool GetElementPtrInst::hasAllZeroIndices() const {
  1547. for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
  1548. if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
  1549. if (!CI->isZero()) return false;
  1550. } else {
  1551. return false;
  1552. }
  1553. }
  1554. return true;
  1555. }
  1556. /// hasAllConstantIndices - Return true if all of the indices of this GEP are
  1557. /// constant integers. If so, the result pointer and the first operand have
  1558. /// a constant offset between them.
  1559. bool GetElementPtrInst::hasAllConstantIndices() const {
  1560. for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
  1561. if (!isa<ConstantInt>(getOperand(i)))
  1562. return false;
  1563. }
  1564. return true;
  1565. }
  1566. void GetElementPtrInst::setIsInBounds(bool B) {
  1567. cast<GEPOperator>(this)->setIsInBounds(B);
  1568. }
  1569. bool GetElementPtrInst::isInBounds() const {
  1570. return cast<GEPOperator>(this)->isInBounds();
  1571. }
  1572. bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
  1573. APInt &Offset) const {
  1574. // Delegate to the generic GEPOperator implementation.
  1575. return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
  1576. }
  1577. bool GetElementPtrInst::collectOffset(
  1578. const DataLayout &DL, unsigned BitWidth,
  1579. MapVector<Value *, APInt> &VariableOffsets,
  1580. APInt &ConstantOffset) const {
  1581. // Delegate to the generic GEPOperator implementation.
  1582. return cast<GEPOperator>(this)->collectOffset(DL, BitWidth, VariableOffsets,
  1583. ConstantOffset);
  1584. }
  1585. //===----------------------------------------------------------------------===//
  1586. // ExtractElementInst Implementation
  1587. //===----------------------------------------------------------------------===//
  1588. ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
  1589. const Twine &Name,
  1590. Instruction *InsertBef)
  1591. : Instruction(cast<VectorType>(Val->getType())->getElementType(),
  1592. ExtractElement,
  1593. OperandTraits<ExtractElementInst>::op_begin(this),
  1594. 2, InsertBef) {
  1595. assert(isValidOperands(Val, Index) &&
  1596. "Invalid extractelement instruction operands!");
  1597. Op<0>() = Val;
  1598. Op<1>() = Index;
  1599. setName(Name);
  1600. }
  1601. ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
  1602. const Twine &Name,
  1603. BasicBlock *InsertAE)
  1604. : Instruction(cast<VectorType>(Val->getType())->getElementType(),
  1605. ExtractElement,
  1606. OperandTraits<ExtractElementInst>::op_begin(this),
  1607. 2, InsertAE) {
  1608. assert(isValidOperands(Val, Index) &&
  1609. "Invalid extractelement instruction operands!");
  1610. Op<0>() = Val;
  1611. Op<1>() = Index;
  1612. setName(Name);
  1613. }
  1614. bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
  1615. if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
  1616. return false;
  1617. return true;
  1618. }
  1619. //===----------------------------------------------------------------------===//
  1620. // InsertElementInst Implementation
  1621. //===----------------------------------------------------------------------===//
  1622. InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
  1623. const Twine &Name,
  1624. Instruction *InsertBef)
  1625. : Instruction(Vec->getType(), InsertElement,
  1626. OperandTraits<InsertElementInst>::op_begin(this),
  1627. 3, InsertBef) {
  1628. assert(isValidOperands(Vec, Elt, Index) &&
  1629. "Invalid insertelement instruction operands!");
  1630. Op<0>() = Vec;
  1631. Op<1>() = Elt;
  1632. Op<2>() = Index;
  1633. setName(Name);
  1634. }
  1635. InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
  1636. const Twine &Name,
  1637. BasicBlock *InsertAE)
  1638. : Instruction(Vec->getType(), InsertElement,
  1639. OperandTraits<InsertElementInst>::op_begin(this),
  1640. 3, InsertAE) {
  1641. assert(isValidOperands(Vec, Elt, Index) &&
  1642. "Invalid insertelement instruction operands!");
  1643. Op<0>() = Vec;
  1644. Op<1>() = Elt;
  1645. Op<2>() = Index;
  1646. setName(Name);
  1647. }
  1648. bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
  1649. const Value *Index) {
  1650. if (!Vec->getType()->isVectorTy())
  1651. return false; // First operand of insertelement must be vector type.
  1652. if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
  1653. return false;// Second operand of insertelement must be vector element type.
  1654. if (!Index->getType()->isIntegerTy())
  1655. return false; // Third operand of insertelement must be i32.
  1656. return true;
  1657. }
  1658. //===----------------------------------------------------------------------===//
  1659. // ShuffleVectorInst Implementation
  1660. //===----------------------------------------------------------------------===//
  1661. static Value *createPlaceholderForShuffleVector(Value *V) {
  1662. assert(V && "Cannot create placeholder of nullptr V");
  1663. return PoisonValue::get(V->getType());
  1664. }
  1665. ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *Mask, const Twine &Name,
  1666. Instruction *InsertBefore)
  1667. : ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name,
  1668. InsertBefore) {}
  1669. ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *Mask, const Twine &Name,
  1670. BasicBlock *InsertAtEnd)
  1671. : ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name,
  1672. InsertAtEnd) {}
  1673. ShuffleVectorInst::ShuffleVectorInst(Value *V1, ArrayRef<int> Mask,
  1674. const Twine &Name,
  1675. Instruction *InsertBefore)
  1676. : ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name,
  1677. InsertBefore) {}
  1678. ShuffleVectorInst::ShuffleVectorInst(Value *V1, ArrayRef<int> Mask,
  1679. const Twine &Name, BasicBlock *InsertAtEnd)
  1680. : ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name,
  1681. InsertAtEnd) {}
  1682. ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
  1683. const Twine &Name,
  1684. Instruction *InsertBefore)
  1685. : Instruction(
  1686. VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
  1687. cast<VectorType>(Mask->getType())->getElementCount()),
  1688. ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
  1689. OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) {
  1690. assert(isValidOperands(V1, V2, Mask) &&
  1691. "Invalid shuffle vector instruction operands!");
  1692. Op<0>() = V1;
  1693. Op<1>() = V2;
  1694. SmallVector<int, 16> MaskArr;
  1695. getShuffleMask(cast<Constant>(Mask), MaskArr);
  1696. setShuffleMask(MaskArr);
  1697. setName(Name);
  1698. }
  1699. ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
  1700. const Twine &Name, BasicBlock *InsertAtEnd)
  1701. : Instruction(
  1702. VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
  1703. cast<VectorType>(Mask->getType())->getElementCount()),
  1704. ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
  1705. OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) {
  1706. assert(isValidOperands(V1, V2, Mask) &&
  1707. "Invalid shuffle vector instruction operands!");
  1708. Op<0>() = V1;
  1709. Op<1>() = V2;
  1710. SmallVector<int, 16> MaskArr;
  1711. getShuffleMask(cast<Constant>(Mask), MaskArr);
  1712. setShuffleMask(MaskArr);
  1713. setName(Name);
  1714. }
  1715. ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
  1716. const Twine &Name,
  1717. Instruction *InsertBefore)
  1718. : Instruction(
  1719. VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
  1720. Mask.size(), isa<ScalableVectorType>(V1->getType())),
  1721. ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
  1722. OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) {
  1723. assert(isValidOperands(V1, V2, Mask) &&
  1724. "Invalid shuffle vector instruction operands!");
  1725. Op<0>() = V1;
  1726. Op<1>() = V2;
  1727. setShuffleMask(Mask);
  1728. setName(Name);
  1729. }
  1730. ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
  1731. const Twine &Name, BasicBlock *InsertAtEnd)
  1732. : Instruction(
  1733. VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
  1734. Mask.size(), isa<ScalableVectorType>(V1->getType())),
  1735. ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
  1736. OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) {
  1737. assert(isValidOperands(V1, V2, Mask) &&
  1738. "Invalid shuffle vector instruction operands!");
  1739. Op<0>() = V1;
  1740. Op<1>() = V2;
  1741. setShuffleMask(Mask);
  1742. setName(Name);
  1743. }
  1744. void ShuffleVectorInst::commute() {
  1745. int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
  1746. int NumMaskElts = ShuffleMask.size();
  1747. SmallVector<int, 16> NewMask(NumMaskElts);
  1748. for (int i = 0; i != NumMaskElts; ++i) {
  1749. int MaskElt = getMaskValue(i);
  1750. if (MaskElt == UndefMaskElem) {
  1751. NewMask[i] = UndefMaskElem;
  1752. continue;
  1753. }
  1754. assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask");
  1755. MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts;
  1756. NewMask[i] = MaskElt;
  1757. }
  1758. setShuffleMask(NewMask);
  1759. Op<0>().swap(Op<1>());
  1760. }
  1761. bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
  1762. ArrayRef<int> Mask) {
  1763. // V1 and V2 must be vectors of the same type.
  1764. if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
  1765. return false;
  1766. // Make sure the mask elements make sense.
  1767. int V1Size =
  1768. cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue();
  1769. for (int Elem : Mask)
  1770. if (Elem != UndefMaskElem && Elem >= V1Size * 2)
  1771. return false;
  1772. if (isa<ScalableVectorType>(V1->getType()))
  1773. if ((Mask[0] != 0 && Mask[0] != UndefMaskElem) || !is_splat(Mask))
  1774. return false;
  1775. return true;
  1776. }
  1777. bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
  1778. const Value *Mask) {
  1779. // V1 and V2 must be vectors of the same type.
  1780. if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
  1781. return false;
  1782. // Mask must be vector of i32, and must be the same kind of vector as the
  1783. // input vectors
  1784. auto *MaskTy = dyn_cast<VectorType>(Mask->getType());
  1785. if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32) ||
  1786. isa<ScalableVectorType>(MaskTy) != isa<ScalableVectorType>(V1->getType()))
  1787. return false;
  1788. // Check to see if Mask is valid.
  1789. if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
  1790. return true;
  1791. if (const auto *MV = dyn_cast<ConstantVector>(Mask)) {
  1792. unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements();
  1793. for (Value *Op : MV->operands()) {
  1794. if (auto *CI = dyn_cast<ConstantInt>(Op)) {
  1795. if (CI->uge(V1Size*2))
  1796. return false;
  1797. } else if (!isa<UndefValue>(Op)) {
  1798. return false;
  1799. }
  1800. }
  1801. return true;
  1802. }
  1803. if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
  1804. unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements();
  1805. for (unsigned i = 0, e = cast<FixedVectorType>(MaskTy)->getNumElements();
  1806. i != e; ++i)
  1807. if (CDS->getElementAsInteger(i) >= V1Size*2)
  1808. return false;
  1809. return true;
  1810. }
  1811. return false;
  1812. }
  1813. void ShuffleVectorInst::getShuffleMask(const Constant *Mask,
  1814. SmallVectorImpl<int> &Result) {
  1815. ElementCount EC = cast<VectorType>(Mask->getType())->getElementCount();
  1816. if (isa<ConstantAggregateZero>(Mask)) {
  1817. Result.resize(EC.getKnownMinValue(), 0);
  1818. return;
  1819. }
  1820. Result.reserve(EC.getKnownMinValue());
  1821. if (EC.isScalable()) {
  1822. assert((isa<ConstantAggregateZero>(Mask) || isa<UndefValue>(Mask)) &&
  1823. "Scalable vector shuffle mask must be undef or zeroinitializer");
  1824. int MaskVal = isa<UndefValue>(Mask) ? -1 : 0;
  1825. for (unsigned I = 0; I < EC.getKnownMinValue(); ++I)
  1826. Result.emplace_back(MaskVal);
  1827. return;
  1828. }
  1829. unsigned NumElts = EC.getKnownMinValue();
  1830. if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
  1831. for (unsigned i = 0; i != NumElts; ++i)
  1832. Result.push_back(CDS->getElementAsInteger(i));
  1833. return;
  1834. }
  1835. for (unsigned i = 0; i != NumElts; ++i) {
  1836. Constant *C = Mask->getAggregateElement(i);
  1837. Result.push_back(isa<UndefValue>(C) ? -1 :
  1838. cast<ConstantInt>(C)->getZExtValue());
  1839. }
  1840. }
  1841. void ShuffleVectorInst::setShuffleMask(ArrayRef<int> Mask) {
  1842. ShuffleMask.assign(Mask.begin(), Mask.end());
  1843. ShuffleMaskForBitcode = convertShuffleMaskForBitcode(Mask, getType());
  1844. }
  1845. Constant *ShuffleVectorInst::convertShuffleMaskForBitcode(ArrayRef<int> Mask,
  1846. Type *ResultTy) {
  1847. Type *Int32Ty = Type::getInt32Ty(ResultTy->getContext());
  1848. if (isa<ScalableVectorType>(ResultTy)) {
  1849. assert(is_splat(Mask) && "Unexpected shuffle");
  1850. Type *VecTy = VectorType::get(Int32Ty, Mask.size(), true);
  1851. if (Mask[0] == 0)
  1852. return Constant::getNullValue(VecTy);
  1853. return UndefValue::get(VecTy);
  1854. }
  1855. SmallVector<Constant *, 16> MaskConst;
  1856. for (int Elem : Mask) {
  1857. if (Elem == UndefMaskElem)
  1858. MaskConst.push_back(UndefValue::get(Int32Ty));
  1859. else
  1860. MaskConst.push_back(ConstantInt::get(Int32Ty, Elem));
  1861. }
  1862. return ConstantVector::get(MaskConst);
  1863. }
  1864. static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
  1865. assert(!Mask.empty() && "Shuffle mask must contain elements");
  1866. bool UsesLHS = false;
  1867. bool UsesRHS = false;
  1868. for (int I : Mask) {
  1869. if (I == -1)
  1870. continue;
  1871. assert(I >= 0 && I < (NumOpElts * 2) &&
  1872. "Out-of-bounds shuffle mask element");
  1873. UsesLHS |= (I < NumOpElts);
  1874. UsesRHS |= (I >= NumOpElts);
  1875. if (UsesLHS && UsesRHS)
  1876. return false;
  1877. }
  1878. // Allow for degenerate case: completely undef mask means neither source is used.
  1879. return UsesLHS || UsesRHS;
  1880. }
  1881. bool ShuffleVectorInst::isSingleSourceMask(ArrayRef<int> Mask) {
  1882. // We don't have vector operand size information, so assume operands are the
  1883. // same size as the mask.
  1884. return isSingleSourceMaskImpl(Mask, Mask.size());
  1885. }
  1886. static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
  1887. if (!isSingleSourceMaskImpl(Mask, NumOpElts))
  1888. return false;
  1889. for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
  1890. if (Mask[i] == -1)
  1891. continue;
  1892. if (Mask[i] != i && Mask[i] != (NumOpElts + i))
  1893. return false;
  1894. }
  1895. return true;
  1896. }
  1897. bool ShuffleVectorInst::isIdentityMask(ArrayRef<int> Mask) {
  1898. // We don't have vector operand size information, so assume operands are the
  1899. // same size as the mask.
  1900. return isIdentityMaskImpl(Mask, Mask.size());
  1901. }
  1902. bool ShuffleVectorInst::isReverseMask(ArrayRef<int> Mask) {
  1903. if (!isSingleSourceMask(Mask))
  1904. return false;
  1905. for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
  1906. if (Mask[i] == -1)
  1907. continue;
  1908. if (Mask[i] != (NumElts - 1 - i) && Mask[i] != (NumElts + NumElts - 1 - i))
  1909. return false;
  1910. }
  1911. return true;
  1912. }
  1913. bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef<int> Mask) {
  1914. if (!isSingleSourceMask(Mask))
  1915. return false;
  1916. for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
  1917. if (Mask[i] == -1)
  1918. continue;
  1919. if (Mask[i] != 0 && Mask[i] != NumElts)
  1920. return false;
  1921. }
  1922. return true;
  1923. }
  1924. bool ShuffleVectorInst::isSelectMask(ArrayRef<int> Mask) {
  1925. // Select is differentiated from identity. It requires using both sources.
  1926. if (isSingleSourceMask(Mask))
  1927. return false;
  1928. for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
  1929. if (Mask[i] == -1)
  1930. continue;
  1931. if (Mask[i] != i && Mask[i] != (NumElts + i))
  1932. return false;
  1933. }
  1934. return true;
  1935. }
  1936. bool ShuffleVectorInst::isTransposeMask(ArrayRef<int> Mask) {
  1937. // Example masks that will return true:
  1938. // v1 = <a, b, c, d>
  1939. // v2 = <e, f, g, h>
  1940. // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g>
  1941. // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h>
  1942. // 1. The number of elements in the mask must be a power-of-2 and at least 2.
  1943. int NumElts = Mask.size();
  1944. if (NumElts < 2 || !isPowerOf2_32(NumElts))
  1945. return false;
  1946. // 2. The first element of the mask must be either a 0 or a 1.
  1947. if (Mask[0] != 0 && Mask[0] != 1)
  1948. return false;
  1949. // 3. The difference between the first 2 elements must be equal to the
  1950. // number of elements in the mask.
  1951. if ((Mask[1] - Mask[0]) != NumElts)
  1952. return false;
  1953. // 4. The difference between consecutive even-numbered and odd-numbered
  1954. // elements must be equal to 2.
  1955. for (int i = 2; i < NumElts; ++i) {
  1956. int MaskEltVal = Mask[i];
  1957. if (MaskEltVal == -1)
  1958. return false;
  1959. int MaskEltPrevVal = Mask[i - 2];
  1960. if (MaskEltVal - MaskEltPrevVal != 2)
  1961. return false;
  1962. }
  1963. return true;
  1964. }
  1965. bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef<int> Mask,
  1966. int NumSrcElts, int &Index) {
  1967. // Must extract from a single source.
  1968. if (!isSingleSourceMaskImpl(Mask, NumSrcElts))
  1969. return false;
  1970. // Must be smaller (else this is an Identity shuffle).
  1971. if (NumSrcElts <= (int)Mask.size())
  1972. return false;
  1973. // Find start of extraction, accounting that we may start with an UNDEF.
  1974. int SubIndex = -1;
  1975. for (int i = 0, e = Mask.size(); i != e; ++i) {
  1976. int M = Mask[i];
  1977. if (M < 0)
  1978. continue;
  1979. int Offset = (M % NumSrcElts) - i;
  1980. if (0 <= SubIndex && SubIndex != Offset)
  1981. return false;
  1982. SubIndex = Offset;
  1983. }
  1984. if (0 <= SubIndex && SubIndex + (int)Mask.size() <= NumSrcElts) {
  1985. Index = SubIndex;
  1986. return true;
  1987. }
  1988. return false;
  1989. }
  1990. bool ShuffleVectorInst::isInsertSubvectorMask(ArrayRef<int> Mask,
  1991. int NumSrcElts, int &NumSubElts,
  1992. int &Index) {
  1993. int NumMaskElts = Mask.size();
  1994. // Don't try to match if we're shuffling to a smaller size.
  1995. if (NumMaskElts < NumSrcElts)
  1996. return false;
  1997. // TODO: We don't recognize self-insertion/widening.
  1998. if (isSingleSourceMaskImpl(Mask, NumSrcElts))
  1999. return false;
  2000. // Determine which mask elements are attributed to which source.
  2001. APInt UndefElts = APInt::getZero(NumMaskElts);
  2002. APInt Src0Elts = APInt::getZero(NumMaskElts);
  2003. APInt Src1Elts = APInt::getZero(NumMaskElts);
  2004. bool Src0Identity = true;
  2005. bool Src1Identity = true;
  2006. for (int i = 0; i != NumMaskElts; ++i) {
  2007. int M = Mask[i];
  2008. if (M < 0) {
  2009. UndefElts.setBit(i);
  2010. continue;
  2011. }
  2012. if (M < NumSrcElts) {
  2013. Src0Elts.setBit(i);
  2014. Src0Identity &= (M == i);
  2015. continue;
  2016. }
  2017. Src1Elts.setBit(i);
  2018. Src1Identity &= (M == (i + NumSrcElts));
  2019. }
  2020. assert((Src0Elts | Src1Elts | UndefElts).isAllOnes() &&
  2021. "unknown shuffle elements");
  2022. assert(!Src0Elts.isZero() && !Src1Elts.isZero() &&
  2023. "2-source shuffle not found");
  2024. // Determine lo/hi span ranges.
  2025. // TODO: How should we handle undefs at the start of subvector insertions?
  2026. int Src0Lo = Src0Elts.countTrailingZeros();
  2027. int Src1Lo = Src1Elts.countTrailingZeros();
  2028. int Src0Hi = NumMaskElts - Src0Elts.countLeadingZeros();
  2029. int Src1Hi = NumMaskElts - Src1Elts.countLeadingZeros();
  2030. // If src0 is in place, see if the src1 elements is inplace within its own
  2031. // span.
  2032. if (Src0Identity) {
  2033. int NumSub1Elts = Src1Hi - Src1Lo;
  2034. ArrayRef<int> Sub1Mask = Mask.slice(Src1Lo, NumSub1Elts);
  2035. if (isIdentityMaskImpl(Sub1Mask, NumSrcElts)) {
  2036. NumSubElts = NumSub1Elts;
  2037. Index = Src1Lo;
  2038. return true;
  2039. }
  2040. }
  2041. // If src1 is in place, see if the src0 elements is inplace within its own
  2042. // span.
  2043. if (Src1Identity) {
  2044. int NumSub0Elts = Src0Hi - Src0Lo;
  2045. ArrayRef<int> Sub0Mask = Mask.slice(Src0Lo, NumSub0Elts);
  2046. if (isIdentityMaskImpl(Sub0Mask, NumSrcElts)) {
  2047. NumSubElts = NumSub0Elts;
  2048. Index = Src0Lo;
  2049. return true;
  2050. }
  2051. }
  2052. return false;
  2053. }
  2054. bool ShuffleVectorInst::isIdentityWithPadding() const {
  2055. if (isa<UndefValue>(Op<2>()))
  2056. return false;
  2057. // FIXME: Not currently possible to express a shuffle mask for a scalable
  2058. // vector for this case.
  2059. if (isa<ScalableVectorType>(getType()))
  2060. return false;
  2061. int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
  2062. int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
  2063. if (NumMaskElts <= NumOpElts)
  2064. return false;
  2065. // The first part of the mask must choose elements from exactly 1 source op.
  2066. ArrayRef<int> Mask = getShuffleMask();
  2067. if (!isIdentityMaskImpl(Mask, NumOpElts))
  2068. return false;
  2069. // All extending must be with undef elements.
  2070. for (int i = NumOpElts; i < NumMaskElts; ++i)
  2071. if (Mask[i] != -1)
  2072. return false;
  2073. return true;
  2074. }
  2075. bool ShuffleVectorInst::isIdentityWithExtract() const {
  2076. if (isa<UndefValue>(Op<2>()))
  2077. return false;
  2078. // FIXME: Not currently possible to express a shuffle mask for a scalable
  2079. // vector for this case.
  2080. if (isa<ScalableVectorType>(getType()))
  2081. return false;
  2082. int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
  2083. int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
  2084. if (NumMaskElts >= NumOpElts)
  2085. return false;
  2086. return isIdentityMaskImpl(getShuffleMask(), NumOpElts);
  2087. }
  2088. bool ShuffleVectorInst::isConcat() const {
  2089. // Vector concatenation is differentiated from identity with padding.
  2090. if (isa<UndefValue>(Op<0>()) || isa<UndefValue>(Op<1>()) ||
  2091. isa<UndefValue>(Op<2>()))
  2092. return false;
  2093. // FIXME: Not currently possible to express a shuffle mask for a scalable
  2094. // vector for this case.
  2095. if (isa<ScalableVectorType>(getType()))
  2096. return false;
  2097. int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
  2098. int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
  2099. if (NumMaskElts != NumOpElts * 2)
  2100. return false;
  2101. // Use the mask length rather than the operands' vector lengths here. We
  2102. // already know that the shuffle returns a vector twice as long as the inputs,
  2103. // and neither of the inputs are undef vectors. If the mask picks consecutive
  2104. // elements from both inputs, then this is a concatenation of the inputs.
  2105. return isIdentityMaskImpl(getShuffleMask(), NumMaskElts);
  2106. }
  2107. static bool isReplicationMaskWithParams(ArrayRef<int> Mask,
  2108. int ReplicationFactor, int VF) {
  2109. assert(Mask.size() == (unsigned)ReplicationFactor * VF &&
  2110. "Unexpected mask size.");
  2111. for (int CurrElt : seq(0, VF)) {
  2112. ArrayRef<int> CurrSubMask = Mask.take_front(ReplicationFactor);
  2113. assert(CurrSubMask.size() == (unsigned)ReplicationFactor &&
  2114. "Run out of mask?");
  2115. Mask = Mask.drop_front(ReplicationFactor);
  2116. if (!all_of(CurrSubMask, [CurrElt](int MaskElt) {
  2117. return MaskElt == UndefMaskElem || MaskElt == CurrElt;
  2118. }))
  2119. return false;
  2120. }
  2121. assert(Mask.empty() && "Did not consume the whole mask?");
  2122. return true;
  2123. }
  2124. bool ShuffleVectorInst::isReplicationMask(ArrayRef<int> Mask,
  2125. int &ReplicationFactor, int &VF) {
  2126. // undef-less case is trivial.
  2127. if (none_of(Mask, [](int MaskElt) { return MaskElt == UndefMaskElem; })) {
  2128. ReplicationFactor =
  2129. Mask.take_while([](int MaskElt) { return MaskElt == 0; }).size();
  2130. if (ReplicationFactor == 0 || Mask.size() % ReplicationFactor != 0)
  2131. return false;
  2132. VF = Mask.size() / ReplicationFactor;
  2133. return isReplicationMaskWithParams(Mask, ReplicationFactor, VF);
  2134. }
  2135. // However, if the mask contains undef's, we have to enumerate possible tuples
  2136. // and pick one. There are bounds on replication factor: [1, mask size]
  2137. // (where RF=1 is an identity shuffle, RF=mask size is a broadcast shuffle)
  2138. // Additionally, mask size is a replication factor multiplied by vector size,
  2139. // which further significantly reduces the search space.
  2140. // Before doing that, let's perform basic correctness checking first.
  2141. int Largest = -1;
  2142. for (int MaskElt : Mask) {
  2143. if (MaskElt == UndefMaskElem)
  2144. continue;
  2145. // Elements must be in non-decreasing order.
  2146. if (MaskElt < Largest)
  2147. return false;
  2148. Largest = std::max(Largest, MaskElt);
  2149. }
  2150. // Prefer larger replication factor if all else equal.
  2151. for (int PossibleReplicationFactor :
  2152. reverse(seq_inclusive<unsigned>(1, Mask.size()))) {
  2153. if (Mask.size() % PossibleReplicationFactor != 0)
  2154. continue;
  2155. int PossibleVF = Mask.size() / PossibleReplicationFactor;
  2156. if (!isReplicationMaskWithParams(Mask, PossibleReplicationFactor,
  2157. PossibleVF))
  2158. continue;
  2159. ReplicationFactor = PossibleReplicationFactor;
  2160. VF = PossibleVF;
  2161. return true;
  2162. }
  2163. return false;
  2164. }
  2165. bool ShuffleVectorInst::isReplicationMask(int &ReplicationFactor,
  2166. int &VF) const {
  2167. // Not possible to express a shuffle mask for a scalable vector for this
  2168. // case.
  2169. if (isa<ScalableVectorType>(getType()))
  2170. return false;
  2171. VF = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
  2172. if (ShuffleMask.size() % VF != 0)
  2173. return false;
  2174. ReplicationFactor = ShuffleMask.size() / VF;
  2175. return isReplicationMaskWithParams(ShuffleMask, ReplicationFactor, VF);
  2176. }
  2177. //===----------------------------------------------------------------------===//
  2178. // InsertValueInst Class
  2179. //===----------------------------------------------------------------------===//
  2180. void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
  2181. const Twine &Name) {
  2182. assert(getNumOperands() == 2 && "NumOperands not initialized?");
  2183. // There's no fundamental reason why we require at least one index
  2184. // (other than weirdness with &*IdxBegin being invalid; see
  2185. // getelementptr's init routine for example). But there's no
  2186. // present need to support it.
  2187. assert(!Idxs.empty() && "InsertValueInst must have at least one index");
  2188. assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
  2189. Val->getType() && "Inserted value must match indexed type!");
  2190. Op<0>() = Agg;
  2191. Op<1>() = Val;
  2192. Indices.append(Idxs.begin(), Idxs.end());
  2193. setName(Name);
  2194. }
  2195. InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
  2196. : Instruction(IVI.getType(), InsertValue,
  2197. OperandTraits<InsertValueInst>::op_begin(this), 2),
  2198. Indices(IVI.Indices) {
  2199. Op<0>() = IVI.getOperand(0);
  2200. Op<1>() = IVI.getOperand(1);
  2201. SubclassOptionalData = IVI.SubclassOptionalData;
  2202. }
  2203. //===----------------------------------------------------------------------===//
  2204. // ExtractValueInst Class
  2205. //===----------------------------------------------------------------------===//
  2206. void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
  2207. assert(getNumOperands() == 1 && "NumOperands not initialized?");
  2208. // There's no fundamental reason why we require at least one index.
  2209. // But there's no present need to support it.
  2210. assert(!Idxs.empty() && "ExtractValueInst must have at least one index");
  2211. Indices.append(Idxs.begin(), Idxs.end());
  2212. setName(Name);
  2213. }
  2214. ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
  2215. : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
  2216. Indices(EVI.Indices) {
  2217. SubclassOptionalData = EVI.SubclassOptionalData;
  2218. }
  2219. // getIndexedType - Returns the type of the element that would be extracted
  2220. // with an extractvalue instruction with the specified parameters.
  2221. //
  2222. // A null type is returned if the indices are invalid for the specified
  2223. // pointer type.
  2224. //
  2225. Type *ExtractValueInst::getIndexedType(Type *Agg,
  2226. ArrayRef<unsigned> Idxs) {
  2227. for (unsigned Index : Idxs) {
  2228. // We can't use CompositeType::indexValid(Index) here.
  2229. // indexValid() always returns true for arrays because getelementptr allows
  2230. // out-of-bounds indices. Since we don't allow those for extractvalue and
  2231. // insertvalue we need to check array indexing manually.
  2232. // Since the only other types we can index into are struct types it's just
  2233. // as easy to check those manually as well.
  2234. if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
  2235. if (Index >= AT->getNumElements())
  2236. return nullptr;
  2237. Agg = AT->getElementType();
  2238. } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
  2239. if (Index >= ST->getNumElements())
  2240. return nullptr;
  2241. Agg = ST->getElementType(Index);
  2242. } else {
  2243. // Not a valid type to index into.
  2244. return nullptr;
  2245. }
  2246. }
  2247. return const_cast<Type*>(Agg);
  2248. }
  2249. //===----------------------------------------------------------------------===//
  2250. // UnaryOperator Class
  2251. //===----------------------------------------------------------------------===//
  2252. UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
  2253. Type *Ty, const Twine &Name,
  2254. Instruction *InsertBefore)
  2255. : UnaryInstruction(Ty, iType, S, InsertBefore) {
  2256. Op<0>() = S;
  2257. setName(Name);
  2258. AssertOK();
  2259. }
  2260. UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
  2261. Type *Ty, const Twine &Name,
  2262. BasicBlock *InsertAtEnd)
  2263. : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
  2264. Op<0>() = S;
  2265. setName(Name);
  2266. AssertOK();
  2267. }
  2268. UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
  2269. const Twine &Name,
  2270. Instruction *InsertBefore) {
  2271. return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore);
  2272. }
  2273. UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
  2274. const Twine &Name,
  2275. BasicBlock *InsertAtEnd) {
  2276. UnaryOperator *Res = Create(Op, S, Name);
  2277. InsertAtEnd->getInstList().push_back(Res);
  2278. return Res;
  2279. }
  2280. void UnaryOperator::AssertOK() {
  2281. Value *LHS = getOperand(0);
  2282. (void)LHS; // Silence warnings.
  2283. #ifndef NDEBUG
  2284. switch (getOpcode()) {
  2285. case FNeg:
  2286. assert(getType() == LHS->getType() &&
  2287. "Unary operation should return same type as operand!");
  2288. assert(getType()->isFPOrFPVectorTy() &&
  2289. "Tried to create a floating-point operation on a "
  2290. "non-floating-point type!");
  2291. break;
  2292. default: llvm_unreachable("Invalid opcode provided");
  2293. }
  2294. #endif
  2295. }
  2296. //===----------------------------------------------------------------------===//
  2297. // BinaryOperator Class
  2298. //===----------------------------------------------------------------------===//
  2299. BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
  2300. Type *Ty, const Twine &Name,
  2301. Instruction *InsertBefore)
  2302. : Instruction(Ty, iType,
  2303. OperandTraits<BinaryOperator>::op_begin(this),
  2304. OperandTraits<BinaryOperator>::operands(this),
  2305. InsertBefore) {
  2306. Op<0>() = S1;
  2307. Op<1>() = S2;
  2308. setName(Name);
  2309. AssertOK();
  2310. }
  2311. BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
  2312. Type *Ty, const Twine &Name,
  2313. BasicBlock *InsertAtEnd)
  2314. : Instruction(Ty, iType,
  2315. OperandTraits<BinaryOperator>::op_begin(this),
  2316. OperandTraits<BinaryOperator>::operands(this),
  2317. InsertAtEnd) {
  2318. Op<0>() = S1;
  2319. Op<1>() = S2;
  2320. setName(Name);
  2321. AssertOK();
  2322. }
  2323. void BinaryOperator::AssertOK() {
  2324. Value *LHS = getOperand(0), *RHS = getOperand(1);
  2325. (void)LHS; (void)RHS; // Silence warnings.
  2326. assert(LHS->getType() == RHS->getType() &&
  2327. "Binary operator operand types must match!");
  2328. #ifndef NDEBUG
  2329. switch (getOpcode()) {
  2330. case Add: case Sub:
  2331. case Mul:
  2332. assert(getType() == LHS->getType() &&
  2333. "Arithmetic operation should return same type as operands!");
  2334. assert(getType()->isIntOrIntVectorTy() &&
  2335. "Tried to create an integer operation on a non-integer type!");
  2336. break;
  2337. case FAdd: case FSub:
  2338. case FMul:
  2339. assert(getType() == LHS->getType() &&
  2340. "Arithmetic operation should return same type as operands!");
  2341. assert(getType()->isFPOrFPVectorTy() &&
  2342. "Tried to create a floating-point operation on a "
  2343. "non-floating-point type!");
  2344. break;
  2345. case UDiv:
  2346. case SDiv:
  2347. assert(getType() == LHS->getType() &&
  2348. "Arithmetic operation should return same type as operands!");
  2349. assert(getType()->isIntOrIntVectorTy() &&
  2350. "Incorrect operand type (not integer) for S/UDIV");
  2351. break;
  2352. case FDiv:
  2353. assert(getType() == LHS->getType() &&
  2354. "Arithmetic operation should return same type as operands!");
  2355. assert(getType()->isFPOrFPVectorTy() &&
  2356. "Incorrect operand type (not floating point) for FDIV");
  2357. break;
  2358. case URem:
  2359. case SRem:
  2360. assert(getType() == LHS->getType() &&
  2361. "Arithmetic operation should return same type as operands!");
  2362. assert(getType()->isIntOrIntVectorTy() &&
  2363. "Incorrect operand type (not integer) for S/UREM");
  2364. break;
  2365. case FRem:
  2366. assert(getType() == LHS->getType() &&
  2367. "Arithmetic operation should return same type as operands!");
  2368. assert(getType()->isFPOrFPVectorTy() &&
  2369. "Incorrect operand type (not floating point) for FREM");
  2370. break;
  2371. case Shl:
  2372. case LShr:
  2373. case AShr:
  2374. assert(getType() == LHS->getType() &&
  2375. "Shift operation should return same type as operands!");
  2376. assert(getType()->isIntOrIntVectorTy() &&
  2377. "Tried to create a shift operation on a non-integral type!");
  2378. break;
  2379. case And: case Or:
  2380. case Xor:
  2381. assert(getType() == LHS->getType() &&
  2382. "Logical operation should return same type as operands!");
  2383. assert(getType()->isIntOrIntVectorTy() &&
  2384. "Tried to create a logical operation on a non-integral type!");
  2385. break;
  2386. default: llvm_unreachable("Invalid opcode provided");
  2387. }
  2388. #endif
  2389. }
  2390. BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
  2391. const Twine &Name,
  2392. Instruction *InsertBefore) {
  2393. assert(S1->getType() == S2->getType() &&
  2394. "Cannot create binary operator with two operands of differing type!");
  2395. return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
  2396. }
  2397. BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
  2398. const Twine &Name,
  2399. BasicBlock *InsertAtEnd) {
  2400. BinaryOperator *Res = Create(Op, S1, S2, Name);
  2401. InsertAtEnd->getInstList().push_back(Res);
  2402. return Res;
  2403. }
  2404. BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
  2405. Instruction *InsertBefore) {
  2406. Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
  2407. return new BinaryOperator(Instruction::Sub,
  2408. zero, Op,
  2409. Op->getType(), Name, InsertBefore);
  2410. }
  2411. BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
  2412. BasicBlock *InsertAtEnd) {
  2413. Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
  2414. return new BinaryOperator(Instruction::Sub,
  2415. zero, Op,
  2416. Op->getType(), Name, InsertAtEnd);
  2417. }
  2418. BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
  2419. Instruction *InsertBefore) {
  2420. Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
  2421. return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
  2422. }
  2423. BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
  2424. BasicBlock *InsertAtEnd) {
  2425. Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
  2426. return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
  2427. }
  2428. BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
  2429. Instruction *InsertBefore) {
  2430. Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
  2431. return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
  2432. }
  2433. BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
  2434. BasicBlock *InsertAtEnd) {
  2435. Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
  2436. return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
  2437. }
  2438. BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
  2439. Instruction *InsertBefore) {
  2440. Constant *C = Constant::getAllOnesValue(Op->getType());
  2441. return new BinaryOperator(Instruction::Xor, Op, C,
  2442. Op->getType(), Name, InsertBefore);
  2443. }
  2444. BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
  2445. BasicBlock *InsertAtEnd) {
  2446. Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
  2447. return new BinaryOperator(Instruction::Xor, Op, AllOnes,
  2448. Op->getType(), Name, InsertAtEnd);
  2449. }
  2450. // Exchange the two operands to this instruction. This instruction is safe to
  2451. // use on any binary instruction and does not modify the semantics of the
  2452. // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode
  2453. // is changed.
  2454. bool BinaryOperator::swapOperands() {
  2455. if (!isCommutative())
  2456. return true; // Can't commute operands
  2457. Op<0>().swap(Op<1>());
  2458. return false;
  2459. }
  2460. //===----------------------------------------------------------------------===//
  2461. // FPMathOperator Class
  2462. //===----------------------------------------------------------------------===//
  2463. float FPMathOperator::getFPAccuracy() const {
  2464. const MDNode *MD =
  2465. cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
  2466. if (!MD)
  2467. return 0.0;
  2468. ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
  2469. return Accuracy->getValueAPF().convertToFloat();
  2470. }
  2471. //===----------------------------------------------------------------------===//
  2472. // CastInst Class
  2473. //===----------------------------------------------------------------------===//
  2474. // Just determine if this cast only deals with integral->integral conversion.
  2475. bool CastInst::isIntegerCast() const {
  2476. switch (getOpcode()) {
  2477. default: return false;
  2478. case Instruction::ZExt:
  2479. case Instruction::SExt:
  2480. case Instruction::Trunc:
  2481. return true;
  2482. case Instruction::BitCast:
  2483. return getOperand(0)->getType()->isIntegerTy() &&
  2484. getType()->isIntegerTy();
  2485. }
  2486. }
  2487. bool CastInst::isLosslessCast() const {
  2488. // Only BitCast can be lossless, exit fast if we're not BitCast
  2489. if (getOpcode() != Instruction::BitCast)
  2490. return false;
  2491. // Identity cast is always lossless
  2492. Type *SrcTy = getOperand(0)->getType();
  2493. Type *DstTy = getType();
  2494. if (SrcTy == DstTy)
  2495. return true;
  2496. // Pointer to pointer is always lossless.
  2497. if (SrcTy->isPointerTy())
  2498. return DstTy->isPointerTy();
  2499. return false; // Other types have no identity values
  2500. }
  2501. /// This function determines if the CastInst does not require any bits to be
  2502. /// changed in order to effect the cast. Essentially, it identifies cases where
  2503. /// no code gen is necessary for the cast, hence the name no-op cast. For
  2504. /// example, the following are all no-op casts:
  2505. /// # bitcast i32* %x to i8*
  2506. /// # bitcast <2 x i32> %x to <4 x i16>
  2507. /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
  2508. /// Determine if the described cast is a no-op.
  2509. bool CastInst::isNoopCast(Instruction::CastOps Opcode,
  2510. Type *SrcTy,
  2511. Type *DestTy,
  2512. const DataLayout &DL) {
  2513. assert(castIsValid(Opcode, SrcTy, DestTy) && "method precondition");
  2514. switch (Opcode) {
  2515. default: llvm_unreachable("Invalid CastOp");
  2516. case Instruction::Trunc:
  2517. case Instruction::ZExt:
  2518. case Instruction::SExt:
  2519. case Instruction::FPTrunc:
  2520. case Instruction::FPExt:
  2521. case Instruction::UIToFP:
  2522. case Instruction::SIToFP:
  2523. case Instruction::FPToUI:
  2524. case Instruction::FPToSI:
  2525. case Instruction::AddrSpaceCast:
  2526. // TODO: Target informations may give a more accurate answer here.
  2527. return false;
  2528. case Instruction::BitCast:
  2529. return true; // BitCast never modifies bits.
  2530. case Instruction::PtrToInt:
  2531. return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() ==
  2532. DestTy->getScalarSizeInBits();
  2533. case Instruction::IntToPtr:
  2534. return DL.getIntPtrType(DestTy)->getScalarSizeInBits() ==
  2535. SrcTy->getScalarSizeInBits();
  2536. }
  2537. }
  2538. bool CastInst::isNoopCast(const DataLayout &DL) const {
  2539. return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL);
  2540. }
  2541. /// This function determines if a pair of casts can be eliminated and what
  2542. /// opcode should be used in the elimination. This assumes that there are two
  2543. /// instructions like this:
  2544. /// * %F = firstOpcode SrcTy %x to MidTy
  2545. /// * %S = secondOpcode MidTy %F to DstTy
  2546. /// The function returns a resultOpcode so these two casts can be replaced with:
  2547. /// * %Replacement = resultOpcode %SrcTy %x to DstTy
  2548. /// If no such cast is permitted, the function returns 0.
  2549. unsigned CastInst::isEliminableCastPair(
  2550. Instruction::CastOps firstOp, Instruction::CastOps secondOp,
  2551. Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
  2552. Type *DstIntPtrTy) {
  2553. // Define the 144 possibilities for these two cast instructions. The values
  2554. // in this matrix determine what to do in a given situation and select the
  2555. // case in the switch below. The rows correspond to firstOp, the columns
  2556. // correspond to secondOp. In looking at the table below, keep in mind
  2557. // the following cast properties:
  2558. //
  2559. // Size Compare Source Destination
  2560. // Operator Src ? Size Type Sign Type Sign
  2561. // -------- ------------ ------------------- ---------------------
  2562. // TRUNC > Integer Any Integral Any
  2563. // ZEXT < Integral Unsigned Integer Any
  2564. // SEXT < Integral Signed Integer Any
  2565. // FPTOUI n/a FloatPt n/a Integral Unsigned
  2566. // FPTOSI n/a FloatPt n/a Integral Signed
  2567. // UITOFP n/a Integral Unsigned FloatPt n/a
  2568. // SITOFP n/a Integral Signed FloatPt n/a
  2569. // FPTRUNC > FloatPt n/a FloatPt n/a
  2570. // FPEXT < FloatPt n/a FloatPt n/a
  2571. // PTRTOINT n/a Pointer n/a Integral Unsigned
  2572. // INTTOPTR n/a Integral Unsigned Pointer n/a
  2573. // BITCAST = FirstClass n/a FirstClass n/a
  2574. // ADDRSPCST n/a Pointer n/a Pointer n/a
  2575. //
  2576. // NOTE: some transforms are safe, but we consider them to be non-profitable.
  2577. // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
  2578. // into "fptoui double to i64", but this loses information about the range
  2579. // of the produced value (we no longer know the top-part is all zeros).
  2580. // Further this conversion is often much more expensive for typical hardware,
  2581. // and causes issues when building libgcc. We disallow fptosi+sext for the
  2582. // same reason.
  2583. const unsigned numCastOps =
  2584. Instruction::CastOpsEnd - Instruction::CastOpsBegin;
  2585. static const uint8_t CastResults[numCastOps][numCastOps] = {
  2586. // T F F U S F F P I B A -+
  2587. // R Z S P P I I T P 2 N T S |
  2588. // U E E 2 2 2 2 R E I T C C +- secondOp
  2589. // N X X U S F F N X N 2 V V |
  2590. // C T T I I P P C T T P T T -+
  2591. { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
  2592. { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
  2593. { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
  2594. { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
  2595. { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
  2596. { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
  2597. { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
  2598. { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
  2599. { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt |
  2600. { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
  2601. { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
  2602. { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
  2603. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
  2604. };
  2605. // TODO: This logic could be encoded into the table above and handled in the
  2606. // switch below.
  2607. // If either of the casts are a bitcast from scalar to vector, disallow the
  2608. // merging. However, any pair of bitcasts are allowed.
  2609. bool IsFirstBitcast = (firstOp == Instruction::BitCast);
  2610. bool IsSecondBitcast = (secondOp == Instruction::BitCast);
  2611. bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast;
  2612. // Check if any of the casts convert scalars <-> vectors.
  2613. if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
  2614. (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
  2615. if (!AreBothBitcasts)
  2616. return 0;
  2617. int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
  2618. [secondOp-Instruction::CastOpsBegin];
  2619. switch (ElimCase) {
  2620. case 0:
  2621. // Categorically disallowed.
  2622. return 0;
  2623. case 1:
  2624. // Allowed, use first cast's opcode.
  2625. return firstOp;
  2626. case 2:
  2627. // Allowed, use second cast's opcode.
  2628. return secondOp;
  2629. case 3:
  2630. // No-op cast in second op implies firstOp as long as the DestTy
  2631. // is integer and we are not converting between a vector and a
  2632. // non-vector type.
  2633. if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
  2634. return firstOp;
  2635. return 0;
  2636. case 4:
  2637. // No-op cast in second op implies firstOp as long as the DestTy
  2638. // is floating point.
  2639. if (DstTy->isFloatingPointTy())
  2640. return firstOp;
  2641. return 0;
  2642. case 5:
  2643. // No-op cast in first op implies secondOp as long as the SrcTy
  2644. // is an integer.
  2645. if (SrcTy->isIntegerTy())
  2646. return secondOp;
  2647. return 0;
  2648. case 6:
  2649. // No-op cast in first op implies secondOp as long as the SrcTy
  2650. // is a floating point.
  2651. if (SrcTy->isFloatingPointTy())
  2652. return secondOp;
  2653. return 0;
  2654. case 7: {
  2655. // Disable inttoptr/ptrtoint optimization if enabled.
  2656. if (DisableI2pP2iOpt)
  2657. return 0;
  2658. // Cannot simplify if address spaces are different!
  2659. if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
  2660. return 0;
  2661. unsigned MidSize = MidTy->getScalarSizeInBits();
  2662. // We can still fold this without knowing the actual sizes as long we
  2663. // know that the intermediate pointer is the largest possible
  2664. // pointer size.
  2665. // FIXME: Is this always true?
  2666. if (MidSize == 64)
  2667. return Instruction::BitCast;
  2668. // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
  2669. if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
  2670. return 0;
  2671. unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
  2672. if (MidSize >= PtrSize)
  2673. return Instruction::BitCast;
  2674. return 0;
  2675. }
  2676. case 8: {
  2677. // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
  2678. // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
  2679. // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
  2680. unsigned SrcSize = SrcTy->getScalarSizeInBits();
  2681. unsigned DstSize = DstTy->getScalarSizeInBits();
  2682. if (SrcSize == DstSize)
  2683. return Instruction::BitCast;
  2684. else if (SrcSize < DstSize)
  2685. return firstOp;
  2686. return secondOp;
  2687. }
  2688. case 9:
  2689. // zext, sext -> zext, because sext can't sign extend after zext
  2690. return Instruction::ZExt;
  2691. case 11: {
  2692. // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
  2693. if (!MidIntPtrTy)
  2694. return 0;
  2695. unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
  2696. unsigned SrcSize = SrcTy->getScalarSizeInBits();
  2697. unsigned DstSize = DstTy->getScalarSizeInBits();
  2698. if (SrcSize <= PtrSize && SrcSize == DstSize)
  2699. return Instruction::BitCast;
  2700. return 0;
  2701. }
  2702. case 12:
  2703. // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
  2704. // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
  2705. if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
  2706. return Instruction::AddrSpaceCast;
  2707. return Instruction::BitCast;
  2708. case 13:
  2709. // FIXME: this state can be merged with (1), but the following assert
  2710. // is useful to check the correcteness of the sequence due to semantic
  2711. // change of bitcast.
  2712. assert(
  2713. SrcTy->isPtrOrPtrVectorTy() &&
  2714. MidTy->isPtrOrPtrVectorTy() &&
  2715. DstTy->isPtrOrPtrVectorTy() &&
  2716. SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
  2717. MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
  2718. "Illegal addrspacecast, bitcast sequence!");
  2719. // Allowed, use first cast's opcode
  2720. return firstOp;
  2721. case 14: {
  2722. // bitcast, addrspacecast -> addrspacecast if the element type of
  2723. // bitcast's source is the same as that of addrspacecast's destination.
  2724. PointerType *SrcPtrTy = cast<PointerType>(SrcTy->getScalarType());
  2725. PointerType *DstPtrTy = cast<PointerType>(DstTy->getScalarType());
  2726. if (SrcPtrTy->hasSameElementTypeAs(DstPtrTy))
  2727. return Instruction::AddrSpaceCast;
  2728. return 0;
  2729. }
  2730. case 15:
  2731. // FIXME: this state can be merged with (1), but the following assert
  2732. // is useful to check the correcteness of the sequence due to semantic
  2733. // change of bitcast.
  2734. assert(
  2735. SrcTy->isIntOrIntVectorTy() &&
  2736. MidTy->isPtrOrPtrVectorTy() &&
  2737. DstTy->isPtrOrPtrVectorTy() &&
  2738. MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
  2739. "Illegal inttoptr, bitcast sequence!");
  2740. // Allowed, use first cast's opcode
  2741. return firstOp;
  2742. case 16:
  2743. // FIXME: this state can be merged with (2), but the following assert
  2744. // is useful to check the correcteness of the sequence due to semantic
  2745. // change of bitcast.
  2746. assert(
  2747. SrcTy->isPtrOrPtrVectorTy() &&
  2748. MidTy->isPtrOrPtrVectorTy() &&
  2749. DstTy->isIntOrIntVectorTy() &&
  2750. SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
  2751. "Illegal bitcast, ptrtoint sequence!");
  2752. // Allowed, use second cast's opcode
  2753. return secondOp;
  2754. case 17:
  2755. // (sitofp (zext x)) -> (uitofp x)
  2756. return Instruction::UIToFP;
  2757. case 99:
  2758. // Cast combination can't happen (error in input). This is for all cases
  2759. // where the MidTy is not the same for the two cast instructions.
  2760. llvm_unreachable("Invalid Cast Combination");
  2761. default:
  2762. llvm_unreachable("Error in CastResults table!!!");
  2763. }
  2764. }
  2765. CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
  2766. const Twine &Name, Instruction *InsertBefore) {
  2767. assert(castIsValid(op, S, Ty) && "Invalid cast!");
  2768. // Construct and return the appropriate CastInst subclass
  2769. switch (op) {
  2770. case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
  2771. case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
  2772. case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
  2773. case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
  2774. case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
  2775. case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
  2776. case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
  2777. case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
  2778. case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
  2779. case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
  2780. case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
  2781. case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
  2782. case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
  2783. default: llvm_unreachable("Invalid opcode provided");
  2784. }
  2785. }
  2786. CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
  2787. const Twine &Name, BasicBlock *InsertAtEnd) {
  2788. assert(castIsValid(op, S, Ty) && "Invalid cast!");
  2789. // Construct and return the appropriate CastInst subclass
  2790. switch (op) {
  2791. case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
  2792. case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
  2793. case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
  2794. case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
  2795. case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
  2796. case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
  2797. case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
  2798. case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
  2799. case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
  2800. case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
  2801. case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
  2802. case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
  2803. case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
  2804. default: llvm_unreachable("Invalid opcode provided");
  2805. }
  2806. }
  2807. CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
  2808. const Twine &Name,
  2809. Instruction *InsertBefore) {
  2810. if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  2811. return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
  2812. return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
  2813. }
  2814. CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
  2815. const Twine &Name,
  2816. BasicBlock *InsertAtEnd) {
  2817. if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  2818. return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
  2819. return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
  2820. }
  2821. CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
  2822. const Twine &Name,
  2823. Instruction *InsertBefore) {
  2824. if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  2825. return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
  2826. return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
  2827. }
  2828. CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
  2829. const Twine &Name,
  2830. BasicBlock *InsertAtEnd) {
  2831. if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  2832. return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
  2833. return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
  2834. }
  2835. CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
  2836. const Twine &Name,
  2837. Instruction *InsertBefore) {
  2838. if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  2839. return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
  2840. return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
  2841. }
  2842. CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
  2843. const Twine &Name,
  2844. BasicBlock *InsertAtEnd) {
  2845. if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  2846. return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
  2847. return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
  2848. }
  2849. CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
  2850. const Twine &Name,
  2851. BasicBlock *InsertAtEnd) {
  2852. assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
  2853. assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
  2854. "Invalid cast");
  2855. assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
  2856. assert((!Ty->isVectorTy() ||
  2857. cast<VectorType>(Ty)->getElementCount() ==
  2858. cast<VectorType>(S->getType())->getElementCount()) &&
  2859. "Invalid cast");
  2860. if (Ty->isIntOrIntVectorTy())
  2861. return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
  2862. return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
  2863. }
  2864. /// Create a BitCast or a PtrToInt cast instruction
  2865. CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
  2866. const Twine &Name,
  2867. Instruction *InsertBefore) {
  2868. assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
  2869. assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
  2870. "Invalid cast");
  2871. assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
  2872. assert((!Ty->isVectorTy() ||
  2873. cast<VectorType>(Ty)->getElementCount() ==
  2874. cast<VectorType>(S->getType())->getElementCount()) &&
  2875. "Invalid cast");
  2876. if (Ty->isIntOrIntVectorTy())
  2877. return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
  2878. return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
  2879. }
  2880. CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
  2881. Value *S, Type *Ty,
  2882. const Twine &Name,
  2883. BasicBlock *InsertAtEnd) {
  2884. assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
  2885. assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
  2886. if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
  2887. return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
  2888. return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
  2889. }
  2890. CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
  2891. Value *S, Type *Ty,
  2892. const Twine &Name,
  2893. Instruction *InsertBefore) {
  2894. assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
  2895. assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
  2896. if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
  2897. return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
  2898. return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
  2899. }
  2900. CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
  2901. const Twine &Name,
  2902. Instruction *InsertBefore) {
  2903. if (S->getType()->isPointerTy() && Ty->isIntegerTy())
  2904. return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
  2905. if (S->getType()->isIntegerTy() && Ty->isPointerTy())
  2906. return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
  2907. return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
  2908. }
  2909. CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
  2910. bool isSigned, const Twine &Name,
  2911. Instruction *InsertBefore) {
  2912. assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
  2913. "Invalid integer cast");
  2914. unsigned SrcBits = C->getType()->getScalarSizeInBits();
  2915. unsigned DstBits = Ty->getScalarSizeInBits();
  2916. Instruction::CastOps opcode =
  2917. (SrcBits == DstBits ? Instruction::BitCast :
  2918. (SrcBits > DstBits ? Instruction::Trunc :
  2919. (isSigned ? Instruction::SExt : Instruction::ZExt)));
  2920. return Create(opcode, C, Ty, Name, InsertBefore);
  2921. }
  2922. CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
  2923. bool isSigned, const Twine &Name,
  2924. BasicBlock *InsertAtEnd) {
  2925. assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
  2926. "Invalid cast");
  2927. unsigned SrcBits = C->getType()->getScalarSizeInBits();
  2928. unsigned DstBits = Ty->getScalarSizeInBits();
  2929. Instruction::CastOps opcode =
  2930. (SrcBits == DstBits ? Instruction::BitCast :
  2931. (SrcBits > DstBits ? Instruction::Trunc :
  2932. (isSigned ? Instruction::SExt : Instruction::ZExt)));
  2933. return Create(opcode, C, Ty, Name, InsertAtEnd);
  2934. }
  2935. CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
  2936. const Twine &Name,
  2937. Instruction *InsertBefore) {
  2938. assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
  2939. "Invalid cast");
  2940. unsigned SrcBits = C->getType()->getScalarSizeInBits();
  2941. unsigned DstBits = Ty->getScalarSizeInBits();
  2942. Instruction::CastOps opcode =
  2943. (SrcBits == DstBits ? Instruction::BitCast :
  2944. (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
  2945. return Create(opcode, C, Ty, Name, InsertBefore);
  2946. }
  2947. CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
  2948. const Twine &Name,
  2949. BasicBlock *InsertAtEnd) {
  2950. assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
  2951. "Invalid cast");
  2952. unsigned SrcBits = C->getType()->getScalarSizeInBits();
  2953. unsigned DstBits = Ty->getScalarSizeInBits();
  2954. Instruction::CastOps opcode =
  2955. (SrcBits == DstBits ? Instruction::BitCast :
  2956. (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
  2957. return Create(opcode, C, Ty, Name, InsertAtEnd);
  2958. }
  2959. bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
  2960. if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
  2961. return false;
  2962. if (SrcTy == DestTy)
  2963. return true;
  2964. if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
  2965. if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
  2966. if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
  2967. // An element by element cast. Valid if casting the elements is valid.
  2968. SrcTy = SrcVecTy->getElementType();
  2969. DestTy = DestVecTy->getElementType();
  2970. }
  2971. }
  2972. }
  2973. if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
  2974. if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
  2975. return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
  2976. }
  2977. }
  2978. TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
  2979. TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
  2980. // Could still have vectors of pointers if the number of elements doesn't
  2981. // match
  2982. if (SrcBits.getKnownMinSize() == 0 || DestBits.getKnownMinSize() == 0)
  2983. return false;
  2984. if (SrcBits != DestBits)
  2985. return false;
  2986. if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
  2987. return false;
  2988. return true;
  2989. }
  2990. bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
  2991. const DataLayout &DL) {
  2992. // ptrtoint and inttoptr are not allowed on non-integral pointers
  2993. if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
  2994. if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
  2995. return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
  2996. !DL.isNonIntegralPointerType(PtrTy));
  2997. if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
  2998. if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
  2999. return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
  3000. !DL.isNonIntegralPointerType(PtrTy));
  3001. return isBitCastable(SrcTy, DestTy);
  3002. }
  3003. // Provide a way to get a "cast" where the cast opcode is inferred from the
  3004. // types and size of the operand. This, basically, is a parallel of the
  3005. // logic in the castIsValid function below. This axiom should hold:
  3006. // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
  3007. // should not assert in castIsValid. In other words, this produces a "correct"
  3008. // casting opcode for the arguments passed to it.
  3009. Instruction::CastOps
  3010. CastInst::getCastOpcode(
  3011. const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
  3012. Type *SrcTy = Src->getType();
  3013. assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
  3014. "Only first class types are castable!");
  3015. if (SrcTy == DestTy)
  3016. return BitCast;
  3017. // FIXME: Check address space sizes here
  3018. if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
  3019. if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
  3020. if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
  3021. // An element by element cast. Find the appropriate opcode based on the
  3022. // element types.
  3023. SrcTy = SrcVecTy->getElementType();
  3024. DestTy = DestVecTy->getElementType();
  3025. }
  3026. // Get the bit sizes, we'll need these
  3027. unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
  3028. unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
  3029. // Run through the possibilities ...
  3030. if (DestTy->isIntegerTy()) { // Casting to integral
  3031. if (SrcTy->isIntegerTy()) { // Casting from integral
  3032. if (DestBits < SrcBits)
  3033. return Trunc; // int -> smaller int
  3034. else if (DestBits > SrcBits) { // its an extension
  3035. if (SrcIsSigned)
  3036. return SExt; // signed -> SEXT
  3037. else
  3038. return ZExt; // unsigned -> ZEXT
  3039. } else {
  3040. return BitCast; // Same size, No-op cast
  3041. }
  3042. } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
  3043. if (DestIsSigned)
  3044. return FPToSI; // FP -> sint
  3045. else
  3046. return FPToUI; // FP -> uint
  3047. } else if (SrcTy->isVectorTy()) {
  3048. assert(DestBits == SrcBits &&
  3049. "Casting vector to integer of different width");
  3050. return BitCast; // Same size, no-op cast
  3051. } else {
  3052. assert(SrcTy->isPointerTy() &&
  3053. "Casting from a value that is not first-class type");
  3054. return PtrToInt; // ptr -> int
  3055. }
  3056. } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
  3057. if (SrcTy->isIntegerTy()) { // Casting from integral
  3058. if (SrcIsSigned)
  3059. return SIToFP; // sint -> FP
  3060. else
  3061. return UIToFP; // uint -> FP
  3062. } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
  3063. if (DestBits < SrcBits) {
  3064. return FPTrunc; // FP -> smaller FP
  3065. } else if (DestBits > SrcBits) {
  3066. return FPExt; // FP -> larger FP
  3067. } else {
  3068. return BitCast; // same size, no-op cast
  3069. }
  3070. } else if (SrcTy->isVectorTy()) {
  3071. assert(DestBits == SrcBits &&
  3072. "Casting vector to floating point of different width");
  3073. return BitCast; // same size, no-op cast
  3074. }
  3075. llvm_unreachable("Casting pointer or non-first class to float");
  3076. } else if (DestTy->isVectorTy()) {
  3077. assert(DestBits == SrcBits &&
  3078. "Illegal cast to vector (wrong type or size)");
  3079. return BitCast;
  3080. } else if (DestTy->isPointerTy()) {
  3081. if (SrcTy->isPointerTy()) {
  3082. if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
  3083. return AddrSpaceCast;
  3084. return BitCast; // ptr -> ptr
  3085. } else if (SrcTy->isIntegerTy()) {
  3086. return IntToPtr; // int -> ptr
  3087. }
  3088. llvm_unreachable("Casting pointer to other than pointer or int");
  3089. } else if (DestTy->isX86_MMXTy()) {
  3090. if (SrcTy->isVectorTy()) {
  3091. assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
  3092. return BitCast; // 64-bit vector to MMX
  3093. }
  3094. llvm_unreachable("Illegal cast to X86_MMX");
  3095. }
  3096. llvm_unreachable("Casting to type that is not first-class");
  3097. }
  3098. //===----------------------------------------------------------------------===//
  3099. // CastInst SubClass Constructors
  3100. //===----------------------------------------------------------------------===//
  3101. /// Check that the construction parameters for a CastInst are correct. This
  3102. /// could be broken out into the separate constructors but it is useful to have
  3103. /// it in one place and to eliminate the redundant code for getting the sizes
  3104. /// of the types involved.
  3105. bool
  3106. CastInst::castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy) {
  3107. if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
  3108. SrcTy->isAggregateType() || DstTy->isAggregateType())
  3109. return false;
  3110. // Get the size of the types in bits, and whether we are dealing
  3111. // with vector types, we'll need this later.
  3112. bool SrcIsVec = isa<VectorType>(SrcTy);
  3113. bool DstIsVec = isa<VectorType>(DstTy);
  3114. unsigned SrcScalarBitSize = SrcTy->getScalarSizeInBits();
  3115. unsigned DstScalarBitSize = DstTy->getScalarSizeInBits();
  3116. // If these are vector types, get the lengths of the vectors (using zero for
  3117. // scalar types means that checking that vector lengths match also checks that
  3118. // scalars are not being converted to vectors or vectors to scalars).
  3119. ElementCount SrcEC = SrcIsVec ? cast<VectorType>(SrcTy)->getElementCount()
  3120. : ElementCount::getFixed(0);
  3121. ElementCount DstEC = DstIsVec ? cast<VectorType>(DstTy)->getElementCount()
  3122. : ElementCount::getFixed(0);
  3123. // Switch on the opcode provided
  3124. switch (op) {
  3125. default: return false; // This is an input error
  3126. case Instruction::Trunc:
  3127. return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
  3128. SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
  3129. case Instruction::ZExt:
  3130. return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
  3131. SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
  3132. case Instruction::SExt:
  3133. return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
  3134. SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
  3135. case Instruction::FPTrunc:
  3136. return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
  3137. SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
  3138. case Instruction::FPExt:
  3139. return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
  3140. SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
  3141. case Instruction::UIToFP:
  3142. case Instruction::SIToFP:
  3143. return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
  3144. SrcEC == DstEC;
  3145. case Instruction::FPToUI:
  3146. case Instruction::FPToSI:
  3147. return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
  3148. SrcEC == DstEC;
  3149. case Instruction::PtrToInt:
  3150. if (SrcEC != DstEC)
  3151. return false;
  3152. return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy();
  3153. case Instruction::IntToPtr:
  3154. if (SrcEC != DstEC)
  3155. return false;
  3156. return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy();
  3157. case Instruction::BitCast: {
  3158. PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
  3159. PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
  3160. // BitCast implies a no-op cast of type only. No bits change.
  3161. // However, you can't cast pointers to anything but pointers.
  3162. if (!SrcPtrTy != !DstPtrTy)
  3163. return false;
  3164. // For non-pointer cases, the cast is okay if the source and destination bit
  3165. // widths are identical.
  3166. if (!SrcPtrTy)
  3167. return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
  3168. // If both are pointers then the address spaces must match.
  3169. if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
  3170. return false;
  3171. // A vector of pointers must have the same number of elements.
  3172. if (SrcIsVec && DstIsVec)
  3173. return SrcEC == DstEC;
  3174. if (SrcIsVec)
  3175. return SrcEC == ElementCount::getFixed(1);
  3176. if (DstIsVec)
  3177. return DstEC == ElementCount::getFixed(1);
  3178. return true;
  3179. }
  3180. case Instruction::AddrSpaceCast: {
  3181. PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
  3182. if (!SrcPtrTy)
  3183. return false;
  3184. PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
  3185. if (!DstPtrTy)
  3186. return false;
  3187. if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
  3188. return false;
  3189. return SrcEC == DstEC;
  3190. }
  3191. }
  3192. }
  3193. TruncInst::TruncInst(
  3194. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  3195. ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
  3196. assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
  3197. }
  3198. TruncInst::TruncInst(
  3199. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  3200. ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
  3201. assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
  3202. }
  3203. ZExtInst::ZExtInst(
  3204. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  3205. ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
  3206. assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
  3207. }
  3208. ZExtInst::ZExtInst(
  3209. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  3210. ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
  3211. assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
  3212. }
  3213. SExtInst::SExtInst(
  3214. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  3215. ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
  3216. assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
  3217. }
  3218. SExtInst::SExtInst(
  3219. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  3220. ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
  3221. assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
  3222. }
  3223. FPTruncInst::FPTruncInst(
  3224. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  3225. ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
  3226. assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
  3227. }
  3228. FPTruncInst::FPTruncInst(
  3229. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  3230. ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
  3231. assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
  3232. }
  3233. FPExtInst::FPExtInst(
  3234. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  3235. ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
  3236. assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
  3237. }
  3238. FPExtInst::FPExtInst(
  3239. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  3240. ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
  3241. assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
  3242. }
  3243. UIToFPInst::UIToFPInst(
  3244. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  3245. ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
  3246. assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
  3247. }
  3248. UIToFPInst::UIToFPInst(
  3249. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  3250. ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
  3251. assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
  3252. }
  3253. SIToFPInst::SIToFPInst(
  3254. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  3255. ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
  3256. assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
  3257. }
  3258. SIToFPInst::SIToFPInst(
  3259. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  3260. ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
  3261. assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
  3262. }
  3263. FPToUIInst::FPToUIInst(
  3264. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  3265. ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
  3266. assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
  3267. }
  3268. FPToUIInst::FPToUIInst(
  3269. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  3270. ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
  3271. assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
  3272. }
  3273. FPToSIInst::FPToSIInst(
  3274. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  3275. ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
  3276. assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
  3277. }
  3278. FPToSIInst::FPToSIInst(
  3279. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  3280. ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
  3281. assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
  3282. }
  3283. PtrToIntInst::PtrToIntInst(
  3284. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  3285. ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
  3286. assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
  3287. }
  3288. PtrToIntInst::PtrToIntInst(
  3289. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  3290. ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
  3291. assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
  3292. }
  3293. IntToPtrInst::IntToPtrInst(
  3294. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  3295. ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
  3296. assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
  3297. }
  3298. IntToPtrInst::IntToPtrInst(
  3299. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  3300. ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
  3301. assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
  3302. }
  3303. BitCastInst::BitCastInst(
  3304. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  3305. ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
  3306. assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
  3307. }
  3308. BitCastInst::BitCastInst(
  3309. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  3310. ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
  3311. assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
  3312. }
  3313. AddrSpaceCastInst::AddrSpaceCastInst(
  3314. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  3315. ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
  3316. assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
  3317. }
  3318. AddrSpaceCastInst::AddrSpaceCastInst(
  3319. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  3320. ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
  3321. assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
  3322. }
  3323. //===----------------------------------------------------------------------===//
  3324. // CmpInst Classes
  3325. //===----------------------------------------------------------------------===//
  3326. CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
  3327. Value *RHS, const Twine &Name, Instruction *InsertBefore,
  3328. Instruction *FlagsSource)
  3329. : Instruction(ty, op,
  3330. OperandTraits<CmpInst>::op_begin(this),
  3331. OperandTraits<CmpInst>::operands(this),
  3332. InsertBefore) {
  3333. Op<0>() = LHS;
  3334. Op<1>() = RHS;
  3335. setPredicate((Predicate)predicate);
  3336. setName(Name);
  3337. if (FlagsSource)
  3338. copyIRFlags(FlagsSource);
  3339. }
  3340. CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
  3341. Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd)
  3342. : Instruction(ty, op,
  3343. OperandTraits<CmpInst>::op_begin(this),
  3344. OperandTraits<CmpInst>::operands(this),
  3345. InsertAtEnd) {
  3346. Op<0>() = LHS;
  3347. Op<1>() = RHS;
  3348. setPredicate((Predicate)predicate);
  3349. setName(Name);
  3350. }
  3351. CmpInst *
  3352. CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
  3353. const Twine &Name, Instruction *InsertBefore) {
  3354. if (Op == Instruction::ICmp) {
  3355. if (InsertBefore)
  3356. return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
  3357. S1, S2, Name);
  3358. else
  3359. return new ICmpInst(CmpInst::Predicate(predicate),
  3360. S1, S2, Name);
  3361. }
  3362. if (InsertBefore)
  3363. return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
  3364. S1, S2, Name);
  3365. else
  3366. return new FCmpInst(CmpInst::Predicate(predicate),
  3367. S1, S2, Name);
  3368. }
  3369. CmpInst *
  3370. CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
  3371. const Twine &Name, BasicBlock *InsertAtEnd) {
  3372. if (Op == Instruction::ICmp) {
  3373. return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
  3374. S1, S2, Name);
  3375. }
  3376. return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
  3377. S1, S2, Name);
  3378. }
  3379. void CmpInst::swapOperands() {
  3380. if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
  3381. IC->swapOperands();
  3382. else
  3383. cast<FCmpInst>(this)->swapOperands();
  3384. }
  3385. bool CmpInst::isCommutative() const {
  3386. if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
  3387. return IC->isCommutative();
  3388. return cast<FCmpInst>(this)->isCommutative();
  3389. }
  3390. bool CmpInst::isEquality(Predicate P) {
  3391. if (ICmpInst::isIntPredicate(P))
  3392. return ICmpInst::isEquality(P);
  3393. if (FCmpInst::isFPPredicate(P))
  3394. return FCmpInst::isEquality(P);
  3395. llvm_unreachable("Unsupported predicate kind");
  3396. }
  3397. CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
  3398. switch (pred) {
  3399. default: llvm_unreachable("Unknown cmp predicate!");
  3400. case ICMP_EQ: return ICMP_NE;
  3401. case ICMP_NE: return ICMP_EQ;
  3402. case ICMP_UGT: return ICMP_ULE;
  3403. case ICMP_ULT: return ICMP_UGE;
  3404. case ICMP_UGE: return ICMP_ULT;
  3405. case ICMP_ULE: return ICMP_UGT;
  3406. case ICMP_SGT: return ICMP_SLE;
  3407. case ICMP_SLT: return ICMP_SGE;
  3408. case ICMP_SGE: return ICMP_SLT;
  3409. case ICMP_SLE: return ICMP_SGT;
  3410. case FCMP_OEQ: return FCMP_UNE;
  3411. case FCMP_ONE: return FCMP_UEQ;
  3412. case FCMP_OGT: return FCMP_ULE;
  3413. case FCMP_OLT: return FCMP_UGE;
  3414. case FCMP_OGE: return FCMP_ULT;
  3415. case FCMP_OLE: return FCMP_UGT;
  3416. case FCMP_UEQ: return FCMP_ONE;
  3417. case FCMP_UNE: return FCMP_OEQ;
  3418. case FCMP_UGT: return FCMP_OLE;
  3419. case FCMP_ULT: return FCMP_OGE;
  3420. case FCMP_UGE: return FCMP_OLT;
  3421. case FCMP_ULE: return FCMP_OGT;
  3422. case FCMP_ORD: return FCMP_UNO;
  3423. case FCMP_UNO: return FCMP_ORD;
  3424. case FCMP_TRUE: return FCMP_FALSE;
  3425. case FCMP_FALSE: return FCMP_TRUE;
  3426. }
  3427. }
  3428. StringRef CmpInst::getPredicateName(Predicate Pred) {
  3429. switch (Pred) {
  3430. default: return "unknown";
  3431. case FCmpInst::FCMP_FALSE: return "false";
  3432. case FCmpInst::FCMP_OEQ: return "oeq";
  3433. case FCmpInst::FCMP_OGT: return "ogt";
  3434. case FCmpInst::FCMP_OGE: return "oge";
  3435. case FCmpInst::FCMP_OLT: return "olt";
  3436. case FCmpInst::FCMP_OLE: return "ole";
  3437. case FCmpInst::FCMP_ONE: return "one";
  3438. case FCmpInst::FCMP_ORD: return "ord";
  3439. case FCmpInst::FCMP_UNO: return "uno";
  3440. case FCmpInst::FCMP_UEQ: return "ueq";
  3441. case FCmpInst::FCMP_UGT: return "ugt";
  3442. case FCmpInst::FCMP_UGE: return "uge";
  3443. case FCmpInst::FCMP_ULT: return "ult";
  3444. case FCmpInst::FCMP_ULE: return "ule";
  3445. case FCmpInst::FCMP_UNE: return "une";
  3446. case FCmpInst::FCMP_TRUE: return "true";
  3447. case ICmpInst::ICMP_EQ: return "eq";
  3448. case ICmpInst::ICMP_NE: return "ne";
  3449. case ICmpInst::ICMP_SGT: return "sgt";
  3450. case ICmpInst::ICMP_SGE: return "sge";
  3451. case ICmpInst::ICMP_SLT: return "slt";
  3452. case ICmpInst::ICMP_SLE: return "sle";
  3453. case ICmpInst::ICMP_UGT: return "ugt";
  3454. case ICmpInst::ICMP_UGE: return "uge";
  3455. case ICmpInst::ICMP_ULT: return "ult";
  3456. case ICmpInst::ICMP_ULE: return "ule";
  3457. }
  3458. }
  3459. ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
  3460. switch (pred) {
  3461. default: llvm_unreachable("Unknown icmp predicate!");
  3462. case ICMP_EQ: case ICMP_NE:
  3463. case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
  3464. return pred;
  3465. case ICMP_UGT: return ICMP_SGT;
  3466. case ICMP_ULT: return ICMP_SLT;
  3467. case ICMP_UGE: return ICMP_SGE;
  3468. case ICMP_ULE: return ICMP_SLE;
  3469. }
  3470. }
  3471. ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
  3472. switch (pred) {
  3473. default: llvm_unreachable("Unknown icmp predicate!");
  3474. case ICMP_EQ: case ICMP_NE:
  3475. case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
  3476. return pred;
  3477. case ICMP_SGT: return ICMP_UGT;
  3478. case ICMP_SLT: return ICMP_ULT;
  3479. case ICMP_SGE: return ICMP_UGE;
  3480. case ICMP_SLE: return ICMP_ULE;
  3481. }
  3482. }
  3483. CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
  3484. switch (pred) {
  3485. default: llvm_unreachable("Unknown cmp predicate!");
  3486. case ICMP_EQ: case ICMP_NE:
  3487. return pred;
  3488. case ICMP_SGT: return ICMP_SLT;
  3489. case ICMP_SLT: return ICMP_SGT;
  3490. case ICMP_SGE: return ICMP_SLE;
  3491. case ICMP_SLE: return ICMP_SGE;
  3492. case ICMP_UGT: return ICMP_ULT;
  3493. case ICMP_ULT: return ICMP_UGT;
  3494. case ICMP_UGE: return ICMP_ULE;
  3495. case ICMP_ULE: return ICMP_UGE;
  3496. case FCMP_FALSE: case FCMP_TRUE:
  3497. case FCMP_OEQ: case FCMP_ONE:
  3498. case FCMP_UEQ: case FCMP_UNE:
  3499. case FCMP_ORD: case FCMP_UNO:
  3500. return pred;
  3501. case FCMP_OGT: return FCMP_OLT;
  3502. case FCMP_OLT: return FCMP_OGT;
  3503. case FCMP_OGE: return FCMP_OLE;
  3504. case FCMP_OLE: return FCMP_OGE;
  3505. case FCMP_UGT: return FCMP_ULT;
  3506. case FCMP_ULT: return FCMP_UGT;
  3507. case FCMP_UGE: return FCMP_ULE;
  3508. case FCMP_ULE: return FCMP_UGE;
  3509. }
  3510. }
  3511. bool CmpInst::isNonStrictPredicate(Predicate pred) {
  3512. switch (pred) {
  3513. case ICMP_SGE:
  3514. case ICMP_SLE:
  3515. case ICMP_UGE:
  3516. case ICMP_ULE:
  3517. case FCMP_OGE:
  3518. case FCMP_OLE:
  3519. case FCMP_UGE:
  3520. case FCMP_ULE:
  3521. return true;
  3522. default:
  3523. return false;
  3524. }
  3525. }
  3526. bool CmpInst::isStrictPredicate(Predicate pred) {
  3527. switch (pred) {
  3528. case ICMP_SGT:
  3529. case ICMP_SLT:
  3530. case ICMP_UGT:
  3531. case ICMP_ULT:
  3532. case FCMP_OGT:
  3533. case FCMP_OLT:
  3534. case FCMP_UGT:
  3535. case FCMP_ULT:
  3536. return true;
  3537. default:
  3538. return false;
  3539. }
  3540. }
  3541. CmpInst::Predicate CmpInst::getStrictPredicate(Predicate pred) {
  3542. switch (pred) {
  3543. case ICMP_SGE:
  3544. return ICMP_SGT;
  3545. case ICMP_SLE:
  3546. return ICMP_SLT;
  3547. case ICMP_UGE:
  3548. return ICMP_UGT;
  3549. case ICMP_ULE:
  3550. return ICMP_ULT;
  3551. case FCMP_OGE:
  3552. return FCMP_OGT;
  3553. case FCMP_OLE:
  3554. return FCMP_OLT;
  3555. case FCMP_UGE:
  3556. return FCMP_UGT;
  3557. case FCMP_ULE:
  3558. return FCMP_ULT;
  3559. default:
  3560. return pred;
  3561. }
  3562. }
  3563. CmpInst::Predicate CmpInst::getNonStrictPredicate(Predicate pred) {
  3564. switch (pred) {
  3565. case ICMP_SGT:
  3566. return ICMP_SGE;
  3567. case ICMP_SLT:
  3568. return ICMP_SLE;
  3569. case ICMP_UGT:
  3570. return ICMP_UGE;
  3571. case ICMP_ULT:
  3572. return ICMP_ULE;
  3573. case FCMP_OGT:
  3574. return FCMP_OGE;
  3575. case FCMP_OLT:
  3576. return FCMP_OLE;
  3577. case FCMP_UGT:
  3578. return FCMP_UGE;
  3579. case FCMP_ULT:
  3580. return FCMP_ULE;
  3581. default:
  3582. return pred;
  3583. }
  3584. }
  3585. CmpInst::Predicate CmpInst::getFlippedStrictnessPredicate(Predicate pred) {
  3586. assert(CmpInst::isRelational(pred) && "Call only with relational predicate!");
  3587. if (isStrictPredicate(pred))
  3588. return getNonStrictPredicate(pred);
  3589. if (isNonStrictPredicate(pred))
  3590. return getStrictPredicate(pred);
  3591. llvm_unreachable("Unknown predicate!");
  3592. }
  3593. CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) {
  3594. assert(CmpInst::isUnsigned(pred) && "Call only with unsigned predicates!");
  3595. switch (pred) {
  3596. default:
  3597. llvm_unreachable("Unknown predicate!");
  3598. case CmpInst::ICMP_ULT:
  3599. return CmpInst::ICMP_SLT;
  3600. case CmpInst::ICMP_ULE:
  3601. return CmpInst::ICMP_SLE;
  3602. case CmpInst::ICMP_UGT:
  3603. return CmpInst::ICMP_SGT;
  3604. case CmpInst::ICMP_UGE:
  3605. return CmpInst::ICMP_SGE;
  3606. }
  3607. }
  3608. CmpInst::Predicate CmpInst::getUnsignedPredicate(Predicate pred) {
  3609. assert(CmpInst::isSigned(pred) && "Call only with signed predicates!");
  3610. switch (pred) {
  3611. default:
  3612. llvm_unreachable("Unknown predicate!");
  3613. case CmpInst::ICMP_SLT:
  3614. return CmpInst::ICMP_ULT;
  3615. case CmpInst::ICMP_SLE:
  3616. return CmpInst::ICMP_ULE;
  3617. case CmpInst::ICMP_SGT:
  3618. return CmpInst::ICMP_UGT;
  3619. case CmpInst::ICMP_SGE:
  3620. return CmpInst::ICMP_UGE;
  3621. }
  3622. }
  3623. bool CmpInst::isUnsigned(Predicate predicate) {
  3624. switch (predicate) {
  3625. default: return false;
  3626. case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
  3627. case ICmpInst::ICMP_UGE: return true;
  3628. }
  3629. }
  3630. bool CmpInst::isSigned(Predicate predicate) {
  3631. switch (predicate) {
  3632. default: return false;
  3633. case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
  3634. case ICmpInst::ICMP_SGE: return true;
  3635. }
  3636. }
  3637. bool ICmpInst::compare(const APInt &LHS, const APInt &RHS,
  3638. ICmpInst::Predicate Pred) {
  3639. assert(ICmpInst::isIntPredicate(Pred) && "Only for integer predicates!");
  3640. switch (Pred) {
  3641. case ICmpInst::Predicate::ICMP_EQ:
  3642. return LHS.eq(RHS);
  3643. case ICmpInst::Predicate::ICMP_NE:
  3644. return LHS.ne(RHS);
  3645. case ICmpInst::Predicate::ICMP_UGT:
  3646. return LHS.ugt(RHS);
  3647. case ICmpInst::Predicate::ICMP_UGE:
  3648. return LHS.uge(RHS);
  3649. case ICmpInst::Predicate::ICMP_ULT:
  3650. return LHS.ult(RHS);
  3651. case ICmpInst::Predicate::ICMP_ULE:
  3652. return LHS.ule(RHS);
  3653. case ICmpInst::Predicate::ICMP_SGT:
  3654. return LHS.sgt(RHS);
  3655. case ICmpInst::Predicate::ICMP_SGE:
  3656. return LHS.sge(RHS);
  3657. case ICmpInst::Predicate::ICMP_SLT:
  3658. return LHS.slt(RHS);
  3659. case ICmpInst::Predicate::ICMP_SLE:
  3660. return LHS.sle(RHS);
  3661. default:
  3662. llvm_unreachable("Unexpected non-integer predicate.");
  3663. };
  3664. }
  3665. bool FCmpInst::compare(const APFloat &LHS, const APFloat &RHS,
  3666. FCmpInst::Predicate Pred) {
  3667. APFloat::cmpResult R = LHS.compare(RHS);
  3668. switch (Pred) {
  3669. default:
  3670. llvm_unreachable("Invalid FCmp Predicate");
  3671. case FCmpInst::FCMP_FALSE:
  3672. return false;
  3673. case FCmpInst::FCMP_TRUE:
  3674. return true;
  3675. case FCmpInst::FCMP_UNO:
  3676. return R == APFloat::cmpUnordered;
  3677. case FCmpInst::FCMP_ORD:
  3678. return R != APFloat::cmpUnordered;
  3679. case FCmpInst::FCMP_UEQ:
  3680. return R == APFloat::cmpUnordered || R == APFloat::cmpEqual;
  3681. case FCmpInst::FCMP_OEQ:
  3682. return R == APFloat::cmpEqual;
  3683. case FCmpInst::FCMP_UNE:
  3684. return R != APFloat::cmpEqual;
  3685. case FCmpInst::FCMP_ONE:
  3686. return R == APFloat::cmpLessThan || R == APFloat::cmpGreaterThan;
  3687. case FCmpInst::FCMP_ULT:
  3688. return R == APFloat::cmpUnordered || R == APFloat::cmpLessThan;
  3689. case FCmpInst::FCMP_OLT:
  3690. return R == APFloat::cmpLessThan;
  3691. case FCmpInst::FCMP_UGT:
  3692. return R == APFloat::cmpUnordered || R == APFloat::cmpGreaterThan;
  3693. case FCmpInst::FCMP_OGT:
  3694. return R == APFloat::cmpGreaterThan;
  3695. case FCmpInst::FCMP_ULE:
  3696. return R != APFloat::cmpGreaterThan;
  3697. case FCmpInst::FCMP_OLE:
  3698. return R == APFloat::cmpLessThan || R == APFloat::cmpEqual;
  3699. case FCmpInst::FCMP_UGE:
  3700. return R != APFloat::cmpLessThan;
  3701. case FCmpInst::FCMP_OGE:
  3702. return R == APFloat::cmpGreaterThan || R == APFloat::cmpEqual;
  3703. }
  3704. }
  3705. CmpInst::Predicate CmpInst::getFlippedSignednessPredicate(Predicate pred) {
  3706. assert(CmpInst::isRelational(pred) &&
  3707. "Call only with non-equality predicates!");
  3708. if (isSigned(pred))
  3709. return getUnsignedPredicate(pred);
  3710. if (isUnsigned(pred))
  3711. return getSignedPredicate(pred);
  3712. llvm_unreachable("Unknown predicate!");
  3713. }
  3714. bool CmpInst::isOrdered(Predicate predicate) {
  3715. switch (predicate) {
  3716. default: return false;
  3717. case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
  3718. case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
  3719. case FCmpInst::FCMP_ORD: return true;
  3720. }
  3721. }
  3722. bool CmpInst::isUnordered(Predicate predicate) {
  3723. switch (predicate) {
  3724. default: return false;
  3725. case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
  3726. case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
  3727. case FCmpInst::FCMP_UNO: return true;
  3728. }
  3729. }
  3730. bool CmpInst::isTrueWhenEqual(Predicate predicate) {
  3731. switch(predicate) {
  3732. default: return false;
  3733. case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
  3734. case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
  3735. }
  3736. }
  3737. bool CmpInst::isFalseWhenEqual(Predicate predicate) {
  3738. switch(predicate) {
  3739. case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
  3740. case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
  3741. default: return false;
  3742. }
  3743. }
  3744. bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2) {
  3745. // If the predicates match, then we know the first condition implies the
  3746. // second is true.
  3747. if (Pred1 == Pred2)
  3748. return true;
  3749. switch (Pred1) {
  3750. default:
  3751. break;
  3752. case ICMP_EQ:
  3753. // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
  3754. return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE ||
  3755. Pred2 == ICMP_SLE;
  3756. case ICMP_UGT: // A >u B implies A != B and A >=u B are true.
  3757. return Pred2 == ICMP_NE || Pred2 == ICMP_UGE;
  3758. case ICMP_ULT: // A <u B implies A != B and A <=u B are true.
  3759. return Pred2 == ICMP_NE || Pred2 == ICMP_ULE;
  3760. case ICMP_SGT: // A >s B implies A != B and A >=s B are true.
  3761. return Pred2 == ICMP_NE || Pred2 == ICMP_SGE;
  3762. case ICMP_SLT: // A <s B implies A != B and A <=s B are true.
  3763. return Pred2 == ICMP_NE || Pred2 == ICMP_SLE;
  3764. }
  3765. return false;
  3766. }
  3767. bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2) {
  3768. return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2));
  3769. }
  3770. //===----------------------------------------------------------------------===//
  3771. // SwitchInst Implementation
  3772. //===----------------------------------------------------------------------===//
  3773. void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
  3774. assert(Value && Default && NumReserved);
  3775. ReservedSpace = NumReserved;
  3776. setNumHungOffUseOperands(2);
  3777. allocHungoffUses(ReservedSpace);
  3778. Op<0>() = Value;
  3779. Op<1>() = Default;
  3780. }
  3781. /// SwitchInst ctor - Create a new switch instruction, specifying a value to
  3782. /// switch on and a default destination. The number of additional cases can
  3783. /// be specified here to make memory allocation more efficient. This
  3784. /// constructor can also autoinsert before another instruction.
  3785. SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
  3786. Instruction *InsertBefore)
  3787. : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
  3788. nullptr, 0, InsertBefore) {
  3789. init(Value, Default, 2+NumCases*2);
  3790. }
  3791. /// SwitchInst ctor - Create a new switch instruction, specifying a value to
  3792. /// switch on and a default destination. The number of additional cases can
  3793. /// be specified here to make memory allocation more efficient. This
  3794. /// constructor also autoinserts at the end of the specified BasicBlock.
  3795. SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
  3796. BasicBlock *InsertAtEnd)
  3797. : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
  3798. nullptr, 0, InsertAtEnd) {
  3799. init(Value, Default, 2+NumCases*2);
  3800. }
  3801. SwitchInst::SwitchInst(const SwitchInst &SI)
  3802. : Instruction(SI.getType(), Instruction::Switch, nullptr, 0) {
  3803. init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
  3804. setNumHungOffUseOperands(SI.getNumOperands());
  3805. Use *OL = getOperandList();
  3806. const Use *InOL = SI.getOperandList();
  3807. for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
  3808. OL[i] = InOL[i];
  3809. OL[i+1] = InOL[i+1];
  3810. }
  3811. SubclassOptionalData = SI.SubclassOptionalData;
  3812. }
  3813. /// addCase - Add an entry to the switch instruction...
  3814. ///
  3815. void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
  3816. unsigned NewCaseIdx = getNumCases();
  3817. unsigned OpNo = getNumOperands();
  3818. if (OpNo+2 > ReservedSpace)
  3819. growOperands(); // Get more space!
  3820. // Initialize some new operands.
  3821. assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
  3822. setNumHungOffUseOperands(OpNo+2);
  3823. CaseHandle Case(this, NewCaseIdx);
  3824. Case.setValue(OnVal);
  3825. Case.setSuccessor(Dest);
  3826. }
  3827. /// removeCase - This method removes the specified case and its successor
  3828. /// from the switch instruction.
  3829. SwitchInst::CaseIt SwitchInst::removeCase(CaseIt I) {
  3830. unsigned idx = I->getCaseIndex();
  3831. assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
  3832. unsigned NumOps = getNumOperands();
  3833. Use *OL = getOperandList();
  3834. // Overwrite this case with the end of the list.
  3835. if (2 + (idx + 1) * 2 != NumOps) {
  3836. OL[2 + idx * 2] = OL[NumOps - 2];
  3837. OL[2 + idx * 2 + 1] = OL[NumOps - 1];
  3838. }
  3839. // Nuke the last value.
  3840. OL[NumOps-2].set(nullptr);
  3841. OL[NumOps-2+1].set(nullptr);
  3842. setNumHungOffUseOperands(NumOps-2);
  3843. return CaseIt(this, idx);
  3844. }
  3845. /// growOperands - grow operands - This grows the operand list in response
  3846. /// to a push_back style of operation. This grows the number of ops by 3 times.
  3847. ///
  3848. void SwitchInst::growOperands() {
  3849. unsigned e = getNumOperands();
  3850. unsigned NumOps = e*3;
  3851. ReservedSpace = NumOps;
  3852. growHungoffUses(ReservedSpace);
  3853. }
  3854. MDNode *
  3855. SwitchInstProfUpdateWrapper::getProfBranchWeightsMD(const SwitchInst &SI) {
  3856. if (MDNode *ProfileData = SI.getMetadata(LLVMContext::MD_prof))
  3857. if (auto *MDName = dyn_cast<MDString>(ProfileData->getOperand(0)))
  3858. if (MDName->getString() == "branch_weights")
  3859. return ProfileData;
  3860. return nullptr;
  3861. }
  3862. MDNode *SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() {
  3863. assert(Changed && "called only if metadata has changed");
  3864. if (!Weights)
  3865. return nullptr;
  3866. assert(SI.getNumSuccessors() == Weights->size() &&
  3867. "num of prof branch_weights must accord with num of successors");
  3868. bool AllZeroes =
  3869. all_of(Weights.getValue(), [](uint32_t W) { return W == 0; });
  3870. if (AllZeroes || Weights.getValue().size() < 2)
  3871. return nullptr;
  3872. return MDBuilder(SI.getParent()->getContext()).createBranchWeights(*Weights);
  3873. }
  3874. void SwitchInstProfUpdateWrapper::init() {
  3875. MDNode *ProfileData = getProfBranchWeightsMD(SI);
  3876. if (!ProfileData)
  3877. return;
  3878. if (ProfileData->getNumOperands() != SI.getNumSuccessors() + 1) {
  3879. llvm_unreachable("number of prof branch_weights metadata operands does "
  3880. "not correspond to number of succesors");
  3881. }
  3882. SmallVector<uint32_t, 8> Weights;
  3883. for (unsigned CI = 1, CE = SI.getNumSuccessors(); CI <= CE; ++CI) {
  3884. ConstantInt *C = mdconst::extract<ConstantInt>(ProfileData->getOperand(CI));
  3885. uint32_t CW = C->getValue().getZExtValue();
  3886. Weights.push_back(CW);
  3887. }
  3888. this->Weights = std::move(Weights);
  3889. }
  3890. SwitchInst::CaseIt
  3891. SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I) {
  3892. if (Weights) {
  3893. assert(SI.getNumSuccessors() == Weights->size() &&
  3894. "num of prof branch_weights must accord with num of successors");
  3895. Changed = true;
  3896. // Copy the last case to the place of the removed one and shrink.
  3897. // This is tightly coupled with the way SwitchInst::removeCase() removes
  3898. // the cases in SwitchInst::removeCase(CaseIt).
  3899. Weights.getValue()[I->getCaseIndex() + 1] = Weights.getValue().back();
  3900. Weights.getValue().pop_back();
  3901. }
  3902. return SI.removeCase(I);
  3903. }
  3904. void SwitchInstProfUpdateWrapper::addCase(
  3905. ConstantInt *OnVal, BasicBlock *Dest,
  3906. SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
  3907. SI.addCase(OnVal, Dest);
  3908. if (!Weights && W && *W) {
  3909. Changed = true;
  3910. Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
  3911. Weights.getValue()[SI.getNumSuccessors() - 1] = *W;
  3912. } else if (Weights) {
  3913. Changed = true;
  3914. Weights.getValue().push_back(W.getValueOr(0));
  3915. }
  3916. if (Weights)
  3917. assert(SI.getNumSuccessors() == Weights->size() &&
  3918. "num of prof branch_weights must accord with num of successors");
  3919. }
  3920. SymbolTableList<Instruction>::iterator
  3921. SwitchInstProfUpdateWrapper::eraseFromParent() {
  3922. // Instruction is erased. Mark as unchanged to not touch it in the destructor.
  3923. Changed = false;
  3924. if (Weights)
  3925. Weights->resize(0);
  3926. return SI.eraseFromParent();
  3927. }
  3928. SwitchInstProfUpdateWrapper::CaseWeightOpt
  3929. SwitchInstProfUpdateWrapper::getSuccessorWeight(unsigned idx) {
  3930. if (!Weights)
  3931. return None;
  3932. return Weights.getValue()[idx];
  3933. }
  3934. void SwitchInstProfUpdateWrapper::setSuccessorWeight(
  3935. unsigned idx, SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
  3936. if (!W)
  3937. return;
  3938. if (!Weights && *W)
  3939. Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
  3940. if (Weights) {
  3941. auto &OldW = Weights.getValue()[idx];
  3942. if (*W != OldW) {
  3943. Changed = true;
  3944. OldW = *W;
  3945. }
  3946. }
  3947. }
  3948. SwitchInstProfUpdateWrapper::CaseWeightOpt
  3949. SwitchInstProfUpdateWrapper::getSuccessorWeight(const SwitchInst &SI,
  3950. unsigned idx) {
  3951. if (MDNode *ProfileData = getProfBranchWeightsMD(SI))
  3952. if (ProfileData->getNumOperands() == SI.getNumSuccessors() + 1)
  3953. return mdconst::extract<ConstantInt>(ProfileData->getOperand(idx + 1))
  3954. ->getValue()
  3955. .getZExtValue();
  3956. return None;
  3957. }
  3958. //===----------------------------------------------------------------------===//
  3959. // IndirectBrInst Implementation
  3960. //===----------------------------------------------------------------------===//
  3961. void IndirectBrInst::init(Value *Address, unsigned NumDests) {
  3962. assert(Address && Address->getType()->isPointerTy() &&
  3963. "Address of indirectbr must be a pointer");
  3964. ReservedSpace = 1+NumDests;
  3965. setNumHungOffUseOperands(1);
  3966. allocHungoffUses(ReservedSpace);
  3967. Op<0>() = Address;
  3968. }
  3969. /// growOperands - grow operands - This grows the operand list in response
  3970. /// to a push_back style of operation. This grows the number of ops by 2 times.
  3971. ///
  3972. void IndirectBrInst::growOperands() {
  3973. unsigned e = getNumOperands();
  3974. unsigned NumOps = e*2;
  3975. ReservedSpace = NumOps;
  3976. growHungoffUses(ReservedSpace);
  3977. }
  3978. IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
  3979. Instruction *InsertBefore)
  3980. : Instruction(Type::getVoidTy(Address->getContext()),
  3981. Instruction::IndirectBr, nullptr, 0, InsertBefore) {
  3982. init(Address, NumCases);
  3983. }
  3984. IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
  3985. BasicBlock *InsertAtEnd)
  3986. : Instruction(Type::getVoidTy(Address->getContext()),
  3987. Instruction::IndirectBr, nullptr, 0, InsertAtEnd) {
  3988. init(Address, NumCases);
  3989. }
  3990. IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
  3991. : Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
  3992. nullptr, IBI.getNumOperands()) {
  3993. allocHungoffUses(IBI.getNumOperands());
  3994. Use *OL = getOperandList();
  3995. const Use *InOL = IBI.getOperandList();
  3996. for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
  3997. OL[i] = InOL[i];
  3998. SubclassOptionalData = IBI.SubclassOptionalData;
  3999. }
  4000. /// addDestination - Add a destination.
  4001. ///
  4002. void IndirectBrInst::addDestination(BasicBlock *DestBB) {
  4003. unsigned OpNo = getNumOperands();
  4004. if (OpNo+1 > ReservedSpace)
  4005. growOperands(); // Get more space!
  4006. // Initialize some new operands.
  4007. assert(OpNo < ReservedSpace && "Growing didn't work!");
  4008. setNumHungOffUseOperands(OpNo+1);
  4009. getOperandList()[OpNo] = DestBB;
  4010. }
  4011. /// removeDestination - This method removes the specified successor from the
  4012. /// indirectbr instruction.
  4013. void IndirectBrInst::removeDestination(unsigned idx) {
  4014. assert(idx < getNumOperands()-1 && "Successor index out of range!");
  4015. unsigned NumOps = getNumOperands();
  4016. Use *OL = getOperandList();
  4017. // Replace this value with the last one.
  4018. OL[idx+1] = OL[NumOps-1];
  4019. // Nuke the last value.
  4020. OL[NumOps-1].set(nullptr);
  4021. setNumHungOffUseOperands(NumOps-1);
  4022. }
  4023. //===----------------------------------------------------------------------===//
  4024. // FreezeInst Implementation
  4025. //===----------------------------------------------------------------------===//
  4026. FreezeInst::FreezeInst(Value *S,
  4027. const Twine &Name, Instruction *InsertBefore)
  4028. : UnaryInstruction(S->getType(), Freeze, S, InsertBefore) {
  4029. setName(Name);
  4030. }
  4031. FreezeInst::FreezeInst(Value *S,
  4032. const Twine &Name, BasicBlock *InsertAtEnd)
  4033. : UnaryInstruction(S->getType(), Freeze, S, InsertAtEnd) {
  4034. setName(Name);
  4035. }
  4036. //===----------------------------------------------------------------------===//
  4037. // cloneImpl() implementations
  4038. //===----------------------------------------------------------------------===//
  4039. // Define these methods here so vtables don't get emitted into every translation
  4040. // unit that uses these classes.
  4041. GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
  4042. return new (getNumOperands()) GetElementPtrInst(*this);
  4043. }
  4044. UnaryOperator *UnaryOperator::cloneImpl() const {
  4045. return Create(getOpcode(), Op<0>());
  4046. }
  4047. BinaryOperator *BinaryOperator::cloneImpl() const {
  4048. return Create(getOpcode(), Op<0>(), Op<1>());
  4049. }
  4050. FCmpInst *FCmpInst::cloneImpl() const {
  4051. return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
  4052. }
  4053. ICmpInst *ICmpInst::cloneImpl() const {
  4054. return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
  4055. }
  4056. ExtractValueInst *ExtractValueInst::cloneImpl() const {
  4057. return new ExtractValueInst(*this);
  4058. }
  4059. InsertValueInst *InsertValueInst::cloneImpl() const {
  4060. return new InsertValueInst(*this);
  4061. }
  4062. AllocaInst *AllocaInst::cloneImpl() const {
  4063. AllocaInst *Result =
  4064. new AllocaInst(getAllocatedType(), getType()->getAddressSpace(),
  4065. getOperand(0), getAlign());
  4066. Result->setUsedWithInAlloca(isUsedWithInAlloca());
  4067. Result->setSwiftError(isSwiftError());
  4068. return Result;
  4069. }
  4070. LoadInst *LoadInst::cloneImpl() const {
  4071. return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(),
  4072. getAlign(), getOrdering(), getSyncScopeID());
  4073. }
  4074. StoreInst *StoreInst::cloneImpl() const {
  4075. return new StoreInst(getOperand(0), getOperand(1), isVolatile(), getAlign(),
  4076. getOrdering(), getSyncScopeID());
  4077. }
  4078. AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const {
  4079. AtomicCmpXchgInst *Result = new AtomicCmpXchgInst(
  4080. getOperand(0), getOperand(1), getOperand(2), getAlign(),
  4081. getSuccessOrdering(), getFailureOrdering(), getSyncScopeID());
  4082. Result->setVolatile(isVolatile());
  4083. Result->setWeak(isWeak());
  4084. return Result;
  4085. }
  4086. AtomicRMWInst *AtomicRMWInst::cloneImpl() const {
  4087. AtomicRMWInst *Result =
  4088. new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1),
  4089. getAlign(), getOrdering(), getSyncScopeID());
  4090. Result->setVolatile(isVolatile());
  4091. return Result;
  4092. }
  4093. FenceInst *FenceInst::cloneImpl() const {
  4094. return new FenceInst(getContext(), getOrdering(), getSyncScopeID());
  4095. }
  4096. TruncInst *TruncInst::cloneImpl() const {
  4097. return new TruncInst(getOperand(0), getType());
  4098. }
  4099. ZExtInst *ZExtInst::cloneImpl() const {
  4100. return new ZExtInst(getOperand(0), getType());
  4101. }
  4102. SExtInst *SExtInst::cloneImpl() const {
  4103. return new SExtInst(getOperand(0), getType());
  4104. }
  4105. FPTruncInst *FPTruncInst::cloneImpl() const {
  4106. return new FPTruncInst(getOperand(0), getType());
  4107. }
  4108. FPExtInst *FPExtInst::cloneImpl() const {
  4109. return new FPExtInst(getOperand(0), getType());
  4110. }
  4111. UIToFPInst *UIToFPInst::cloneImpl() const {
  4112. return new UIToFPInst(getOperand(0), getType());
  4113. }
  4114. SIToFPInst *SIToFPInst::cloneImpl() const {
  4115. return new SIToFPInst(getOperand(0), getType());
  4116. }
  4117. FPToUIInst *FPToUIInst::cloneImpl() const {
  4118. return new FPToUIInst(getOperand(0), getType());
  4119. }
  4120. FPToSIInst *FPToSIInst::cloneImpl() const {
  4121. return new FPToSIInst(getOperand(0), getType());
  4122. }
  4123. PtrToIntInst *PtrToIntInst::cloneImpl() const {
  4124. return new PtrToIntInst(getOperand(0), getType());
  4125. }
  4126. IntToPtrInst *IntToPtrInst::cloneImpl() const {
  4127. return new IntToPtrInst(getOperand(0), getType());
  4128. }
  4129. BitCastInst *BitCastInst::cloneImpl() const {
  4130. return new BitCastInst(getOperand(0), getType());
  4131. }
  4132. AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const {
  4133. return new AddrSpaceCastInst(getOperand(0), getType());
  4134. }
  4135. CallInst *CallInst::cloneImpl() const {
  4136. if (hasOperandBundles()) {
  4137. unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
  4138. return new(getNumOperands(), DescriptorBytes) CallInst(*this);
  4139. }
  4140. return new(getNumOperands()) CallInst(*this);
  4141. }
  4142. SelectInst *SelectInst::cloneImpl() const {
  4143. return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
  4144. }
  4145. VAArgInst *VAArgInst::cloneImpl() const {
  4146. return new VAArgInst(getOperand(0), getType());
  4147. }
  4148. ExtractElementInst *ExtractElementInst::cloneImpl() const {
  4149. return ExtractElementInst::Create(getOperand(0), getOperand(1));
  4150. }
  4151. InsertElementInst *InsertElementInst::cloneImpl() const {
  4152. return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
  4153. }
  4154. ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const {
  4155. return new ShuffleVectorInst(getOperand(0), getOperand(1), getShuffleMask());
  4156. }
  4157. PHINode *PHINode::cloneImpl() const { return new PHINode(*this); }
  4158. LandingPadInst *LandingPadInst::cloneImpl() const {
  4159. return new LandingPadInst(*this);
  4160. }
  4161. ReturnInst *ReturnInst::cloneImpl() const {
  4162. return new(getNumOperands()) ReturnInst(*this);
  4163. }
  4164. BranchInst *BranchInst::cloneImpl() const {
  4165. return new(getNumOperands()) BranchInst(*this);
  4166. }
  4167. SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
  4168. IndirectBrInst *IndirectBrInst::cloneImpl() const {
  4169. return new IndirectBrInst(*this);
  4170. }
  4171. InvokeInst *InvokeInst::cloneImpl() const {
  4172. if (hasOperandBundles()) {
  4173. unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
  4174. return new(getNumOperands(), DescriptorBytes) InvokeInst(*this);
  4175. }
  4176. return new(getNumOperands()) InvokeInst(*this);
  4177. }
  4178. CallBrInst *CallBrInst::cloneImpl() const {
  4179. if (hasOperandBundles()) {
  4180. unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
  4181. return new (getNumOperands(), DescriptorBytes) CallBrInst(*this);
  4182. }
  4183. return new (getNumOperands()) CallBrInst(*this);
  4184. }
  4185. ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
  4186. CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
  4187. return new (getNumOperands()) CleanupReturnInst(*this);
  4188. }
  4189. CatchReturnInst *CatchReturnInst::cloneImpl() const {
  4190. return new (getNumOperands()) CatchReturnInst(*this);
  4191. }
  4192. CatchSwitchInst *CatchSwitchInst::cloneImpl() const {
  4193. return new CatchSwitchInst(*this);
  4194. }
  4195. FuncletPadInst *FuncletPadInst::cloneImpl() const {
  4196. return new (getNumOperands()) FuncletPadInst(*this);
  4197. }
  4198. UnreachableInst *UnreachableInst::cloneImpl() const {
  4199. LLVMContext &Context = getContext();
  4200. return new UnreachableInst(Context);
  4201. }
  4202. FreezeInst *FreezeInst::cloneImpl() const {
  4203. return new FreezeInst(getOperand(0));
  4204. }