Instructions.cpp 136 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624
  1. //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements all of the non-inline methods for the LLVM instruction
  11. // classes.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/IR/Instructions.h"
  15. #include "LLVMContextImpl.h"
  16. #include "llvm/IR/CallSite.h"
  17. #include "llvm/IR/ConstantRange.h"
  18. #include "llvm/IR/Constants.h"
  19. #include "llvm/IR/DataLayout.h"
  20. #include "llvm/IR/DerivedTypes.h"
  21. #include "llvm/IR/Function.h"
  22. #include "llvm/IR/Module.h"
  23. #include "llvm/IR/Operator.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include "llvm/Support/MathExtras.h"
  26. using namespace llvm;
  27. //===----------------------------------------------------------------------===//
  28. // CallSite Class
  29. //===----------------------------------------------------------------------===//
  30. User::op_iterator CallSite::getCallee() const {
  31. Instruction *II(getInstruction());
  32. return isCall()
  33. ? cast<CallInst>(II)->op_end() - 1 // Skip Callee
  34. : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee
  35. }
  36. //===----------------------------------------------------------------------===//
  37. // TerminatorInst Class
  38. //===----------------------------------------------------------------------===//
  39. // Out of line virtual method, so the vtable, etc has a home.
  40. TerminatorInst::~TerminatorInst() {
  41. }
  42. //===----------------------------------------------------------------------===//
  43. // UnaryInstruction Class
  44. //===----------------------------------------------------------------------===//
  45. // Out of line virtual method, so the vtable, etc has a home.
  46. UnaryInstruction::~UnaryInstruction() {
  47. }
  48. //===----------------------------------------------------------------------===//
  49. // SelectInst Class
  50. //===----------------------------------------------------------------------===//
  51. /// areInvalidOperands - Return a string if the specified operands are invalid
  52. /// for a select operation, otherwise return null.
  53. const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
  54. if (Op1->getType() != Op2->getType())
  55. return "both values to select must have same type";
  56. if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
  57. // Vector select.
  58. if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
  59. return "vector select condition element type must be i1";
  60. VectorType *ET = dyn_cast<VectorType>(Op1->getType());
  61. if (!ET)
  62. return "selected values for vector select must be vectors";
  63. if (ET->getNumElements() != VT->getNumElements())
  64. return "vector select requires selected vectors to have "
  65. "the same vector length as select condition";
  66. } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
  67. return "select condition must be i1 or <n x i1>";
  68. }
  69. return nullptr;
  70. }
  71. //===----------------------------------------------------------------------===//
  72. // PHINode Class
  73. //===----------------------------------------------------------------------===//
  74. PHINode::PHINode(const PHINode &PN)
  75. : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()),
  76. ReservedSpace(PN.getNumOperands()) {
  77. allocHungoffUses(PN.getNumOperands());
  78. std::copy(PN.op_begin(), PN.op_end(), op_begin());
  79. std::copy(PN.block_begin(), PN.block_end(), block_begin());
  80. SubclassOptionalData = PN.SubclassOptionalData;
  81. }
  82. // removeIncomingValue - Remove an incoming value. This is useful if a
  83. // predecessor basic block is deleted.
  84. Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
  85. Value *Removed = getIncomingValue(Idx);
  86. // Move everything after this operand down.
  87. //
  88. // FIXME: we could just swap with the end of the list, then erase. However,
  89. // clients might not expect this to happen. The code as it is thrashes the
  90. // use/def lists, which is kinda lame.
  91. std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
  92. std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
  93. // Nuke the last value.
  94. Op<-1>().set(nullptr);
  95. setNumHungOffUseOperands(getNumOperands() - 1);
  96. // If the PHI node is dead, because it has zero entries, nuke it now.
  97. if (getNumOperands() == 0 && DeletePHIIfEmpty) {
  98. // If anyone is using this PHI, make them use a dummy value instead...
  99. replaceAllUsesWith(UndefValue::get(getType()));
  100. eraseFromParent();
  101. }
  102. return Removed;
  103. }
  104. /// growOperands - grow operands - This grows the operand list in response
  105. /// to a push_back style of operation. This grows the number of ops by 1.5
  106. /// times.
  107. ///
  108. void PHINode::growOperands() {
  109. unsigned e = getNumOperands();
  110. unsigned NumOps = e + e / 2;
  111. if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
  112. ReservedSpace = NumOps;
  113. growHungoffUses(ReservedSpace, /* IsPhi */ true);
  114. }
  115. /// hasConstantValue - If the specified PHI node always merges together the same
  116. /// value, return the value, otherwise return null.
  117. Value *PHINode::hasConstantValue() const {
  118. // Exploit the fact that phi nodes always have at least one entry.
  119. Value *ConstantValue = getIncomingValue(0);
  120. for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
  121. if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
  122. if (ConstantValue != this)
  123. return nullptr; // Incoming values not all the same.
  124. // The case where the first value is this PHI.
  125. ConstantValue = getIncomingValue(i);
  126. }
  127. if (ConstantValue == this)
  128. return UndefValue::get(getType());
  129. return ConstantValue;
  130. }
  131. //===----------------------------------------------------------------------===//
  132. // LandingPadInst Implementation
  133. //===----------------------------------------------------------------------===//
  134. LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
  135. const Twine &NameStr, Instruction *InsertBefore)
  136. : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
  137. init(NumReservedValues, NameStr);
  138. }
  139. LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
  140. const Twine &NameStr, BasicBlock *InsertAtEnd)
  141. : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
  142. init(NumReservedValues, NameStr);
  143. }
  144. LandingPadInst::LandingPadInst(const LandingPadInst &LP)
  145. : Instruction(LP.getType(), Instruction::LandingPad, nullptr,
  146. LP.getNumOperands()),
  147. ReservedSpace(LP.getNumOperands()) {
  148. allocHungoffUses(LP.getNumOperands());
  149. Use *OL = getOperandList();
  150. const Use *InOL = LP.getOperandList();
  151. for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
  152. OL[I] = InOL[I];
  153. setCleanup(LP.isCleanup());
  154. }
  155. LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
  156. const Twine &NameStr,
  157. Instruction *InsertBefore) {
  158. return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
  159. }
  160. LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
  161. const Twine &NameStr,
  162. BasicBlock *InsertAtEnd) {
  163. return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd);
  164. }
  165. void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
  166. ReservedSpace = NumReservedValues;
  167. setNumHungOffUseOperands(0);
  168. allocHungoffUses(ReservedSpace);
  169. setName(NameStr);
  170. setCleanup(false);
  171. }
  172. /// growOperands - grow operands - This grows the operand list in response to a
  173. /// push_back style of operation. This grows the number of ops by 2 times.
  174. void LandingPadInst::growOperands(unsigned Size) {
  175. unsigned e = getNumOperands();
  176. if (ReservedSpace >= e + Size) return;
  177. ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
  178. growHungoffUses(ReservedSpace);
  179. }
  180. void LandingPadInst::addClause(Constant *Val) {
  181. unsigned OpNo = getNumOperands();
  182. growOperands(1);
  183. assert(OpNo < ReservedSpace && "Growing didn't work!");
  184. setNumHungOffUseOperands(getNumOperands() + 1);
  185. getOperandList()[OpNo] = Val;
  186. }
  187. //===----------------------------------------------------------------------===//
  188. // CallInst Implementation
  189. //===----------------------------------------------------------------------===//
  190. CallInst::~CallInst() {
  191. }
  192. void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
  193. const Twine &NameStr) {
  194. this->FTy = FTy;
  195. assert(getNumOperands() == Args.size() + 1 && "NumOperands not set up?");
  196. Op<-1>() = Func;
  197. #ifndef NDEBUG
  198. assert((Args.size() == FTy->getNumParams() ||
  199. (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
  200. "Calling a function with bad signature!");
  201. for (unsigned i = 0; i != Args.size(); ++i)
  202. assert((i >= FTy->getNumParams() ||
  203. FTy->getParamType(i) == Args[i]->getType()) &&
  204. "Calling a function with a bad signature!");
  205. #endif
  206. std::copy(Args.begin(), Args.end(), op_begin());
  207. setName(NameStr);
  208. }
  209. void CallInst::init(Value *Func, const Twine &NameStr) {
  210. FTy =
  211. cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
  212. assert(getNumOperands() == 1 && "NumOperands not set up?");
  213. Op<-1>() = Func;
  214. assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
  215. setName(NameStr);
  216. }
  217. CallInst::CallInst(Value *Func, const Twine &Name,
  218. Instruction *InsertBefore)
  219. : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
  220. ->getElementType())->getReturnType(),
  221. Instruction::Call,
  222. OperandTraits<CallInst>::op_end(this) - 1,
  223. 1, InsertBefore) {
  224. init(Func, Name);
  225. }
  226. CallInst::CallInst(Value *Func, const Twine &Name,
  227. BasicBlock *InsertAtEnd)
  228. : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
  229. ->getElementType())->getReturnType(),
  230. Instruction::Call,
  231. OperandTraits<CallInst>::op_end(this) - 1,
  232. 1, InsertAtEnd) {
  233. init(Func, Name);
  234. }
  235. CallInst::CallInst(const CallInst &CI)
  236. : Instruction(CI.getType(), Instruction::Call,
  237. OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
  238. CI.getNumOperands()),
  239. AttributeList(CI.AttributeList), FTy(CI.FTy) {
  240. setTailCallKind(CI.getTailCallKind());
  241. setCallingConv(CI.getCallingConv());
  242. std::copy(CI.op_begin(), CI.op_end(), op_begin());
  243. SubclassOptionalData = CI.SubclassOptionalData;
  244. }
  245. void CallInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
  246. AttributeSet PAL = getAttributes();
  247. PAL = PAL.addAttribute(getContext(), i, attr);
  248. setAttributes(PAL);
  249. }
  250. void CallInst::addAttribute(unsigned i, StringRef Kind, StringRef Value) {
  251. AttributeSet PAL = getAttributes();
  252. PAL = PAL.addAttribute(getContext(), i, Kind, Value);
  253. setAttributes(PAL);
  254. }
  255. void CallInst::removeAttribute(unsigned i, Attribute attr) {
  256. AttributeSet PAL = getAttributes();
  257. AttrBuilder B(attr);
  258. LLVMContext &Context = getContext();
  259. PAL = PAL.removeAttributes(Context, i,
  260. AttributeSet::get(Context, i, B));
  261. setAttributes(PAL);
  262. }
  263. void CallInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
  264. AttributeSet PAL = getAttributes();
  265. PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
  266. setAttributes(PAL);
  267. }
  268. void CallInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
  269. AttributeSet PAL = getAttributes();
  270. PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
  271. setAttributes(PAL);
  272. }
  273. bool CallInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
  274. if (AttributeList.hasAttribute(i, A))
  275. return true;
  276. if (const Function *F = getCalledFunction())
  277. return F->getAttributes().hasAttribute(i, A);
  278. return false;
  279. }
  280. /// IsConstantOne - Return true only if val is constant int 1
  281. static bool IsConstantOne(Value *val) {
  282. assert(val && "IsConstantOne does not work with nullptr val");
  283. const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
  284. return CVal && CVal->isOne();
  285. }
  286. static Instruction *createMalloc(Instruction *InsertBefore,
  287. BasicBlock *InsertAtEnd, Type *IntPtrTy,
  288. Type *AllocTy, Value *AllocSize,
  289. Value *ArraySize, Function *MallocF,
  290. const Twine &Name) {
  291. assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
  292. "createMalloc needs either InsertBefore or InsertAtEnd");
  293. // malloc(type) becomes:
  294. // bitcast (i8* malloc(typeSize)) to type*
  295. // malloc(type, arraySize) becomes:
  296. // bitcast (i8 *malloc(typeSize*arraySize)) to type*
  297. if (!ArraySize)
  298. ArraySize = ConstantInt::get(IntPtrTy, 1);
  299. else if (ArraySize->getType() != IntPtrTy) {
  300. if (InsertBefore)
  301. ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
  302. "", InsertBefore);
  303. else
  304. ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
  305. "", InsertAtEnd);
  306. }
  307. if (!IsConstantOne(ArraySize)) {
  308. if (IsConstantOne(AllocSize)) {
  309. AllocSize = ArraySize; // Operand * 1 = Operand
  310. } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
  311. Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
  312. false /*ZExt*/);
  313. // Malloc arg is constant product of type size and array size
  314. AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
  315. } else {
  316. // Multiply type size by the array size...
  317. if (InsertBefore)
  318. AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
  319. "mallocsize", InsertBefore);
  320. else
  321. AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
  322. "mallocsize", InsertAtEnd);
  323. }
  324. }
  325. assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
  326. // Create the call to Malloc.
  327. BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
  328. Module* M = BB->getParent()->getParent();
  329. Type *BPTy = Type::getInt8PtrTy(BB->getContext());
  330. Value *MallocFunc = MallocF;
  331. if (!MallocFunc)
  332. // prototype malloc as "void *malloc(size_t)"
  333. MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, nullptr);
  334. PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
  335. CallInst *MCall = nullptr;
  336. Instruction *Result = nullptr;
  337. if (InsertBefore) {
  338. MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
  339. Result = MCall;
  340. if (Result->getType() != AllocPtrType)
  341. // Create a cast instruction to convert to the right type...
  342. Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
  343. } else {
  344. MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
  345. Result = MCall;
  346. if (Result->getType() != AllocPtrType) {
  347. InsertAtEnd->getInstList().push_back(MCall);
  348. // Create a cast instruction to convert to the right type...
  349. Result = new BitCastInst(MCall, AllocPtrType, Name);
  350. }
  351. }
  352. MCall->setTailCall();
  353. if (Function *F = dyn_cast<Function>(MallocFunc)) {
  354. MCall->setCallingConv(F->getCallingConv());
  355. if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
  356. }
  357. assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
  358. return Result;
  359. }
  360. /// CreateMalloc - Generate the IR for a call to malloc:
  361. /// 1. Compute the malloc call's argument as the specified type's size,
  362. /// possibly multiplied by the array size if the array size is not
  363. /// constant 1.
  364. /// 2. Call malloc with that argument.
  365. /// 3. Bitcast the result of the malloc call to the specified type.
  366. Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
  367. Type *IntPtrTy, Type *AllocTy,
  368. Value *AllocSize, Value *ArraySize,
  369. Function * MallocF,
  370. const Twine &Name) {
  371. return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
  372. ArraySize, MallocF, Name);
  373. }
  374. /// CreateMalloc - Generate the IR for a call to malloc:
  375. /// 1. Compute the malloc call's argument as the specified type's size,
  376. /// possibly multiplied by the array size if the array size is not
  377. /// constant 1.
  378. /// 2. Call malloc with that argument.
  379. /// 3. Bitcast the result of the malloc call to the specified type.
  380. /// Note: This function does not add the bitcast to the basic block, that is the
  381. /// responsibility of the caller.
  382. Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
  383. Type *IntPtrTy, Type *AllocTy,
  384. Value *AllocSize, Value *ArraySize,
  385. Function *MallocF, const Twine &Name) {
  386. return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
  387. ArraySize, MallocF, Name);
  388. }
  389. static Instruction* createFree(Value* Source, Instruction *InsertBefore,
  390. BasicBlock *InsertAtEnd) {
  391. assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
  392. "createFree needs either InsertBefore or InsertAtEnd");
  393. assert(Source->getType()->isPointerTy() &&
  394. "Can not free something of nonpointer type!");
  395. BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
  396. Module* M = BB->getParent()->getParent();
  397. Type *VoidTy = Type::getVoidTy(M->getContext());
  398. Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
  399. // prototype free as "void free(void*)"
  400. Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, nullptr);
  401. CallInst* Result = nullptr;
  402. Value *PtrCast = Source;
  403. if (InsertBefore) {
  404. if (Source->getType() != IntPtrTy)
  405. PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
  406. Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
  407. } else {
  408. if (Source->getType() != IntPtrTy)
  409. PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
  410. Result = CallInst::Create(FreeFunc, PtrCast, "");
  411. }
  412. Result->setTailCall();
  413. if (Function *F = dyn_cast<Function>(FreeFunc))
  414. Result->setCallingConv(F->getCallingConv());
  415. return Result;
  416. }
  417. /// CreateFree - Generate the IR for a call to the builtin free function.
  418. Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
  419. return createFree(Source, InsertBefore, nullptr);
  420. }
  421. /// CreateFree - Generate the IR for a call to the builtin free function.
  422. /// Note: This function does not add the call to the basic block, that is the
  423. /// responsibility of the caller.
  424. Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
  425. Instruction* FreeCall = createFree(Source, nullptr, InsertAtEnd);
  426. assert(FreeCall && "CreateFree did not create a CallInst");
  427. return FreeCall;
  428. }
  429. //===----------------------------------------------------------------------===//
  430. // InvokeInst Implementation
  431. //===----------------------------------------------------------------------===//
  432. void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
  433. BasicBlock *IfException, ArrayRef<Value *> Args,
  434. const Twine &NameStr) {
  435. this->FTy = FTy;
  436. assert(getNumOperands() == 3 + Args.size() && "NumOperands not set up?");
  437. Op<-3>() = Fn;
  438. Op<-2>() = IfNormal;
  439. Op<-1>() = IfException;
  440. #ifndef NDEBUG
  441. assert(((Args.size() == FTy->getNumParams()) ||
  442. (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
  443. "Invoking a function with bad signature");
  444. for (unsigned i = 0, e = Args.size(); i != e; i++)
  445. assert((i >= FTy->getNumParams() ||
  446. FTy->getParamType(i) == Args[i]->getType()) &&
  447. "Invoking a function with a bad signature!");
  448. #endif
  449. std::copy(Args.begin(), Args.end(), op_begin());
  450. setName(NameStr);
  451. }
  452. InvokeInst::InvokeInst(const InvokeInst &II)
  453. : TerminatorInst(II.getType(), Instruction::Invoke,
  454. OperandTraits<InvokeInst>::op_end(this) -
  455. II.getNumOperands(),
  456. II.getNumOperands()),
  457. AttributeList(II.AttributeList), FTy(II.FTy) {
  458. setCallingConv(II.getCallingConv());
  459. std::copy(II.op_begin(), II.op_end(), op_begin());
  460. SubclassOptionalData = II.SubclassOptionalData;
  461. }
  462. BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
  463. return getSuccessor(idx);
  464. }
  465. unsigned InvokeInst::getNumSuccessorsV() const {
  466. return getNumSuccessors();
  467. }
  468. void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
  469. return setSuccessor(idx, B);
  470. }
  471. bool InvokeInst::hasFnAttrImpl(Attribute::AttrKind A) const {
  472. if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
  473. return true;
  474. if (const Function *F = getCalledFunction())
  475. return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
  476. return false;
  477. }
  478. bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
  479. if (AttributeList.hasAttribute(i, A))
  480. return true;
  481. if (const Function *F = getCalledFunction())
  482. return F->getAttributes().hasAttribute(i, A);
  483. return false;
  484. }
  485. void InvokeInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
  486. AttributeSet PAL = getAttributes();
  487. PAL = PAL.addAttribute(getContext(), i, attr);
  488. setAttributes(PAL);
  489. }
  490. void InvokeInst::removeAttribute(unsigned i, Attribute attr) {
  491. AttributeSet PAL = getAttributes();
  492. AttrBuilder B(attr);
  493. PAL = PAL.removeAttributes(getContext(), i,
  494. AttributeSet::get(getContext(), i, B));
  495. setAttributes(PAL);
  496. }
  497. void InvokeInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
  498. AttributeSet PAL = getAttributes();
  499. PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
  500. setAttributes(PAL);
  501. }
  502. void InvokeInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
  503. AttributeSet PAL = getAttributes();
  504. PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
  505. setAttributes(PAL);
  506. }
  507. LandingPadInst *InvokeInst::getLandingPadInst() const {
  508. return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
  509. }
  510. //===----------------------------------------------------------------------===//
  511. // ReturnInst Implementation
  512. //===----------------------------------------------------------------------===//
  513. ReturnInst::ReturnInst(const ReturnInst &RI)
  514. : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
  515. OperandTraits<ReturnInst>::op_end(this) -
  516. RI.getNumOperands(),
  517. RI.getNumOperands()) {
  518. if (RI.getNumOperands())
  519. Op<0>() = RI.Op<0>();
  520. SubclassOptionalData = RI.SubclassOptionalData;
  521. }
  522. ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
  523. : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
  524. OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
  525. InsertBefore) {
  526. if (retVal)
  527. Op<0>() = retVal;
  528. }
  529. ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
  530. : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
  531. OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
  532. InsertAtEnd) {
  533. if (retVal)
  534. Op<0>() = retVal;
  535. }
  536. ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
  537. : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
  538. OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
  539. }
  540. unsigned ReturnInst::getNumSuccessorsV() const {
  541. return getNumSuccessors();
  542. }
  543. /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
  544. /// emit the vtable for the class in this translation unit.
  545. void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
  546. llvm_unreachable("ReturnInst has no successors!");
  547. }
  548. BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
  549. llvm_unreachable("ReturnInst has no successors!");
  550. }
  551. ReturnInst::~ReturnInst() {
  552. }
  553. //===----------------------------------------------------------------------===//
  554. // ResumeInst Implementation
  555. //===----------------------------------------------------------------------===//
  556. ResumeInst::ResumeInst(const ResumeInst &RI)
  557. : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
  558. OperandTraits<ResumeInst>::op_begin(this), 1) {
  559. Op<0>() = RI.Op<0>();
  560. }
  561. ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
  562. : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
  563. OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
  564. Op<0>() = Exn;
  565. }
  566. ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
  567. : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
  568. OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
  569. Op<0>() = Exn;
  570. }
  571. unsigned ResumeInst::getNumSuccessorsV() const {
  572. return getNumSuccessors();
  573. }
  574. void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
  575. llvm_unreachable("ResumeInst has no successors!");
  576. }
  577. BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
  578. llvm_unreachable("ResumeInst has no successors!");
  579. }
  580. //===----------------------------------------------------------------------===//
  581. // UnreachableInst Implementation
  582. //===----------------------------------------------------------------------===//
  583. UnreachableInst::UnreachableInst(LLVMContext &Context,
  584. Instruction *InsertBefore)
  585. : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
  586. nullptr, 0, InsertBefore) {
  587. }
  588. UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
  589. : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
  590. nullptr, 0, InsertAtEnd) {
  591. }
  592. unsigned UnreachableInst::getNumSuccessorsV() const {
  593. return getNumSuccessors();
  594. }
  595. void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
  596. llvm_unreachable("UnreachableInst has no successors!");
  597. }
  598. BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
  599. llvm_unreachable("UnreachableInst has no successors!");
  600. }
  601. //===----------------------------------------------------------------------===//
  602. // BranchInst Implementation
  603. //===----------------------------------------------------------------------===//
  604. void BranchInst::AssertOK() {
  605. if (isConditional())
  606. assert(getCondition()->getType()->isIntegerTy(1) &&
  607. "May only branch on boolean predicates!");
  608. }
  609. BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
  610. : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
  611. OperandTraits<BranchInst>::op_end(this) - 1,
  612. 1, InsertBefore) {
  613. assert(IfTrue && "Branch destination may not be null!");
  614. Op<-1>() = IfTrue;
  615. }
  616. BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
  617. Instruction *InsertBefore)
  618. : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
  619. OperandTraits<BranchInst>::op_end(this) - 3,
  620. 3, InsertBefore) {
  621. Op<-1>() = IfTrue;
  622. Op<-2>() = IfFalse;
  623. Op<-3>() = Cond;
  624. #ifndef NDEBUG
  625. AssertOK();
  626. #endif
  627. }
  628. BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
  629. : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
  630. OperandTraits<BranchInst>::op_end(this) - 1,
  631. 1, InsertAtEnd) {
  632. assert(IfTrue && "Branch destination may not be null!");
  633. Op<-1>() = IfTrue;
  634. }
  635. BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
  636. BasicBlock *InsertAtEnd)
  637. : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
  638. OperandTraits<BranchInst>::op_end(this) - 3,
  639. 3, InsertAtEnd) {
  640. Op<-1>() = IfTrue;
  641. Op<-2>() = IfFalse;
  642. Op<-3>() = Cond;
  643. #ifndef NDEBUG
  644. AssertOK();
  645. #endif
  646. }
  647. BranchInst::BranchInst(const BranchInst &BI) :
  648. TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
  649. OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
  650. BI.getNumOperands()) {
  651. Op<-1>() = BI.Op<-1>();
  652. if (BI.getNumOperands() != 1) {
  653. assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
  654. Op<-3>() = BI.Op<-3>();
  655. Op<-2>() = BI.Op<-2>();
  656. }
  657. SubclassOptionalData = BI.SubclassOptionalData;
  658. }
  659. void BranchInst::swapSuccessors() {
  660. assert(isConditional() &&
  661. "Cannot swap successors of an unconditional branch");
  662. Op<-1>().swap(Op<-2>());
  663. // Update profile metadata if present and it matches our structural
  664. // expectations.
  665. MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
  666. if (!ProfileData || ProfileData->getNumOperands() != 3)
  667. return;
  668. // The first operand is the name. Fetch them backwards and build a new one.
  669. Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2),
  670. ProfileData->getOperand(1)};
  671. setMetadata(LLVMContext::MD_prof,
  672. MDNode::get(ProfileData->getContext(), Ops));
  673. }
  674. BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
  675. return getSuccessor(idx);
  676. }
  677. unsigned BranchInst::getNumSuccessorsV() const {
  678. return getNumSuccessors();
  679. }
  680. void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
  681. setSuccessor(idx, B);
  682. }
  683. //===----------------------------------------------------------------------===//
  684. // AllocaInst Implementation
  685. //===----------------------------------------------------------------------===//
  686. static Value *getAISize(LLVMContext &Context, Value *Amt) {
  687. if (!Amt)
  688. Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
  689. else {
  690. assert(!isa<BasicBlock>(Amt) &&
  691. "Passed basic block into allocation size parameter! Use other ctor");
  692. assert(Amt->getType()->isIntegerTy() &&
  693. "Allocation array size is not an integer!");
  694. }
  695. return Amt;
  696. }
  697. AllocaInst::AllocaInst(Type *Ty, const Twine &Name, Instruction *InsertBefore)
  698. : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertBefore) {}
  699. AllocaInst::AllocaInst(Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd)
  700. : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertAtEnd) {}
  701. AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name,
  702. Instruction *InsertBefore)
  703. : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertBefore) {}
  704. AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name,
  705. BasicBlock *InsertAtEnd)
  706. : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertAtEnd) {}
  707. AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
  708. const Twine &Name, Instruction *InsertBefore)
  709. : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
  710. getAISize(Ty->getContext(), ArraySize), InsertBefore),
  711. AllocatedType(Ty) {
  712. setAlignment(Align);
  713. assert(!Ty->isVoidTy() && "Cannot allocate void!");
  714. setName(Name);
  715. }
  716. AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
  717. const Twine &Name, BasicBlock *InsertAtEnd)
  718. : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
  719. getAISize(Ty->getContext(), ArraySize), InsertAtEnd),
  720. AllocatedType(Ty) {
  721. setAlignment(Align);
  722. assert(!Ty->isVoidTy() && "Cannot allocate void!");
  723. setName(Name);
  724. }
  725. // Out of line virtual method, so the vtable, etc has a home.
  726. AllocaInst::~AllocaInst() {
  727. }
  728. void AllocaInst::setAlignment(unsigned Align) {
  729. assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
  730. assert(Align <= MaximumAlignment &&
  731. "Alignment is greater than MaximumAlignment!");
  732. setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
  733. (Log2_32(Align) + 1));
  734. assert(getAlignment() == Align && "Alignment representation error!");
  735. }
  736. bool AllocaInst::isArrayAllocation() const {
  737. if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
  738. return !CI->isOne();
  739. return true;
  740. }
  741. /// isStaticAlloca - Return true if this alloca is in the entry block of the
  742. /// function and is a constant size. If so, the code generator will fold it
  743. /// into the prolog/epilog code, so it is basically free.
  744. bool AllocaInst::isStaticAlloca() const {
  745. // Must be constant size.
  746. if (!isa<ConstantInt>(getArraySize())) return false;
  747. // Must be in the entry block.
  748. const BasicBlock *Parent = getParent();
  749. return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
  750. }
  751. //===----------------------------------------------------------------------===//
  752. // LoadInst Implementation
  753. //===----------------------------------------------------------------------===//
  754. void LoadInst::AssertOK() {
  755. assert(getOperand(0)->getType()->isPointerTy() &&
  756. "Ptr must have pointer type.");
  757. assert(!(isAtomic() && getAlignment() == 0) &&
  758. "Alignment required for atomic load");
  759. }
  760. LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
  761. : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertBef) {}
  762. LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
  763. : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertAE) {}
  764. LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
  765. Instruction *InsertBef)
  766. : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/0, InsertBef) {}
  767. LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
  768. BasicBlock *InsertAE)
  769. : LoadInst(Ptr, Name, isVolatile, /*Align=*/0, InsertAE) {}
  770. LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
  771. unsigned Align, Instruction *InsertBef)
  772. : LoadInst(Ty, Ptr, Name, isVolatile, Align, NotAtomic, CrossThread,
  773. InsertBef) {}
  774. LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
  775. unsigned Align, BasicBlock *InsertAE)
  776. : LoadInst(Ptr, Name, isVolatile, Align, NotAtomic, CrossThread, InsertAE) {
  777. }
  778. LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
  779. unsigned Align, AtomicOrdering Order,
  780. SynchronizationScope SynchScope, Instruction *InsertBef)
  781. : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
  782. assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
  783. setVolatile(isVolatile);
  784. setAlignment(Align);
  785. setAtomic(Order, SynchScope);
  786. AssertOK();
  787. setName(Name);
  788. }
  789. LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
  790. unsigned Align, AtomicOrdering Order,
  791. SynchronizationScope SynchScope,
  792. BasicBlock *InsertAE)
  793. : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
  794. Load, Ptr, InsertAE) {
  795. setVolatile(isVolatile);
  796. setAlignment(Align);
  797. setAtomic(Order, SynchScope);
  798. AssertOK();
  799. setName(Name);
  800. }
  801. LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
  802. : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
  803. Load, Ptr, InsertBef) {
  804. setVolatile(false);
  805. setAlignment(0);
  806. setAtomic(NotAtomic);
  807. AssertOK();
  808. if (Name && Name[0]) setName(Name);
  809. }
  810. LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
  811. : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
  812. Load, Ptr, InsertAE) {
  813. setVolatile(false);
  814. setAlignment(0);
  815. setAtomic(NotAtomic);
  816. AssertOK();
  817. if (Name && Name[0]) setName(Name);
  818. }
  819. LoadInst::LoadInst(Type *Ty, Value *Ptr, const char *Name, bool isVolatile,
  820. Instruction *InsertBef)
  821. : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
  822. assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
  823. setVolatile(isVolatile);
  824. setAlignment(0);
  825. setAtomic(NotAtomic);
  826. AssertOK();
  827. if (Name && Name[0]) setName(Name);
  828. }
  829. LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
  830. BasicBlock *InsertAE)
  831. : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
  832. Load, Ptr, InsertAE) {
  833. setVolatile(isVolatile);
  834. setAlignment(0);
  835. setAtomic(NotAtomic);
  836. AssertOK();
  837. if (Name && Name[0]) setName(Name);
  838. }
  839. void LoadInst::setAlignment(unsigned Align) {
  840. assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
  841. assert(Align <= MaximumAlignment &&
  842. "Alignment is greater than MaximumAlignment!");
  843. setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
  844. ((Log2_32(Align)+1)<<1));
  845. assert(getAlignment() == Align && "Alignment representation error!");
  846. }
  847. //===----------------------------------------------------------------------===//
  848. // StoreInst Implementation
  849. //===----------------------------------------------------------------------===//
  850. void StoreInst::AssertOK() {
  851. assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
  852. assert(getOperand(1)->getType()->isPointerTy() &&
  853. "Ptr must have pointer type!");
  854. assert(getOperand(0)->getType() ==
  855. cast<PointerType>(getOperand(1)->getType())->getElementType()
  856. && "Ptr must be a pointer to Val type!");
  857. assert(!(isAtomic() && getAlignment() == 0) &&
  858. "Alignment required for atomic store");
  859. }
  860. StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
  861. : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
  862. StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
  863. : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {}
  864. StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
  865. Instruction *InsertBefore)
  866. : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertBefore) {}
  867. StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
  868. BasicBlock *InsertAtEnd)
  869. : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertAtEnd) {}
  870. StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
  871. Instruction *InsertBefore)
  872. : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread,
  873. InsertBefore) {}
  874. StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
  875. BasicBlock *InsertAtEnd)
  876. : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread,
  877. InsertAtEnd) {}
  878. StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
  879. unsigned Align, AtomicOrdering Order,
  880. SynchronizationScope SynchScope,
  881. Instruction *InsertBefore)
  882. : Instruction(Type::getVoidTy(val->getContext()), Store,
  883. OperandTraits<StoreInst>::op_begin(this),
  884. OperandTraits<StoreInst>::operands(this),
  885. InsertBefore) {
  886. Op<0>() = val;
  887. Op<1>() = addr;
  888. setVolatile(isVolatile);
  889. setAlignment(Align);
  890. setAtomic(Order, SynchScope);
  891. AssertOK();
  892. }
  893. StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
  894. unsigned Align, AtomicOrdering Order,
  895. SynchronizationScope SynchScope,
  896. BasicBlock *InsertAtEnd)
  897. : Instruction(Type::getVoidTy(val->getContext()), Store,
  898. OperandTraits<StoreInst>::op_begin(this),
  899. OperandTraits<StoreInst>::operands(this),
  900. InsertAtEnd) {
  901. Op<0>() = val;
  902. Op<1>() = addr;
  903. setVolatile(isVolatile);
  904. setAlignment(Align);
  905. setAtomic(Order, SynchScope);
  906. AssertOK();
  907. }
  908. void StoreInst::setAlignment(unsigned Align) {
  909. assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
  910. assert(Align <= MaximumAlignment &&
  911. "Alignment is greater than MaximumAlignment!");
  912. setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
  913. ((Log2_32(Align)+1) << 1));
  914. assert(getAlignment() == Align && "Alignment representation error!");
  915. }
  916. //===----------------------------------------------------------------------===//
  917. // AtomicCmpXchgInst Implementation
  918. //===----------------------------------------------------------------------===//
  919. void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
  920. AtomicOrdering SuccessOrdering,
  921. AtomicOrdering FailureOrdering,
  922. SynchronizationScope SynchScope) {
  923. Op<0>() = Ptr;
  924. Op<1>() = Cmp;
  925. Op<2>() = NewVal;
  926. setSuccessOrdering(SuccessOrdering);
  927. setFailureOrdering(FailureOrdering);
  928. setSynchScope(SynchScope);
  929. assert(getOperand(0) && getOperand(1) && getOperand(2) &&
  930. "All operands must be non-null!");
  931. assert(getOperand(0)->getType()->isPointerTy() &&
  932. "Ptr must have pointer type!");
  933. assert(getOperand(1)->getType() ==
  934. cast<PointerType>(getOperand(0)->getType())->getElementType()
  935. && "Ptr must be a pointer to Cmp type!");
  936. assert(getOperand(2)->getType() ==
  937. cast<PointerType>(getOperand(0)->getType())->getElementType()
  938. && "Ptr must be a pointer to NewVal type!");
  939. assert(SuccessOrdering != NotAtomic &&
  940. "AtomicCmpXchg instructions must be atomic!");
  941. assert(FailureOrdering != NotAtomic &&
  942. "AtomicCmpXchg instructions must be atomic!");
  943. assert(SuccessOrdering >= FailureOrdering &&
  944. "AtomicCmpXchg success ordering must be at least as strong as fail");
  945. assert(FailureOrdering != Release && FailureOrdering != AcquireRelease &&
  946. "AtomicCmpXchg failure ordering cannot include release semantics");
  947. }
  948. AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
  949. AtomicOrdering SuccessOrdering,
  950. AtomicOrdering FailureOrdering,
  951. SynchronizationScope SynchScope,
  952. Instruction *InsertBefore)
  953. : Instruction(
  954. StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
  955. nullptr),
  956. AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
  957. OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
  958. Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
  959. }
  960. AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
  961. AtomicOrdering SuccessOrdering,
  962. AtomicOrdering FailureOrdering,
  963. SynchronizationScope SynchScope,
  964. BasicBlock *InsertAtEnd)
  965. : Instruction(
  966. StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
  967. nullptr),
  968. AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
  969. OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
  970. Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
  971. }
  972. //===----------------------------------------------------------------------===//
  973. // AtomicRMWInst Implementation
  974. //===----------------------------------------------------------------------===//
  975. void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
  976. AtomicOrdering Ordering,
  977. SynchronizationScope SynchScope) {
  978. Op<0>() = Ptr;
  979. Op<1>() = Val;
  980. setOperation(Operation);
  981. setOrdering(Ordering);
  982. setSynchScope(SynchScope);
  983. assert(getOperand(0) && getOperand(1) &&
  984. "All operands must be non-null!");
  985. assert(getOperand(0)->getType()->isPointerTy() &&
  986. "Ptr must have pointer type!");
  987. assert(getOperand(1)->getType() ==
  988. cast<PointerType>(getOperand(0)->getType())->getElementType()
  989. && "Ptr must be a pointer to Val type!");
  990. assert(Ordering != NotAtomic &&
  991. "AtomicRMW instructions must be atomic!");
  992. }
  993. AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
  994. AtomicOrdering Ordering,
  995. SynchronizationScope SynchScope,
  996. Instruction *InsertBefore)
  997. : Instruction(Val->getType(), AtomicRMW,
  998. OperandTraits<AtomicRMWInst>::op_begin(this),
  999. OperandTraits<AtomicRMWInst>::operands(this),
  1000. InsertBefore) {
  1001. Init(Operation, Ptr, Val, Ordering, SynchScope);
  1002. }
  1003. AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
  1004. AtomicOrdering Ordering,
  1005. SynchronizationScope SynchScope,
  1006. BasicBlock *InsertAtEnd)
  1007. : Instruction(Val->getType(), AtomicRMW,
  1008. OperandTraits<AtomicRMWInst>::op_begin(this),
  1009. OperandTraits<AtomicRMWInst>::operands(this),
  1010. InsertAtEnd) {
  1011. Init(Operation, Ptr, Val, Ordering, SynchScope);
  1012. }
  1013. //===----------------------------------------------------------------------===//
  1014. // FenceInst Implementation
  1015. //===----------------------------------------------------------------------===//
  1016. FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
  1017. SynchronizationScope SynchScope,
  1018. Instruction *InsertBefore)
  1019. : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
  1020. setOrdering(Ordering);
  1021. setSynchScope(SynchScope);
  1022. }
  1023. FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
  1024. SynchronizationScope SynchScope,
  1025. BasicBlock *InsertAtEnd)
  1026. : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
  1027. setOrdering(Ordering);
  1028. setSynchScope(SynchScope);
  1029. }
  1030. //===----------------------------------------------------------------------===//
  1031. // GetElementPtrInst Implementation
  1032. //===----------------------------------------------------------------------===//
  1033. void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
  1034. const Twine &Name) {
  1035. assert(getNumOperands() == 1 + IdxList.size() &&
  1036. "NumOperands not initialized?");
  1037. Op<0>() = Ptr;
  1038. std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
  1039. setName(Name);
  1040. }
  1041. GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
  1042. : Instruction(GEPI.getType(), GetElementPtr,
  1043. OperandTraits<GetElementPtrInst>::op_end(this) -
  1044. GEPI.getNumOperands(),
  1045. GEPI.getNumOperands()),
  1046. SourceElementType(GEPI.SourceElementType),
  1047. ResultElementType(GEPI.ResultElementType) {
  1048. std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
  1049. SubclassOptionalData = GEPI.SubclassOptionalData;
  1050. }
  1051. /// getIndexedType - Returns the type of the element that would be accessed with
  1052. /// a gep instruction with the specified parameters.
  1053. ///
  1054. /// The Idxs pointer should point to a continuous piece of memory containing the
  1055. /// indices, either as Value* or uint64_t.
  1056. ///
  1057. /// A null type is returned if the indices are invalid for the specified
  1058. /// pointer type.
  1059. ///
  1060. template <typename IndexTy>
  1061. static Type *getIndexedTypeInternal(Type *Agg, ArrayRef<IndexTy> IdxList) {
  1062. // Handle the special case of the empty set index set, which is always valid.
  1063. if (IdxList.empty())
  1064. return Agg;
  1065. // If there is at least one index, the top level type must be sized, otherwise
  1066. // it cannot be 'stepped over'.
  1067. if (!Agg->isSized())
  1068. return nullptr;
  1069. unsigned CurIdx = 1;
  1070. for (; CurIdx != IdxList.size(); ++CurIdx) {
  1071. CompositeType *CT = dyn_cast<CompositeType>(Agg);
  1072. if (!CT || CT->isPointerTy()) return nullptr;
  1073. IndexTy Index = IdxList[CurIdx];
  1074. if (!CT->indexValid(Index)) return nullptr;
  1075. Agg = CT->getTypeAtIndex(Index);
  1076. }
  1077. return CurIdx == IdxList.size() ? Agg : nullptr;
  1078. }
  1079. Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) {
  1080. return getIndexedTypeInternal(Ty, IdxList);
  1081. }
  1082. Type *GetElementPtrInst::getIndexedType(Type *Ty,
  1083. ArrayRef<Constant *> IdxList) {
  1084. return getIndexedTypeInternal(Ty, IdxList);
  1085. }
  1086. Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) {
  1087. return getIndexedTypeInternal(Ty, IdxList);
  1088. }
  1089. /// hasAllZeroIndices - Return true if all of the indices of this GEP are
  1090. /// zeros. If so, the result pointer and the first operand have the same
  1091. /// value, just potentially different types.
  1092. bool GetElementPtrInst::hasAllZeroIndices() const {
  1093. for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
  1094. if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
  1095. if (!CI->isZero()) return false;
  1096. } else {
  1097. return false;
  1098. }
  1099. }
  1100. return true;
  1101. }
  1102. /// hasAllConstantIndices - Return true if all of the indices of this GEP are
  1103. /// constant integers. If so, the result pointer and the first operand have
  1104. /// a constant offset between them.
  1105. bool GetElementPtrInst::hasAllConstantIndices() const {
  1106. for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
  1107. if (!isa<ConstantInt>(getOperand(i)))
  1108. return false;
  1109. }
  1110. return true;
  1111. }
  1112. void GetElementPtrInst::setIsInBounds(bool B) {
  1113. cast<GEPOperator>(this)->setIsInBounds(B);
  1114. }
  1115. bool GetElementPtrInst::isInBounds() const {
  1116. return cast<GEPOperator>(this)->isInBounds();
  1117. }
  1118. bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
  1119. APInt &Offset) const {
  1120. // Delegate to the generic GEPOperator implementation.
  1121. return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
  1122. }
  1123. //===----------------------------------------------------------------------===//
  1124. // ExtractElementInst Implementation
  1125. //===----------------------------------------------------------------------===//
  1126. ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
  1127. const Twine &Name,
  1128. Instruction *InsertBef)
  1129. : Instruction(cast<VectorType>(Val->getType())->getElementType(),
  1130. ExtractElement,
  1131. OperandTraits<ExtractElementInst>::op_begin(this),
  1132. 2, InsertBef) {
  1133. assert(isValidOperands(Val, Index) &&
  1134. "Invalid extractelement instruction operands!");
  1135. Op<0>() = Val;
  1136. Op<1>() = Index;
  1137. setName(Name);
  1138. }
  1139. ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
  1140. const Twine &Name,
  1141. BasicBlock *InsertAE)
  1142. : Instruction(cast<VectorType>(Val->getType())->getElementType(),
  1143. ExtractElement,
  1144. OperandTraits<ExtractElementInst>::op_begin(this),
  1145. 2, InsertAE) {
  1146. assert(isValidOperands(Val, Index) &&
  1147. "Invalid extractelement instruction operands!");
  1148. Op<0>() = Val;
  1149. Op<1>() = Index;
  1150. setName(Name);
  1151. }
  1152. bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
  1153. if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
  1154. return false;
  1155. return true;
  1156. }
  1157. //===----------------------------------------------------------------------===//
  1158. // InsertElementInst Implementation
  1159. //===----------------------------------------------------------------------===//
  1160. InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
  1161. const Twine &Name,
  1162. Instruction *InsertBef)
  1163. : Instruction(Vec->getType(), InsertElement,
  1164. OperandTraits<InsertElementInst>::op_begin(this),
  1165. 3, InsertBef) {
  1166. assert(isValidOperands(Vec, Elt, Index) &&
  1167. "Invalid insertelement instruction operands!");
  1168. Op<0>() = Vec;
  1169. Op<1>() = Elt;
  1170. Op<2>() = Index;
  1171. setName(Name);
  1172. }
  1173. InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
  1174. const Twine &Name,
  1175. BasicBlock *InsertAE)
  1176. : Instruction(Vec->getType(), InsertElement,
  1177. OperandTraits<InsertElementInst>::op_begin(this),
  1178. 3, InsertAE) {
  1179. assert(isValidOperands(Vec, Elt, Index) &&
  1180. "Invalid insertelement instruction operands!");
  1181. Op<0>() = Vec;
  1182. Op<1>() = Elt;
  1183. Op<2>() = Index;
  1184. setName(Name);
  1185. }
  1186. bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
  1187. const Value *Index) {
  1188. if (!Vec->getType()->isVectorTy())
  1189. return false; // First operand of insertelement must be vector type.
  1190. if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
  1191. return false;// Second operand of insertelement must be vector element type.
  1192. if (!Index->getType()->isIntegerTy())
  1193. return false; // Third operand of insertelement must be i32.
  1194. return true;
  1195. }
  1196. //===----------------------------------------------------------------------===//
  1197. // ShuffleVectorInst Implementation
  1198. //===----------------------------------------------------------------------===//
  1199. ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
  1200. const Twine &Name,
  1201. Instruction *InsertBefore)
  1202. : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
  1203. cast<VectorType>(Mask->getType())->getNumElements()),
  1204. ShuffleVector,
  1205. OperandTraits<ShuffleVectorInst>::op_begin(this),
  1206. OperandTraits<ShuffleVectorInst>::operands(this),
  1207. InsertBefore) {
  1208. assert(isValidOperands(V1, V2, Mask) &&
  1209. "Invalid shuffle vector instruction operands!");
  1210. Op<0>() = V1;
  1211. Op<1>() = V2;
  1212. Op<2>() = Mask;
  1213. setName(Name);
  1214. }
  1215. ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
  1216. const Twine &Name,
  1217. BasicBlock *InsertAtEnd)
  1218. : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
  1219. cast<VectorType>(Mask->getType())->getNumElements()),
  1220. ShuffleVector,
  1221. OperandTraits<ShuffleVectorInst>::op_begin(this),
  1222. OperandTraits<ShuffleVectorInst>::operands(this),
  1223. InsertAtEnd) {
  1224. assert(isValidOperands(V1, V2, Mask) &&
  1225. "Invalid shuffle vector instruction operands!");
  1226. Op<0>() = V1;
  1227. Op<1>() = V2;
  1228. Op<2>() = Mask;
  1229. setName(Name);
  1230. }
  1231. bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
  1232. const Value *Mask) {
  1233. // V1 and V2 must be vectors of the same type.
  1234. if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
  1235. return false;
  1236. // Mask must be vector of i32.
  1237. VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
  1238. if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32))
  1239. return false;
  1240. // Check to see if Mask is valid.
  1241. if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
  1242. return true;
  1243. if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
  1244. unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
  1245. for (Value *Op : MV->operands()) {
  1246. if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
  1247. if (CI->uge(V1Size*2))
  1248. return false;
  1249. } else if (!isa<UndefValue>(Op)) {
  1250. return false;
  1251. }
  1252. }
  1253. return true;
  1254. }
  1255. if (const ConstantDataSequential *CDS =
  1256. dyn_cast<ConstantDataSequential>(Mask)) {
  1257. unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
  1258. for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
  1259. if (CDS->getElementAsInteger(i) >= V1Size*2)
  1260. return false;
  1261. return true;
  1262. }
  1263. // The bitcode reader can create a place holder for a forward reference
  1264. // used as the shuffle mask. When this occurs, the shuffle mask will
  1265. // fall into this case and fail. To avoid this error, do this bit of
  1266. // ugliness to allow such a mask pass.
  1267. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
  1268. if (CE->getOpcode() == Instruction::UserOp1)
  1269. return true;
  1270. return false;
  1271. }
  1272. /// getMaskValue - Return the index from the shuffle mask for the specified
  1273. /// output result. This is either -1 if the element is undef or a number less
  1274. /// than 2*numelements.
  1275. int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
  1276. assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
  1277. if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
  1278. return CDS->getElementAsInteger(i);
  1279. Constant *C = Mask->getAggregateElement(i);
  1280. if (isa<UndefValue>(C))
  1281. return -1;
  1282. return cast<ConstantInt>(C)->getZExtValue();
  1283. }
  1284. /// getShuffleMask - Return the full mask for this instruction, where each
  1285. /// element is the element number and undef's are returned as -1.
  1286. void ShuffleVectorInst::getShuffleMask(Constant *Mask,
  1287. SmallVectorImpl<int> &Result) {
  1288. unsigned NumElts = Mask->getType()->getVectorNumElements();
  1289. if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
  1290. for (unsigned i = 0; i != NumElts; ++i)
  1291. Result.push_back(CDS->getElementAsInteger(i));
  1292. return;
  1293. }
  1294. for (unsigned i = 0; i != NumElts; ++i) {
  1295. Constant *C = Mask->getAggregateElement(i);
  1296. Result.push_back(isa<UndefValue>(C) ? -1 :
  1297. cast<ConstantInt>(C)->getZExtValue());
  1298. }
  1299. }
  1300. //===----------------------------------------------------------------------===//
  1301. // InsertValueInst Class
  1302. //===----------------------------------------------------------------------===//
  1303. void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
  1304. const Twine &Name) {
  1305. assert(getNumOperands() == 2 && "NumOperands not initialized?");
  1306. // There's no fundamental reason why we require at least one index
  1307. // (other than weirdness with &*IdxBegin being invalid; see
  1308. // getelementptr's init routine for example). But there's no
  1309. // present need to support it.
  1310. assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
  1311. assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
  1312. Val->getType() && "Inserted value must match indexed type!");
  1313. Op<0>() = Agg;
  1314. Op<1>() = Val;
  1315. Indices.append(Idxs.begin(), Idxs.end());
  1316. setName(Name);
  1317. }
  1318. InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
  1319. : Instruction(IVI.getType(), InsertValue,
  1320. OperandTraits<InsertValueInst>::op_begin(this), 2),
  1321. Indices(IVI.Indices) {
  1322. Op<0>() = IVI.getOperand(0);
  1323. Op<1>() = IVI.getOperand(1);
  1324. SubclassOptionalData = IVI.SubclassOptionalData;
  1325. }
  1326. //===----------------------------------------------------------------------===//
  1327. // ExtractValueInst Class
  1328. //===----------------------------------------------------------------------===//
  1329. void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
  1330. assert(getNumOperands() == 1 && "NumOperands not initialized?");
  1331. // There's no fundamental reason why we require at least one index.
  1332. // But there's no present need to support it.
  1333. assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
  1334. Indices.append(Idxs.begin(), Idxs.end());
  1335. setName(Name);
  1336. }
  1337. ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
  1338. : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
  1339. Indices(EVI.Indices) {
  1340. SubclassOptionalData = EVI.SubclassOptionalData;
  1341. }
  1342. // getIndexedType - Returns the type of the element that would be extracted
  1343. // with an extractvalue instruction with the specified parameters.
  1344. //
  1345. // A null type is returned if the indices are invalid for the specified
  1346. // pointer type.
  1347. //
  1348. Type *ExtractValueInst::getIndexedType(Type *Agg,
  1349. ArrayRef<unsigned> Idxs) {
  1350. for (unsigned Index : Idxs) {
  1351. // We can't use CompositeType::indexValid(Index) here.
  1352. // indexValid() always returns true for arrays because getelementptr allows
  1353. // out-of-bounds indices. Since we don't allow those for extractvalue and
  1354. // insertvalue we need to check array indexing manually.
  1355. // Since the only other types we can index into are struct types it's just
  1356. // as easy to check those manually as well.
  1357. if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
  1358. if (Index >= AT->getNumElements())
  1359. return nullptr;
  1360. } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
  1361. if (Index >= ST->getNumElements())
  1362. return nullptr;
  1363. } else {
  1364. // Not a valid type to index into.
  1365. return nullptr;
  1366. }
  1367. Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
  1368. }
  1369. return const_cast<Type*>(Agg);
  1370. }
  1371. //===----------------------------------------------------------------------===//
  1372. // BinaryOperator Class
  1373. //===----------------------------------------------------------------------===//
  1374. BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
  1375. Type *Ty, const Twine &Name,
  1376. Instruction *InsertBefore)
  1377. : Instruction(Ty, iType,
  1378. OperandTraits<BinaryOperator>::op_begin(this),
  1379. OperandTraits<BinaryOperator>::operands(this),
  1380. InsertBefore) {
  1381. Op<0>() = S1;
  1382. Op<1>() = S2;
  1383. init(iType);
  1384. setName(Name);
  1385. }
  1386. BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
  1387. Type *Ty, const Twine &Name,
  1388. BasicBlock *InsertAtEnd)
  1389. : Instruction(Ty, iType,
  1390. OperandTraits<BinaryOperator>::op_begin(this),
  1391. OperandTraits<BinaryOperator>::operands(this),
  1392. InsertAtEnd) {
  1393. Op<0>() = S1;
  1394. Op<1>() = S2;
  1395. init(iType);
  1396. setName(Name);
  1397. }
  1398. void BinaryOperator::init(BinaryOps iType) {
  1399. Value *LHS = getOperand(0), *RHS = getOperand(1);
  1400. (void)LHS; (void)RHS; // Silence warnings.
  1401. assert(LHS->getType() == RHS->getType() &&
  1402. "Binary operator operand types must match!");
  1403. #ifndef NDEBUG
  1404. switch (iType) {
  1405. case Add: case Sub:
  1406. case Mul:
  1407. assert(getType() == LHS->getType() &&
  1408. "Arithmetic operation should return same type as operands!");
  1409. assert(getType()->isIntOrIntVectorTy() &&
  1410. "Tried to create an integer operation on a non-integer type!");
  1411. break;
  1412. case FAdd: case FSub:
  1413. case FMul:
  1414. assert(getType() == LHS->getType() &&
  1415. "Arithmetic operation should return same type as operands!");
  1416. assert(getType()->isFPOrFPVectorTy() &&
  1417. "Tried to create a floating-point operation on a "
  1418. "non-floating-point type!");
  1419. break;
  1420. case UDiv:
  1421. case SDiv:
  1422. assert(getType() == LHS->getType() &&
  1423. "Arithmetic operation should return same type as operands!");
  1424. assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
  1425. cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
  1426. "Incorrect operand type (not integer) for S/UDIV");
  1427. break;
  1428. case FDiv:
  1429. assert(getType() == LHS->getType() &&
  1430. "Arithmetic operation should return same type as operands!");
  1431. assert(getType()->isFPOrFPVectorTy() &&
  1432. "Incorrect operand type (not floating point) for FDIV");
  1433. break;
  1434. case URem:
  1435. case SRem:
  1436. assert(getType() == LHS->getType() &&
  1437. "Arithmetic operation should return same type as operands!");
  1438. assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
  1439. cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
  1440. "Incorrect operand type (not integer) for S/UREM");
  1441. break;
  1442. case FRem:
  1443. assert(getType() == LHS->getType() &&
  1444. "Arithmetic operation should return same type as operands!");
  1445. assert(getType()->isFPOrFPVectorTy() &&
  1446. "Incorrect operand type (not floating point) for FREM");
  1447. break;
  1448. case Shl:
  1449. case LShr:
  1450. case AShr:
  1451. assert(getType() == LHS->getType() &&
  1452. "Shift operation should return same type as operands!");
  1453. assert((getType()->isIntegerTy() ||
  1454. (getType()->isVectorTy() &&
  1455. cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
  1456. "Tried to create a shift operation on a non-integral type!");
  1457. break;
  1458. case And: case Or:
  1459. case Xor:
  1460. assert(getType() == LHS->getType() &&
  1461. "Logical operation should return same type as operands!");
  1462. assert((getType()->isIntegerTy() ||
  1463. (getType()->isVectorTy() &&
  1464. cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
  1465. "Tried to create a logical operation on a non-integral type!");
  1466. break;
  1467. default:
  1468. break;
  1469. }
  1470. #endif
  1471. }
  1472. BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
  1473. const Twine &Name,
  1474. Instruction *InsertBefore) {
  1475. assert(S1->getType() == S2->getType() &&
  1476. "Cannot create binary operator with two operands of differing type!");
  1477. return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
  1478. }
  1479. BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
  1480. const Twine &Name,
  1481. BasicBlock *InsertAtEnd) {
  1482. BinaryOperator *Res = Create(Op, S1, S2, Name);
  1483. InsertAtEnd->getInstList().push_back(Res);
  1484. return Res;
  1485. }
  1486. BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
  1487. Instruction *InsertBefore) {
  1488. Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
  1489. return new BinaryOperator(Instruction::Sub,
  1490. zero, Op,
  1491. Op->getType(), Name, InsertBefore);
  1492. }
  1493. BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
  1494. BasicBlock *InsertAtEnd) {
  1495. Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
  1496. return new BinaryOperator(Instruction::Sub,
  1497. zero, Op,
  1498. Op->getType(), Name, InsertAtEnd);
  1499. }
  1500. BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
  1501. Instruction *InsertBefore) {
  1502. Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
  1503. return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
  1504. }
  1505. BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
  1506. BasicBlock *InsertAtEnd) {
  1507. Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
  1508. return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
  1509. }
  1510. BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
  1511. Instruction *InsertBefore) {
  1512. Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
  1513. return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
  1514. }
  1515. BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
  1516. BasicBlock *InsertAtEnd) {
  1517. Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
  1518. return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
  1519. }
  1520. BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
  1521. Instruction *InsertBefore) {
  1522. Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
  1523. return new BinaryOperator(Instruction::FSub, zero, Op,
  1524. Op->getType(), Name, InsertBefore);
  1525. }
  1526. BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
  1527. BasicBlock *InsertAtEnd) {
  1528. Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
  1529. return new BinaryOperator(Instruction::FSub, zero, Op,
  1530. Op->getType(), Name, InsertAtEnd);
  1531. }
  1532. BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
  1533. Instruction *InsertBefore) {
  1534. Constant *C = Constant::getAllOnesValue(Op->getType());
  1535. return new BinaryOperator(Instruction::Xor, Op, C,
  1536. Op->getType(), Name, InsertBefore);
  1537. }
  1538. BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
  1539. BasicBlock *InsertAtEnd) {
  1540. Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
  1541. return new BinaryOperator(Instruction::Xor, Op, AllOnes,
  1542. Op->getType(), Name, InsertAtEnd);
  1543. }
  1544. // isConstantAllOnes - Helper function for several functions below
  1545. static inline bool isConstantAllOnes(const Value *V) {
  1546. if (const Constant *C = dyn_cast<Constant>(V))
  1547. return C->isAllOnesValue();
  1548. return false;
  1549. }
  1550. bool BinaryOperator::isNeg(const Value *V) {
  1551. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
  1552. if (Bop->getOpcode() == Instruction::Sub)
  1553. if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
  1554. return C->isNegativeZeroValue();
  1555. return false;
  1556. }
  1557. bool BinaryOperator::isFNeg(const Value *V, bool IgnoreZeroSign) {
  1558. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
  1559. if (Bop->getOpcode() == Instruction::FSub)
  1560. if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) {
  1561. if (!IgnoreZeroSign)
  1562. IgnoreZeroSign = cast<Instruction>(V)->hasNoSignedZeros();
  1563. return !IgnoreZeroSign ? C->isNegativeZeroValue() : C->isZeroValue();
  1564. }
  1565. return false;
  1566. }
  1567. bool BinaryOperator::isNot(const Value *V) {
  1568. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
  1569. return (Bop->getOpcode() == Instruction::Xor &&
  1570. (isConstantAllOnes(Bop->getOperand(1)) ||
  1571. isConstantAllOnes(Bop->getOperand(0))));
  1572. return false;
  1573. }
  1574. Value *BinaryOperator::getNegArgument(Value *BinOp) {
  1575. return cast<BinaryOperator>(BinOp)->getOperand(1);
  1576. }
  1577. const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
  1578. return getNegArgument(const_cast<Value*>(BinOp));
  1579. }
  1580. Value *BinaryOperator::getFNegArgument(Value *BinOp) {
  1581. return cast<BinaryOperator>(BinOp)->getOperand(1);
  1582. }
  1583. const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
  1584. return getFNegArgument(const_cast<Value*>(BinOp));
  1585. }
  1586. Value *BinaryOperator::getNotArgument(Value *BinOp) {
  1587. assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
  1588. BinaryOperator *BO = cast<BinaryOperator>(BinOp);
  1589. Value *Op0 = BO->getOperand(0);
  1590. Value *Op1 = BO->getOperand(1);
  1591. if (isConstantAllOnes(Op0)) return Op1;
  1592. assert(isConstantAllOnes(Op1));
  1593. return Op0;
  1594. }
  1595. const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
  1596. return getNotArgument(const_cast<Value*>(BinOp));
  1597. }
  1598. // swapOperands - Exchange the two operands to this instruction. This
  1599. // instruction is safe to use on any binary instruction and does not
  1600. // modify the semantics of the instruction. If the instruction is
  1601. // order dependent (SetLT f.e.) the opcode is changed.
  1602. //
  1603. bool BinaryOperator::swapOperands() {
  1604. if (!isCommutative())
  1605. return true; // Can't commute operands
  1606. Op<0>().swap(Op<1>());
  1607. return false;
  1608. }
  1609. void BinaryOperator::setHasNoUnsignedWrap(bool b) {
  1610. cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
  1611. }
  1612. void BinaryOperator::setHasNoSignedWrap(bool b) {
  1613. cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
  1614. }
  1615. void BinaryOperator::setIsExact(bool b) {
  1616. cast<PossiblyExactOperator>(this)->setIsExact(b);
  1617. }
  1618. bool BinaryOperator::hasNoUnsignedWrap() const {
  1619. return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
  1620. }
  1621. bool BinaryOperator::hasNoSignedWrap() const {
  1622. return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
  1623. }
  1624. bool BinaryOperator::isExact() const {
  1625. return cast<PossiblyExactOperator>(this)->isExact();
  1626. }
  1627. void BinaryOperator::copyIRFlags(const Value *V) {
  1628. // Copy the wrapping flags.
  1629. if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
  1630. setHasNoSignedWrap(OB->hasNoSignedWrap());
  1631. setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
  1632. }
  1633. // Copy the exact flag.
  1634. if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
  1635. setIsExact(PE->isExact());
  1636. // Copy the fast-math flags.
  1637. if (auto *FP = dyn_cast<FPMathOperator>(V))
  1638. copyFastMathFlags(FP->getFastMathFlags());
  1639. }
  1640. void BinaryOperator::andIRFlags(const Value *V) {
  1641. if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
  1642. setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap());
  1643. setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap());
  1644. }
  1645. if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
  1646. setIsExact(isExact() & PE->isExact());
  1647. if (auto *FP = dyn_cast<FPMathOperator>(V)) {
  1648. FastMathFlags FM = getFastMathFlags();
  1649. FM &= FP->getFastMathFlags();
  1650. copyFastMathFlags(FM);
  1651. }
  1652. }
  1653. //===----------------------------------------------------------------------===//
  1654. // FPMathOperator Class
  1655. //===----------------------------------------------------------------------===//
  1656. /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
  1657. /// An accuracy of 0.0 means that the operation should be performed with the
  1658. /// default precision.
  1659. float FPMathOperator::getFPAccuracy() const {
  1660. const MDNode *MD =
  1661. cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
  1662. if (!MD)
  1663. return 0.0;
  1664. ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
  1665. return Accuracy->getValueAPF().convertToFloat();
  1666. }
  1667. //===----------------------------------------------------------------------===//
  1668. // CastInst Class
  1669. //===----------------------------------------------------------------------===//
  1670. void CastInst::anchor() {}
  1671. // Just determine if this cast only deals with integral->integral conversion.
  1672. bool CastInst::isIntegerCast() const {
  1673. switch (getOpcode()) {
  1674. default: return false;
  1675. case Instruction::ZExt:
  1676. case Instruction::SExt:
  1677. case Instruction::Trunc:
  1678. return true;
  1679. case Instruction::BitCast:
  1680. return getOperand(0)->getType()->isIntegerTy() &&
  1681. getType()->isIntegerTy();
  1682. }
  1683. }
  1684. bool CastInst::isLosslessCast() const {
  1685. // Only BitCast can be lossless, exit fast if we're not BitCast
  1686. if (getOpcode() != Instruction::BitCast)
  1687. return false;
  1688. // Identity cast is always lossless
  1689. Type* SrcTy = getOperand(0)->getType();
  1690. Type* DstTy = getType();
  1691. if (SrcTy == DstTy)
  1692. return true;
  1693. // Pointer to pointer is always lossless.
  1694. if (SrcTy->isPointerTy())
  1695. return DstTy->isPointerTy();
  1696. return false; // Other types have no identity values
  1697. }
  1698. /// This function determines if the CastInst does not require any bits to be
  1699. /// changed in order to effect the cast. Essentially, it identifies cases where
  1700. /// no code gen is necessary for the cast, hence the name no-op cast. For
  1701. /// example, the following are all no-op casts:
  1702. /// # bitcast i32* %x to i8*
  1703. /// # bitcast <2 x i32> %x to <4 x i16>
  1704. /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
  1705. /// @brief Determine if the described cast is a no-op.
  1706. bool CastInst::isNoopCast(Instruction::CastOps Opcode,
  1707. Type *SrcTy,
  1708. Type *DestTy,
  1709. Type *IntPtrTy) {
  1710. switch (Opcode) {
  1711. default: llvm_unreachable("Invalid CastOp");
  1712. case Instruction::Trunc:
  1713. case Instruction::ZExt:
  1714. case Instruction::SExt:
  1715. case Instruction::FPTrunc:
  1716. case Instruction::FPExt:
  1717. case Instruction::UIToFP:
  1718. case Instruction::SIToFP:
  1719. case Instruction::FPToUI:
  1720. case Instruction::FPToSI:
  1721. case Instruction::AddrSpaceCast:
  1722. // TODO: Target informations may give a more accurate answer here.
  1723. return false;
  1724. case Instruction::BitCast:
  1725. return true; // BitCast never modifies bits.
  1726. case Instruction::PtrToInt:
  1727. return IntPtrTy->getScalarSizeInBits() ==
  1728. DestTy->getScalarSizeInBits();
  1729. case Instruction::IntToPtr:
  1730. return IntPtrTy->getScalarSizeInBits() ==
  1731. SrcTy->getScalarSizeInBits();
  1732. }
  1733. }
  1734. /// @brief Determine if a cast is a no-op.
  1735. bool CastInst::isNoopCast(Type *IntPtrTy) const {
  1736. return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
  1737. }
  1738. bool CastInst::isNoopCast(const DataLayout &DL) const {
  1739. Type *PtrOpTy = nullptr;
  1740. if (getOpcode() == Instruction::PtrToInt)
  1741. PtrOpTy = getOperand(0)->getType();
  1742. else if (getOpcode() == Instruction::IntToPtr)
  1743. PtrOpTy = getType();
  1744. Type *IntPtrTy =
  1745. PtrOpTy ? DL.getIntPtrType(PtrOpTy) : DL.getIntPtrType(getContext(), 0);
  1746. return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
  1747. }
  1748. /// This function determines if a pair of casts can be eliminated and what
  1749. /// opcode should be used in the elimination. This assumes that there are two
  1750. /// instructions like this:
  1751. /// * %F = firstOpcode SrcTy %x to MidTy
  1752. /// * %S = secondOpcode MidTy %F to DstTy
  1753. /// The function returns a resultOpcode so these two casts can be replaced with:
  1754. /// * %Replacement = resultOpcode %SrcTy %x to DstTy
  1755. /// If no such cast is permited, the function returns 0.
  1756. unsigned CastInst::isEliminableCastPair(
  1757. Instruction::CastOps firstOp, Instruction::CastOps secondOp,
  1758. Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
  1759. Type *DstIntPtrTy) {
  1760. // Define the 144 possibilities for these two cast instructions. The values
  1761. // in this matrix determine what to do in a given situation and select the
  1762. // case in the switch below. The rows correspond to firstOp, the columns
  1763. // correspond to secondOp. In looking at the table below, keep in mind
  1764. // the following cast properties:
  1765. //
  1766. // Size Compare Source Destination
  1767. // Operator Src ? Size Type Sign Type Sign
  1768. // -------- ------------ ------------------- ---------------------
  1769. // TRUNC > Integer Any Integral Any
  1770. // ZEXT < Integral Unsigned Integer Any
  1771. // SEXT < Integral Signed Integer Any
  1772. // FPTOUI n/a FloatPt n/a Integral Unsigned
  1773. // FPTOSI n/a FloatPt n/a Integral Signed
  1774. // UITOFP n/a Integral Unsigned FloatPt n/a
  1775. // SITOFP n/a Integral Signed FloatPt n/a
  1776. // FPTRUNC > FloatPt n/a FloatPt n/a
  1777. // FPEXT < FloatPt n/a FloatPt n/a
  1778. // PTRTOINT n/a Pointer n/a Integral Unsigned
  1779. // INTTOPTR n/a Integral Unsigned Pointer n/a
  1780. // BITCAST = FirstClass n/a FirstClass n/a
  1781. // ADDRSPCST n/a Pointer n/a Pointer n/a
  1782. //
  1783. // NOTE: some transforms are safe, but we consider them to be non-profitable.
  1784. // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
  1785. // into "fptoui double to i64", but this loses information about the range
  1786. // of the produced value (we no longer know the top-part is all zeros).
  1787. // Further this conversion is often much more expensive for typical hardware,
  1788. // and causes issues when building libgcc. We disallow fptosi+sext for the
  1789. // same reason.
  1790. const unsigned numCastOps =
  1791. Instruction::CastOpsEnd - Instruction::CastOpsBegin;
  1792. static const uint8_t CastResults[numCastOps][numCastOps] = {
  1793. // T F F U S F F P I B A -+
  1794. // R Z S P P I I T P 2 N T S |
  1795. // U E E 2 2 2 2 R E I T C C +- secondOp
  1796. // N X X U S F F N X N 2 V V |
  1797. // C T T I I P P C T T P T T -+
  1798. { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
  1799. { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
  1800. { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
  1801. { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
  1802. { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
  1803. { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
  1804. { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
  1805. { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
  1806. { 99,99,99, 2, 2,99,99,10, 2,99,99, 4, 0}, // FPExt |
  1807. { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
  1808. { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
  1809. { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
  1810. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
  1811. };
  1812. // If either of the casts are a bitcast from scalar to vector, disallow the
  1813. // merging. However, bitcast of A->B->A are allowed.
  1814. bool isFirstBitcast = (firstOp == Instruction::BitCast);
  1815. bool isSecondBitcast = (secondOp == Instruction::BitCast);
  1816. bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
  1817. // Check if any of the bitcasts convert scalars<->vectors.
  1818. if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
  1819. (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
  1820. // Unless we are bitcasing to the original type, disallow optimizations.
  1821. if (!chainedBitcast) return 0;
  1822. int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
  1823. [secondOp-Instruction::CastOpsBegin];
  1824. switch (ElimCase) {
  1825. case 0:
  1826. // Categorically disallowed.
  1827. return 0;
  1828. case 1:
  1829. // Allowed, use first cast's opcode.
  1830. return firstOp;
  1831. case 2:
  1832. // Allowed, use second cast's opcode.
  1833. return secondOp;
  1834. case 3:
  1835. // No-op cast in second op implies firstOp as long as the DestTy
  1836. // is integer and we are not converting between a vector and a
  1837. // non-vector type.
  1838. if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
  1839. return firstOp;
  1840. return 0;
  1841. case 4:
  1842. // No-op cast in second op implies firstOp as long as the DestTy
  1843. // is floating point.
  1844. if (DstTy->isFloatingPointTy())
  1845. return firstOp;
  1846. return 0;
  1847. case 5:
  1848. // No-op cast in first op implies secondOp as long as the SrcTy
  1849. // is an integer.
  1850. if (SrcTy->isIntegerTy())
  1851. return secondOp;
  1852. return 0;
  1853. case 6:
  1854. // No-op cast in first op implies secondOp as long as the SrcTy
  1855. // is a floating point.
  1856. if (SrcTy->isFloatingPointTy())
  1857. return secondOp;
  1858. return 0;
  1859. case 7: {
  1860. // Cannot simplify if address spaces are different!
  1861. if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
  1862. return 0;
  1863. unsigned MidSize = MidTy->getScalarSizeInBits();
  1864. // We can still fold this without knowing the actual sizes as long we
  1865. // know that the intermediate pointer is the largest possible
  1866. // pointer size.
  1867. // FIXME: Is this always true?
  1868. if (MidSize == 64)
  1869. return Instruction::BitCast;
  1870. // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
  1871. if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
  1872. return 0;
  1873. unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
  1874. if (MidSize >= PtrSize)
  1875. return Instruction::BitCast;
  1876. return 0;
  1877. }
  1878. case 8: {
  1879. // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
  1880. // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
  1881. // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
  1882. unsigned SrcSize = SrcTy->getScalarSizeInBits();
  1883. unsigned DstSize = DstTy->getScalarSizeInBits();
  1884. if (SrcSize == DstSize)
  1885. return Instruction::BitCast;
  1886. else if (SrcSize < DstSize)
  1887. return firstOp;
  1888. return secondOp;
  1889. }
  1890. case 9:
  1891. // zext, sext -> zext, because sext can't sign extend after zext
  1892. return Instruction::ZExt;
  1893. case 10:
  1894. // fpext followed by ftrunc is allowed if the bit size returned to is
  1895. // the same as the original, in which case its just a bitcast
  1896. if (SrcTy == DstTy)
  1897. return Instruction::BitCast;
  1898. return 0; // If the types are not the same we can't eliminate it.
  1899. case 11: {
  1900. // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
  1901. if (!MidIntPtrTy)
  1902. return 0;
  1903. unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
  1904. unsigned SrcSize = SrcTy->getScalarSizeInBits();
  1905. unsigned DstSize = DstTy->getScalarSizeInBits();
  1906. if (SrcSize <= PtrSize && SrcSize == DstSize)
  1907. return Instruction::BitCast;
  1908. return 0;
  1909. }
  1910. case 12: {
  1911. // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
  1912. // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
  1913. if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
  1914. return Instruction::AddrSpaceCast;
  1915. return Instruction::BitCast;
  1916. }
  1917. case 13:
  1918. // FIXME: this state can be merged with (1), but the following assert
  1919. // is useful to check the correcteness of the sequence due to semantic
  1920. // change of bitcast.
  1921. assert(
  1922. SrcTy->isPtrOrPtrVectorTy() &&
  1923. MidTy->isPtrOrPtrVectorTy() &&
  1924. DstTy->isPtrOrPtrVectorTy() &&
  1925. SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
  1926. MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
  1927. "Illegal addrspacecast, bitcast sequence!");
  1928. // Allowed, use first cast's opcode
  1929. return firstOp;
  1930. case 14:
  1931. // bitcast, addrspacecast -> addrspacecast if the element type of
  1932. // bitcast's source is the same as that of addrspacecast's destination.
  1933. if (SrcTy->getPointerElementType() == DstTy->getPointerElementType())
  1934. return Instruction::AddrSpaceCast;
  1935. return 0;
  1936. case 15:
  1937. // FIXME: this state can be merged with (1), but the following assert
  1938. // is useful to check the correcteness of the sequence due to semantic
  1939. // change of bitcast.
  1940. assert(
  1941. SrcTy->isIntOrIntVectorTy() &&
  1942. MidTy->isPtrOrPtrVectorTy() &&
  1943. DstTy->isPtrOrPtrVectorTy() &&
  1944. MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
  1945. "Illegal inttoptr, bitcast sequence!");
  1946. // Allowed, use first cast's opcode
  1947. return firstOp;
  1948. case 16:
  1949. // FIXME: this state can be merged with (2), but the following assert
  1950. // is useful to check the correcteness of the sequence due to semantic
  1951. // change of bitcast.
  1952. assert(
  1953. SrcTy->isPtrOrPtrVectorTy() &&
  1954. MidTy->isPtrOrPtrVectorTy() &&
  1955. DstTy->isIntOrIntVectorTy() &&
  1956. SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
  1957. "Illegal bitcast, ptrtoint sequence!");
  1958. // Allowed, use second cast's opcode
  1959. return secondOp;
  1960. case 17:
  1961. // (sitofp (zext x)) -> (uitofp x)
  1962. return Instruction::UIToFP;
  1963. case 99:
  1964. // Cast combination can't happen (error in input). This is for all cases
  1965. // where the MidTy is not the same for the two cast instructions.
  1966. llvm_unreachable("Invalid Cast Combination");
  1967. default:
  1968. llvm_unreachable("Error in CastResults table!!!");
  1969. }
  1970. }
  1971. CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
  1972. const Twine &Name, Instruction *InsertBefore) {
  1973. assert(castIsValid(op, S, Ty) && "Invalid cast!");
  1974. // Construct and return the appropriate CastInst subclass
  1975. switch (op) {
  1976. case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
  1977. case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
  1978. case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
  1979. case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
  1980. case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
  1981. case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
  1982. case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
  1983. case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
  1984. case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
  1985. case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
  1986. case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
  1987. case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
  1988. case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
  1989. default: llvm_unreachable("Invalid opcode provided");
  1990. }
  1991. }
  1992. CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
  1993. const Twine &Name, BasicBlock *InsertAtEnd) {
  1994. assert(castIsValid(op, S, Ty) && "Invalid cast!");
  1995. // Construct and return the appropriate CastInst subclass
  1996. switch (op) {
  1997. case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
  1998. case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
  1999. case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
  2000. case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
  2001. case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
  2002. case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
  2003. case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
  2004. case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
  2005. case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
  2006. case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
  2007. case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
  2008. case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
  2009. case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
  2010. default: llvm_unreachable("Invalid opcode provided");
  2011. }
  2012. }
  2013. CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
  2014. const Twine &Name,
  2015. Instruction *InsertBefore) {
  2016. if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  2017. return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
  2018. return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
  2019. }
  2020. CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
  2021. const Twine &Name,
  2022. BasicBlock *InsertAtEnd) {
  2023. if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  2024. return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
  2025. return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
  2026. }
  2027. CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
  2028. const Twine &Name,
  2029. Instruction *InsertBefore) {
  2030. if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  2031. return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
  2032. return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
  2033. }
  2034. CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
  2035. const Twine &Name,
  2036. BasicBlock *InsertAtEnd) {
  2037. if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  2038. return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
  2039. return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
  2040. }
  2041. CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
  2042. const Twine &Name,
  2043. Instruction *InsertBefore) {
  2044. if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  2045. return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
  2046. return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
  2047. }
  2048. CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
  2049. const Twine &Name,
  2050. BasicBlock *InsertAtEnd) {
  2051. if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  2052. return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
  2053. return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
  2054. }
  2055. CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
  2056. const Twine &Name,
  2057. BasicBlock *InsertAtEnd) {
  2058. assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
  2059. assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
  2060. "Invalid cast");
  2061. assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
  2062. assert((!Ty->isVectorTy() ||
  2063. Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
  2064. "Invalid cast");
  2065. if (Ty->isIntOrIntVectorTy())
  2066. return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
  2067. return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
  2068. }
  2069. /// @brief Create a BitCast or a PtrToInt cast instruction
  2070. CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
  2071. const Twine &Name,
  2072. Instruction *InsertBefore) {
  2073. assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
  2074. assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
  2075. "Invalid cast");
  2076. assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
  2077. assert((!Ty->isVectorTy() ||
  2078. Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
  2079. "Invalid cast");
  2080. if (Ty->isIntOrIntVectorTy())
  2081. return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
  2082. return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
  2083. }
  2084. CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
  2085. Value *S, Type *Ty,
  2086. const Twine &Name,
  2087. BasicBlock *InsertAtEnd) {
  2088. assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
  2089. assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
  2090. if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
  2091. return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
  2092. return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
  2093. }
  2094. CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
  2095. Value *S, Type *Ty,
  2096. const Twine &Name,
  2097. Instruction *InsertBefore) {
  2098. assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
  2099. assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
  2100. if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
  2101. return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
  2102. return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
  2103. }
  2104. CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
  2105. const Twine &Name,
  2106. Instruction *InsertBefore) {
  2107. if (S->getType()->isPointerTy() && Ty->isIntegerTy())
  2108. return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
  2109. if (S->getType()->isIntegerTy() && Ty->isPointerTy())
  2110. return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
  2111. return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
  2112. }
  2113. CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
  2114. bool isSigned, const Twine &Name,
  2115. Instruction *InsertBefore) {
  2116. assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
  2117. "Invalid integer cast");
  2118. unsigned SrcBits = C->getType()->getScalarSizeInBits();
  2119. unsigned DstBits = Ty->getScalarSizeInBits();
  2120. Instruction::CastOps opcode =
  2121. (SrcBits == DstBits ? Instruction::BitCast :
  2122. (SrcBits > DstBits ? Instruction::Trunc :
  2123. (isSigned ? Instruction::SExt : Instruction::ZExt)));
  2124. return Create(opcode, C, Ty, Name, InsertBefore);
  2125. }
  2126. CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
  2127. bool isSigned, const Twine &Name,
  2128. BasicBlock *InsertAtEnd) {
  2129. assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
  2130. "Invalid cast");
  2131. unsigned SrcBits = C->getType()->getScalarSizeInBits();
  2132. unsigned DstBits = Ty->getScalarSizeInBits();
  2133. Instruction::CastOps opcode =
  2134. (SrcBits == DstBits ? Instruction::BitCast :
  2135. (SrcBits > DstBits ? Instruction::Trunc :
  2136. (isSigned ? Instruction::SExt : Instruction::ZExt)));
  2137. return Create(opcode, C, Ty, Name, InsertAtEnd);
  2138. }
  2139. CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
  2140. const Twine &Name,
  2141. Instruction *InsertBefore) {
  2142. assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
  2143. "Invalid cast");
  2144. unsigned SrcBits = C->getType()->getScalarSizeInBits();
  2145. unsigned DstBits = Ty->getScalarSizeInBits();
  2146. Instruction::CastOps opcode =
  2147. (SrcBits == DstBits ? Instruction::BitCast :
  2148. (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
  2149. return Create(opcode, C, Ty, Name, InsertBefore);
  2150. }
  2151. CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
  2152. const Twine &Name,
  2153. BasicBlock *InsertAtEnd) {
  2154. assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
  2155. "Invalid cast");
  2156. unsigned SrcBits = C->getType()->getScalarSizeInBits();
  2157. unsigned DstBits = Ty->getScalarSizeInBits();
  2158. Instruction::CastOps opcode =
  2159. (SrcBits == DstBits ? Instruction::BitCast :
  2160. (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
  2161. return Create(opcode, C, Ty, Name, InsertAtEnd);
  2162. }
  2163. // Check whether it is valid to call getCastOpcode for these types.
  2164. // This routine must be kept in sync with getCastOpcode.
  2165. bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
  2166. if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
  2167. return false;
  2168. if (SrcTy == DestTy)
  2169. return true;
  2170. if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
  2171. if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
  2172. if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
  2173. // An element by element cast. Valid if casting the elements is valid.
  2174. SrcTy = SrcVecTy->getElementType();
  2175. DestTy = DestVecTy->getElementType();
  2176. }
  2177. // Get the bit sizes, we'll need these
  2178. unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
  2179. unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
  2180. // Run through the possibilities ...
  2181. if (DestTy->isIntegerTy()) { // Casting to integral
  2182. if (SrcTy->isIntegerTy()) // Casting from integral
  2183. return true;
  2184. if (SrcTy->isFloatingPointTy()) // Casting from floating pt
  2185. return true;
  2186. if (SrcTy->isVectorTy()) // Casting from vector
  2187. return DestBits == SrcBits;
  2188. // Casting from something else
  2189. return SrcTy->isPointerTy();
  2190. }
  2191. if (DestTy->isFloatingPointTy()) { // Casting to floating pt
  2192. if (SrcTy->isIntegerTy()) // Casting from integral
  2193. return true;
  2194. if (SrcTy->isFloatingPointTy()) // Casting from floating pt
  2195. return true;
  2196. if (SrcTy->isVectorTy()) // Casting from vector
  2197. return DestBits == SrcBits;
  2198. // Casting from something else
  2199. return false;
  2200. }
  2201. if (DestTy->isVectorTy()) // Casting to vector
  2202. return DestBits == SrcBits;
  2203. if (DestTy->isPointerTy()) { // Casting to pointer
  2204. if (SrcTy->isPointerTy()) // Casting from pointer
  2205. return true;
  2206. return SrcTy->isIntegerTy(); // Casting from integral
  2207. }
  2208. if (DestTy->isX86_MMXTy()) {
  2209. if (SrcTy->isVectorTy())
  2210. return DestBits == SrcBits; // 64-bit vector to MMX
  2211. return false;
  2212. } // Casting to something else
  2213. return false;
  2214. }
  2215. bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
  2216. if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
  2217. return false;
  2218. if (SrcTy == DestTy)
  2219. return true;
  2220. if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
  2221. if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
  2222. if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
  2223. // An element by element cast. Valid if casting the elements is valid.
  2224. SrcTy = SrcVecTy->getElementType();
  2225. DestTy = DestVecTy->getElementType();
  2226. }
  2227. }
  2228. }
  2229. if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
  2230. if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
  2231. return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
  2232. }
  2233. }
  2234. unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
  2235. unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
  2236. // Could still have vectors of pointers if the number of elements doesn't
  2237. // match
  2238. if (SrcBits == 0 || DestBits == 0)
  2239. return false;
  2240. if (SrcBits != DestBits)
  2241. return false;
  2242. if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
  2243. return false;
  2244. return true;
  2245. }
  2246. bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
  2247. const DataLayout &DL) {
  2248. if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
  2249. if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
  2250. return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy);
  2251. if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
  2252. if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
  2253. return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy);
  2254. return isBitCastable(SrcTy, DestTy);
  2255. }
  2256. // Provide a way to get a "cast" where the cast opcode is inferred from the
  2257. // types and size of the operand. This, basically, is a parallel of the
  2258. // logic in the castIsValid function below. This axiom should hold:
  2259. // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
  2260. // should not assert in castIsValid. In other words, this produces a "correct"
  2261. // casting opcode for the arguments passed to it.
  2262. // This routine must be kept in sync with isCastable.
  2263. Instruction::CastOps
  2264. CastInst::getCastOpcode(
  2265. const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
  2266. Type *SrcTy = Src->getType();
  2267. assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
  2268. "Only first class types are castable!");
  2269. if (SrcTy == DestTy)
  2270. return BitCast;
  2271. // FIXME: Check address space sizes here
  2272. if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
  2273. if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
  2274. if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
  2275. // An element by element cast. Find the appropriate opcode based on the
  2276. // element types.
  2277. SrcTy = SrcVecTy->getElementType();
  2278. DestTy = DestVecTy->getElementType();
  2279. }
  2280. // Get the bit sizes, we'll need these
  2281. unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
  2282. unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
  2283. // Run through the possibilities ...
  2284. if (DestTy->isIntegerTy()) { // Casting to integral
  2285. if (SrcTy->isIntegerTy()) { // Casting from integral
  2286. if (DestBits < SrcBits)
  2287. return Trunc; // int -> smaller int
  2288. else if (DestBits > SrcBits) { // its an extension
  2289. if (SrcIsSigned)
  2290. return SExt; // signed -> SEXT
  2291. else
  2292. return ZExt; // unsigned -> ZEXT
  2293. } else {
  2294. return BitCast; // Same size, No-op cast
  2295. }
  2296. } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
  2297. if (DestIsSigned)
  2298. return FPToSI; // FP -> sint
  2299. else
  2300. return FPToUI; // FP -> uint
  2301. } else if (SrcTy->isVectorTy()) {
  2302. assert(DestBits == SrcBits &&
  2303. "Casting vector to integer of different width");
  2304. return BitCast; // Same size, no-op cast
  2305. } else {
  2306. assert(SrcTy->isPointerTy() &&
  2307. "Casting from a value that is not first-class type");
  2308. return PtrToInt; // ptr -> int
  2309. }
  2310. } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
  2311. if (SrcTy->isIntegerTy()) { // Casting from integral
  2312. if (SrcIsSigned)
  2313. return SIToFP; // sint -> FP
  2314. else
  2315. return UIToFP; // uint -> FP
  2316. } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
  2317. if (DestBits < SrcBits) {
  2318. return FPTrunc; // FP -> smaller FP
  2319. } else if (DestBits > SrcBits) {
  2320. return FPExt; // FP -> larger FP
  2321. } else {
  2322. return BitCast; // same size, no-op cast
  2323. }
  2324. } else if (SrcTy->isVectorTy()) {
  2325. assert(DestBits == SrcBits &&
  2326. "Casting vector to floating point of different width");
  2327. return BitCast; // same size, no-op cast
  2328. }
  2329. llvm_unreachable("Casting pointer or non-first class to float");
  2330. } else if (DestTy->isVectorTy()) {
  2331. assert(DestBits == SrcBits &&
  2332. "Illegal cast to vector (wrong type or size)");
  2333. return BitCast;
  2334. } else if (DestTy->isPointerTy()) {
  2335. if (SrcTy->isPointerTy()) {
  2336. if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
  2337. return AddrSpaceCast;
  2338. return BitCast; // ptr -> ptr
  2339. } else if (SrcTy->isIntegerTy()) {
  2340. return IntToPtr; // int -> ptr
  2341. }
  2342. llvm_unreachable("Casting pointer to other than pointer or int");
  2343. } else if (DestTy->isX86_MMXTy()) {
  2344. if (SrcTy->isVectorTy()) {
  2345. assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
  2346. return BitCast; // 64-bit vector to MMX
  2347. }
  2348. llvm_unreachable("Illegal cast to X86_MMX");
  2349. }
  2350. llvm_unreachable("Casting to type that is not first-class");
  2351. }
  2352. //===----------------------------------------------------------------------===//
  2353. // CastInst SubClass Constructors
  2354. //===----------------------------------------------------------------------===//
  2355. /// Check that the construction parameters for a CastInst are correct. This
  2356. /// could be broken out into the separate constructors but it is useful to have
  2357. /// it in one place and to eliminate the redundant code for getting the sizes
  2358. /// of the types involved.
  2359. bool
  2360. CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
  2361. // Check for type sanity on the arguments
  2362. Type *SrcTy = S->getType();
  2363. if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
  2364. SrcTy->isAggregateType() || DstTy->isAggregateType())
  2365. return false;
  2366. // Get the size of the types in bits, we'll need this later
  2367. unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
  2368. unsigned DstBitSize = DstTy->getScalarSizeInBits();
  2369. // If these are vector types, get the lengths of the vectors (using zero for
  2370. // scalar types means that checking that vector lengths match also checks that
  2371. // scalars are not being converted to vectors or vectors to scalars).
  2372. unsigned SrcLength = SrcTy->isVectorTy() ?
  2373. cast<VectorType>(SrcTy)->getNumElements() : 0;
  2374. unsigned DstLength = DstTy->isVectorTy() ?
  2375. cast<VectorType>(DstTy)->getNumElements() : 0;
  2376. // Switch on the opcode provided
  2377. switch (op) {
  2378. default: return false; // This is an input error
  2379. case Instruction::Trunc:
  2380. return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
  2381. SrcLength == DstLength && SrcBitSize > DstBitSize;
  2382. case Instruction::ZExt:
  2383. return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
  2384. SrcLength == DstLength && SrcBitSize < DstBitSize;
  2385. case Instruction::SExt:
  2386. return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
  2387. SrcLength == DstLength && SrcBitSize < DstBitSize;
  2388. case Instruction::FPTrunc:
  2389. return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
  2390. SrcLength == DstLength && SrcBitSize > DstBitSize;
  2391. case Instruction::FPExt:
  2392. return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
  2393. SrcLength == DstLength && SrcBitSize < DstBitSize;
  2394. case Instruction::UIToFP:
  2395. case Instruction::SIToFP:
  2396. return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
  2397. SrcLength == DstLength;
  2398. case Instruction::FPToUI:
  2399. case Instruction::FPToSI:
  2400. return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
  2401. SrcLength == DstLength;
  2402. case Instruction::PtrToInt:
  2403. if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
  2404. return false;
  2405. if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
  2406. if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
  2407. return false;
  2408. return SrcTy->getScalarType()->isPointerTy() &&
  2409. DstTy->getScalarType()->isIntegerTy();
  2410. case Instruction::IntToPtr:
  2411. if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
  2412. return false;
  2413. if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
  2414. if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
  2415. return false;
  2416. return SrcTy->getScalarType()->isIntegerTy() &&
  2417. DstTy->getScalarType()->isPointerTy();
  2418. case Instruction::BitCast: {
  2419. PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
  2420. PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
  2421. // BitCast implies a no-op cast of type only. No bits change.
  2422. // However, you can't cast pointers to anything but pointers.
  2423. if (!SrcPtrTy != !DstPtrTy)
  2424. return false;
  2425. // For non-pointer cases, the cast is okay if the source and destination bit
  2426. // widths are identical.
  2427. if (!SrcPtrTy)
  2428. return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
  2429. // If both are pointers then the address spaces must match.
  2430. if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
  2431. return false;
  2432. // A vector of pointers must have the same number of elements.
  2433. if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
  2434. if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
  2435. return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
  2436. return false;
  2437. }
  2438. return true;
  2439. }
  2440. case Instruction::AddrSpaceCast: {
  2441. PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
  2442. if (!SrcPtrTy)
  2443. return false;
  2444. PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
  2445. if (!DstPtrTy)
  2446. return false;
  2447. if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
  2448. return false;
  2449. if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
  2450. if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
  2451. return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
  2452. return false;
  2453. }
  2454. return true;
  2455. }
  2456. }
  2457. }
  2458. TruncInst::TruncInst(
  2459. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  2460. ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
  2461. assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
  2462. }
  2463. TruncInst::TruncInst(
  2464. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  2465. ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
  2466. assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
  2467. }
  2468. ZExtInst::ZExtInst(
  2469. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  2470. ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
  2471. assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
  2472. }
  2473. ZExtInst::ZExtInst(
  2474. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  2475. ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
  2476. assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
  2477. }
  2478. SExtInst::SExtInst(
  2479. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  2480. ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
  2481. assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
  2482. }
  2483. SExtInst::SExtInst(
  2484. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  2485. ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
  2486. assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
  2487. }
  2488. FPTruncInst::FPTruncInst(
  2489. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  2490. ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
  2491. assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
  2492. }
  2493. FPTruncInst::FPTruncInst(
  2494. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  2495. ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
  2496. assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
  2497. }
  2498. FPExtInst::FPExtInst(
  2499. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  2500. ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
  2501. assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
  2502. }
  2503. FPExtInst::FPExtInst(
  2504. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  2505. ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
  2506. assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
  2507. }
  2508. UIToFPInst::UIToFPInst(
  2509. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  2510. ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
  2511. assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
  2512. }
  2513. UIToFPInst::UIToFPInst(
  2514. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  2515. ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
  2516. assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
  2517. }
  2518. SIToFPInst::SIToFPInst(
  2519. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  2520. ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
  2521. assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
  2522. }
  2523. SIToFPInst::SIToFPInst(
  2524. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  2525. ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
  2526. assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
  2527. }
  2528. FPToUIInst::FPToUIInst(
  2529. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  2530. ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
  2531. assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
  2532. }
  2533. FPToUIInst::FPToUIInst(
  2534. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  2535. ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
  2536. assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
  2537. }
  2538. FPToSIInst::FPToSIInst(
  2539. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  2540. ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
  2541. assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
  2542. }
  2543. FPToSIInst::FPToSIInst(
  2544. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  2545. ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
  2546. assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
  2547. }
  2548. PtrToIntInst::PtrToIntInst(
  2549. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  2550. ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
  2551. assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
  2552. }
  2553. PtrToIntInst::PtrToIntInst(
  2554. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  2555. ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
  2556. assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
  2557. }
  2558. IntToPtrInst::IntToPtrInst(
  2559. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  2560. ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
  2561. assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
  2562. }
  2563. IntToPtrInst::IntToPtrInst(
  2564. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  2565. ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
  2566. assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
  2567. }
  2568. BitCastInst::BitCastInst(
  2569. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  2570. ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
  2571. assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
  2572. }
  2573. BitCastInst::BitCastInst(
  2574. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  2575. ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
  2576. assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
  2577. }
  2578. AddrSpaceCastInst::AddrSpaceCastInst(
  2579. Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
  2580. ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
  2581. assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
  2582. }
  2583. AddrSpaceCastInst::AddrSpaceCastInst(
  2584. Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
  2585. ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
  2586. assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
  2587. }
  2588. //===----------------------------------------------------------------------===//
  2589. // CmpInst Classes
  2590. //===----------------------------------------------------------------------===//
  2591. void CmpInst::anchor() {}
  2592. CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
  2593. Value *LHS, Value *RHS, const Twine &Name,
  2594. Instruction *InsertBefore)
  2595. : Instruction(ty, op,
  2596. OperandTraits<CmpInst>::op_begin(this),
  2597. OperandTraits<CmpInst>::operands(this),
  2598. InsertBefore) {
  2599. Op<0>() = LHS;
  2600. Op<1>() = RHS;
  2601. setPredicate((Predicate)predicate);
  2602. setName(Name);
  2603. }
  2604. CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
  2605. Value *LHS, Value *RHS, const Twine &Name,
  2606. BasicBlock *InsertAtEnd)
  2607. : Instruction(ty, op,
  2608. OperandTraits<CmpInst>::op_begin(this),
  2609. OperandTraits<CmpInst>::operands(this),
  2610. InsertAtEnd) {
  2611. Op<0>() = LHS;
  2612. Op<1>() = RHS;
  2613. setPredicate((Predicate)predicate);
  2614. setName(Name);
  2615. }
  2616. CmpInst *
  2617. CmpInst::Create(OtherOps Op, unsigned short predicate,
  2618. Value *S1, Value *S2,
  2619. const Twine &Name, Instruction *InsertBefore) {
  2620. if (Op == Instruction::ICmp) {
  2621. if (InsertBefore)
  2622. return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
  2623. S1, S2, Name);
  2624. else
  2625. return new ICmpInst(CmpInst::Predicate(predicate),
  2626. S1, S2, Name);
  2627. }
  2628. if (InsertBefore)
  2629. return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
  2630. S1, S2, Name);
  2631. else
  2632. return new FCmpInst(CmpInst::Predicate(predicate),
  2633. S1, S2, Name);
  2634. }
  2635. CmpInst *
  2636. CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
  2637. const Twine &Name, BasicBlock *InsertAtEnd) {
  2638. if (Op == Instruction::ICmp) {
  2639. return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
  2640. S1, S2, Name);
  2641. }
  2642. return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
  2643. S1, S2, Name);
  2644. }
  2645. void CmpInst::swapOperands() {
  2646. if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
  2647. IC->swapOperands();
  2648. else
  2649. cast<FCmpInst>(this)->swapOperands();
  2650. }
  2651. bool CmpInst::isCommutative() const {
  2652. if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
  2653. return IC->isCommutative();
  2654. return cast<FCmpInst>(this)->isCommutative();
  2655. }
  2656. bool CmpInst::isEquality() const {
  2657. if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
  2658. return IC->isEquality();
  2659. return cast<FCmpInst>(this)->isEquality();
  2660. }
  2661. CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
  2662. switch (pred) {
  2663. default: llvm_unreachable("Unknown cmp predicate!");
  2664. case ICMP_EQ: return ICMP_NE;
  2665. case ICMP_NE: return ICMP_EQ;
  2666. case ICMP_UGT: return ICMP_ULE;
  2667. case ICMP_ULT: return ICMP_UGE;
  2668. case ICMP_UGE: return ICMP_ULT;
  2669. case ICMP_ULE: return ICMP_UGT;
  2670. case ICMP_SGT: return ICMP_SLE;
  2671. case ICMP_SLT: return ICMP_SGE;
  2672. case ICMP_SGE: return ICMP_SLT;
  2673. case ICMP_SLE: return ICMP_SGT;
  2674. case FCMP_OEQ: return FCMP_UNE;
  2675. case FCMP_ONE: return FCMP_UEQ;
  2676. case FCMP_OGT: return FCMP_ULE;
  2677. case FCMP_OLT: return FCMP_UGE;
  2678. case FCMP_OGE: return FCMP_ULT;
  2679. case FCMP_OLE: return FCMP_UGT;
  2680. case FCMP_UEQ: return FCMP_ONE;
  2681. case FCMP_UNE: return FCMP_OEQ;
  2682. case FCMP_UGT: return FCMP_OLE;
  2683. case FCMP_ULT: return FCMP_OGE;
  2684. case FCMP_UGE: return FCMP_OLT;
  2685. case FCMP_ULE: return FCMP_OGT;
  2686. case FCMP_ORD: return FCMP_UNO;
  2687. case FCMP_UNO: return FCMP_ORD;
  2688. case FCMP_TRUE: return FCMP_FALSE;
  2689. case FCMP_FALSE: return FCMP_TRUE;
  2690. }
  2691. }
  2692. ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
  2693. switch (pred) {
  2694. default: llvm_unreachable("Unknown icmp predicate!");
  2695. case ICMP_EQ: case ICMP_NE:
  2696. case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
  2697. return pred;
  2698. case ICMP_UGT: return ICMP_SGT;
  2699. case ICMP_ULT: return ICMP_SLT;
  2700. case ICMP_UGE: return ICMP_SGE;
  2701. case ICMP_ULE: return ICMP_SLE;
  2702. }
  2703. }
  2704. ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
  2705. switch (pred) {
  2706. default: llvm_unreachable("Unknown icmp predicate!");
  2707. case ICMP_EQ: case ICMP_NE:
  2708. case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
  2709. return pred;
  2710. case ICMP_SGT: return ICMP_UGT;
  2711. case ICMP_SLT: return ICMP_ULT;
  2712. case ICMP_SGE: return ICMP_UGE;
  2713. case ICMP_SLE: return ICMP_ULE;
  2714. }
  2715. }
  2716. /// Initialize a set of values that all satisfy the condition with C.
  2717. ///
  2718. ConstantRange
  2719. ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
  2720. APInt Lower(C);
  2721. APInt Upper(C);
  2722. uint32_t BitWidth = C.getBitWidth();
  2723. switch (pred) {
  2724. default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
  2725. case ICmpInst::ICMP_EQ: ++Upper; break;
  2726. case ICmpInst::ICMP_NE: ++Lower; break;
  2727. case ICmpInst::ICMP_ULT:
  2728. Lower = APInt::getMinValue(BitWidth);
  2729. // Check for an empty-set condition.
  2730. if (Lower == Upper)
  2731. return ConstantRange(BitWidth, /*isFullSet=*/false);
  2732. break;
  2733. case ICmpInst::ICMP_SLT:
  2734. Lower = APInt::getSignedMinValue(BitWidth);
  2735. // Check for an empty-set condition.
  2736. if (Lower == Upper)
  2737. return ConstantRange(BitWidth, /*isFullSet=*/false);
  2738. break;
  2739. case ICmpInst::ICMP_UGT:
  2740. ++Lower; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
  2741. // Check for an empty-set condition.
  2742. if (Lower == Upper)
  2743. return ConstantRange(BitWidth, /*isFullSet=*/false);
  2744. break;
  2745. case ICmpInst::ICMP_SGT:
  2746. ++Lower; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
  2747. // Check for an empty-set condition.
  2748. if (Lower == Upper)
  2749. return ConstantRange(BitWidth, /*isFullSet=*/false);
  2750. break;
  2751. case ICmpInst::ICMP_ULE:
  2752. Lower = APInt::getMinValue(BitWidth); ++Upper;
  2753. // Check for a full-set condition.
  2754. if (Lower == Upper)
  2755. return ConstantRange(BitWidth, /*isFullSet=*/true);
  2756. break;
  2757. case ICmpInst::ICMP_SLE:
  2758. Lower = APInt::getSignedMinValue(BitWidth); ++Upper;
  2759. // Check for a full-set condition.
  2760. if (Lower == Upper)
  2761. return ConstantRange(BitWidth, /*isFullSet=*/true);
  2762. break;
  2763. case ICmpInst::ICMP_UGE:
  2764. Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
  2765. // Check for a full-set condition.
  2766. if (Lower == Upper)
  2767. return ConstantRange(BitWidth, /*isFullSet=*/true);
  2768. break;
  2769. case ICmpInst::ICMP_SGE:
  2770. Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
  2771. // Check for a full-set condition.
  2772. if (Lower == Upper)
  2773. return ConstantRange(BitWidth, /*isFullSet=*/true);
  2774. break;
  2775. }
  2776. return ConstantRange(Lower, Upper);
  2777. }
  2778. CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
  2779. switch (pred) {
  2780. default: llvm_unreachable("Unknown cmp predicate!");
  2781. case ICMP_EQ: case ICMP_NE:
  2782. return pred;
  2783. case ICMP_SGT: return ICMP_SLT;
  2784. case ICMP_SLT: return ICMP_SGT;
  2785. case ICMP_SGE: return ICMP_SLE;
  2786. case ICMP_SLE: return ICMP_SGE;
  2787. case ICMP_UGT: return ICMP_ULT;
  2788. case ICMP_ULT: return ICMP_UGT;
  2789. case ICMP_UGE: return ICMP_ULE;
  2790. case ICMP_ULE: return ICMP_UGE;
  2791. case FCMP_FALSE: case FCMP_TRUE:
  2792. case FCMP_OEQ: case FCMP_ONE:
  2793. case FCMP_UEQ: case FCMP_UNE:
  2794. case FCMP_ORD: case FCMP_UNO:
  2795. return pred;
  2796. case FCMP_OGT: return FCMP_OLT;
  2797. case FCMP_OLT: return FCMP_OGT;
  2798. case FCMP_OGE: return FCMP_OLE;
  2799. case FCMP_OLE: return FCMP_OGE;
  2800. case FCMP_UGT: return FCMP_ULT;
  2801. case FCMP_ULT: return FCMP_UGT;
  2802. case FCMP_UGE: return FCMP_ULE;
  2803. case FCMP_ULE: return FCMP_UGE;
  2804. }
  2805. }
  2806. bool CmpInst::isUnsigned(unsigned short predicate) {
  2807. switch (predicate) {
  2808. default: return false;
  2809. case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
  2810. case ICmpInst::ICMP_UGE: return true;
  2811. }
  2812. }
  2813. bool CmpInst::isSigned(unsigned short predicate) {
  2814. switch (predicate) {
  2815. default: return false;
  2816. case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
  2817. case ICmpInst::ICMP_SGE: return true;
  2818. }
  2819. }
  2820. bool CmpInst::isOrdered(unsigned short predicate) {
  2821. switch (predicate) {
  2822. default: return false;
  2823. case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
  2824. case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
  2825. case FCmpInst::FCMP_ORD: return true;
  2826. }
  2827. }
  2828. bool CmpInst::isUnordered(unsigned short predicate) {
  2829. switch (predicate) {
  2830. default: return false;
  2831. case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
  2832. case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
  2833. case FCmpInst::FCMP_UNO: return true;
  2834. }
  2835. }
  2836. bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
  2837. switch(predicate) {
  2838. default: return false;
  2839. case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
  2840. case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
  2841. }
  2842. }
  2843. bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
  2844. switch(predicate) {
  2845. case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
  2846. case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
  2847. default: return false;
  2848. }
  2849. }
  2850. //===----------------------------------------------------------------------===//
  2851. // SwitchInst Implementation
  2852. //===----------------------------------------------------------------------===//
  2853. void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
  2854. assert(Value && Default && NumReserved);
  2855. ReservedSpace = NumReserved;
  2856. setNumHungOffUseOperands(2);
  2857. allocHungoffUses(ReservedSpace);
  2858. Op<0>() = Value;
  2859. Op<1>() = Default;
  2860. }
  2861. /// SwitchInst ctor - Create a new switch instruction, specifying a value to
  2862. /// switch on and a default destination. The number of additional cases can
  2863. /// be specified here to make memory allocation more efficient. This
  2864. /// constructor can also autoinsert before another instruction.
  2865. SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
  2866. Instruction *InsertBefore)
  2867. : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
  2868. nullptr, 0, InsertBefore) {
  2869. init(Value, Default, 2+NumCases*2);
  2870. }
  2871. /// SwitchInst ctor - Create a new switch instruction, specifying a value to
  2872. /// switch on and a default destination. The number of additional cases can
  2873. /// be specified here to make memory allocation more efficient. This
  2874. /// constructor also autoinserts at the end of the specified BasicBlock.
  2875. SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
  2876. BasicBlock *InsertAtEnd)
  2877. : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
  2878. nullptr, 0, InsertAtEnd) {
  2879. init(Value, Default, 2+NumCases*2);
  2880. }
  2881. SwitchInst::SwitchInst(const SwitchInst &SI)
  2882. : TerminatorInst(SI.getType(), Instruction::Switch, nullptr, 0) {
  2883. init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
  2884. setNumHungOffUseOperands(SI.getNumOperands());
  2885. Use *OL = getOperandList();
  2886. const Use *InOL = SI.getOperandList();
  2887. for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
  2888. OL[i] = InOL[i];
  2889. OL[i+1] = InOL[i+1];
  2890. }
  2891. SubclassOptionalData = SI.SubclassOptionalData;
  2892. }
  2893. /// addCase - Add an entry to the switch instruction...
  2894. ///
  2895. void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
  2896. unsigned NewCaseIdx = getNumCases();
  2897. unsigned OpNo = getNumOperands();
  2898. if (OpNo+2 > ReservedSpace)
  2899. growOperands(); // Get more space!
  2900. // Initialize some new operands.
  2901. assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
  2902. setNumHungOffUseOperands(OpNo+2);
  2903. CaseIt Case(this, NewCaseIdx);
  2904. Case.setValue(OnVal);
  2905. Case.setSuccessor(Dest);
  2906. }
  2907. /// removeCase - This method removes the specified case and its successor
  2908. /// from the switch instruction.
  2909. void SwitchInst::removeCase(CaseIt i) {
  2910. unsigned idx = i.getCaseIndex();
  2911. assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
  2912. unsigned NumOps = getNumOperands();
  2913. Use *OL = getOperandList();
  2914. // Overwrite this case with the end of the list.
  2915. if (2 + (idx + 1) * 2 != NumOps) {
  2916. OL[2 + idx * 2] = OL[NumOps - 2];
  2917. OL[2 + idx * 2 + 1] = OL[NumOps - 1];
  2918. }
  2919. // Nuke the last value.
  2920. OL[NumOps-2].set(nullptr);
  2921. OL[NumOps-2+1].set(nullptr);
  2922. setNumHungOffUseOperands(NumOps-2);
  2923. }
  2924. /// growOperands - grow operands - This grows the operand list in response
  2925. /// to a push_back style of operation. This grows the number of ops by 3 times.
  2926. ///
  2927. void SwitchInst::growOperands() {
  2928. unsigned e = getNumOperands();
  2929. unsigned NumOps = e*3;
  2930. ReservedSpace = NumOps;
  2931. growHungoffUses(ReservedSpace);
  2932. }
  2933. BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
  2934. return getSuccessor(idx);
  2935. }
  2936. unsigned SwitchInst::getNumSuccessorsV() const {
  2937. return getNumSuccessors();
  2938. }
  2939. void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
  2940. setSuccessor(idx, B);
  2941. }
  2942. //===----------------------------------------------------------------------===//
  2943. // IndirectBrInst Implementation
  2944. //===----------------------------------------------------------------------===//
  2945. void IndirectBrInst::init(Value *Address, unsigned NumDests) {
  2946. assert(Address && Address->getType()->isPointerTy() &&
  2947. "Address of indirectbr must be a pointer");
  2948. ReservedSpace = 1+NumDests;
  2949. setNumHungOffUseOperands(1);
  2950. allocHungoffUses(ReservedSpace);
  2951. Op<0>() = Address;
  2952. }
  2953. /// growOperands - grow operands - This grows the operand list in response
  2954. /// to a push_back style of operation. This grows the number of ops by 2 times.
  2955. ///
  2956. void IndirectBrInst::growOperands() {
  2957. unsigned e = getNumOperands();
  2958. unsigned NumOps = e*2;
  2959. ReservedSpace = NumOps;
  2960. growHungoffUses(ReservedSpace);
  2961. }
  2962. IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
  2963. Instruction *InsertBefore)
  2964. : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
  2965. nullptr, 0, InsertBefore) {
  2966. init(Address, NumCases);
  2967. }
  2968. IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
  2969. BasicBlock *InsertAtEnd)
  2970. : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
  2971. nullptr, 0, InsertAtEnd) {
  2972. init(Address, NumCases);
  2973. }
  2974. IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
  2975. : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
  2976. nullptr, IBI.getNumOperands()) {
  2977. allocHungoffUses(IBI.getNumOperands());
  2978. Use *OL = getOperandList();
  2979. const Use *InOL = IBI.getOperandList();
  2980. for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
  2981. OL[i] = InOL[i];
  2982. SubclassOptionalData = IBI.SubclassOptionalData;
  2983. }
  2984. /// addDestination - Add a destination.
  2985. ///
  2986. void IndirectBrInst::addDestination(BasicBlock *DestBB) {
  2987. unsigned OpNo = getNumOperands();
  2988. if (OpNo+1 > ReservedSpace)
  2989. growOperands(); // Get more space!
  2990. // Initialize some new operands.
  2991. assert(OpNo < ReservedSpace && "Growing didn't work!");
  2992. setNumHungOffUseOperands(OpNo+1);
  2993. getOperandList()[OpNo] = DestBB;
  2994. }
  2995. /// removeDestination - This method removes the specified successor from the
  2996. /// indirectbr instruction.
  2997. void IndirectBrInst::removeDestination(unsigned idx) {
  2998. assert(idx < getNumOperands()-1 && "Successor index out of range!");
  2999. unsigned NumOps = getNumOperands();
  3000. Use *OL = getOperandList();
  3001. // Replace this value with the last one.
  3002. OL[idx+1] = OL[NumOps-1];
  3003. // Nuke the last value.
  3004. OL[NumOps-1].set(nullptr);
  3005. setNumHungOffUseOperands(NumOps-1);
  3006. }
  3007. BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
  3008. return getSuccessor(idx);
  3009. }
  3010. unsigned IndirectBrInst::getNumSuccessorsV() const {
  3011. return getNumSuccessors();
  3012. }
  3013. void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
  3014. setSuccessor(idx, B);
  3015. }
  3016. //===----------------------------------------------------------------------===//
  3017. // cloneImpl() implementations
  3018. //===----------------------------------------------------------------------===//
  3019. // Define these methods here so vtables don't get emitted into every translation
  3020. // unit that uses these classes.
  3021. GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
  3022. return new (getNumOperands()) GetElementPtrInst(*this);
  3023. }
  3024. BinaryOperator *BinaryOperator::cloneImpl() const {
  3025. return Create(getOpcode(), Op<0>(), Op<1>());
  3026. }
  3027. FCmpInst *FCmpInst::cloneImpl() const {
  3028. return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
  3029. }
  3030. ICmpInst *ICmpInst::cloneImpl() const {
  3031. return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
  3032. }
  3033. ExtractValueInst *ExtractValueInst::cloneImpl() const {
  3034. return new ExtractValueInst(*this);
  3035. }
  3036. InsertValueInst *InsertValueInst::cloneImpl() const {
  3037. return new InsertValueInst(*this);
  3038. }
  3039. AllocaInst *AllocaInst::cloneImpl() const {
  3040. AllocaInst *Result = new AllocaInst(getAllocatedType(),
  3041. (Value *)getOperand(0), getAlignment());
  3042. Result->setUsedWithInAlloca(isUsedWithInAlloca());
  3043. return Result;
  3044. }
  3045. LoadInst *LoadInst::cloneImpl() const {
  3046. return new LoadInst(getOperand(0), Twine(), isVolatile(),
  3047. getAlignment(), getOrdering(), getSynchScope());
  3048. }
  3049. StoreInst *StoreInst::cloneImpl() const {
  3050. return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
  3051. getAlignment(), getOrdering(), getSynchScope());
  3052. }
  3053. AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const {
  3054. AtomicCmpXchgInst *Result =
  3055. new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
  3056. getSuccessOrdering(), getFailureOrdering(),
  3057. getSynchScope());
  3058. Result->setVolatile(isVolatile());
  3059. Result->setWeak(isWeak());
  3060. return Result;
  3061. }
  3062. AtomicRMWInst *AtomicRMWInst::cloneImpl() const {
  3063. AtomicRMWInst *Result =
  3064. new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
  3065. getOrdering(), getSynchScope());
  3066. Result->setVolatile(isVolatile());
  3067. return Result;
  3068. }
  3069. FenceInst *FenceInst::cloneImpl() const {
  3070. return new FenceInst(getContext(), getOrdering(), getSynchScope());
  3071. }
  3072. TruncInst *TruncInst::cloneImpl() const {
  3073. return new TruncInst(getOperand(0), getType());
  3074. }
  3075. ZExtInst *ZExtInst::cloneImpl() const {
  3076. return new ZExtInst(getOperand(0), getType());
  3077. }
  3078. SExtInst *SExtInst::cloneImpl() const {
  3079. return new SExtInst(getOperand(0), getType());
  3080. }
  3081. FPTruncInst *FPTruncInst::cloneImpl() const {
  3082. return new FPTruncInst(getOperand(0), getType());
  3083. }
  3084. FPExtInst *FPExtInst::cloneImpl() const {
  3085. return new FPExtInst(getOperand(0), getType());
  3086. }
  3087. UIToFPInst *UIToFPInst::cloneImpl() const {
  3088. return new UIToFPInst(getOperand(0), getType());
  3089. }
  3090. SIToFPInst *SIToFPInst::cloneImpl() const {
  3091. return new SIToFPInst(getOperand(0), getType());
  3092. }
  3093. FPToUIInst *FPToUIInst::cloneImpl() const {
  3094. return new FPToUIInst(getOperand(0), getType());
  3095. }
  3096. FPToSIInst *FPToSIInst::cloneImpl() const {
  3097. return new FPToSIInst(getOperand(0), getType());
  3098. }
  3099. PtrToIntInst *PtrToIntInst::cloneImpl() const {
  3100. return new PtrToIntInst(getOperand(0), getType());
  3101. }
  3102. IntToPtrInst *IntToPtrInst::cloneImpl() const {
  3103. return new IntToPtrInst(getOperand(0), getType());
  3104. }
  3105. BitCastInst *BitCastInst::cloneImpl() const {
  3106. return new BitCastInst(getOperand(0), getType());
  3107. }
  3108. AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const {
  3109. return new AddrSpaceCastInst(getOperand(0), getType());
  3110. }
  3111. CallInst *CallInst::cloneImpl() const {
  3112. return new(getNumOperands()) CallInst(*this);
  3113. }
  3114. SelectInst *SelectInst::cloneImpl() const {
  3115. return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
  3116. }
  3117. VAArgInst *VAArgInst::cloneImpl() const {
  3118. return new VAArgInst(getOperand(0), getType());
  3119. }
  3120. ExtractElementInst *ExtractElementInst::cloneImpl() const {
  3121. return ExtractElementInst::Create(getOperand(0), getOperand(1));
  3122. }
  3123. InsertElementInst *InsertElementInst::cloneImpl() const {
  3124. return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
  3125. }
  3126. ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const {
  3127. return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
  3128. }
  3129. PHINode *PHINode::cloneImpl() const { return new PHINode(*this); }
  3130. LandingPadInst *LandingPadInst::cloneImpl() const {
  3131. return new LandingPadInst(*this);
  3132. }
  3133. ReturnInst *ReturnInst::cloneImpl() const {
  3134. return new(getNumOperands()) ReturnInst(*this);
  3135. }
  3136. BranchInst *BranchInst::cloneImpl() const {
  3137. return new(getNumOperands()) BranchInst(*this);
  3138. }
  3139. SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
  3140. IndirectBrInst *IndirectBrInst::cloneImpl() const {
  3141. return new IndirectBrInst(*this);
  3142. }
  3143. InvokeInst *InvokeInst::cloneImpl() const {
  3144. return new(getNumOperands()) InvokeInst(*this);
  3145. }
  3146. ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
  3147. UnreachableInst *UnreachableInst::cloneImpl() const {
  3148. LLVMContext &Context = getContext();
  3149. return new UnreachableInst(Context);
  3150. }