Constants.cpp 121 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480
  1. //===-- Constants.cpp - Implement Constant nodes --------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Constant* classes.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/IR/Constants.h"
  13. #include "LLVMContextImpl.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/StringMap.h"
  17. #include "llvm/IR/BasicBlock.h"
  18. #include "llvm/IR/ConstantFold.h"
  19. #include "llvm/IR/DerivedTypes.h"
  20. #include "llvm/IR/Function.h"
  21. #include "llvm/IR/GetElementPtrTypeIterator.h"
  22. #include "llvm/IR/GlobalAlias.h"
  23. #include "llvm/IR/GlobalIFunc.h"
  24. #include "llvm/IR/GlobalValue.h"
  25. #include "llvm/IR/GlobalVariable.h"
  26. #include "llvm/IR/Instructions.h"
  27. #include "llvm/IR/Operator.h"
  28. #include "llvm/IR/PatternMatch.h"
  29. #include "llvm/Support/ErrorHandling.h"
  30. #include "llvm/Support/MathExtras.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include <algorithm>
  33. using namespace llvm;
  34. using namespace PatternMatch;
  35. //===----------------------------------------------------------------------===//
  36. // Constant Class
  37. //===----------------------------------------------------------------------===//
  38. bool Constant::isNegativeZeroValue() const {
  39. // Floating point values have an explicit -0.0 value.
  40. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
  41. return CFP->isZero() && CFP->isNegative();
  42. // Equivalent for a vector of -0.0's.
  43. if (getType()->isVectorTy())
  44. if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
  45. return SplatCFP->isNegativeZeroValue();
  46. // We've already handled true FP case; any other FP vectors can't represent -0.0.
  47. if (getType()->isFPOrFPVectorTy())
  48. return false;
  49. // Otherwise, just use +0.0.
  50. return isNullValue();
  51. }
  52. // Return true iff this constant is positive zero (floating point), negative
  53. // zero (floating point), or a null value.
  54. bool Constant::isZeroValue() const {
  55. // Floating point values have an explicit -0.0 value.
  56. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
  57. return CFP->isZero();
  58. // Check for constant splat vectors of 1 values.
  59. if (getType()->isVectorTy())
  60. if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
  61. return SplatCFP->isZero();
  62. // Otherwise, just use +0.0.
  63. return isNullValue();
  64. }
  65. bool Constant::isNullValue() const {
  66. // 0 is null.
  67. if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
  68. return CI->isZero();
  69. // +0.0 is null.
  70. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
  71. // ppc_fp128 determine isZero using high order double only
  72. // Should check the bitwise value to make sure all bits are zero.
  73. return CFP->isExactlyValue(+0.0);
  74. // constant zero is zero for aggregates, cpnull is null for pointers, none for
  75. // tokens.
  76. return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
  77. isa<ConstantTokenNone>(this) || isa<ConstantTargetNone>(this);
  78. }
  79. bool Constant::isAllOnesValue() const {
  80. // Check for -1 integers
  81. if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
  82. return CI->isMinusOne();
  83. // Check for FP which are bitcasted from -1 integers
  84. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
  85. return CFP->getValueAPF().bitcastToAPInt().isAllOnes();
  86. // Check for constant splat vectors of 1 values.
  87. if (getType()->isVectorTy())
  88. if (const auto *SplatVal = getSplatValue())
  89. return SplatVal->isAllOnesValue();
  90. return false;
  91. }
  92. bool Constant::isOneValue() const {
  93. // Check for 1 integers
  94. if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
  95. return CI->isOne();
  96. // Check for FP which are bitcasted from 1 integers
  97. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
  98. return CFP->getValueAPF().bitcastToAPInt().isOne();
  99. // Check for constant splat vectors of 1 values.
  100. if (getType()->isVectorTy())
  101. if (const auto *SplatVal = getSplatValue())
  102. return SplatVal->isOneValue();
  103. return false;
  104. }
  105. bool Constant::isNotOneValue() const {
  106. // Check for 1 integers
  107. if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
  108. return !CI->isOneValue();
  109. // Check for FP which are bitcasted from 1 integers
  110. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
  111. return !CFP->getValueAPF().bitcastToAPInt().isOne();
  112. // Check that vectors don't contain 1
  113. if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
  114. for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
  115. Constant *Elt = getAggregateElement(I);
  116. if (!Elt || !Elt->isNotOneValue())
  117. return false;
  118. }
  119. return true;
  120. }
  121. // Check for splats that don't contain 1
  122. if (getType()->isVectorTy())
  123. if (const auto *SplatVal = getSplatValue())
  124. return SplatVal->isNotOneValue();
  125. // It *may* contain 1, we can't tell.
  126. return false;
  127. }
  128. bool Constant::isMinSignedValue() const {
  129. // Check for INT_MIN integers
  130. if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
  131. return CI->isMinValue(/*isSigned=*/true);
  132. // Check for FP which are bitcasted from INT_MIN integers
  133. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
  134. return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
  135. // Check for splats of INT_MIN values.
  136. if (getType()->isVectorTy())
  137. if (const auto *SplatVal = getSplatValue())
  138. return SplatVal->isMinSignedValue();
  139. return false;
  140. }
  141. bool Constant::isNotMinSignedValue() const {
  142. // Check for INT_MIN integers
  143. if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
  144. return !CI->isMinValue(/*isSigned=*/true);
  145. // Check for FP which are bitcasted from INT_MIN integers
  146. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
  147. return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
  148. // Check that vectors don't contain INT_MIN
  149. if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
  150. for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
  151. Constant *Elt = getAggregateElement(I);
  152. if (!Elt || !Elt->isNotMinSignedValue())
  153. return false;
  154. }
  155. return true;
  156. }
  157. // Check for splats that aren't INT_MIN
  158. if (getType()->isVectorTy())
  159. if (const auto *SplatVal = getSplatValue())
  160. return SplatVal->isNotMinSignedValue();
  161. // It *may* contain INT_MIN, we can't tell.
  162. return false;
  163. }
  164. bool Constant::isFiniteNonZeroFP() const {
  165. if (auto *CFP = dyn_cast<ConstantFP>(this))
  166. return CFP->getValueAPF().isFiniteNonZero();
  167. if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
  168. for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
  169. auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
  170. if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
  171. return false;
  172. }
  173. return true;
  174. }
  175. if (getType()->isVectorTy())
  176. if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
  177. return SplatCFP->isFiniteNonZeroFP();
  178. // It *may* contain finite non-zero, we can't tell.
  179. return false;
  180. }
  181. bool Constant::isNormalFP() const {
  182. if (auto *CFP = dyn_cast<ConstantFP>(this))
  183. return CFP->getValueAPF().isNormal();
  184. if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
  185. for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
  186. auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
  187. if (!CFP || !CFP->getValueAPF().isNormal())
  188. return false;
  189. }
  190. return true;
  191. }
  192. if (getType()->isVectorTy())
  193. if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
  194. return SplatCFP->isNormalFP();
  195. // It *may* contain a normal fp value, we can't tell.
  196. return false;
  197. }
  198. bool Constant::hasExactInverseFP() const {
  199. if (auto *CFP = dyn_cast<ConstantFP>(this))
  200. return CFP->getValueAPF().getExactInverse(nullptr);
  201. if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
  202. for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
  203. auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
  204. if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
  205. return false;
  206. }
  207. return true;
  208. }
  209. if (getType()->isVectorTy())
  210. if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
  211. return SplatCFP->hasExactInverseFP();
  212. // It *may* have an exact inverse fp value, we can't tell.
  213. return false;
  214. }
  215. bool Constant::isNaN() const {
  216. if (auto *CFP = dyn_cast<ConstantFP>(this))
  217. return CFP->isNaN();
  218. if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
  219. for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
  220. auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
  221. if (!CFP || !CFP->isNaN())
  222. return false;
  223. }
  224. return true;
  225. }
  226. if (getType()->isVectorTy())
  227. if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
  228. return SplatCFP->isNaN();
  229. // It *may* be NaN, we can't tell.
  230. return false;
  231. }
  232. bool Constant::isElementWiseEqual(Value *Y) const {
  233. // Are they fully identical?
  234. if (this == Y)
  235. return true;
  236. // The input value must be a vector constant with the same type.
  237. auto *VTy = dyn_cast<VectorType>(getType());
  238. if (!isa<Constant>(Y) || !VTy || VTy != Y->getType())
  239. return false;
  240. // TODO: Compare pointer constants?
  241. if (!(VTy->getElementType()->isIntegerTy() ||
  242. VTy->getElementType()->isFloatingPointTy()))
  243. return false;
  244. // They may still be identical element-wise (if they have `undef`s).
  245. // Bitcast to integer to allow exact bitwise comparison for all types.
  246. Type *IntTy = VectorType::getInteger(VTy);
  247. Constant *C0 = ConstantExpr::getBitCast(const_cast<Constant *>(this), IntTy);
  248. Constant *C1 = ConstantExpr::getBitCast(cast<Constant>(Y), IntTy);
  249. Constant *CmpEq = ConstantExpr::getICmp(ICmpInst::ICMP_EQ, C0, C1);
  250. return isa<UndefValue>(CmpEq) || match(CmpEq, m_One());
  251. }
  252. static bool
  253. containsUndefinedElement(const Constant *C,
  254. function_ref<bool(const Constant *)> HasFn) {
  255. if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
  256. if (HasFn(C))
  257. return true;
  258. if (isa<ConstantAggregateZero>(C))
  259. return false;
  260. if (isa<ScalableVectorType>(C->getType()))
  261. return false;
  262. for (unsigned i = 0, e = cast<FixedVectorType>(VTy)->getNumElements();
  263. i != e; ++i) {
  264. if (Constant *Elem = C->getAggregateElement(i))
  265. if (HasFn(Elem))
  266. return true;
  267. }
  268. }
  269. return false;
  270. }
  271. bool Constant::containsUndefOrPoisonElement() const {
  272. return containsUndefinedElement(
  273. this, [&](const auto *C) { return isa<UndefValue>(C); });
  274. }
  275. bool Constant::containsPoisonElement() const {
  276. return containsUndefinedElement(
  277. this, [&](const auto *C) { return isa<PoisonValue>(C); });
  278. }
  279. bool Constant::containsUndefElement() const {
  280. return containsUndefinedElement(this, [&](const auto *C) {
  281. return isa<UndefValue>(C) && !isa<PoisonValue>(C);
  282. });
  283. }
  284. bool Constant::containsConstantExpression() const {
  285. if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
  286. for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
  287. if (isa<ConstantExpr>(getAggregateElement(i)))
  288. return true;
  289. }
  290. return false;
  291. }
  292. /// Constructor to create a '0' constant of arbitrary type.
  293. Constant *Constant::getNullValue(Type *Ty) {
  294. switch (Ty->getTypeID()) {
  295. case Type::IntegerTyID:
  296. return ConstantInt::get(Ty, 0);
  297. case Type::HalfTyID:
  298. case Type::BFloatTyID:
  299. case Type::FloatTyID:
  300. case Type::DoubleTyID:
  301. case Type::X86_FP80TyID:
  302. case Type::FP128TyID:
  303. case Type::PPC_FP128TyID:
  304. return ConstantFP::get(Ty->getContext(),
  305. APFloat::getZero(Ty->getFltSemantics()));
  306. case Type::PointerTyID:
  307. return ConstantPointerNull::get(cast<PointerType>(Ty));
  308. case Type::StructTyID:
  309. case Type::ArrayTyID:
  310. case Type::FixedVectorTyID:
  311. case Type::ScalableVectorTyID:
  312. return ConstantAggregateZero::get(Ty);
  313. case Type::TokenTyID:
  314. return ConstantTokenNone::get(Ty->getContext());
  315. case Type::TargetExtTyID:
  316. return ConstantTargetNone::get(cast<TargetExtType>(Ty));
  317. default:
  318. // Function, Label, or Opaque type?
  319. llvm_unreachable("Cannot create a null constant of that type!");
  320. }
  321. }
  322. Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
  323. Type *ScalarTy = Ty->getScalarType();
  324. // Create the base integer constant.
  325. Constant *C = ConstantInt::get(Ty->getContext(), V);
  326. // Convert an integer to a pointer, if necessary.
  327. if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
  328. C = ConstantExpr::getIntToPtr(C, PTy);
  329. // Broadcast a scalar to a vector, if necessary.
  330. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  331. C = ConstantVector::getSplat(VTy->getElementCount(), C);
  332. return C;
  333. }
  334. Constant *Constant::getAllOnesValue(Type *Ty) {
  335. if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
  336. return ConstantInt::get(Ty->getContext(),
  337. APInt::getAllOnes(ITy->getBitWidth()));
  338. if (Ty->isFloatingPointTy()) {
  339. APFloat FL = APFloat::getAllOnesValue(Ty->getFltSemantics());
  340. return ConstantFP::get(Ty->getContext(), FL);
  341. }
  342. VectorType *VTy = cast<VectorType>(Ty);
  343. return ConstantVector::getSplat(VTy->getElementCount(),
  344. getAllOnesValue(VTy->getElementType()));
  345. }
  346. Constant *Constant::getAggregateElement(unsigned Elt) const {
  347. assert((getType()->isAggregateType() || getType()->isVectorTy()) &&
  348. "Must be an aggregate/vector constant");
  349. if (const auto *CC = dyn_cast<ConstantAggregate>(this))
  350. return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
  351. if (const auto *CAZ = dyn_cast<ConstantAggregateZero>(this))
  352. return Elt < CAZ->getElementCount().getKnownMinValue()
  353. ? CAZ->getElementValue(Elt)
  354. : nullptr;
  355. // FIXME: getNumElements() will fail for non-fixed vector types.
  356. if (isa<ScalableVectorType>(getType()))
  357. return nullptr;
  358. if (const auto *PV = dyn_cast<PoisonValue>(this))
  359. return Elt < PV->getNumElements() ? PV->getElementValue(Elt) : nullptr;
  360. if (const auto *UV = dyn_cast<UndefValue>(this))
  361. return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
  362. if (const auto *CDS = dyn_cast<ConstantDataSequential>(this))
  363. return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
  364. : nullptr;
  365. return nullptr;
  366. }
  367. Constant *Constant::getAggregateElement(Constant *Elt) const {
  368. assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
  369. if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
  370. // Check if the constant fits into an uint64_t.
  371. if (CI->getValue().getActiveBits() > 64)
  372. return nullptr;
  373. return getAggregateElement(CI->getZExtValue());
  374. }
  375. return nullptr;
  376. }
  377. void Constant::destroyConstant() {
  378. /// First call destroyConstantImpl on the subclass. This gives the subclass
  379. /// a chance to remove the constant from any maps/pools it's contained in.
  380. switch (getValueID()) {
  381. default:
  382. llvm_unreachable("Not a constant!");
  383. #define HANDLE_CONSTANT(Name) \
  384. case Value::Name##Val: \
  385. cast<Name>(this)->destroyConstantImpl(); \
  386. break;
  387. #include "llvm/IR/Value.def"
  388. }
  389. // When a Constant is destroyed, there may be lingering
  390. // references to the constant by other constants in the constant pool. These
  391. // constants are implicitly dependent on the module that is being deleted,
  392. // but they don't know that. Because we only find out when the CPV is
  393. // deleted, we must now notify all of our users (that should only be
  394. // Constants) that they are, in fact, invalid now and should be deleted.
  395. //
  396. while (!use_empty()) {
  397. Value *V = user_back();
  398. #ifndef NDEBUG // Only in -g mode...
  399. if (!isa<Constant>(V)) {
  400. dbgs() << "While deleting: " << *this
  401. << "\n\nUse still stuck around after Def is destroyed: " << *V
  402. << "\n\n";
  403. }
  404. #endif
  405. assert(isa<Constant>(V) && "References remain to Constant being destroyed");
  406. cast<Constant>(V)->destroyConstant();
  407. // The constant should remove itself from our use list...
  408. assert((use_empty() || user_back() != V) && "Constant not removed!");
  409. }
  410. // Value has no outstanding references it is safe to delete it now...
  411. deleteConstant(this);
  412. }
  413. void llvm::deleteConstant(Constant *C) {
  414. switch (C->getValueID()) {
  415. case Constant::ConstantIntVal:
  416. delete static_cast<ConstantInt *>(C);
  417. break;
  418. case Constant::ConstantFPVal:
  419. delete static_cast<ConstantFP *>(C);
  420. break;
  421. case Constant::ConstantAggregateZeroVal:
  422. delete static_cast<ConstantAggregateZero *>(C);
  423. break;
  424. case Constant::ConstantArrayVal:
  425. delete static_cast<ConstantArray *>(C);
  426. break;
  427. case Constant::ConstantStructVal:
  428. delete static_cast<ConstantStruct *>(C);
  429. break;
  430. case Constant::ConstantVectorVal:
  431. delete static_cast<ConstantVector *>(C);
  432. break;
  433. case Constant::ConstantPointerNullVal:
  434. delete static_cast<ConstantPointerNull *>(C);
  435. break;
  436. case Constant::ConstantDataArrayVal:
  437. delete static_cast<ConstantDataArray *>(C);
  438. break;
  439. case Constant::ConstantDataVectorVal:
  440. delete static_cast<ConstantDataVector *>(C);
  441. break;
  442. case Constant::ConstantTokenNoneVal:
  443. delete static_cast<ConstantTokenNone *>(C);
  444. break;
  445. case Constant::BlockAddressVal:
  446. delete static_cast<BlockAddress *>(C);
  447. break;
  448. case Constant::DSOLocalEquivalentVal:
  449. delete static_cast<DSOLocalEquivalent *>(C);
  450. break;
  451. case Constant::NoCFIValueVal:
  452. delete static_cast<NoCFIValue *>(C);
  453. break;
  454. case Constant::UndefValueVal:
  455. delete static_cast<UndefValue *>(C);
  456. break;
  457. case Constant::PoisonValueVal:
  458. delete static_cast<PoisonValue *>(C);
  459. break;
  460. case Constant::ConstantExprVal:
  461. if (isa<CastConstantExpr>(C))
  462. delete static_cast<CastConstantExpr *>(C);
  463. else if (isa<BinaryConstantExpr>(C))
  464. delete static_cast<BinaryConstantExpr *>(C);
  465. else if (isa<SelectConstantExpr>(C))
  466. delete static_cast<SelectConstantExpr *>(C);
  467. else if (isa<ExtractElementConstantExpr>(C))
  468. delete static_cast<ExtractElementConstantExpr *>(C);
  469. else if (isa<InsertElementConstantExpr>(C))
  470. delete static_cast<InsertElementConstantExpr *>(C);
  471. else if (isa<ShuffleVectorConstantExpr>(C))
  472. delete static_cast<ShuffleVectorConstantExpr *>(C);
  473. else if (isa<GetElementPtrConstantExpr>(C))
  474. delete static_cast<GetElementPtrConstantExpr *>(C);
  475. else if (isa<CompareConstantExpr>(C))
  476. delete static_cast<CompareConstantExpr *>(C);
  477. else
  478. llvm_unreachable("Unexpected constant expr");
  479. break;
  480. default:
  481. llvm_unreachable("Unexpected constant");
  482. }
  483. }
  484. /// Check if C contains a GlobalValue for which Predicate is true.
  485. static bool
  486. ConstHasGlobalValuePredicate(const Constant *C,
  487. bool (*Predicate)(const GlobalValue *)) {
  488. SmallPtrSet<const Constant *, 8> Visited;
  489. SmallVector<const Constant *, 8> WorkList;
  490. WorkList.push_back(C);
  491. Visited.insert(C);
  492. while (!WorkList.empty()) {
  493. const Constant *WorkItem = WorkList.pop_back_val();
  494. if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
  495. if (Predicate(GV))
  496. return true;
  497. for (const Value *Op : WorkItem->operands()) {
  498. const Constant *ConstOp = dyn_cast<Constant>(Op);
  499. if (!ConstOp)
  500. continue;
  501. if (Visited.insert(ConstOp).second)
  502. WorkList.push_back(ConstOp);
  503. }
  504. }
  505. return false;
  506. }
  507. bool Constant::isThreadDependent() const {
  508. auto DLLImportPredicate = [](const GlobalValue *GV) {
  509. return GV->isThreadLocal();
  510. };
  511. return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
  512. }
  513. bool Constant::isDLLImportDependent() const {
  514. auto DLLImportPredicate = [](const GlobalValue *GV) {
  515. return GV->hasDLLImportStorageClass();
  516. };
  517. return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
  518. }
  519. bool Constant::isConstantUsed() const {
  520. for (const User *U : users()) {
  521. const Constant *UC = dyn_cast<Constant>(U);
  522. if (!UC || isa<GlobalValue>(UC))
  523. return true;
  524. if (UC->isConstantUsed())
  525. return true;
  526. }
  527. return false;
  528. }
  529. bool Constant::needsDynamicRelocation() const {
  530. return getRelocationInfo() == GlobalRelocation;
  531. }
  532. bool Constant::needsRelocation() const {
  533. return getRelocationInfo() != NoRelocation;
  534. }
  535. Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
  536. if (isa<GlobalValue>(this))
  537. return GlobalRelocation; // Global reference.
  538. if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
  539. return BA->getFunction()->getRelocationInfo();
  540. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
  541. if (CE->getOpcode() == Instruction::Sub) {
  542. ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
  543. ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
  544. if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
  545. RHS->getOpcode() == Instruction::PtrToInt) {
  546. Constant *LHSOp0 = LHS->getOperand(0);
  547. Constant *RHSOp0 = RHS->getOperand(0);
  548. // While raw uses of blockaddress need to be relocated, differences
  549. // between two of them don't when they are for labels in the same
  550. // function. This is a common idiom when creating a table for the
  551. // indirect goto extension, so we handle it efficiently here.
  552. if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
  553. cast<BlockAddress>(LHSOp0)->getFunction() ==
  554. cast<BlockAddress>(RHSOp0)->getFunction())
  555. return NoRelocation;
  556. // Relative pointers do not need to be dynamically relocated.
  557. if (auto *RHSGV =
  558. dyn_cast<GlobalValue>(RHSOp0->stripInBoundsConstantOffsets())) {
  559. auto *LHS = LHSOp0->stripInBoundsConstantOffsets();
  560. if (auto *LHSGV = dyn_cast<GlobalValue>(LHS)) {
  561. if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
  562. return LocalRelocation;
  563. } else if (isa<DSOLocalEquivalent>(LHS)) {
  564. if (RHSGV->isDSOLocal())
  565. return LocalRelocation;
  566. }
  567. }
  568. }
  569. }
  570. }
  571. PossibleRelocationsTy Result = NoRelocation;
  572. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  573. Result =
  574. std::max(cast<Constant>(getOperand(i))->getRelocationInfo(), Result);
  575. return Result;
  576. }
  577. /// Return true if the specified constantexpr is dead. This involves
  578. /// recursively traversing users of the constantexpr.
  579. /// If RemoveDeadUsers is true, also remove dead users at the same time.
  580. static bool constantIsDead(const Constant *C, bool RemoveDeadUsers) {
  581. if (isa<GlobalValue>(C)) return false; // Cannot remove this
  582. Value::const_user_iterator I = C->user_begin(), E = C->user_end();
  583. while (I != E) {
  584. const Constant *User = dyn_cast<Constant>(*I);
  585. if (!User) return false; // Non-constant usage;
  586. if (!constantIsDead(User, RemoveDeadUsers))
  587. return false; // Constant wasn't dead
  588. // Just removed User, so the iterator was invalidated.
  589. // Since we return immediately upon finding a live user, we can always
  590. // restart from user_begin().
  591. if (RemoveDeadUsers)
  592. I = C->user_begin();
  593. else
  594. ++I;
  595. }
  596. if (RemoveDeadUsers) {
  597. // If C is only used by metadata, it should not be preserved but should
  598. // have its uses replaced.
  599. ReplaceableMetadataImpl::SalvageDebugInfo(*C);
  600. const_cast<Constant *>(C)->destroyConstant();
  601. }
  602. return true;
  603. }
  604. void Constant::removeDeadConstantUsers() const {
  605. Value::const_user_iterator I = user_begin(), E = user_end();
  606. Value::const_user_iterator LastNonDeadUser = E;
  607. while (I != E) {
  608. const Constant *User = dyn_cast<Constant>(*I);
  609. if (!User) {
  610. LastNonDeadUser = I;
  611. ++I;
  612. continue;
  613. }
  614. if (!constantIsDead(User, /* RemoveDeadUsers= */ true)) {
  615. // If the constant wasn't dead, remember that this was the last live use
  616. // and move on to the next constant.
  617. LastNonDeadUser = I;
  618. ++I;
  619. continue;
  620. }
  621. // If the constant was dead, then the iterator is invalidated.
  622. if (LastNonDeadUser == E)
  623. I = user_begin();
  624. else
  625. I = std::next(LastNonDeadUser);
  626. }
  627. }
  628. bool Constant::hasOneLiveUse() const { return hasNLiveUses(1); }
  629. bool Constant::hasZeroLiveUses() const { return hasNLiveUses(0); }
  630. bool Constant::hasNLiveUses(unsigned N) const {
  631. unsigned NumUses = 0;
  632. for (const Use &U : uses()) {
  633. const Constant *User = dyn_cast<Constant>(U.getUser());
  634. if (!User || !constantIsDead(User, /* RemoveDeadUsers= */ false)) {
  635. ++NumUses;
  636. if (NumUses > N)
  637. return false;
  638. }
  639. }
  640. return NumUses == N;
  641. }
  642. Constant *Constant::replaceUndefsWith(Constant *C, Constant *Replacement) {
  643. assert(C && Replacement && "Expected non-nullptr constant arguments");
  644. Type *Ty = C->getType();
  645. if (match(C, m_Undef())) {
  646. assert(Ty == Replacement->getType() && "Expected matching types");
  647. return Replacement;
  648. }
  649. // Don't know how to deal with this constant.
  650. auto *VTy = dyn_cast<FixedVectorType>(Ty);
  651. if (!VTy)
  652. return C;
  653. unsigned NumElts = VTy->getNumElements();
  654. SmallVector<Constant *, 32> NewC(NumElts);
  655. for (unsigned i = 0; i != NumElts; ++i) {
  656. Constant *EltC = C->getAggregateElement(i);
  657. assert((!EltC || EltC->getType() == Replacement->getType()) &&
  658. "Expected matching types");
  659. NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC;
  660. }
  661. return ConstantVector::get(NewC);
  662. }
  663. Constant *Constant::mergeUndefsWith(Constant *C, Constant *Other) {
  664. assert(C && Other && "Expected non-nullptr constant arguments");
  665. if (match(C, m_Undef()))
  666. return C;
  667. Type *Ty = C->getType();
  668. if (match(Other, m_Undef()))
  669. return UndefValue::get(Ty);
  670. auto *VTy = dyn_cast<FixedVectorType>(Ty);
  671. if (!VTy)
  672. return C;
  673. Type *EltTy = VTy->getElementType();
  674. unsigned NumElts = VTy->getNumElements();
  675. assert(isa<FixedVectorType>(Other->getType()) &&
  676. cast<FixedVectorType>(Other->getType())->getNumElements() == NumElts &&
  677. "Type mismatch");
  678. bool FoundExtraUndef = false;
  679. SmallVector<Constant *, 32> NewC(NumElts);
  680. for (unsigned I = 0; I != NumElts; ++I) {
  681. NewC[I] = C->getAggregateElement(I);
  682. Constant *OtherEltC = Other->getAggregateElement(I);
  683. assert(NewC[I] && OtherEltC && "Unknown vector element");
  684. if (!match(NewC[I], m_Undef()) && match(OtherEltC, m_Undef())) {
  685. NewC[I] = UndefValue::get(EltTy);
  686. FoundExtraUndef = true;
  687. }
  688. }
  689. if (FoundExtraUndef)
  690. return ConstantVector::get(NewC);
  691. return C;
  692. }
  693. bool Constant::isManifestConstant() const {
  694. if (isa<ConstantData>(this))
  695. return true;
  696. if (isa<ConstantAggregate>(this) || isa<ConstantExpr>(this)) {
  697. for (const Value *Op : operand_values())
  698. if (!cast<Constant>(Op)->isManifestConstant())
  699. return false;
  700. return true;
  701. }
  702. return false;
  703. }
  704. //===----------------------------------------------------------------------===//
  705. // ConstantInt
  706. //===----------------------------------------------------------------------===//
  707. ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
  708. : ConstantData(Ty, ConstantIntVal), Val(V) {
  709. assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
  710. }
  711. ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
  712. LLVMContextImpl *pImpl = Context.pImpl;
  713. if (!pImpl->TheTrueVal)
  714. pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
  715. return pImpl->TheTrueVal;
  716. }
  717. ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
  718. LLVMContextImpl *pImpl = Context.pImpl;
  719. if (!pImpl->TheFalseVal)
  720. pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
  721. return pImpl->TheFalseVal;
  722. }
  723. ConstantInt *ConstantInt::getBool(LLVMContext &Context, bool V) {
  724. return V ? getTrue(Context) : getFalse(Context);
  725. }
  726. Constant *ConstantInt::getTrue(Type *Ty) {
  727. assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
  728. ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
  729. if (auto *VTy = dyn_cast<VectorType>(Ty))
  730. return ConstantVector::getSplat(VTy->getElementCount(), TrueC);
  731. return TrueC;
  732. }
  733. Constant *ConstantInt::getFalse(Type *Ty) {
  734. assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
  735. ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
  736. if (auto *VTy = dyn_cast<VectorType>(Ty))
  737. return ConstantVector::getSplat(VTy->getElementCount(), FalseC);
  738. return FalseC;
  739. }
  740. Constant *ConstantInt::getBool(Type *Ty, bool V) {
  741. return V ? getTrue(Ty) : getFalse(Ty);
  742. }
  743. // Get a ConstantInt from an APInt.
  744. ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
  745. // get an existing value or the insertion position
  746. LLVMContextImpl *pImpl = Context.pImpl;
  747. std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
  748. if (!Slot) {
  749. // Get the corresponding integer type for the bit width of the value.
  750. IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
  751. Slot.reset(new ConstantInt(ITy, V));
  752. }
  753. assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
  754. return Slot.get();
  755. }
  756. Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
  757. Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
  758. // For vectors, broadcast the value.
  759. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  760. return ConstantVector::getSplat(VTy->getElementCount(), C);
  761. return C;
  762. }
  763. ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
  764. return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
  765. }
  766. ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
  767. return get(Ty, V, true);
  768. }
  769. Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
  770. return get(Ty, V, true);
  771. }
  772. Constant *ConstantInt::get(Type *Ty, const APInt& V) {
  773. ConstantInt *C = get(Ty->getContext(), V);
  774. assert(C->getType() == Ty->getScalarType() &&
  775. "ConstantInt type doesn't match the type implied by its value!");
  776. // For vectors, broadcast the value.
  777. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  778. return ConstantVector::getSplat(VTy->getElementCount(), C);
  779. return C;
  780. }
  781. ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
  782. return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
  783. }
  784. /// Remove the constant from the constant table.
  785. void ConstantInt::destroyConstantImpl() {
  786. llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
  787. }
  788. //===----------------------------------------------------------------------===//
  789. // ConstantFP
  790. //===----------------------------------------------------------------------===//
  791. Constant *ConstantFP::get(Type *Ty, double V) {
  792. LLVMContext &Context = Ty->getContext();
  793. APFloat FV(V);
  794. bool ignored;
  795. FV.convert(Ty->getScalarType()->getFltSemantics(),
  796. APFloat::rmNearestTiesToEven, &ignored);
  797. Constant *C = get(Context, FV);
  798. // For vectors, broadcast the value.
  799. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  800. return ConstantVector::getSplat(VTy->getElementCount(), C);
  801. return C;
  802. }
  803. Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
  804. ConstantFP *C = get(Ty->getContext(), V);
  805. assert(C->getType() == Ty->getScalarType() &&
  806. "ConstantFP type doesn't match the type implied by its value!");
  807. // For vectors, broadcast the value.
  808. if (auto *VTy = dyn_cast<VectorType>(Ty))
  809. return ConstantVector::getSplat(VTy->getElementCount(), C);
  810. return C;
  811. }
  812. Constant *ConstantFP::get(Type *Ty, StringRef Str) {
  813. LLVMContext &Context = Ty->getContext();
  814. APFloat FV(Ty->getScalarType()->getFltSemantics(), Str);
  815. Constant *C = get(Context, FV);
  816. // For vectors, broadcast the value.
  817. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  818. return ConstantVector::getSplat(VTy->getElementCount(), C);
  819. return C;
  820. }
  821. Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
  822. const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
  823. APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
  824. Constant *C = get(Ty->getContext(), NaN);
  825. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  826. return ConstantVector::getSplat(VTy->getElementCount(), C);
  827. return C;
  828. }
  829. Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
  830. const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
  831. APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
  832. Constant *C = get(Ty->getContext(), NaN);
  833. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  834. return ConstantVector::getSplat(VTy->getElementCount(), C);
  835. return C;
  836. }
  837. Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
  838. const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
  839. APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
  840. Constant *C = get(Ty->getContext(), NaN);
  841. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  842. return ConstantVector::getSplat(VTy->getElementCount(), C);
  843. return C;
  844. }
  845. Constant *ConstantFP::getZero(Type *Ty, bool Negative) {
  846. const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
  847. APFloat NegZero = APFloat::getZero(Semantics, Negative);
  848. Constant *C = get(Ty->getContext(), NegZero);
  849. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  850. return ConstantVector::getSplat(VTy->getElementCount(), C);
  851. return C;
  852. }
  853. Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
  854. if (Ty->isFPOrFPVectorTy())
  855. return getNegativeZero(Ty);
  856. return Constant::getNullValue(Ty);
  857. }
  858. // ConstantFP accessors.
  859. ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
  860. LLVMContextImpl* pImpl = Context.pImpl;
  861. std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
  862. if (!Slot) {
  863. Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics());
  864. Slot.reset(new ConstantFP(Ty, V));
  865. }
  866. return Slot.get();
  867. }
  868. Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
  869. const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
  870. Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
  871. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  872. return ConstantVector::getSplat(VTy->getElementCount(), C);
  873. return C;
  874. }
  875. ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
  876. : ConstantData(Ty, ConstantFPVal), Val(V) {
  877. assert(&V.getSemantics() == &Ty->getFltSemantics() &&
  878. "FP type Mismatch");
  879. }
  880. bool ConstantFP::isExactlyValue(const APFloat &V) const {
  881. return Val.bitwiseIsEqual(V);
  882. }
  883. /// Remove the constant from the constant table.
  884. void ConstantFP::destroyConstantImpl() {
  885. llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
  886. }
  887. //===----------------------------------------------------------------------===//
  888. // ConstantAggregateZero Implementation
  889. //===----------------------------------------------------------------------===//
  890. Constant *ConstantAggregateZero::getSequentialElement() const {
  891. if (auto *AT = dyn_cast<ArrayType>(getType()))
  892. return Constant::getNullValue(AT->getElementType());
  893. return Constant::getNullValue(cast<VectorType>(getType())->getElementType());
  894. }
  895. Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
  896. return Constant::getNullValue(getType()->getStructElementType(Elt));
  897. }
  898. Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
  899. if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
  900. return getSequentialElement();
  901. return getStructElement(cast<ConstantInt>(C)->getZExtValue());
  902. }
  903. Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
  904. if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
  905. return getSequentialElement();
  906. return getStructElement(Idx);
  907. }
  908. ElementCount ConstantAggregateZero::getElementCount() const {
  909. Type *Ty = getType();
  910. if (auto *AT = dyn_cast<ArrayType>(Ty))
  911. return ElementCount::getFixed(AT->getNumElements());
  912. if (auto *VT = dyn_cast<VectorType>(Ty))
  913. return VT->getElementCount();
  914. return ElementCount::getFixed(Ty->getStructNumElements());
  915. }
  916. //===----------------------------------------------------------------------===//
  917. // UndefValue Implementation
  918. //===----------------------------------------------------------------------===//
  919. UndefValue *UndefValue::getSequentialElement() const {
  920. if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
  921. return UndefValue::get(ATy->getElementType());
  922. return UndefValue::get(cast<VectorType>(getType())->getElementType());
  923. }
  924. UndefValue *UndefValue::getStructElement(unsigned Elt) const {
  925. return UndefValue::get(getType()->getStructElementType(Elt));
  926. }
  927. UndefValue *UndefValue::getElementValue(Constant *C) const {
  928. if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
  929. return getSequentialElement();
  930. return getStructElement(cast<ConstantInt>(C)->getZExtValue());
  931. }
  932. UndefValue *UndefValue::getElementValue(unsigned Idx) const {
  933. if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
  934. return getSequentialElement();
  935. return getStructElement(Idx);
  936. }
  937. unsigned UndefValue::getNumElements() const {
  938. Type *Ty = getType();
  939. if (auto *AT = dyn_cast<ArrayType>(Ty))
  940. return AT->getNumElements();
  941. if (auto *VT = dyn_cast<VectorType>(Ty))
  942. return cast<FixedVectorType>(VT)->getNumElements();
  943. return Ty->getStructNumElements();
  944. }
  945. //===----------------------------------------------------------------------===//
  946. // PoisonValue Implementation
  947. //===----------------------------------------------------------------------===//
  948. PoisonValue *PoisonValue::getSequentialElement() const {
  949. if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
  950. return PoisonValue::get(ATy->getElementType());
  951. return PoisonValue::get(cast<VectorType>(getType())->getElementType());
  952. }
  953. PoisonValue *PoisonValue::getStructElement(unsigned Elt) const {
  954. return PoisonValue::get(getType()->getStructElementType(Elt));
  955. }
  956. PoisonValue *PoisonValue::getElementValue(Constant *C) const {
  957. if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
  958. return getSequentialElement();
  959. return getStructElement(cast<ConstantInt>(C)->getZExtValue());
  960. }
  961. PoisonValue *PoisonValue::getElementValue(unsigned Idx) const {
  962. if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
  963. return getSequentialElement();
  964. return getStructElement(Idx);
  965. }
  966. //===----------------------------------------------------------------------===//
  967. // ConstantXXX Classes
  968. //===----------------------------------------------------------------------===//
  969. template <typename ItTy, typename EltTy>
  970. static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
  971. for (; Start != End; ++Start)
  972. if (*Start != Elt)
  973. return false;
  974. return true;
  975. }
  976. template <typename SequentialTy, typename ElementTy>
  977. static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
  978. assert(!V.empty() && "Cannot get empty int sequence.");
  979. SmallVector<ElementTy, 16> Elts;
  980. for (Constant *C : V)
  981. if (auto *CI = dyn_cast<ConstantInt>(C))
  982. Elts.push_back(CI->getZExtValue());
  983. else
  984. return nullptr;
  985. return SequentialTy::get(V[0]->getContext(), Elts);
  986. }
  987. template <typename SequentialTy, typename ElementTy>
  988. static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
  989. assert(!V.empty() && "Cannot get empty FP sequence.");
  990. SmallVector<ElementTy, 16> Elts;
  991. for (Constant *C : V)
  992. if (auto *CFP = dyn_cast<ConstantFP>(C))
  993. Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
  994. else
  995. return nullptr;
  996. return SequentialTy::getFP(V[0]->getType(), Elts);
  997. }
  998. template <typename SequenceTy>
  999. static Constant *getSequenceIfElementsMatch(Constant *C,
  1000. ArrayRef<Constant *> V) {
  1001. // We speculatively build the elements here even if it turns out that there is
  1002. // a constantexpr or something else weird, since it is so uncommon for that to
  1003. // happen.
  1004. if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
  1005. if (CI->getType()->isIntegerTy(8))
  1006. return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
  1007. else if (CI->getType()->isIntegerTy(16))
  1008. return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
  1009. else if (CI->getType()->isIntegerTy(32))
  1010. return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
  1011. else if (CI->getType()->isIntegerTy(64))
  1012. return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
  1013. } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  1014. if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())
  1015. return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
  1016. else if (CFP->getType()->isFloatTy())
  1017. return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
  1018. else if (CFP->getType()->isDoubleTy())
  1019. return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
  1020. }
  1021. return nullptr;
  1022. }
  1023. ConstantAggregate::ConstantAggregate(Type *T, ValueTy VT,
  1024. ArrayRef<Constant *> V)
  1025. : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
  1026. V.size()) {
  1027. llvm::copy(V, op_begin());
  1028. // Check that types match, unless this is an opaque struct.
  1029. if (auto *ST = dyn_cast<StructType>(T)) {
  1030. if (ST->isOpaque())
  1031. return;
  1032. for (unsigned I = 0, E = V.size(); I != E; ++I)
  1033. assert(V[I]->getType() == ST->getTypeAtIndex(I) &&
  1034. "Initializer for struct element doesn't match!");
  1035. }
  1036. }
  1037. ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
  1038. : ConstantAggregate(T, ConstantArrayVal, V) {
  1039. assert(V.size() == T->getNumElements() &&
  1040. "Invalid initializer for constant array");
  1041. }
  1042. Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
  1043. if (Constant *C = getImpl(Ty, V))
  1044. return C;
  1045. return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
  1046. }
  1047. Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
  1048. // Empty arrays are canonicalized to ConstantAggregateZero.
  1049. if (V.empty())
  1050. return ConstantAggregateZero::get(Ty);
  1051. for (Constant *C : V) {
  1052. assert(C->getType() == Ty->getElementType() &&
  1053. "Wrong type in array element initializer");
  1054. (void)C;
  1055. }
  1056. // If this is an all-zero array, return a ConstantAggregateZero object. If
  1057. // all undef, return an UndefValue, if "all simple", then return a
  1058. // ConstantDataArray.
  1059. Constant *C = V[0];
  1060. if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
  1061. return PoisonValue::get(Ty);
  1062. if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
  1063. return UndefValue::get(Ty);
  1064. if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
  1065. return ConstantAggregateZero::get(Ty);
  1066. // Check to see if all of the elements are ConstantFP or ConstantInt and if
  1067. // the element type is compatible with ConstantDataVector. If so, use it.
  1068. if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
  1069. return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
  1070. // Otherwise, we really do want to create a ConstantArray.
  1071. return nullptr;
  1072. }
  1073. StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
  1074. ArrayRef<Constant*> V,
  1075. bool Packed) {
  1076. unsigned VecSize = V.size();
  1077. SmallVector<Type*, 16> EltTypes(VecSize);
  1078. for (unsigned i = 0; i != VecSize; ++i)
  1079. EltTypes[i] = V[i]->getType();
  1080. return StructType::get(Context, EltTypes, Packed);
  1081. }
  1082. StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
  1083. bool Packed) {
  1084. assert(!V.empty() &&
  1085. "ConstantStruct::getTypeForElements cannot be called on empty list");
  1086. return getTypeForElements(V[0]->getContext(), V, Packed);
  1087. }
  1088. ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
  1089. : ConstantAggregate(T, ConstantStructVal, V) {
  1090. assert((T->isOpaque() || V.size() == T->getNumElements()) &&
  1091. "Invalid initializer for constant struct");
  1092. }
  1093. // ConstantStruct accessors.
  1094. Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
  1095. assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
  1096. "Incorrect # elements specified to ConstantStruct::get");
  1097. // Create a ConstantAggregateZero value if all elements are zeros.
  1098. bool isZero = true;
  1099. bool isUndef = false;
  1100. bool isPoison = false;
  1101. if (!V.empty()) {
  1102. isUndef = isa<UndefValue>(V[0]);
  1103. isPoison = isa<PoisonValue>(V[0]);
  1104. isZero = V[0]->isNullValue();
  1105. // PoisonValue inherits UndefValue, so its check is not necessary.
  1106. if (isUndef || isZero) {
  1107. for (Constant *C : V) {
  1108. if (!C->isNullValue())
  1109. isZero = false;
  1110. if (!isa<PoisonValue>(C))
  1111. isPoison = false;
  1112. if (isa<PoisonValue>(C) || !isa<UndefValue>(C))
  1113. isUndef = false;
  1114. }
  1115. }
  1116. }
  1117. if (isZero)
  1118. return ConstantAggregateZero::get(ST);
  1119. if (isPoison)
  1120. return PoisonValue::get(ST);
  1121. if (isUndef)
  1122. return UndefValue::get(ST);
  1123. return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
  1124. }
  1125. ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
  1126. : ConstantAggregate(T, ConstantVectorVal, V) {
  1127. assert(V.size() == cast<FixedVectorType>(T)->getNumElements() &&
  1128. "Invalid initializer for constant vector");
  1129. }
  1130. // ConstantVector accessors.
  1131. Constant *ConstantVector::get(ArrayRef<Constant*> V) {
  1132. if (Constant *C = getImpl(V))
  1133. return C;
  1134. auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());
  1135. return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
  1136. }
  1137. Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
  1138. assert(!V.empty() && "Vectors can't be empty");
  1139. auto *T = FixedVectorType::get(V.front()->getType(), V.size());
  1140. // If this is an all-undef or all-zero vector, return a
  1141. // ConstantAggregateZero or UndefValue.
  1142. Constant *C = V[0];
  1143. bool isZero = C->isNullValue();
  1144. bool isUndef = isa<UndefValue>(C);
  1145. bool isPoison = isa<PoisonValue>(C);
  1146. if (isZero || isUndef) {
  1147. for (unsigned i = 1, e = V.size(); i != e; ++i)
  1148. if (V[i] != C) {
  1149. isZero = isUndef = isPoison = false;
  1150. break;
  1151. }
  1152. }
  1153. if (isZero)
  1154. return ConstantAggregateZero::get(T);
  1155. if (isPoison)
  1156. return PoisonValue::get(T);
  1157. if (isUndef)
  1158. return UndefValue::get(T);
  1159. // Check to see if all of the elements are ConstantFP or ConstantInt and if
  1160. // the element type is compatible with ConstantDataVector. If so, use it.
  1161. if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
  1162. return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
  1163. // Otherwise, the element type isn't compatible with ConstantDataVector, or
  1164. // the operand list contains a ConstantExpr or something else strange.
  1165. return nullptr;
  1166. }
  1167. Constant *ConstantVector::getSplat(ElementCount EC, Constant *V) {
  1168. if (!EC.isScalable()) {
  1169. // If this splat is compatible with ConstantDataVector, use it instead of
  1170. // ConstantVector.
  1171. if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
  1172. ConstantDataSequential::isElementTypeCompatible(V->getType()))
  1173. return ConstantDataVector::getSplat(EC.getKnownMinValue(), V);
  1174. SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V);
  1175. return get(Elts);
  1176. }
  1177. Type *VTy = VectorType::get(V->getType(), EC);
  1178. if (V->isNullValue())
  1179. return ConstantAggregateZero::get(VTy);
  1180. else if (isa<UndefValue>(V))
  1181. return UndefValue::get(VTy);
  1182. Type *IdxTy = Type::getInt64Ty(VTy->getContext());
  1183. // Move scalar into vector.
  1184. Constant *PoisonV = PoisonValue::get(VTy);
  1185. V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(IdxTy, 0));
  1186. // Build shuffle mask to perform the splat.
  1187. SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0);
  1188. // Splat.
  1189. return ConstantExpr::getShuffleVector(V, PoisonV, Zeros);
  1190. }
  1191. ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
  1192. LLVMContextImpl *pImpl = Context.pImpl;
  1193. if (!pImpl->TheNoneToken)
  1194. pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
  1195. return pImpl->TheNoneToken.get();
  1196. }
  1197. /// Remove the constant from the constant table.
  1198. void ConstantTokenNone::destroyConstantImpl() {
  1199. llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
  1200. }
  1201. // Utility function for determining if a ConstantExpr is a CastOp or not. This
  1202. // can't be inline because we don't want to #include Instruction.h into
  1203. // Constant.h
  1204. bool ConstantExpr::isCast() const {
  1205. return Instruction::isCast(getOpcode());
  1206. }
  1207. bool ConstantExpr::isCompare() const {
  1208. return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
  1209. }
  1210. unsigned ConstantExpr::getPredicate() const {
  1211. return cast<CompareConstantExpr>(this)->predicate;
  1212. }
  1213. ArrayRef<int> ConstantExpr::getShuffleMask() const {
  1214. return cast<ShuffleVectorConstantExpr>(this)->ShuffleMask;
  1215. }
  1216. Constant *ConstantExpr::getShuffleMaskForBitcode() const {
  1217. return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;
  1218. }
  1219. Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
  1220. bool OnlyIfReduced, Type *SrcTy) const {
  1221. assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
  1222. // If no operands changed return self.
  1223. if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
  1224. return const_cast<ConstantExpr*>(this);
  1225. Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
  1226. switch (getOpcode()) {
  1227. case Instruction::Trunc:
  1228. case Instruction::ZExt:
  1229. case Instruction::SExt:
  1230. case Instruction::FPTrunc:
  1231. case Instruction::FPExt:
  1232. case Instruction::UIToFP:
  1233. case Instruction::SIToFP:
  1234. case Instruction::FPToUI:
  1235. case Instruction::FPToSI:
  1236. case Instruction::PtrToInt:
  1237. case Instruction::IntToPtr:
  1238. case Instruction::BitCast:
  1239. case Instruction::AddrSpaceCast:
  1240. return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
  1241. case Instruction::Select:
  1242. return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
  1243. case Instruction::InsertElement:
  1244. return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
  1245. OnlyIfReducedTy);
  1246. case Instruction::ExtractElement:
  1247. return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
  1248. case Instruction::ShuffleVector:
  1249. return ConstantExpr::getShuffleVector(Ops[0], Ops[1], getShuffleMask(),
  1250. OnlyIfReducedTy);
  1251. case Instruction::GetElementPtr: {
  1252. auto *GEPO = cast<GEPOperator>(this);
  1253. assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
  1254. return ConstantExpr::getGetElementPtr(
  1255. SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
  1256. GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
  1257. }
  1258. case Instruction::ICmp:
  1259. case Instruction::FCmp:
  1260. return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
  1261. OnlyIfReducedTy);
  1262. default:
  1263. assert(getNumOperands() == 2 && "Must be binary operator?");
  1264. return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
  1265. OnlyIfReducedTy);
  1266. }
  1267. }
  1268. //===----------------------------------------------------------------------===//
  1269. // isValueValidForType implementations
  1270. bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
  1271. unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
  1272. if (Ty->isIntegerTy(1))
  1273. return Val == 0 || Val == 1;
  1274. return isUIntN(NumBits, Val);
  1275. }
  1276. bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
  1277. unsigned NumBits = Ty->getIntegerBitWidth();
  1278. if (Ty->isIntegerTy(1))
  1279. return Val == 0 || Val == 1 || Val == -1;
  1280. return isIntN(NumBits, Val);
  1281. }
  1282. bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
  1283. // convert modifies in place, so make a copy.
  1284. APFloat Val2 = APFloat(Val);
  1285. bool losesInfo;
  1286. switch (Ty->getTypeID()) {
  1287. default:
  1288. return false; // These can't be represented as floating point!
  1289. // FIXME rounding mode needs to be more flexible
  1290. case Type::HalfTyID: {
  1291. if (&Val2.getSemantics() == &APFloat::IEEEhalf())
  1292. return true;
  1293. Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
  1294. return !losesInfo;
  1295. }
  1296. case Type::BFloatTyID: {
  1297. if (&Val2.getSemantics() == &APFloat::BFloat())
  1298. return true;
  1299. Val2.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven, &losesInfo);
  1300. return !losesInfo;
  1301. }
  1302. case Type::FloatTyID: {
  1303. if (&Val2.getSemantics() == &APFloat::IEEEsingle())
  1304. return true;
  1305. Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
  1306. return !losesInfo;
  1307. }
  1308. case Type::DoubleTyID: {
  1309. if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
  1310. &Val2.getSemantics() == &APFloat::BFloat() ||
  1311. &Val2.getSemantics() == &APFloat::IEEEsingle() ||
  1312. &Val2.getSemantics() == &APFloat::IEEEdouble())
  1313. return true;
  1314. Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
  1315. return !losesInfo;
  1316. }
  1317. case Type::X86_FP80TyID:
  1318. return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
  1319. &Val2.getSemantics() == &APFloat::BFloat() ||
  1320. &Val2.getSemantics() == &APFloat::IEEEsingle() ||
  1321. &Val2.getSemantics() == &APFloat::IEEEdouble() ||
  1322. &Val2.getSemantics() == &APFloat::x87DoubleExtended();
  1323. case Type::FP128TyID:
  1324. return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
  1325. &Val2.getSemantics() == &APFloat::BFloat() ||
  1326. &Val2.getSemantics() == &APFloat::IEEEsingle() ||
  1327. &Val2.getSemantics() == &APFloat::IEEEdouble() ||
  1328. &Val2.getSemantics() == &APFloat::IEEEquad();
  1329. case Type::PPC_FP128TyID:
  1330. return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
  1331. &Val2.getSemantics() == &APFloat::BFloat() ||
  1332. &Val2.getSemantics() == &APFloat::IEEEsingle() ||
  1333. &Val2.getSemantics() == &APFloat::IEEEdouble() ||
  1334. &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
  1335. }
  1336. }
  1337. //===----------------------------------------------------------------------===//
  1338. // Factory Function Implementation
  1339. ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
  1340. assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
  1341. "Cannot create an aggregate zero of non-aggregate type!");
  1342. std::unique_ptr<ConstantAggregateZero> &Entry =
  1343. Ty->getContext().pImpl->CAZConstants[Ty];
  1344. if (!Entry)
  1345. Entry.reset(new ConstantAggregateZero(Ty));
  1346. return Entry.get();
  1347. }
  1348. /// Remove the constant from the constant table.
  1349. void ConstantAggregateZero::destroyConstantImpl() {
  1350. getContext().pImpl->CAZConstants.erase(getType());
  1351. }
  1352. /// Remove the constant from the constant table.
  1353. void ConstantArray::destroyConstantImpl() {
  1354. getType()->getContext().pImpl->ArrayConstants.remove(this);
  1355. }
  1356. //---- ConstantStruct::get() implementation...
  1357. //
  1358. /// Remove the constant from the constant table.
  1359. void ConstantStruct::destroyConstantImpl() {
  1360. getType()->getContext().pImpl->StructConstants.remove(this);
  1361. }
  1362. /// Remove the constant from the constant table.
  1363. void ConstantVector::destroyConstantImpl() {
  1364. getType()->getContext().pImpl->VectorConstants.remove(this);
  1365. }
  1366. Constant *Constant::getSplatValue(bool AllowUndefs) const {
  1367. assert(this->getType()->isVectorTy() && "Only valid for vectors!");
  1368. if (isa<ConstantAggregateZero>(this))
  1369. return getNullValue(cast<VectorType>(getType())->getElementType());
  1370. if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
  1371. return CV->getSplatValue();
  1372. if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
  1373. return CV->getSplatValue(AllowUndefs);
  1374. // Check if this is a constant expression splat of the form returned by
  1375. // ConstantVector::getSplat()
  1376. const auto *Shuf = dyn_cast<ConstantExpr>(this);
  1377. if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&
  1378. isa<UndefValue>(Shuf->getOperand(1))) {
  1379. const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));
  1380. if (IElt && IElt->getOpcode() == Instruction::InsertElement &&
  1381. isa<UndefValue>(IElt->getOperand(0))) {
  1382. ArrayRef<int> Mask = Shuf->getShuffleMask();
  1383. Constant *SplatVal = IElt->getOperand(1);
  1384. ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));
  1385. if (Index && Index->getValue() == 0 &&
  1386. llvm::all_of(Mask, [](int I) { return I == 0; }))
  1387. return SplatVal;
  1388. }
  1389. }
  1390. return nullptr;
  1391. }
  1392. Constant *ConstantVector::getSplatValue(bool AllowUndefs) const {
  1393. // Check out first element.
  1394. Constant *Elt = getOperand(0);
  1395. // Then make sure all remaining elements point to the same value.
  1396. for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
  1397. Constant *OpC = getOperand(I);
  1398. if (OpC == Elt)
  1399. continue;
  1400. // Strict mode: any mismatch is not a splat.
  1401. if (!AllowUndefs)
  1402. return nullptr;
  1403. // Allow undefs mode: ignore undefined elements.
  1404. if (isa<UndefValue>(OpC))
  1405. continue;
  1406. // If we do not have a defined element yet, use the current operand.
  1407. if (isa<UndefValue>(Elt))
  1408. Elt = OpC;
  1409. if (OpC != Elt)
  1410. return nullptr;
  1411. }
  1412. return Elt;
  1413. }
  1414. const APInt &Constant::getUniqueInteger() const {
  1415. if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
  1416. return CI->getValue();
  1417. // Scalable vectors can use a ConstantExpr to build a splat.
  1418. if (isa<ConstantExpr>(this))
  1419. return cast<ConstantInt>(this->getSplatValue())->getValue();
  1420. // For non-ConstantExpr we use getAggregateElement as a fast path to avoid
  1421. // calling getSplatValue in release builds.
  1422. assert(this->getSplatValue() && "Doesn't contain a unique integer!");
  1423. const Constant *C = this->getAggregateElement(0U);
  1424. assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
  1425. return cast<ConstantInt>(C)->getValue();
  1426. }
  1427. //---- ConstantPointerNull::get() implementation.
  1428. //
  1429. ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
  1430. std::unique_ptr<ConstantPointerNull> &Entry =
  1431. Ty->getContext().pImpl->CPNConstants[Ty];
  1432. if (!Entry)
  1433. Entry.reset(new ConstantPointerNull(Ty));
  1434. return Entry.get();
  1435. }
  1436. /// Remove the constant from the constant table.
  1437. void ConstantPointerNull::destroyConstantImpl() {
  1438. getContext().pImpl->CPNConstants.erase(getType());
  1439. }
  1440. //---- ConstantTargetNone::get() implementation.
  1441. //
  1442. ConstantTargetNone *ConstantTargetNone::get(TargetExtType *Ty) {
  1443. assert(Ty->hasProperty(TargetExtType::HasZeroInit) &&
  1444. "Target extension type not allowed to have a zeroinitializer");
  1445. std::unique_ptr<ConstantTargetNone> &Entry =
  1446. Ty->getContext().pImpl->CTNConstants[Ty];
  1447. if (!Entry)
  1448. Entry.reset(new ConstantTargetNone(Ty));
  1449. return Entry.get();
  1450. }
  1451. /// Remove the constant from the constant table.
  1452. void ConstantTargetNone::destroyConstantImpl() {
  1453. getContext().pImpl->CTNConstants.erase(getType());
  1454. }
  1455. UndefValue *UndefValue::get(Type *Ty) {
  1456. std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
  1457. if (!Entry)
  1458. Entry.reset(new UndefValue(Ty));
  1459. return Entry.get();
  1460. }
  1461. /// Remove the constant from the constant table.
  1462. void UndefValue::destroyConstantImpl() {
  1463. // Free the constant and any dangling references to it.
  1464. if (getValueID() == UndefValueVal) {
  1465. getContext().pImpl->UVConstants.erase(getType());
  1466. } else if (getValueID() == PoisonValueVal) {
  1467. getContext().pImpl->PVConstants.erase(getType());
  1468. }
  1469. llvm_unreachable("Not a undef or a poison!");
  1470. }
  1471. PoisonValue *PoisonValue::get(Type *Ty) {
  1472. std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];
  1473. if (!Entry)
  1474. Entry.reset(new PoisonValue(Ty));
  1475. return Entry.get();
  1476. }
  1477. /// Remove the constant from the constant table.
  1478. void PoisonValue::destroyConstantImpl() {
  1479. // Free the constant and any dangling references to it.
  1480. getContext().pImpl->PVConstants.erase(getType());
  1481. }
  1482. BlockAddress *BlockAddress::get(BasicBlock *BB) {
  1483. assert(BB->getParent() && "Block must have a parent");
  1484. return get(BB->getParent(), BB);
  1485. }
  1486. BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
  1487. BlockAddress *&BA =
  1488. F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
  1489. if (!BA)
  1490. BA = new BlockAddress(F, BB);
  1491. assert(BA->getFunction() == F && "Basic block moved between functions");
  1492. return BA;
  1493. }
  1494. BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
  1495. : Constant(Type::getInt8PtrTy(F->getContext(), F->getAddressSpace()),
  1496. Value::BlockAddressVal, &Op<0>(), 2) {
  1497. setOperand(0, F);
  1498. setOperand(1, BB);
  1499. BB->AdjustBlockAddressRefCount(1);
  1500. }
  1501. BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
  1502. if (!BB->hasAddressTaken())
  1503. return nullptr;
  1504. const Function *F = BB->getParent();
  1505. assert(F && "Block must have a parent");
  1506. BlockAddress *BA =
  1507. F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
  1508. assert(BA && "Refcount and block address map disagree!");
  1509. return BA;
  1510. }
  1511. /// Remove the constant from the constant table.
  1512. void BlockAddress::destroyConstantImpl() {
  1513. getFunction()->getType()->getContext().pImpl
  1514. ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
  1515. getBasicBlock()->AdjustBlockAddressRefCount(-1);
  1516. }
  1517. Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
  1518. // This could be replacing either the Basic Block or the Function. In either
  1519. // case, we have to remove the map entry.
  1520. Function *NewF = getFunction();
  1521. BasicBlock *NewBB = getBasicBlock();
  1522. if (From == NewF)
  1523. NewF = cast<Function>(To->stripPointerCasts());
  1524. else {
  1525. assert(From == NewBB && "From does not match any operand");
  1526. NewBB = cast<BasicBlock>(To);
  1527. }
  1528. // See if the 'new' entry already exists, if not, just update this in place
  1529. // and return early.
  1530. BlockAddress *&NewBA =
  1531. getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
  1532. if (NewBA)
  1533. return NewBA;
  1534. getBasicBlock()->AdjustBlockAddressRefCount(-1);
  1535. // Remove the old entry, this can't cause the map to rehash (just a
  1536. // tombstone will get added).
  1537. getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
  1538. getBasicBlock()));
  1539. NewBA = this;
  1540. setOperand(0, NewF);
  1541. setOperand(1, NewBB);
  1542. getBasicBlock()->AdjustBlockAddressRefCount(1);
  1543. // If we just want to keep the existing value, then return null.
  1544. // Callers know that this means we shouldn't delete this value.
  1545. return nullptr;
  1546. }
  1547. DSOLocalEquivalent *DSOLocalEquivalent::get(GlobalValue *GV) {
  1548. DSOLocalEquivalent *&Equiv = GV->getContext().pImpl->DSOLocalEquivalents[GV];
  1549. if (!Equiv)
  1550. Equiv = new DSOLocalEquivalent(GV);
  1551. assert(Equiv->getGlobalValue() == GV &&
  1552. "DSOLocalFunction does not match the expected global value");
  1553. return Equiv;
  1554. }
  1555. DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)
  1556. : Constant(GV->getType(), Value::DSOLocalEquivalentVal, &Op<0>(), 1) {
  1557. setOperand(0, GV);
  1558. }
  1559. /// Remove the constant from the constant table.
  1560. void DSOLocalEquivalent::destroyConstantImpl() {
  1561. const GlobalValue *GV = getGlobalValue();
  1562. GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);
  1563. }
  1564. Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {
  1565. assert(From == getGlobalValue() && "Changing value does not match operand.");
  1566. assert(isa<Constant>(To) && "Can only replace the operands with a constant");
  1567. // The replacement is with another global value.
  1568. if (const auto *ToObj = dyn_cast<GlobalValue>(To)) {
  1569. DSOLocalEquivalent *&NewEquiv =
  1570. getContext().pImpl->DSOLocalEquivalents[ToObj];
  1571. if (NewEquiv)
  1572. return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
  1573. }
  1574. // If the argument is replaced with a null value, just replace this constant
  1575. // with a null value.
  1576. if (cast<Constant>(To)->isNullValue())
  1577. return To;
  1578. // The replacement could be a bitcast or an alias to another function. We can
  1579. // replace it with a bitcast to the dso_local_equivalent of that function.
  1580. auto *Func = cast<Function>(To->stripPointerCastsAndAliases());
  1581. DSOLocalEquivalent *&NewEquiv = getContext().pImpl->DSOLocalEquivalents[Func];
  1582. if (NewEquiv)
  1583. return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
  1584. // Replace this with the new one.
  1585. getContext().pImpl->DSOLocalEquivalents.erase(getGlobalValue());
  1586. NewEquiv = this;
  1587. setOperand(0, Func);
  1588. if (Func->getType() != getType()) {
  1589. // It is ok to mutate the type here because this constant should always
  1590. // reflect the type of the function it's holding.
  1591. mutateType(Func->getType());
  1592. }
  1593. return nullptr;
  1594. }
  1595. NoCFIValue *NoCFIValue::get(GlobalValue *GV) {
  1596. NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];
  1597. if (!NC)
  1598. NC = new NoCFIValue(GV);
  1599. assert(NC->getGlobalValue() == GV &&
  1600. "NoCFIValue does not match the expected global value");
  1601. return NC;
  1602. }
  1603. NoCFIValue::NoCFIValue(GlobalValue *GV)
  1604. : Constant(GV->getType(), Value::NoCFIValueVal, &Op<0>(), 1) {
  1605. setOperand(0, GV);
  1606. }
  1607. /// Remove the constant from the constant table.
  1608. void NoCFIValue::destroyConstantImpl() {
  1609. const GlobalValue *GV = getGlobalValue();
  1610. GV->getContext().pImpl->NoCFIValues.erase(GV);
  1611. }
  1612. Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {
  1613. assert(From == getGlobalValue() && "Changing value does not match operand.");
  1614. GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());
  1615. assert(GV && "Can only replace the operands with a global value");
  1616. NoCFIValue *&NewNC = getContext().pImpl->NoCFIValues[GV];
  1617. if (NewNC)
  1618. return llvm::ConstantExpr::getBitCast(NewNC, getType());
  1619. getContext().pImpl->NoCFIValues.erase(getGlobalValue());
  1620. NewNC = this;
  1621. setOperand(0, GV);
  1622. if (GV->getType() != getType())
  1623. mutateType(GV->getType());
  1624. return nullptr;
  1625. }
  1626. //---- ConstantExpr::get() implementations.
  1627. //
  1628. /// This is a utility function to handle folding of casts and lookup of the
  1629. /// cast in the ExprConstants map. It is used by the various get* methods below.
  1630. static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
  1631. bool OnlyIfReduced = false) {
  1632. assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
  1633. // Fold a few common cases
  1634. if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
  1635. return FC;
  1636. if (OnlyIfReduced)
  1637. return nullptr;
  1638. LLVMContextImpl *pImpl = Ty->getContext().pImpl;
  1639. // Look up the constant in the table first to ensure uniqueness.
  1640. ConstantExprKeyType Key(opc, C);
  1641. return pImpl->ExprConstants.getOrCreate(Ty, Key);
  1642. }
  1643. Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
  1644. bool OnlyIfReduced) {
  1645. Instruction::CastOps opc = Instruction::CastOps(oc);
  1646. assert(Instruction::isCast(opc) && "opcode out of range");
  1647. assert(C && Ty && "Null arguments to getCast");
  1648. assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
  1649. switch (opc) {
  1650. default:
  1651. llvm_unreachable("Invalid cast opcode");
  1652. case Instruction::Trunc:
  1653. return getTrunc(C, Ty, OnlyIfReduced);
  1654. case Instruction::ZExt:
  1655. return getZExt(C, Ty, OnlyIfReduced);
  1656. case Instruction::SExt:
  1657. return getSExt(C, Ty, OnlyIfReduced);
  1658. case Instruction::FPTrunc:
  1659. return getFPTrunc(C, Ty, OnlyIfReduced);
  1660. case Instruction::FPExt:
  1661. return getFPExtend(C, Ty, OnlyIfReduced);
  1662. case Instruction::UIToFP:
  1663. return getUIToFP(C, Ty, OnlyIfReduced);
  1664. case Instruction::SIToFP:
  1665. return getSIToFP(C, Ty, OnlyIfReduced);
  1666. case Instruction::FPToUI:
  1667. return getFPToUI(C, Ty, OnlyIfReduced);
  1668. case Instruction::FPToSI:
  1669. return getFPToSI(C, Ty, OnlyIfReduced);
  1670. case Instruction::PtrToInt:
  1671. return getPtrToInt(C, Ty, OnlyIfReduced);
  1672. case Instruction::IntToPtr:
  1673. return getIntToPtr(C, Ty, OnlyIfReduced);
  1674. case Instruction::BitCast:
  1675. return getBitCast(C, Ty, OnlyIfReduced);
  1676. case Instruction::AddrSpaceCast:
  1677. return getAddrSpaceCast(C, Ty, OnlyIfReduced);
  1678. }
  1679. }
  1680. Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
  1681. if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  1682. return getBitCast(C, Ty);
  1683. return getZExt(C, Ty);
  1684. }
  1685. Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
  1686. if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  1687. return getBitCast(C, Ty);
  1688. return getSExt(C, Ty);
  1689. }
  1690. Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
  1691. if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  1692. return getBitCast(C, Ty);
  1693. return getTrunc(C, Ty);
  1694. }
  1695. Constant *ConstantExpr::getSExtOrTrunc(Constant *C, Type *Ty) {
  1696. assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
  1697. "Can only sign extend/truncate integers!");
  1698. Type *CTy = C->getType();
  1699. if (CTy->getScalarSizeInBits() < Ty->getScalarSizeInBits())
  1700. return getSExt(C, Ty);
  1701. if (CTy->getScalarSizeInBits() > Ty->getScalarSizeInBits())
  1702. return getTrunc(C, Ty);
  1703. return C;
  1704. }
  1705. Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
  1706. assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
  1707. assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
  1708. "Invalid cast");
  1709. if (Ty->isIntOrIntVectorTy())
  1710. return getPtrToInt(S, Ty);
  1711. unsigned SrcAS = S->getType()->getPointerAddressSpace();
  1712. if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
  1713. return getAddrSpaceCast(S, Ty);
  1714. return getBitCast(S, Ty);
  1715. }
  1716. Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
  1717. Type *Ty) {
  1718. assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
  1719. assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
  1720. if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
  1721. return getAddrSpaceCast(S, Ty);
  1722. return getBitCast(S, Ty);
  1723. }
  1724. Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
  1725. assert(C->getType()->isIntOrIntVectorTy() &&
  1726. Ty->isIntOrIntVectorTy() && "Invalid cast");
  1727. unsigned SrcBits = C->getType()->getScalarSizeInBits();
  1728. unsigned DstBits = Ty->getScalarSizeInBits();
  1729. Instruction::CastOps opcode =
  1730. (SrcBits == DstBits ? Instruction::BitCast :
  1731. (SrcBits > DstBits ? Instruction::Trunc :
  1732. (isSigned ? Instruction::SExt : Instruction::ZExt)));
  1733. return getCast(opcode, C, Ty);
  1734. }
  1735. Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
  1736. assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
  1737. "Invalid cast");
  1738. unsigned SrcBits = C->getType()->getScalarSizeInBits();
  1739. unsigned DstBits = Ty->getScalarSizeInBits();
  1740. if (SrcBits == DstBits)
  1741. return C; // Avoid a useless cast
  1742. Instruction::CastOps opcode =
  1743. (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
  1744. return getCast(opcode, C, Ty);
  1745. }
  1746. Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1747. #ifndef NDEBUG
  1748. bool fromVec = isa<VectorType>(C->getType());
  1749. bool toVec = isa<VectorType>(Ty);
  1750. #endif
  1751. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1752. assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
  1753. assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
  1754. assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
  1755. "SrcTy must be larger than DestTy for Trunc!");
  1756. return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
  1757. }
  1758. Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1759. #ifndef NDEBUG
  1760. bool fromVec = isa<VectorType>(C->getType());
  1761. bool toVec = isa<VectorType>(Ty);
  1762. #endif
  1763. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1764. assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
  1765. assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
  1766. assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
  1767. "SrcTy must be smaller than DestTy for SExt!");
  1768. return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
  1769. }
  1770. Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1771. #ifndef NDEBUG
  1772. bool fromVec = isa<VectorType>(C->getType());
  1773. bool toVec = isa<VectorType>(Ty);
  1774. #endif
  1775. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1776. assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
  1777. assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
  1778. assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
  1779. "SrcTy must be smaller than DestTy for ZExt!");
  1780. return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
  1781. }
  1782. Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1783. #ifndef NDEBUG
  1784. bool fromVec = isa<VectorType>(C->getType());
  1785. bool toVec = isa<VectorType>(Ty);
  1786. #endif
  1787. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1788. assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
  1789. C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
  1790. "This is an illegal floating point truncation!");
  1791. return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
  1792. }
  1793. Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1794. #ifndef NDEBUG
  1795. bool fromVec = isa<VectorType>(C->getType());
  1796. bool toVec = isa<VectorType>(Ty);
  1797. #endif
  1798. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1799. assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
  1800. C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
  1801. "This is an illegal floating point extension!");
  1802. return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
  1803. }
  1804. Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1805. #ifndef NDEBUG
  1806. bool fromVec = isa<VectorType>(C->getType());
  1807. bool toVec = isa<VectorType>(Ty);
  1808. #endif
  1809. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1810. assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
  1811. "This is an illegal uint to floating point cast!");
  1812. return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
  1813. }
  1814. Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1815. #ifndef NDEBUG
  1816. bool fromVec = isa<VectorType>(C->getType());
  1817. bool toVec = isa<VectorType>(Ty);
  1818. #endif
  1819. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1820. assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
  1821. "This is an illegal sint to floating point cast!");
  1822. return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
  1823. }
  1824. Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1825. #ifndef NDEBUG
  1826. bool fromVec = isa<VectorType>(C->getType());
  1827. bool toVec = isa<VectorType>(Ty);
  1828. #endif
  1829. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1830. assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
  1831. "This is an illegal floating point to uint cast!");
  1832. return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
  1833. }
  1834. Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1835. #ifndef NDEBUG
  1836. bool fromVec = isa<VectorType>(C->getType());
  1837. bool toVec = isa<VectorType>(Ty);
  1838. #endif
  1839. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1840. assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
  1841. "This is an illegal floating point to sint cast!");
  1842. return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
  1843. }
  1844. Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
  1845. bool OnlyIfReduced) {
  1846. assert(C->getType()->isPtrOrPtrVectorTy() &&
  1847. "PtrToInt source must be pointer or pointer vector");
  1848. assert(DstTy->isIntOrIntVectorTy() &&
  1849. "PtrToInt destination must be integer or integer vector");
  1850. assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
  1851. if (isa<VectorType>(C->getType()))
  1852. assert(cast<VectorType>(C->getType())->getElementCount() ==
  1853. cast<VectorType>(DstTy)->getElementCount() &&
  1854. "Invalid cast between a different number of vector elements");
  1855. return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
  1856. }
  1857. Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
  1858. bool OnlyIfReduced) {
  1859. assert(C->getType()->isIntOrIntVectorTy() &&
  1860. "IntToPtr source must be integer or integer vector");
  1861. assert(DstTy->isPtrOrPtrVectorTy() &&
  1862. "IntToPtr destination must be a pointer or pointer vector");
  1863. assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
  1864. if (isa<VectorType>(C->getType()))
  1865. assert(cast<VectorType>(C->getType())->getElementCount() ==
  1866. cast<VectorType>(DstTy)->getElementCount() &&
  1867. "Invalid cast between a different number of vector elements");
  1868. return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
  1869. }
  1870. Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
  1871. bool OnlyIfReduced) {
  1872. assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
  1873. "Invalid constantexpr bitcast!");
  1874. // It is common to ask for a bitcast of a value to its own type, handle this
  1875. // speedily.
  1876. if (C->getType() == DstTy) return C;
  1877. return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
  1878. }
  1879. Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
  1880. bool OnlyIfReduced) {
  1881. assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
  1882. "Invalid constantexpr addrspacecast!");
  1883. // Canonicalize addrspacecasts between different pointer types by first
  1884. // bitcasting the pointer type and then converting the address space.
  1885. PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
  1886. PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
  1887. if (!SrcScalarTy->hasSameElementTypeAs(DstScalarTy)) {
  1888. Type *MidTy = PointerType::getWithSamePointeeType(
  1889. DstScalarTy, SrcScalarTy->getAddressSpace());
  1890. if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
  1891. // Handle vectors of pointers.
  1892. MidTy = FixedVectorType::get(MidTy,
  1893. cast<FixedVectorType>(VT)->getNumElements());
  1894. }
  1895. C = getBitCast(C, MidTy);
  1896. }
  1897. return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
  1898. }
  1899. Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
  1900. unsigned Flags, Type *OnlyIfReducedTy) {
  1901. // Check the operands for consistency first.
  1902. assert(Instruction::isBinaryOp(Opcode) &&
  1903. "Invalid opcode in binary constant expression");
  1904. assert(isSupportedBinOp(Opcode) &&
  1905. "Binop not supported as constant expression");
  1906. assert(C1->getType() == C2->getType() &&
  1907. "Operand types in binary constant expression should match");
  1908. #ifndef NDEBUG
  1909. switch (Opcode) {
  1910. case Instruction::Add:
  1911. case Instruction::Sub:
  1912. case Instruction::Mul:
  1913. case Instruction::UDiv:
  1914. case Instruction::SDiv:
  1915. case Instruction::URem:
  1916. case Instruction::SRem:
  1917. assert(C1->getType()->isIntOrIntVectorTy() &&
  1918. "Tried to create an integer operation on a non-integer type!");
  1919. break;
  1920. case Instruction::FAdd:
  1921. case Instruction::FSub:
  1922. case Instruction::FMul:
  1923. case Instruction::FDiv:
  1924. case Instruction::FRem:
  1925. assert(C1->getType()->isFPOrFPVectorTy() &&
  1926. "Tried to create a floating-point operation on a "
  1927. "non-floating-point type!");
  1928. break;
  1929. case Instruction::And:
  1930. case Instruction::Or:
  1931. case Instruction::Xor:
  1932. assert(C1->getType()->isIntOrIntVectorTy() &&
  1933. "Tried to create a logical operation on a non-integral type!");
  1934. break;
  1935. case Instruction::Shl:
  1936. case Instruction::LShr:
  1937. case Instruction::AShr:
  1938. assert(C1->getType()->isIntOrIntVectorTy() &&
  1939. "Tried to create a shift operation on a non-integer type!");
  1940. break;
  1941. default:
  1942. break;
  1943. }
  1944. #endif
  1945. if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
  1946. return FC;
  1947. if (OnlyIfReducedTy == C1->getType())
  1948. return nullptr;
  1949. Constant *ArgVec[] = { C1, C2 };
  1950. ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
  1951. LLVMContextImpl *pImpl = C1->getContext().pImpl;
  1952. return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
  1953. }
  1954. bool ConstantExpr::isDesirableBinOp(unsigned Opcode) {
  1955. switch (Opcode) {
  1956. case Instruction::UDiv:
  1957. case Instruction::SDiv:
  1958. case Instruction::URem:
  1959. case Instruction::SRem:
  1960. case Instruction::FAdd:
  1961. case Instruction::FSub:
  1962. case Instruction::FMul:
  1963. case Instruction::FDiv:
  1964. case Instruction::FRem:
  1965. return false;
  1966. case Instruction::Add:
  1967. case Instruction::Sub:
  1968. case Instruction::Mul:
  1969. case Instruction::Shl:
  1970. case Instruction::LShr:
  1971. case Instruction::AShr:
  1972. case Instruction::And:
  1973. case Instruction::Or:
  1974. case Instruction::Xor:
  1975. return true;
  1976. default:
  1977. llvm_unreachable("Argument must be binop opcode");
  1978. }
  1979. }
  1980. bool ConstantExpr::isSupportedBinOp(unsigned Opcode) {
  1981. switch (Opcode) {
  1982. case Instruction::UDiv:
  1983. case Instruction::SDiv:
  1984. case Instruction::URem:
  1985. case Instruction::SRem:
  1986. case Instruction::FAdd:
  1987. case Instruction::FSub:
  1988. case Instruction::FMul:
  1989. case Instruction::FDiv:
  1990. case Instruction::FRem:
  1991. return false;
  1992. case Instruction::Add:
  1993. case Instruction::Sub:
  1994. case Instruction::Mul:
  1995. case Instruction::Shl:
  1996. case Instruction::LShr:
  1997. case Instruction::AShr:
  1998. case Instruction::And:
  1999. case Instruction::Or:
  2000. case Instruction::Xor:
  2001. return true;
  2002. default:
  2003. llvm_unreachable("Argument must be binop opcode");
  2004. }
  2005. }
  2006. Constant *ConstantExpr::getSizeOf(Type* Ty) {
  2007. // sizeof is implemented as: (i64) gep (Ty*)null, 1
  2008. // Note that a non-inbounds gep is used, as null isn't within any object.
  2009. Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
  2010. Constant *GEP = getGetElementPtr(
  2011. Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
  2012. return getPtrToInt(GEP,
  2013. Type::getInt64Ty(Ty->getContext()));
  2014. }
  2015. Constant *ConstantExpr::getAlignOf(Type* Ty) {
  2016. // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
  2017. // Note that a non-inbounds gep is used, as null isn't within any object.
  2018. Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
  2019. Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
  2020. Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
  2021. Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
  2022. Constant *Indices[2] = { Zero, One };
  2023. Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
  2024. return getPtrToInt(GEP,
  2025. Type::getInt64Ty(Ty->getContext()));
  2026. }
  2027. Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
  2028. return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
  2029. FieldNo));
  2030. }
  2031. Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
  2032. // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
  2033. // Note that a non-inbounds gep is used, as null isn't within any object.
  2034. Constant *GEPIdx[] = {
  2035. ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
  2036. FieldNo
  2037. };
  2038. Constant *GEP = getGetElementPtr(
  2039. Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
  2040. return getPtrToInt(GEP,
  2041. Type::getInt64Ty(Ty->getContext()));
  2042. }
  2043. Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
  2044. Constant *C2, bool OnlyIfReduced) {
  2045. assert(C1->getType() == C2->getType() && "Op types should be identical!");
  2046. switch (Predicate) {
  2047. default: llvm_unreachable("Invalid CmpInst predicate");
  2048. case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
  2049. case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
  2050. case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
  2051. case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
  2052. case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
  2053. case CmpInst::FCMP_TRUE:
  2054. return getFCmp(Predicate, C1, C2, OnlyIfReduced);
  2055. case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
  2056. case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
  2057. case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
  2058. case CmpInst::ICMP_SLE:
  2059. return getICmp(Predicate, C1, C2, OnlyIfReduced);
  2060. }
  2061. }
  2062. Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
  2063. Type *OnlyIfReducedTy) {
  2064. assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
  2065. if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
  2066. return SC; // Fold common cases
  2067. if (OnlyIfReducedTy == V1->getType())
  2068. return nullptr;
  2069. Constant *ArgVec[] = { C, V1, V2 };
  2070. ConstantExprKeyType Key(Instruction::Select, ArgVec);
  2071. LLVMContextImpl *pImpl = C->getContext().pImpl;
  2072. return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
  2073. }
  2074. Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
  2075. ArrayRef<Value *> Idxs, bool InBounds,
  2076. std::optional<unsigned> InRangeIndex,
  2077. Type *OnlyIfReducedTy) {
  2078. PointerType *OrigPtrTy = cast<PointerType>(C->getType()->getScalarType());
  2079. assert(Ty && "Must specify element type");
  2080. assert(OrigPtrTy->isOpaqueOrPointeeTypeMatches(Ty));
  2081. if (Constant *FC =
  2082. ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
  2083. return FC; // Fold a few common cases.
  2084. // Get the result type of the getelementptr!
  2085. Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
  2086. assert(DestTy && "GEP indices invalid!");
  2087. unsigned AS = OrigPtrTy->getAddressSpace();
  2088. Type *ReqTy = OrigPtrTy->isOpaque()
  2089. ? PointerType::get(OrigPtrTy->getContext(), AS)
  2090. : DestTy->getPointerTo(AS);
  2091. auto EltCount = ElementCount::getFixed(0);
  2092. if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
  2093. EltCount = VecTy->getElementCount();
  2094. else
  2095. for (auto *Idx : Idxs)
  2096. if (VectorType *VecTy = dyn_cast<VectorType>(Idx->getType()))
  2097. EltCount = VecTy->getElementCount();
  2098. if (EltCount.isNonZero())
  2099. ReqTy = VectorType::get(ReqTy, EltCount);
  2100. if (OnlyIfReducedTy == ReqTy)
  2101. return nullptr;
  2102. // Look up the constant in the table first to ensure uniqueness
  2103. std::vector<Constant*> ArgVec;
  2104. ArgVec.reserve(1 + Idxs.size());
  2105. ArgVec.push_back(C);
  2106. auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
  2107. for (; GTI != GTE; ++GTI) {
  2108. auto *Idx = cast<Constant>(GTI.getOperand());
  2109. assert(
  2110. (!isa<VectorType>(Idx->getType()) ||
  2111. cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
  2112. "getelementptr index type missmatch");
  2113. if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
  2114. Idx = Idx->getSplatValue();
  2115. } else if (GTI.isSequential() && EltCount.isNonZero() &&
  2116. !Idx->getType()->isVectorTy()) {
  2117. Idx = ConstantVector::getSplat(EltCount, Idx);
  2118. }
  2119. ArgVec.push_back(Idx);
  2120. }
  2121. unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
  2122. if (InRangeIndex && *InRangeIndex < 63)
  2123. SubClassOptionalData |= (*InRangeIndex + 1) << 1;
  2124. const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
  2125. SubClassOptionalData, std::nullopt, Ty);
  2126. LLVMContextImpl *pImpl = C->getContext().pImpl;
  2127. return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
  2128. }
  2129. Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
  2130. Constant *RHS, bool OnlyIfReduced) {
  2131. auto Predicate = static_cast<CmpInst::Predicate>(pred);
  2132. assert(LHS->getType() == RHS->getType());
  2133. assert(CmpInst::isIntPredicate(Predicate) && "Invalid ICmp Predicate");
  2134. if (Constant *FC = ConstantFoldCompareInstruction(Predicate, LHS, RHS))
  2135. return FC; // Fold a few common cases...
  2136. if (OnlyIfReduced)
  2137. return nullptr;
  2138. // Look up the constant in the table first to ensure uniqueness
  2139. Constant *ArgVec[] = { LHS, RHS };
  2140. // Get the key type with both the opcode and predicate
  2141. const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, Predicate);
  2142. Type *ResultTy = Type::getInt1Ty(LHS->getContext());
  2143. if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
  2144. ResultTy = VectorType::get(ResultTy, VT->getElementCount());
  2145. LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
  2146. return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
  2147. }
  2148. Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
  2149. Constant *RHS, bool OnlyIfReduced) {
  2150. auto Predicate = static_cast<CmpInst::Predicate>(pred);
  2151. assert(LHS->getType() == RHS->getType());
  2152. assert(CmpInst::isFPPredicate(Predicate) && "Invalid FCmp Predicate");
  2153. if (Constant *FC = ConstantFoldCompareInstruction(Predicate, LHS, RHS))
  2154. return FC; // Fold a few common cases...
  2155. if (OnlyIfReduced)
  2156. return nullptr;
  2157. // Look up the constant in the table first to ensure uniqueness
  2158. Constant *ArgVec[] = { LHS, RHS };
  2159. // Get the key type with both the opcode and predicate
  2160. const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, Predicate);
  2161. Type *ResultTy = Type::getInt1Ty(LHS->getContext());
  2162. if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
  2163. ResultTy = VectorType::get(ResultTy, VT->getElementCount());
  2164. LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
  2165. return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
  2166. }
  2167. Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
  2168. Type *OnlyIfReducedTy) {
  2169. assert(Val->getType()->isVectorTy() &&
  2170. "Tried to create extractelement operation on non-vector type!");
  2171. assert(Idx->getType()->isIntegerTy() &&
  2172. "Extractelement index must be an integer type!");
  2173. if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
  2174. return FC; // Fold a few common cases.
  2175. Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
  2176. if (OnlyIfReducedTy == ReqTy)
  2177. return nullptr;
  2178. // Look up the constant in the table first to ensure uniqueness
  2179. Constant *ArgVec[] = { Val, Idx };
  2180. const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
  2181. LLVMContextImpl *pImpl = Val->getContext().pImpl;
  2182. return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
  2183. }
  2184. Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
  2185. Constant *Idx, Type *OnlyIfReducedTy) {
  2186. assert(Val->getType()->isVectorTy() &&
  2187. "Tried to create insertelement operation on non-vector type!");
  2188. assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
  2189. "Insertelement types must match!");
  2190. assert(Idx->getType()->isIntegerTy() &&
  2191. "Insertelement index must be i32 type!");
  2192. if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
  2193. return FC; // Fold a few common cases.
  2194. if (OnlyIfReducedTy == Val->getType())
  2195. return nullptr;
  2196. // Look up the constant in the table first to ensure uniqueness
  2197. Constant *ArgVec[] = { Val, Elt, Idx };
  2198. const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
  2199. LLVMContextImpl *pImpl = Val->getContext().pImpl;
  2200. return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
  2201. }
  2202. Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
  2203. ArrayRef<int> Mask,
  2204. Type *OnlyIfReducedTy) {
  2205. assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
  2206. "Invalid shuffle vector constant expr operands!");
  2207. if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
  2208. return FC; // Fold a few common cases.
  2209. unsigned NElts = Mask.size();
  2210. auto V1VTy = cast<VectorType>(V1->getType());
  2211. Type *EltTy = V1VTy->getElementType();
  2212. bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
  2213. Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
  2214. if (OnlyIfReducedTy == ShufTy)
  2215. return nullptr;
  2216. // Look up the constant in the table first to ensure uniqueness
  2217. Constant *ArgVec[] = {V1, V2};
  2218. ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, 0, Mask);
  2219. LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
  2220. return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
  2221. }
  2222. Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
  2223. assert(C->getType()->isIntOrIntVectorTy() &&
  2224. "Cannot NEG a nonintegral value!");
  2225. return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
  2226. C, HasNUW, HasNSW);
  2227. }
  2228. Constant *ConstantExpr::getNot(Constant *C) {
  2229. assert(C->getType()->isIntOrIntVectorTy() &&
  2230. "Cannot NOT a nonintegral value!");
  2231. return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
  2232. }
  2233. Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
  2234. bool HasNUW, bool HasNSW) {
  2235. unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
  2236. (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
  2237. return get(Instruction::Add, C1, C2, Flags);
  2238. }
  2239. Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
  2240. bool HasNUW, bool HasNSW) {
  2241. unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
  2242. (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
  2243. return get(Instruction::Sub, C1, C2, Flags);
  2244. }
  2245. Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
  2246. bool HasNUW, bool HasNSW) {
  2247. unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
  2248. (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
  2249. return get(Instruction::Mul, C1, C2, Flags);
  2250. }
  2251. Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
  2252. return get(Instruction::And, C1, C2);
  2253. }
  2254. Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
  2255. return get(Instruction::Or, C1, C2);
  2256. }
  2257. Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
  2258. return get(Instruction::Xor, C1, C2);
  2259. }
  2260. Constant *ConstantExpr::getUMin(Constant *C1, Constant *C2) {
  2261. Constant *Cmp = ConstantExpr::getICmp(CmpInst::ICMP_ULT, C1, C2);
  2262. return getSelect(Cmp, C1, C2);
  2263. }
  2264. Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
  2265. bool HasNUW, bool HasNSW) {
  2266. unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
  2267. (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
  2268. return get(Instruction::Shl, C1, C2, Flags);
  2269. }
  2270. Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
  2271. return get(Instruction::LShr, C1, C2,
  2272. isExact ? PossiblyExactOperator::IsExact : 0);
  2273. }
  2274. Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
  2275. return get(Instruction::AShr, C1, C2,
  2276. isExact ? PossiblyExactOperator::IsExact : 0);
  2277. }
  2278. Constant *ConstantExpr::getExactLogBase2(Constant *C) {
  2279. Type *Ty = C->getType();
  2280. const APInt *IVal;
  2281. if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
  2282. return ConstantInt::get(Ty, IVal->logBase2());
  2283. // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
  2284. auto *VecTy = dyn_cast<FixedVectorType>(Ty);
  2285. if (!VecTy)
  2286. return nullptr;
  2287. SmallVector<Constant *, 4> Elts;
  2288. for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
  2289. Constant *Elt = C->getAggregateElement(I);
  2290. if (!Elt)
  2291. return nullptr;
  2292. // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.
  2293. if (isa<UndefValue>(Elt)) {
  2294. Elts.push_back(Constant::getNullValue(Ty->getScalarType()));
  2295. continue;
  2296. }
  2297. if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
  2298. return nullptr;
  2299. Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
  2300. }
  2301. return ConstantVector::get(Elts);
  2302. }
  2303. Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,
  2304. bool AllowRHSConstant, bool NSZ) {
  2305. assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
  2306. // Commutative opcodes: it does not matter if AllowRHSConstant is set.
  2307. if (Instruction::isCommutative(Opcode)) {
  2308. switch (Opcode) {
  2309. case Instruction::Add: // X + 0 = X
  2310. case Instruction::Or: // X | 0 = X
  2311. case Instruction::Xor: // X ^ 0 = X
  2312. return Constant::getNullValue(Ty);
  2313. case Instruction::Mul: // X * 1 = X
  2314. return ConstantInt::get(Ty, 1);
  2315. case Instruction::And: // X & -1 = X
  2316. return Constant::getAllOnesValue(Ty);
  2317. case Instruction::FAdd: // X + -0.0 = X
  2318. return ConstantFP::getZero(Ty, !NSZ);
  2319. case Instruction::FMul: // X * 1.0 = X
  2320. return ConstantFP::get(Ty, 1.0);
  2321. default:
  2322. llvm_unreachable("Every commutative binop has an identity constant");
  2323. }
  2324. }
  2325. // Non-commutative opcodes: AllowRHSConstant must be set.
  2326. if (!AllowRHSConstant)
  2327. return nullptr;
  2328. switch (Opcode) {
  2329. case Instruction::Sub: // X - 0 = X
  2330. case Instruction::Shl: // X << 0 = X
  2331. case Instruction::LShr: // X >>u 0 = X
  2332. case Instruction::AShr: // X >> 0 = X
  2333. case Instruction::FSub: // X - 0.0 = X
  2334. return Constant::getNullValue(Ty);
  2335. case Instruction::SDiv: // X / 1 = X
  2336. case Instruction::UDiv: // X /u 1 = X
  2337. return ConstantInt::get(Ty, 1);
  2338. case Instruction::FDiv: // X / 1.0 = X
  2339. return ConstantFP::get(Ty, 1.0);
  2340. default:
  2341. return nullptr;
  2342. }
  2343. }
  2344. Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
  2345. switch (Opcode) {
  2346. default:
  2347. // Doesn't have an absorber.
  2348. return nullptr;
  2349. case Instruction::Or:
  2350. return Constant::getAllOnesValue(Ty);
  2351. case Instruction::And:
  2352. case Instruction::Mul:
  2353. return Constant::getNullValue(Ty);
  2354. }
  2355. }
  2356. /// Remove the constant from the constant table.
  2357. void ConstantExpr::destroyConstantImpl() {
  2358. getType()->getContext().pImpl->ExprConstants.remove(this);
  2359. }
  2360. const char *ConstantExpr::getOpcodeName() const {
  2361. return Instruction::getOpcodeName(getOpcode());
  2362. }
  2363. GetElementPtrConstantExpr::GetElementPtrConstantExpr(
  2364. Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
  2365. : ConstantExpr(DestTy, Instruction::GetElementPtr,
  2366. OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
  2367. (IdxList.size() + 1),
  2368. IdxList.size() + 1),
  2369. SrcElementTy(SrcElementTy),
  2370. ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
  2371. Op<0>() = C;
  2372. Use *OperandList = getOperandList();
  2373. for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
  2374. OperandList[i+1] = IdxList[i];
  2375. }
  2376. Type *GetElementPtrConstantExpr::getSourceElementType() const {
  2377. return SrcElementTy;
  2378. }
  2379. Type *GetElementPtrConstantExpr::getResultElementType() const {
  2380. return ResElementTy;
  2381. }
  2382. //===----------------------------------------------------------------------===//
  2383. // ConstantData* implementations
  2384. Type *ConstantDataSequential::getElementType() const {
  2385. if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
  2386. return ATy->getElementType();
  2387. return cast<VectorType>(getType())->getElementType();
  2388. }
  2389. StringRef ConstantDataSequential::getRawDataValues() const {
  2390. return StringRef(DataElements, getNumElements()*getElementByteSize());
  2391. }
  2392. bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
  2393. if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
  2394. return true;
  2395. if (auto *IT = dyn_cast<IntegerType>(Ty)) {
  2396. switch (IT->getBitWidth()) {
  2397. case 8:
  2398. case 16:
  2399. case 32:
  2400. case 64:
  2401. return true;
  2402. default: break;
  2403. }
  2404. }
  2405. return false;
  2406. }
  2407. unsigned ConstantDataSequential::getNumElements() const {
  2408. if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
  2409. return AT->getNumElements();
  2410. return cast<FixedVectorType>(getType())->getNumElements();
  2411. }
  2412. uint64_t ConstantDataSequential::getElementByteSize() const {
  2413. return getElementType()->getPrimitiveSizeInBits()/8;
  2414. }
  2415. /// Return the start of the specified element.
  2416. const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
  2417. assert(Elt < getNumElements() && "Invalid Elt");
  2418. return DataElements+Elt*getElementByteSize();
  2419. }
  2420. /// Return true if the array is empty or all zeros.
  2421. static bool isAllZeros(StringRef Arr) {
  2422. for (char I : Arr)
  2423. if (I != 0)
  2424. return false;
  2425. return true;
  2426. }
  2427. /// This is the underlying implementation of all of the
  2428. /// ConstantDataSequential::get methods. They all thunk down to here, providing
  2429. /// the correct element type. We take the bytes in as a StringRef because
  2430. /// we *want* an underlying "char*" to avoid TBAA type punning violations.
  2431. Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
  2432. #ifndef NDEBUG
  2433. if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
  2434. assert(isElementTypeCompatible(ATy->getElementType()));
  2435. else
  2436. assert(isElementTypeCompatible(cast<VectorType>(Ty)->getElementType()));
  2437. #endif
  2438. // If the elements are all zero or there are no elements, return a CAZ, which
  2439. // is more dense and canonical.
  2440. if (isAllZeros(Elements))
  2441. return ConstantAggregateZero::get(Ty);
  2442. // Do a lookup to see if we have already formed one of these.
  2443. auto &Slot =
  2444. *Ty->getContext()
  2445. .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
  2446. .first;
  2447. // The bucket can point to a linked list of different CDS's that have the same
  2448. // body but different types. For example, 0,0,0,1 could be a 4 element array
  2449. // of i8, or a 1-element array of i32. They'll both end up in the same
  2450. /// StringMap bucket, linked up by their Next pointers. Walk the list.
  2451. std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;
  2452. for (; *Entry; Entry = &(*Entry)->Next)
  2453. if ((*Entry)->getType() == Ty)
  2454. return Entry->get();
  2455. // Okay, we didn't get a hit. Create a node of the right class, link it in,
  2456. // and return it.
  2457. if (isa<ArrayType>(Ty)) {
  2458. // Use reset because std::make_unique can't access the constructor.
  2459. Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));
  2460. return Entry->get();
  2461. }
  2462. assert(isa<VectorType>(Ty));
  2463. // Use reset because std::make_unique can't access the constructor.
  2464. Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));
  2465. return Entry->get();
  2466. }
  2467. void ConstantDataSequential::destroyConstantImpl() {
  2468. // Remove the constant from the StringMap.
  2469. StringMap<std::unique_ptr<ConstantDataSequential>> &CDSConstants =
  2470. getType()->getContext().pImpl->CDSConstants;
  2471. auto Slot = CDSConstants.find(getRawDataValues());
  2472. assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
  2473. std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();
  2474. // Remove the entry from the hash table.
  2475. if (!(*Entry)->Next) {
  2476. // If there is only one value in the bucket (common case) it must be this
  2477. // entry, and removing the entry should remove the bucket completely.
  2478. assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");
  2479. getContext().pImpl->CDSConstants.erase(Slot);
  2480. return;
  2481. }
  2482. // Otherwise, there are multiple entries linked off the bucket, unlink the
  2483. // node we care about but keep the bucket around.
  2484. while (true) {
  2485. std::unique_ptr<ConstantDataSequential> &Node = *Entry;
  2486. assert(Node && "Didn't find entry in its uniquing hash table!");
  2487. // If we found our entry, unlink it from the list and we're done.
  2488. if (Node.get() == this) {
  2489. Node = std::move(Node->Next);
  2490. return;
  2491. }
  2492. Entry = &Node->Next;
  2493. }
  2494. }
  2495. /// getFP() constructors - Return a constant of array type with a float
  2496. /// element type taken from argument `ElementType', and count taken from
  2497. /// argument `Elts'. The amount of bits of the contained type must match the
  2498. /// number of bits of the type contained in the passed in ArrayRef.
  2499. /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
  2500. /// that this can return a ConstantAggregateZero object.
  2501. Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint16_t> Elts) {
  2502. assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
  2503. "Element type is not a 16-bit float type");
  2504. Type *Ty = ArrayType::get(ElementType, Elts.size());
  2505. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2506. return getImpl(StringRef(Data, Elts.size() * 2), Ty);
  2507. }
  2508. Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint32_t> Elts) {
  2509. assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
  2510. Type *Ty = ArrayType::get(ElementType, Elts.size());
  2511. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2512. return getImpl(StringRef(Data, Elts.size() * 4), Ty);
  2513. }
  2514. Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint64_t> Elts) {
  2515. assert(ElementType->isDoubleTy() &&
  2516. "Element type is not a 64-bit float type");
  2517. Type *Ty = ArrayType::get(ElementType, Elts.size());
  2518. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2519. return getImpl(StringRef(Data, Elts.size() * 8), Ty);
  2520. }
  2521. Constant *ConstantDataArray::getString(LLVMContext &Context,
  2522. StringRef Str, bool AddNull) {
  2523. if (!AddNull) {
  2524. const uint8_t *Data = Str.bytes_begin();
  2525. return get(Context, ArrayRef(Data, Str.size()));
  2526. }
  2527. SmallVector<uint8_t, 64> ElementVals;
  2528. ElementVals.append(Str.begin(), Str.end());
  2529. ElementVals.push_back(0);
  2530. return get(Context, ElementVals);
  2531. }
  2532. /// get() constructors - Return a constant with vector type with an element
  2533. /// count and element type matching the ArrayRef passed in. Note that this
  2534. /// can return a ConstantAggregateZero object.
  2535. Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
  2536. auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
  2537. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2538. return getImpl(StringRef(Data, Elts.size() * 1), Ty);
  2539. }
  2540. Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
  2541. auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());
  2542. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2543. return getImpl(StringRef(Data, Elts.size() * 2), Ty);
  2544. }
  2545. Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
  2546. auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());
  2547. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2548. return getImpl(StringRef(Data, Elts.size() * 4), Ty);
  2549. }
  2550. Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
  2551. auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());
  2552. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2553. return getImpl(StringRef(Data, Elts.size() * 8), Ty);
  2554. }
  2555. Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
  2556. auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());
  2557. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2558. return getImpl(StringRef(Data, Elts.size() * 4), Ty);
  2559. }
  2560. Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
  2561. auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());
  2562. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2563. return getImpl(StringRef(Data, Elts.size() * 8), Ty);
  2564. }
  2565. /// getFP() constructors - Return a constant of vector type with a float
  2566. /// element type taken from argument `ElementType', and count taken from
  2567. /// argument `Elts'. The amount of bits of the contained type must match the
  2568. /// number of bits of the type contained in the passed in ArrayRef.
  2569. /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
  2570. /// that this can return a ConstantAggregateZero object.
  2571. Constant *ConstantDataVector::getFP(Type *ElementType,
  2572. ArrayRef<uint16_t> Elts) {
  2573. assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
  2574. "Element type is not a 16-bit float type");
  2575. auto *Ty = FixedVectorType::get(ElementType, Elts.size());
  2576. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2577. return getImpl(StringRef(Data, Elts.size() * 2), Ty);
  2578. }
  2579. Constant *ConstantDataVector::getFP(Type *ElementType,
  2580. ArrayRef<uint32_t> Elts) {
  2581. assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
  2582. auto *Ty = FixedVectorType::get(ElementType, Elts.size());
  2583. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2584. return getImpl(StringRef(Data, Elts.size() * 4), Ty);
  2585. }
  2586. Constant *ConstantDataVector::getFP(Type *ElementType,
  2587. ArrayRef<uint64_t> Elts) {
  2588. assert(ElementType->isDoubleTy() &&
  2589. "Element type is not a 64-bit float type");
  2590. auto *Ty = FixedVectorType::get(ElementType, Elts.size());
  2591. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2592. return getImpl(StringRef(Data, Elts.size() * 8), Ty);
  2593. }
  2594. Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
  2595. assert(isElementTypeCompatible(V->getType()) &&
  2596. "Element type not compatible with ConstantData");
  2597. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  2598. if (CI->getType()->isIntegerTy(8)) {
  2599. SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
  2600. return get(V->getContext(), Elts);
  2601. }
  2602. if (CI->getType()->isIntegerTy(16)) {
  2603. SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
  2604. return get(V->getContext(), Elts);
  2605. }
  2606. if (CI->getType()->isIntegerTy(32)) {
  2607. SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
  2608. return get(V->getContext(), Elts);
  2609. }
  2610. assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
  2611. SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
  2612. return get(V->getContext(), Elts);
  2613. }
  2614. if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
  2615. if (CFP->getType()->isHalfTy()) {
  2616. SmallVector<uint16_t, 16> Elts(
  2617. NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
  2618. return getFP(V->getType(), Elts);
  2619. }
  2620. if (CFP->getType()->isBFloatTy()) {
  2621. SmallVector<uint16_t, 16> Elts(
  2622. NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
  2623. return getFP(V->getType(), Elts);
  2624. }
  2625. if (CFP->getType()->isFloatTy()) {
  2626. SmallVector<uint32_t, 16> Elts(
  2627. NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
  2628. return getFP(V->getType(), Elts);
  2629. }
  2630. if (CFP->getType()->isDoubleTy()) {
  2631. SmallVector<uint64_t, 16> Elts(
  2632. NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
  2633. return getFP(V->getType(), Elts);
  2634. }
  2635. }
  2636. return ConstantVector::getSplat(ElementCount::getFixed(NumElts), V);
  2637. }
  2638. uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
  2639. assert(isa<IntegerType>(getElementType()) &&
  2640. "Accessor can only be used when element is an integer");
  2641. const char *EltPtr = getElementPointer(Elt);
  2642. // The data is stored in host byte order, make sure to cast back to the right
  2643. // type to load with the right endianness.
  2644. switch (getElementType()->getIntegerBitWidth()) {
  2645. default: llvm_unreachable("Invalid bitwidth for CDS");
  2646. case 8:
  2647. return *reinterpret_cast<const uint8_t *>(EltPtr);
  2648. case 16:
  2649. return *reinterpret_cast<const uint16_t *>(EltPtr);
  2650. case 32:
  2651. return *reinterpret_cast<const uint32_t *>(EltPtr);
  2652. case 64:
  2653. return *reinterpret_cast<const uint64_t *>(EltPtr);
  2654. }
  2655. }
  2656. APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
  2657. assert(isa<IntegerType>(getElementType()) &&
  2658. "Accessor can only be used when element is an integer");
  2659. const char *EltPtr = getElementPointer(Elt);
  2660. // The data is stored in host byte order, make sure to cast back to the right
  2661. // type to load with the right endianness.
  2662. switch (getElementType()->getIntegerBitWidth()) {
  2663. default: llvm_unreachable("Invalid bitwidth for CDS");
  2664. case 8: {
  2665. auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
  2666. return APInt(8, EltVal);
  2667. }
  2668. case 16: {
  2669. auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
  2670. return APInt(16, EltVal);
  2671. }
  2672. case 32: {
  2673. auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
  2674. return APInt(32, EltVal);
  2675. }
  2676. case 64: {
  2677. auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
  2678. return APInt(64, EltVal);
  2679. }
  2680. }
  2681. }
  2682. APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
  2683. const char *EltPtr = getElementPointer(Elt);
  2684. switch (getElementType()->getTypeID()) {
  2685. default:
  2686. llvm_unreachable("Accessor can only be used when element is float/double!");
  2687. case Type::HalfTyID: {
  2688. auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
  2689. return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
  2690. }
  2691. case Type::BFloatTyID: {
  2692. auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
  2693. return APFloat(APFloat::BFloat(), APInt(16, EltVal));
  2694. }
  2695. case Type::FloatTyID: {
  2696. auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
  2697. return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
  2698. }
  2699. case Type::DoubleTyID: {
  2700. auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
  2701. return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
  2702. }
  2703. }
  2704. }
  2705. float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
  2706. assert(getElementType()->isFloatTy() &&
  2707. "Accessor can only be used when element is a 'float'");
  2708. return *reinterpret_cast<const float *>(getElementPointer(Elt));
  2709. }
  2710. double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
  2711. assert(getElementType()->isDoubleTy() &&
  2712. "Accessor can only be used when element is a 'float'");
  2713. return *reinterpret_cast<const double *>(getElementPointer(Elt));
  2714. }
  2715. Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
  2716. if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
  2717. getElementType()->isFloatTy() || getElementType()->isDoubleTy())
  2718. return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
  2719. return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
  2720. }
  2721. bool ConstantDataSequential::isString(unsigned CharSize) const {
  2722. return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
  2723. }
  2724. bool ConstantDataSequential::isCString() const {
  2725. if (!isString())
  2726. return false;
  2727. StringRef Str = getAsString();
  2728. // The last value must be nul.
  2729. if (Str.back() != 0) return false;
  2730. // Other elements must be non-nul.
  2731. return !Str.drop_back().contains(0);
  2732. }
  2733. bool ConstantDataVector::isSplatData() const {
  2734. const char *Base = getRawDataValues().data();
  2735. // Compare elements 1+ to the 0'th element.
  2736. unsigned EltSize = getElementByteSize();
  2737. for (unsigned i = 1, e = getNumElements(); i != e; ++i)
  2738. if (memcmp(Base, Base+i*EltSize, EltSize))
  2739. return false;
  2740. return true;
  2741. }
  2742. bool ConstantDataVector::isSplat() const {
  2743. if (!IsSplatSet) {
  2744. IsSplatSet = true;
  2745. IsSplat = isSplatData();
  2746. }
  2747. return IsSplat;
  2748. }
  2749. Constant *ConstantDataVector::getSplatValue() const {
  2750. // If they're all the same, return the 0th one as a representative.
  2751. return isSplat() ? getElementAsConstant(0) : nullptr;
  2752. }
  2753. //===----------------------------------------------------------------------===//
  2754. // handleOperandChange implementations
  2755. /// Update this constant array to change uses of
  2756. /// 'From' to be uses of 'To'. This must update the uniquing data structures
  2757. /// etc.
  2758. ///
  2759. /// Note that we intentionally replace all uses of From with To here. Consider
  2760. /// a large array that uses 'From' 1000 times. By handling this case all here,
  2761. /// ConstantArray::handleOperandChange is only invoked once, and that
  2762. /// single invocation handles all 1000 uses. Handling them one at a time would
  2763. /// work, but would be really slow because it would have to unique each updated
  2764. /// array instance.
  2765. ///
  2766. void Constant::handleOperandChange(Value *From, Value *To) {
  2767. Value *Replacement = nullptr;
  2768. switch (getValueID()) {
  2769. default:
  2770. llvm_unreachable("Not a constant!");
  2771. #define HANDLE_CONSTANT(Name) \
  2772. case Value::Name##Val: \
  2773. Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
  2774. break;
  2775. #include "llvm/IR/Value.def"
  2776. }
  2777. // If handleOperandChangeImpl returned nullptr, then it handled
  2778. // replacing itself and we don't want to delete or replace anything else here.
  2779. if (!Replacement)
  2780. return;
  2781. // I do need to replace this with an existing value.
  2782. assert(Replacement != this && "I didn't contain From!");
  2783. // Everyone using this now uses the replacement.
  2784. replaceAllUsesWith(Replacement);
  2785. // Delete the old constant!
  2786. destroyConstant();
  2787. }
  2788. Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
  2789. assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
  2790. Constant *ToC = cast<Constant>(To);
  2791. SmallVector<Constant*, 8> Values;
  2792. Values.reserve(getNumOperands()); // Build replacement array.
  2793. // Fill values with the modified operands of the constant array. Also,
  2794. // compute whether this turns into an all-zeros array.
  2795. unsigned NumUpdated = 0;
  2796. // Keep track of whether all the values in the array are "ToC".
  2797. bool AllSame = true;
  2798. Use *OperandList = getOperandList();
  2799. unsigned OperandNo = 0;
  2800. for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
  2801. Constant *Val = cast<Constant>(O->get());
  2802. if (Val == From) {
  2803. OperandNo = (O - OperandList);
  2804. Val = ToC;
  2805. ++NumUpdated;
  2806. }
  2807. Values.push_back(Val);
  2808. AllSame &= Val == ToC;
  2809. }
  2810. if (AllSame && ToC->isNullValue())
  2811. return ConstantAggregateZero::get(getType());
  2812. if (AllSame && isa<UndefValue>(ToC))
  2813. return UndefValue::get(getType());
  2814. // Check for any other type of constant-folding.
  2815. if (Constant *C = getImpl(getType(), Values))
  2816. return C;
  2817. // Update to the new value.
  2818. return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
  2819. Values, this, From, ToC, NumUpdated, OperandNo);
  2820. }
  2821. Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
  2822. assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
  2823. Constant *ToC = cast<Constant>(To);
  2824. Use *OperandList = getOperandList();
  2825. SmallVector<Constant*, 8> Values;
  2826. Values.reserve(getNumOperands()); // Build replacement struct.
  2827. // Fill values with the modified operands of the constant struct. Also,
  2828. // compute whether this turns into an all-zeros struct.
  2829. unsigned NumUpdated = 0;
  2830. bool AllSame = true;
  2831. unsigned OperandNo = 0;
  2832. for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
  2833. Constant *Val = cast<Constant>(O->get());
  2834. if (Val == From) {
  2835. OperandNo = (O - OperandList);
  2836. Val = ToC;
  2837. ++NumUpdated;
  2838. }
  2839. Values.push_back(Val);
  2840. AllSame &= Val == ToC;
  2841. }
  2842. if (AllSame && ToC->isNullValue())
  2843. return ConstantAggregateZero::get(getType());
  2844. if (AllSame && isa<UndefValue>(ToC))
  2845. return UndefValue::get(getType());
  2846. // Update to the new value.
  2847. return getContext().pImpl->StructConstants.replaceOperandsInPlace(
  2848. Values, this, From, ToC, NumUpdated, OperandNo);
  2849. }
  2850. Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
  2851. assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
  2852. Constant *ToC = cast<Constant>(To);
  2853. SmallVector<Constant*, 8> Values;
  2854. Values.reserve(getNumOperands()); // Build replacement array...
  2855. unsigned NumUpdated = 0;
  2856. unsigned OperandNo = 0;
  2857. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  2858. Constant *Val = getOperand(i);
  2859. if (Val == From) {
  2860. OperandNo = i;
  2861. ++NumUpdated;
  2862. Val = ToC;
  2863. }
  2864. Values.push_back(Val);
  2865. }
  2866. if (Constant *C = getImpl(Values))
  2867. return C;
  2868. // Update to the new value.
  2869. return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
  2870. Values, this, From, ToC, NumUpdated, OperandNo);
  2871. }
  2872. Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
  2873. assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
  2874. Constant *To = cast<Constant>(ToV);
  2875. SmallVector<Constant*, 8> NewOps;
  2876. unsigned NumUpdated = 0;
  2877. unsigned OperandNo = 0;
  2878. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  2879. Constant *Op = getOperand(i);
  2880. if (Op == From) {
  2881. OperandNo = i;
  2882. ++NumUpdated;
  2883. Op = To;
  2884. }
  2885. NewOps.push_back(Op);
  2886. }
  2887. assert(NumUpdated && "I didn't contain From!");
  2888. if (Constant *C = getWithOperands(NewOps, getType(), true))
  2889. return C;
  2890. // Update to the new value.
  2891. return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
  2892. NewOps, this, From, To, NumUpdated, OperandNo);
  2893. }
  2894. Instruction *ConstantExpr::getAsInstruction(Instruction *InsertBefore) const {
  2895. SmallVector<Value *, 4> ValueOperands(operands());
  2896. ArrayRef<Value*> Ops(ValueOperands);
  2897. switch (getOpcode()) {
  2898. case Instruction::Trunc:
  2899. case Instruction::ZExt:
  2900. case Instruction::SExt:
  2901. case Instruction::FPTrunc:
  2902. case Instruction::FPExt:
  2903. case Instruction::UIToFP:
  2904. case Instruction::SIToFP:
  2905. case Instruction::FPToUI:
  2906. case Instruction::FPToSI:
  2907. case Instruction::PtrToInt:
  2908. case Instruction::IntToPtr:
  2909. case Instruction::BitCast:
  2910. case Instruction::AddrSpaceCast:
  2911. return CastInst::Create((Instruction::CastOps)getOpcode(), Ops[0],
  2912. getType(), "", InsertBefore);
  2913. case Instruction::Select:
  2914. return SelectInst::Create(Ops[0], Ops[1], Ops[2], "", InsertBefore);
  2915. case Instruction::InsertElement:
  2916. return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "", InsertBefore);
  2917. case Instruction::ExtractElement:
  2918. return ExtractElementInst::Create(Ops[0], Ops[1], "", InsertBefore);
  2919. case Instruction::ShuffleVector:
  2920. return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "",
  2921. InsertBefore);
  2922. case Instruction::GetElementPtr: {
  2923. const auto *GO = cast<GEPOperator>(this);
  2924. if (GO->isInBounds())
  2925. return GetElementPtrInst::CreateInBounds(
  2926. GO->getSourceElementType(), Ops[0], Ops.slice(1), "", InsertBefore);
  2927. return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
  2928. Ops.slice(1), "", InsertBefore);
  2929. }
  2930. case Instruction::ICmp:
  2931. case Instruction::FCmp:
  2932. return CmpInst::Create((Instruction::OtherOps)getOpcode(),
  2933. (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1],
  2934. "", InsertBefore);
  2935. default:
  2936. assert(getNumOperands() == 2 && "Must be binary operator?");
  2937. BinaryOperator *BO = BinaryOperator::Create(
  2938. (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "", InsertBefore);
  2939. if (isa<OverflowingBinaryOperator>(BO)) {
  2940. BO->setHasNoUnsignedWrap(SubclassOptionalData &
  2941. OverflowingBinaryOperator::NoUnsignedWrap);
  2942. BO->setHasNoSignedWrap(SubclassOptionalData &
  2943. OverflowingBinaryOperator::NoSignedWrap);
  2944. }
  2945. if (isa<PossiblyExactOperator>(BO))
  2946. BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
  2947. return BO;
  2948. }
  2949. }