ConstantFold.cpp 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449
  1. //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
  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 folding of constants for LLVM. This implements the
  10. // (internal) ConstantFold.h interface, which is used by the
  11. // ConstantExpr::get* methods to automatically fold constants when possible.
  12. //
  13. // The current constant folding implementation is implemented in two pieces: the
  14. // pieces that don't need DataLayout, and the pieces that do. This is to avoid
  15. // a dependence in IR on Target.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "ConstantFold.h"
  19. #include "llvm/ADT/APSInt.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/DerivedTypes.h"
  23. #include "llvm/IR/Function.h"
  24. #include "llvm/IR/GetElementPtrTypeIterator.h"
  25. #include "llvm/IR/GlobalAlias.h"
  26. #include "llvm/IR/GlobalVariable.h"
  27. #include "llvm/IR/Instructions.h"
  28. #include "llvm/IR/Module.h"
  29. #include "llvm/IR/Operator.h"
  30. #include "llvm/IR/PatternMatch.h"
  31. #include "llvm/Support/ErrorHandling.h"
  32. #include "llvm/Support/ManagedStatic.h"
  33. #include "llvm/Support/MathExtras.h"
  34. using namespace llvm;
  35. using namespace llvm::PatternMatch;
  36. //===----------------------------------------------------------------------===//
  37. // ConstantFold*Instruction Implementations
  38. //===----------------------------------------------------------------------===//
  39. /// Convert the specified vector Constant node to the specified vector type.
  40. /// At this point, we know that the elements of the input vector constant are
  41. /// all simple integer or FP values.
  42. static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) {
  43. if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
  44. if (CV->isNullValue()) return Constant::getNullValue(DstTy);
  45. // If this cast changes element count then we can't handle it here:
  46. // doing so requires endianness information. This should be handled by
  47. // Analysis/ConstantFolding.cpp
  48. unsigned NumElts = DstTy->getNumElements();
  49. if (NumElts != CV->getType()->getVectorNumElements())
  50. return nullptr;
  51. Type *DstEltTy = DstTy->getElementType();
  52. SmallVector<Constant*, 16> Result;
  53. Type *Ty = IntegerType::get(CV->getContext(), 32);
  54. for (unsigned i = 0; i != NumElts; ++i) {
  55. Constant *C =
  56. ConstantExpr::getExtractElement(CV, ConstantInt::get(Ty, i));
  57. C = ConstantExpr::getBitCast(C, DstEltTy);
  58. Result.push_back(C);
  59. }
  60. return ConstantVector::get(Result);
  61. }
  62. /// This function determines which opcode to use to fold two constant cast
  63. /// expressions together. It uses CastInst::isEliminableCastPair to determine
  64. /// the opcode. Consequently its just a wrapper around that function.
  65. /// Determine if it is valid to fold a cast of a cast
  66. static unsigned
  67. foldConstantCastPair(
  68. unsigned opc, ///< opcode of the second cast constant expression
  69. ConstantExpr *Op, ///< the first cast constant expression
  70. Type *DstTy ///< destination type of the first cast
  71. ) {
  72. assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
  73. assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
  74. assert(CastInst::isCast(opc) && "Invalid cast opcode");
  75. // The types and opcodes for the two Cast constant expressions
  76. Type *SrcTy = Op->getOperand(0)->getType();
  77. Type *MidTy = Op->getType();
  78. Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
  79. Instruction::CastOps secondOp = Instruction::CastOps(opc);
  80. // Assume that pointers are never more than 64 bits wide, and only use this
  81. // for the middle type. Otherwise we could end up folding away illegal
  82. // bitcasts between address spaces with different sizes.
  83. IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
  84. // Let CastInst::isEliminableCastPair do the heavy lifting.
  85. return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
  86. nullptr, FakeIntPtrTy, nullptr);
  87. }
  88. static Constant *FoldBitCast(Constant *V, Type *DestTy) {
  89. Type *SrcTy = V->getType();
  90. if (SrcTy == DestTy)
  91. return V; // no-op cast
  92. // Check to see if we are casting a pointer to an aggregate to a pointer to
  93. // the first element. If so, return the appropriate GEP instruction.
  94. if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
  95. if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
  96. if (PTy->getAddressSpace() == DPTy->getAddressSpace()
  97. && PTy->getElementType()->isSized()) {
  98. SmallVector<Value*, 8> IdxList;
  99. Value *Zero =
  100. Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
  101. IdxList.push_back(Zero);
  102. Type *ElTy = PTy->getElementType();
  103. while (ElTy != DPTy->getElementType()) {
  104. if (StructType *STy = dyn_cast<StructType>(ElTy)) {
  105. if (STy->getNumElements() == 0) break;
  106. ElTy = STy->getElementType(0);
  107. IdxList.push_back(Zero);
  108. } else if (SequentialType *STy =
  109. dyn_cast<SequentialType>(ElTy)) {
  110. ElTy = STy->getElementType();
  111. IdxList.push_back(Zero);
  112. } else {
  113. break;
  114. }
  115. }
  116. if (ElTy == DPTy->getElementType())
  117. // This GEP is inbounds because all indices are zero.
  118. return ConstantExpr::getInBoundsGetElementPtr(PTy->getElementType(),
  119. V, IdxList);
  120. }
  121. // Handle casts from one vector constant to another. We know that the src
  122. // and dest type have the same size (otherwise its an illegal cast).
  123. if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
  124. if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
  125. assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
  126. "Not cast between same sized vectors!");
  127. SrcTy = nullptr;
  128. // First, check for null. Undef is already handled.
  129. if (isa<ConstantAggregateZero>(V))
  130. return Constant::getNullValue(DestTy);
  131. // Handle ConstantVector and ConstantAggregateVector.
  132. return BitCastConstantVector(V, DestPTy);
  133. }
  134. // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
  135. // This allows for other simplifications (although some of them
  136. // can only be handled by Analysis/ConstantFolding.cpp).
  137. if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
  138. return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
  139. }
  140. // Finally, implement bitcast folding now. The code below doesn't handle
  141. // bitcast right.
  142. if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
  143. return ConstantPointerNull::get(cast<PointerType>(DestTy));
  144. // Handle integral constant input.
  145. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  146. if (DestTy->isIntegerTy())
  147. // Integral -> Integral. This is a no-op because the bit widths must
  148. // be the same. Consequently, we just fold to V.
  149. return V;
  150. // See note below regarding the PPC_FP128 restriction.
  151. if (DestTy->isFloatingPointTy() && !DestTy->isPPC_FP128Ty())
  152. return ConstantFP::get(DestTy->getContext(),
  153. APFloat(DestTy->getFltSemantics(),
  154. CI->getValue()));
  155. // Otherwise, can't fold this (vector?)
  156. return nullptr;
  157. }
  158. // Handle ConstantFP input: FP -> Integral.
  159. if (ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
  160. // PPC_FP128 is really the sum of two consecutive doubles, where the first
  161. // double is always stored first in memory, regardless of the target
  162. // endianness. The memory layout of i128, however, depends on the target
  163. // endianness, and so we can't fold this without target endianness
  164. // information. This should instead be handled by
  165. // Analysis/ConstantFolding.cpp
  166. if (FP->getType()->isPPC_FP128Ty())
  167. return nullptr;
  168. // Make sure dest type is compatible with the folded integer constant.
  169. if (!DestTy->isIntegerTy())
  170. return nullptr;
  171. return ConstantInt::get(FP->getContext(),
  172. FP->getValueAPF().bitcastToAPInt());
  173. }
  174. return nullptr;
  175. }
  176. /// V is an integer constant which only has a subset of its bytes used.
  177. /// The bytes used are indicated by ByteStart (which is the first byte used,
  178. /// counting from the least significant byte) and ByteSize, which is the number
  179. /// of bytes used.
  180. ///
  181. /// This function analyzes the specified constant to see if the specified byte
  182. /// range can be returned as a simplified constant. If so, the constant is
  183. /// returned, otherwise null is returned.
  184. static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
  185. unsigned ByteSize) {
  186. assert(C->getType()->isIntegerTy() &&
  187. (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
  188. "Non-byte sized integer input");
  189. unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
  190. assert(ByteSize && "Must be accessing some piece");
  191. assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
  192. assert(ByteSize != CSize && "Should not extract everything");
  193. // Constant Integers are simple.
  194. if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
  195. APInt V = CI->getValue();
  196. if (ByteStart)
  197. V.lshrInPlace(ByteStart*8);
  198. V = V.trunc(ByteSize*8);
  199. return ConstantInt::get(CI->getContext(), V);
  200. }
  201. // In the input is a constant expr, we might be able to recursively simplify.
  202. // If not, we definitely can't do anything.
  203. ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
  204. if (!CE) return nullptr;
  205. switch (CE->getOpcode()) {
  206. default: return nullptr;
  207. case Instruction::Or: {
  208. Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
  209. if (!RHS)
  210. return nullptr;
  211. // X | -1 -> -1.
  212. if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
  213. if (RHSC->isMinusOne())
  214. return RHSC;
  215. Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
  216. if (!LHS)
  217. return nullptr;
  218. return ConstantExpr::getOr(LHS, RHS);
  219. }
  220. case Instruction::And: {
  221. Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
  222. if (!RHS)
  223. return nullptr;
  224. // X & 0 -> 0.
  225. if (RHS->isNullValue())
  226. return RHS;
  227. Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
  228. if (!LHS)
  229. return nullptr;
  230. return ConstantExpr::getAnd(LHS, RHS);
  231. }
  232. case Instruction::LShr: {
  233. ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
  234. if (!Amt)
  235. return nullptr;
  236. APInt ShAmt = Amt->getValue();
  237. // Cannot analyze non-byte shifts.
  238. if ((ShAmt & 7) != 0)
  239. return nullptr;
  240. ShAmt.lshrInPlace(3);
  241. // If the extract is known to be all zeros, return zero.
  242. if (ShAmt.uge(CSize - ByteStart))
  243. return Constant::getNullValue(
  244. IntegerType::get(CE->getContext(), ByteSize * 8));
  245. // If the extract is known to be fully in the input, extract it.
  246. if (ShAmt.ule(CSize - (ByteStart + ByteSize)))
  247. return ExtractConstantBytes(CE->getOperand(0),
  248. ByteStart + ShAmt.getZExtValue(), ByteSize);
  249. // TODO: Handle the 'partially zero' case.
  250. return nullptr;
  251. }
  252. case Instruction::Shl: {
  253. ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
  254. if (!Amt)
  255. return nullptr;
  256. APInt ShAmt = Amt->getValue();
  257. // Cannot analyze non-byte shifts.
  258. if ((ShAmt & 7) != 0)
  259. return nullptr;
  260. ShAmt.lshrInPlace(3);
  261. // If the extract is known to be all zeros, return zero.
  262. if (ShAmt.uge(ByteStart + ByteSize))
  263. return Constant::getNullValue(
  264. IntegerType::get(CE->getContext(), ByteSize * 8));
  265. // If the extract is known to be fully in the input, extract it.
  266. if (ShAmt.ule(ByteStart))
  267. return ExtractConstantBytes(CE->getOperand(0),
  268. ByteStart - ShAmt.getZExtValue(), ByteSize);
  269. // TODO: Handle the 'partially zero' case.
  270. return nullptr;
  271. }
  272. case Instruction::ZExt: {
  273. unsigned SrcBitSize =
  274. cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
  275. // If extracting something that is completely zero, return 0.
  276. if (ByteStart*8 >= SrcBitSize)
  277. return Constant::getNullValue(IntegerType::get(CE->getContext(),
  278. ByteSize*8));
  279. // If exactly extracting the input, return it.
  280. if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
  281. return CE->getOperand(0);
  282. // If extracting something completely in the input, if the input is a
  283. // multiple of 8 bits, recurse.
  284. if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
  285. return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
  286. // Otherwise, if extracting a subset of the input, which is not multiple of
  287. // 8 bits, do a shift and trunc to get the bits.
  288. if ((ByteStart+ByteSize)*8 < SrcBitSize) {
  289. assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
  290. Constant *Res = CE->getOperand(0);
  291. if (ByteStart)
  292. Res = ConstantExpr::getLShr(Res,
  293. ConstantInt::get(Res->getType(), ByteStart*8));
  294. return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
  295. ByteSize*8));
  296. }
  297. // TODO: Handle the 'partially zero' case.
  298. return nullptr;
  299. }
  300. }
  301. }
  302. /// Return a ConstantExpr with type DestTy for sizeof on Ty, with any known
  303. /// factors factored out. If Folded is false, return null if no factoring was
  304. /// possible, to avoid endlessly bouncing an unfoldable expression back into the
  305. /// top-level folder.
  306. static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy, bool Folded) {
  307. if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  308. Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
  309. Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
  310. return ConstantExpr::getNUWMul(E, N);
  311. }
  312. if (StructType *STy = dyn_cast<StructType>(Ty))
  313. if (!STy->isPacked()) {
  314. unsigned NumElems = STy->getNumElements();
  315. // An empty struct has size zero.
  316. if (NumElems == 0)
  317. return ConstantExpr::getNullValue(DestTy);
  318. // Check for a struct with all members having the same size.
  319. Constant *MemberSize =
  320. getFoldedSizeOf(STy->getElementType(0), DestTy, true);
  321. bool AllSame = true;
  322. for (unsigned i = 1; i != NumElems; ++i)
  323. if (MemberSize !=
  324. getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
  325. AllSame = false;
  326. break;
  327. }
  328. if (AllSame) {
  329. Constant *N = ConstantInt::get(DestTy, NumElems);
  330. return ConstantExpr::getNUWMul(MemberSize, N);
  331. }
  332. }
  333. // Pointer size doesn't depend on the pointee type, so canonicalize them
  334. // to an arbitrary pointee.
  335. if (PointerType *PTy = dyn_cast<PointerType>(Ty))
  336. if (!PTy->getElementType()->isIntegerTy(1))
  337. return
  338. getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
  339. PTy->getAddressSpace()),
  340. DestTy, true);
  341. // If there's no interesting folding happening, bail so that we don't create
  342. // a constant that looks like it needs folding but really doesn't.
  343. if (!Folded)
  344. return nullptr;
  345. // Base case: Get a regular sizeof expression.
  346. Constant *C = ConstantExpr::getSizeOf(Ty);
  347. C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
  348. DestTy, false),
  349. C, DestTy);
  350. return C;
  351. }
  352. /// Return a ConstantExpr with type DestTy for alignof on Ty, with any known
  353. /// factors factored out. If Folded is false, return null if no factoring was
  354. /// possible, to avoid endlessly bouncing an unfoldable expression back into the
  355. /// top-level folder.
  356. static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy, bool Folded) {
  357. // The alignment of an array is equal to the alignment of the
  358. // array element. Note that this is not always true for vectors.
  359. if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  360. Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
  361. C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
  362. DestTy,
  363. false),
  364. C, DestTy);
  365. return C;
  366. }
  367. if (StructType *STy = dyn_cast<StructType>(Ty)) {
  368. // Packed structs always have an alignment of 1.
  369. if (STy->isPacked())
  370. return ConstantInt::get(DestTy, 1);
  371. // Otherwise, struct alignment is the maximum alignment of any member.
  372. // Without target data, we can't compare much, but we can check to see
  373. // if all the members have the same alignment.
  374. unsigned NumElems = STy->getNumElements();
  375. // An empty struct has minimal alignment.
  376. if (NumElems == 0)
  377. return ConstantInt::get(DestTy, 1);
  378. // Check for a struct with all members having the same alignment.
  379. Constant *MemberAlign =
  380. getFoldedAlignOf(STy->getElementType(0), DestTy, true);
  381. bool AllSame = true;
  382. for (unsigned i = 1; i != NumElems; ++i)
  383. if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
  384. AllSame = false;
  385. break;
  386. }
  387. if (AllSame)
  388. return MemberAlign;
  389. }
  390. // Pointer alignment doesn't depend on the pointee type, so canonicalize them
  391. // to an arbitrary pointee.
  392. if (PointerType *PTy = dyn_cast<PointerType>(Ty))
  393. if (!PTy->getElementType()->isIntegerTy(1))
  394. return
  395. getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
  396. 1),
  397. PTy->getAddressSpace()),
  398. DestTy, true);
  399. // If there's no interesting folding happening, bail so that we don't create
  400. // a constant that looks like it needs folding but really doesn't.
  401. if (!Folded)
  402. return nullptr;
  403. // Base case: Get a regular alignof expression.
  404. Constant *C = ConstantExpr::getAlignOf(Ty);
  405. C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
  406. DestTy, false),
  407. C, DestTy);
  408. return C;
  409. }
  410. /// Return a ConstantExpr with type DestTy for offsetof on Ty and FieldNo, with
  411. /// any known factors factored out. If Folded is false, return null if no
  412. /// factoring was possible, to avoid endlessly bouncing an unfoldable expression
  413. /// back into the top-level folder.
  414. static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo, Type *DestTy,
  415. bool Folded) {
  416. if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  417. Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
  418. DestTy, false),
  419. FieldNo, DestTy);
  420. Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
  421. return ConstantExpr::getNUWMul(E, N);
  422. }
  423. if (StructType *STy = dyn_cast<StructType>(Ty))
  424. if (!STy->isPacked()) {
  425. unsigned NumElems = STy->getNumElements();
  426. // An empty struct has no members.
  427. if (NumElems == 0)
  428. return nullptr;
  429. // Check for a struct with all members having the same size.
  430. Constant *MemberSize =
  431. getFoldedSizeOf(STy->getElementType(0), DestTy, true);
  432. bool AllSame = true;
  433. for (unsigned i = 1; i != NumElems; ++i)
  434. if (MemberSize !=
  435. getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
  436. AllSame = false;
  437. break;
  438. }
  439. if (AllSame) {
  440. Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
  441. false,
  442. DestTy,
  443. false),
  444. FieldNo, DestTy);
  445. return ConstantExpr::getNUWMul(MemberSize, N);
  446. }
  447. }
  448. // If there's no interesting folding happening, bail so that we don't create
  449. // a constant that looks like it needs folding but really doesn't.
  450. if (!Folded)
  451. return nullptr;
  452. // Base case: Get a regular offsetof expression.
  453. Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
  454. C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
  455. DestTy, false),
  456. C, DestTy);
  457. return C;
  458. }
  459. Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
  460. Type *DestTy) {
  461. if (isa<UndefValue>(V)) {
  462. // zext(undef) = 0, because the top bits will be zero.
  463. // sext(undef) = 0, because the top bits will all be the same.
  464. // [us]itofp(undef) = 0, because the result value is bounded.
  465. if (opc == Instruction::ZExt || opc == Instruction::SExt ||
  466. opc == Instruction::UIToFP || opc == Instruction::SIToFP)
  467. return Constant::getNullValue(DestTy);
  468. return UndefValue::get(DestTy);
  469. }
  470. if (V->isNullValue() && !DestTy->isX86_MMXTy() &&
  471. opc != Instruction::AddrSpaceCast)
  472. return Constant::getNullValue(DestTy);
  473. // If the cast operand is a constant expression, there's a few things we can
  474. // do to try to simplify it.
  475. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
  476. if (CE->isCast()) {
  477. // Try hard to fold cast of cast because they are often eliminable.
  478. if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
  479. return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
  480. } else if (CE->getOpcode() == Instruction::GetElementPtr &&
  481. // Do not fold addrspacecast (gep 0, .., 0). It might make the
  482. // addrspacecast uncanonicalized.
  483. opc != Instruction::AddrSpaceCast &&
  484. // Do not fold bitcast (gep) with inrange index, as this loses
  485. // information.
  486. !cast<GEPOperator>(CE)->getInRangeIndex().hasValue() &&
  487. // Do not fold if the gep type is a vector, as bitcasting
  488. // operand 0 of a vector gep will result in a bitcast between
  489. // different sizes.
  490. !CE->getType()->isVectorTy()) {
  491. // If all of the indexes in the GEP are null values, there is no pointer
  492. // adjustment going on. We might as well cast the source pointer.
  493. bool isAllNull = true;
  494. for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
  495. if (!CE->getOperand(i)->isNullValue()) {
  496. isAllNull = false;
  497. break;
  498. }
  499. if (isAllNull)
  500. // This is casting one pointer type to another, always BitCast
  501. return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
  502. }
  503. }
  504. // If the cast operand is a constant vector, perform the cast by
  505. // operating on each element. In the cast of bitcasts, the element
  506. // count may be mismatched; don't attempt to handle that here.
  507. if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
  508. DestTy->isVectorTy() &&
  509. DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) {
  510. SmallVector<Constant*, 16> res;
  511. VectorType *DestVecTy = cast<VectorType>(DestTy);
  512. Type *DstEltTy = DestVecTy->getElementType();
  513. Type *Ty = IntegerType::get(V->getContext(), 32);
  514. for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i) {
  515. Constant *C =
  516. ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
  517. res.push_back(ConstantExpr::getCast(opc, C, DstEltTy));
  518. }
  519. return ConstantVector::get(res);
  520. }
  521. // We actually have to do a cast now. Perform the cast according to the
  522. // opcode specified.
  523. switch (opc) {
  524. default:
  525. llvm_unreachable("Failed to cast constant expression");
  526. case Instruction::FPTrunc:
  527. case Instruction::FPExt:
  528. if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
  529. bool ignored;
  530. APFloat Val = FPC->getValueAPF();
  531. Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf() :
  532. DestTy->isFloatTy() ? APFloat::IEEEsingle() :
  533. DestTy->isDoubleTy() ? APFloat::IEEEdouble() :
  534. DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended() :
  535. DestTy->isFP128Ty() ? APFloat::IEEEquad() :
  536. DestTy->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble() :
  537. APFloat::Bogus(),
  538. APFloat::rmNearestTiesToEven, &ignored);
  539. return ConstantFP::get(V->getContext(), Val);
  540. }
  541. return nullptr; // Can't fold.
  542. case Instruction::FPToUI:
  543. case Instruction::FPToSI:
  544. if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
  545. const APFloat &V = FPC->getValueAPF();
  546. bool ignored;
  547. uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
  548. APSInt IntVal(DestBitWidth, opc == Instruction::FPToUI);
  549. if (APFloat::opInvalidOp ==
  550. V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored)) {
  551. // Undefined behavior invoked - the destination type can't represent
  552. // the input constant.
  553. return UndefValue::get(DestTy);
  554. }
  555. return ConstantInt::get(FPC->getContext(), IntVal);
  556. }
  557. return nullptr; // Can't fold.
  558. case Instruction::IntToPtr: //always treated as unsigned
  559. if (V->isNullValue()) // Is it an integral null value?
  560. return ConstantPointerNull::get(cast<PointerType>(DestTy));
  561. return nullptr; // Other pointer types cannot be casted
  562. case Instruction::PtrToInt: // always treated as unsigned
  563. // Is it a null pointer value?
  564. if (V->isNullValue())
  565. return ConstantInt::get(DestTy, 0);
  566. // If this is a sizeof-like expression, pull out multiplications by
  567. // known factors to expose them to subsequent folding. If it's an
  568. // alignof-like expression, factor out known factors.
  569. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
  570. if (CE->getOpcode() == Instruction::GetElementPtr &&
  571. CE->getOperand(0)->isNullValue()) {
  572. // FIXME: Looks like getFoldedSizeOf(), getFoldedOffsetOf() and
  573. // getFoldedAlignOf() don't handle the case when DestTy is a vector of
  574. // pointers yet. We end up in asserts in CastInst::getCastOpcode (see
  575. // test/Analysis/ConstantFolding/cast-vector.ll). I've only seen this
  576. // happen in one "real" C-code test case, so it does not seem to be an
  577. // important optimization to handle vectors here. For now, simply bail
  578. // out.
  579. if (DestTy->isVectorTy())
  580. return nullptr;
  581. GEPOperator *GEPO = cast<GEPOperator>(CE);
  582. Type *Ty = GEPO->getSourceElementType();
  583. if (CE->getNumOperands() == 2) {
  584. // Handle a sizeof-like expression.
  585. Constant *Idx = CE->getOperand(1);
  586. bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
  587. if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
  588. Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
  589. DestTy, false),
  590. Idx, DestTy);
  591. return ConstantExpr::getMul(C, Idx);
  592. }
  593. } else if (CE->getNumOperands() == 3 &&
  594. CE->getOperand(1)->isNullValue()) {
  595. // Handle an alignof-like expression.
  596. if (StructType *STy = dyn_cast<StructType>(Ty))
  597. if (!STy->isPacked()) {
  598. ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
  599. if (CI->isOne() &&
  600. STy->getNumElements() == 2 &&
  601. STy->getElementType(0)->isIntegerTy(1)) {
  602. return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
  603. }
  604. }
  605. // Handle an offsetof-like expression.
  606. if (Ty->isStructTy() || Ty->isArrayTy()) {
  607. if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
  608. DestTy, false))
  609. return C;
  610. }
  611. }
  612. }
  613. // Other pointer types cannot be casted
  614. return nullptr;
  615. case Instruction::UIToFP:
  616. case Instruction::SIToFP:
  617. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  618. const APInt &api = CI->getValue();
  619. APFloat apf(DestTy->getFltSemantics(),
  620. APInt::getNullValue(DestTy->getPrimitiveSizeInBits()));
  621. apf.convertFromAPInt(api, opc==Instruction::SIToFP,
  622. APFloat::rmNearestTiesToEven);
  623. return ConstantFP::get(V->getContext(), apf);
  624. }
  625. return nullptr;
  626. case Instruction::ZExt:
  627. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  628. uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
  629. return ConstantInt::get(V->getContext(),
  630. CI->getValue().zext(BitWidth));
  631. }
  632. return nullptr;
  633. case Instruction::SExt:
  634. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  635. uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
  636. return ConstantInt::get(V->getContext(),
  637. CI->getValue().sext(BitWidth));
  638. }
  639. return nullptr;
  640. case Instruction::Trunc: {
  641. if (V->getType()->isVectorTy())
  642. return nullptr;
  643. uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
  644. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  645. return ConstantInt::get(V->getContext(),
  646. CI->getValue().trunc(DestBitWidth));
  647. }
  648. // The input must be a constantexpr. See if we can simplify this based on
  649. // the bytes we are demanding. Only do this if the source and dest are an
  650. // even multiple of a byte.
  651. if ((DestBitWidth & 7) == 0 &&
  652. (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
  653. if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
  654. return Res;
  655. return nullptr;
  656. }
  657. case Instruction::BitCast:
  658. return FoldBitCast(V, DestTy);
  659. case Instruction::AddrSpaceCast:
  660. return nullptr;
  661. }
  662. }
  663. Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
  664. Constant *V1, Constant *V2) {
  665. // Check for i1 and vector true/false conditions.
  666. if (Cond->isNullValue()) return V2;
  667. if (Cond->isAllOnesValue()) return V1;
  668. // If the condition is a vector constant, fold the result elementwise.
  669. if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
  670. SmallVector<Constant*, 16> Result;
  671. Type *Ty = IntegerType::get(CondV->getContext(), 32);
  672. for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
  673. Constant *V;
  674. Constant *V1Element = ConstantExpr::getExtractElement(V1,
  675. ConstantInt::get(Ty, i));
  676. Constant *V2Element = ConstantExpr::getExtractElement(V2,
  677. ConstantInt::get(Ty, i));
  678. Constant *Cond = dyn_cast<Constant>(CondV->getOperand(i));
  679. if (V1Element == V2Element) {
  680. V = V1Element;
  681. } else if (isa<UndefValue>(Cond)) {
  682. V = isa<UndefValue>(V1Element) ? V1Element : V2Element;
  683. } else {
  684. if (!isa<ConstantInt>(Cond)) break;
  685. V = Cond->isNullValue() ? V2Element : V1Element;
  686. }
  687. Result.push_back(V);
  688. }
  689. // If we were able to build the vector, return it.
  690. if (Result.size() == V1->getType()->getVectorNumElements())
  691. return ConstantVector::get(Result);
  692. }
  693. if (isa<UndefValue>(Cond)) {
  694. if (isa<UndefValue>(V1)) return V1;
  695. return V2;
  696. }
  697. if (isa<UndefValue>(V1)) return V2;
  698. if (isa<UndefValue>(V2)) return V1;
  699. if (V1 == V2) return V1;
  700. if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
  701. if (TrueVal->getOpcode() == Instruction::Select)
  702. if (TrueVal->getOperand(0) == Cond)
  703. return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
  704. }
  705. if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
  706. if (FalseVal->getOpcode() == Instruction::Select)
  707. if (FalseVal->getOperand(0) == Cond)
  708. return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
  709. }
  710. return nullptr;
  711. }
  712. Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
  713. Constant *Idx) {
  714. if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
  715. return UndefValue::get(Val->getType()->getVectorElementType());
  716. if (Val->isNullValue()) // ee(zero, x) -> zero
  717. return Constant::getNullValue(Val->getType()->getVectorElementType());
  718. // ee({w,x,y,z}, undef) -> undef
  719. if (isa<UndefValue>(Idx))
  720. return UndefValue::get(Val->getType()->getVectorElementType());
  721. if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
  722. // ee({w,x,y,z}, wrong_value) -> undef
  723. if (CIdx->uge(Val->getType()->getVectorNumElements()))
  724. return UndefValue::get(Val->getType()->getVectorElementType());
  725. return Val->getAggregateElement(CIdx->getZExtValue());
  726. }
  727. return nullptr;
  728. }
  729. Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
  730. Constant *Elt,
  731. Constant *Idx) {
  732. if (isa<UndefValue>(Idx))
  733. return UndefValue::get(Val->getType());
  734. ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
  735. if (!CIdx) return nullptr;
  736. unsigned NumElts = Val->getType()->getVectorNumElements();
  737. if (CIdx->uge(NumElts))
  738. return UndefValue::get(Val->getType());
  739. SmallVector<Constant*, 16> Result;
  740. Result.reserve(NumElts);
  741. auto *Ty = Type::getInt32Ty(Val->getContext());
  742. uint64_t IdxVal = CIdx->getZExtValue();
  743. for (unsigned i = 0; i != NumElts; ++i) {
  744. if (i == IdxVal) {
  745. Result.push_back(Elt);
  746. continue;
  747. }
  748. Constant *C = ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
  749. Result.push_back(C);
  750. }
  751. return ConstantVector::get(Result);
  752. }
  753. Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
  754. Constant *V2,
  755. Constant *Mask) {
  756. unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
  757. Type *EltTy = V1->getType()->getVectorElementType();
  758. // Undefined shuffle mask -> undefined value.
  759. if (isa<UndefValue>(Mask))
  760. return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
  761. // Don't break the bitcode reader hack.
  762. if (isa<ConstantExpr>(Mask)) return nullptr;
  763. unsigned SrcNumElts = V1->getType()->getVectorNumElements();
  764. // Loop over the shuffle mask, evaluating each element.
  765. SmallVector<Constant*, 32> Result;
  766. for (unsigned i = 0; i != MaskNumElts; ++i) {
  767. int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
  768. if (Elt == -1) {
  769. Result.push_back(UndefValue::get(EltTy));
  770. continue;
  771. }
  772. Constant *InElt;
  773. if (unsigned(Elt) >= SrcNumElts*2)
  774. InElt = UndefValue::get(EltTy);
  775. else if (unsigned(Elt) >= SrcNumElts) {
  776. Type *Ty = IntegerType::get(V2->getContext(), 32);
  777. InElt =
  778. ConstantExpr::getExtractElement(V2,
  779. ConstantInt::get(Ty, Elt - SrcNumElts));
  780. } else {
  781. Type *Ty = IntegerType::get(V1->getContext(), 32);
  782. InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
  783. }
  784. Result.push_back(InElt);
  785. }
  786. return ConstantVector::get(Result);
  787. }
  788. Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
  789. ArrayRef<unsigned> Idxs) {
  790. // Base case: no indices, so return the entire value.
  791. if (Idxs.empty())
  792. return Agg;
  793. if (Constant *C = Agg->getAggregateElement(Idxs[0]))
  794. return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
  795. return nullptr;
  796. }
  797. Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
  798. Constant *Val,
  799. ArrayRef<unsigned> Idxs) {
  800. // Base case: no indices, so replace the entire value.
  801. if (Idxs.empty())
  802. return Val;
  803. unsigned NumElts;
  804. if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
  805. NumElts = ST->getNumElements();
  806. else
  807. NumElts = cast<SequentialType>(Agg->getType())->getNumElements();
  808. SmallVector<Constant*, 32> Result;
  809. for (unsigned i = 0; i != NumElts; ++i) {
  810. Constant *C = Agg->getAggregateElement(i);
  811. if (!C) return nullptr;
  812. if (Idxs[0] == i)
  813. C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
  814. Result.push_back(C);
  815. }
  816. if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
  817. return ConstantStruct::get(ST, Result);
  818. if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
  819. return ConstantArray::get(AT, Result);
  820. return ConstantVector::get(Result);
  821. }
  822. Constant *llvm::ConstantFoldUnaryInstruction(unsigned Opcode, Constant *C) {
  823. assert(Instruction::isUnaryOp(Opcode) && "Non-unary instruction detected");
  824. // Handle scalar UndefValue. Vectors are always evaluated per element.
  825. bool HasScalarUndef = !C->getType()->isVectorTy() && isa<UndefValue>(C);
  826. if (HasScalarUndef) {
  827. switch (static_cast<Instruction::UnaryOps>(Opcode)) {
  828. case Instruction::FNeg:
  829. return C; // -undef -> undef
  830. case Instruction::UnaryOpsEnd:
  831. llvm_unreachable("Invalid UnaryOp");
  832. }
  833. }
  834. // Constant should not be UndefValue, unless these are vector constants.
  835. assert(!HasScalarUndef && "Unexpected UndefValue");
  836. // We only have FP UnaryOps right now.
  837. assert(!isa<ConstantInt>(C) && "Unexpected Integer UnaryOp");
  838. if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  839. const APFloat &CV = CFP->getValueAPF();
  840. switch (Opcode) {
  841. default:
  842. break;
  843. case Instruction::FNeg:
  844. return ConstantFP::get(C->getContext(), neg(CV));
  845. }
  846. } else if (VectorType *VTy = dyn_cast<VectorType>(C->getType())) {
  847. // Fold each element and create a vector constant from those constants.
  848. SmallVector<Constant*, 16> Result;
  849. Type *Ty = IntegerType::get(VTy->getContext(), 32);
  850. for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
  851. Constant *ExtractIdx = ConstantInt::get(Ty, i);
  852. Constant *Elt = ConstantExpr::getExtractElement(C, ExtractIdx);
  853. Result.push_back(ConstantExpr::get(Opcode, Elt));
  854. }
  855. return ConstantVector::get(Result);
  856. }
  857. // We don't know how to fold this.
  858. return nullptr;
  859. }
  860. Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode, Constant *C1,
  861. Constant *C2) {
  862. assert(Instruction::isBinaryOp(Opcode) && "Non-binary instruction detected");
  863. // Handle scalar UndefValue. Vectors are always evaluated per element.
  864. bool HasScalarUndef = !C1->getType()->isVectorTy() &&
  865. (isa<UndefValue>(C1) || isa<UndefValue>(C2));
  866. if (HasScalarUndef) {
  867. switch (static_cast<Instruction::BinaryOps>(Opcode)) {
  868. case Instruction::Xor:
  869. if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
  870. // Handle undef ^ undef -> 0 special case. This is a common
  871. // idiom (misuse).
  872. return Constant::getNullValue(C1->getType());
  873. LLVM_FALLTHROUGH;
  874. case Instruction::Add:
  875. case Instruction::Sub:
  876. return UndefValue::get(C1->getType());
  877. case Instruction::And:
  878. if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
  879. return C1;
  880. return Constant::getNullValue(C1->getType()); // undef & X -> 0
  881. case Instruction::Mul: {
  882. // undef * undef -> undef
  883. if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
  884. return C1;
  885. const APInt *CV;
  886. // X * undef -> undef if X is odd
  887. if (match(C1, m_APInt(CV)) || match(C2, m_APInt(CV)))
  888. if ((*CV)[0])
  889. return UndefValue::get(C1->getType());
  890. // X * undef -> 0 otherwise
  891. return Constant::getNullValue(C1->getType());
  892. }
  893. case Instruction::SDiv:
  894. case Instruction::UDiv:
  895. // X / undef -> undef
  896. if (isa<UndefValue>(C2))
  897. return C2;
  898. // undef / 0 -> undef
  899. // undef / 1 -> undef
  900. if (match(C2, m_Zero()) || match(C2, m_One()))
  901. return C1;
  902. // undef / X -> 0 otherwise
  903. return Constant::getNullValue(C1->getType());
  904. case Instruction::URem:
  905. case Instruction::SRem:
  906. // X % undef -> undef
  907. if (match(C2, m_Undef()))
  908. return C2;
  909. // undef % 0 -> undef
  910. if (match(C2, m_Zero()))
  911. return C1;
  912. // undef % X -> 0 otherwise
  913. return Constant::getNullValue(C1->getType());
  914. case Instruction::Or: // X | undef -> -1
  915. if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
  916. return C1;
  917. return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
  918. case Instruction::LShr:
  919. // X >>l undef -> undef
  920. if (isa<UndefValue>(C2))
  921. return C2;
  922. // undef >>l 0 -> undef
  923. if (match(C2, m_Zero()))
  924. return C1;
  925. // undef >>l X -> 0
  926. return Constant::getNullValue(C1->getType());
  927. case Instruction::AShr:
  928. // X >>a undef -> undef
  929. if (isa<UndefValue>(C2))
  930. return C2;
  931. // undef >>a 0 -> undef
  932. if (match(C2, m_Zero()))
  933. return C1;
  934. // TODO: undef >>a X -> undef if the shift is exact
  935. // undef >>a X -> 0
  936. return Constant::getNullValue(C1->getType());
  937. case Instruction::Shl:
  938. // X << undef -> undef
  939. if (isa<UndefValue>(C2))
  940. return C2;
  941. // undef << 0 -> undef
  942. if (match(C2, m_Zero()))
  943. return C1;
  944. // undef << X -> 0
  945. return Constant::getNullValue(C1->getType());
  946. case Instruction::FAdd:
  947. case Instruction::FSub:
  948. case Instruction::FMul:
  949. case Instruction::FDiv:
  950. case Instruction::FRem:
  951. // [any flop] undef, undef -> undef
  952. if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
  953. return C1;
  954. // [any flop] C, undef -> NaN
  955. // [any flop] undef, C -> NaN
  956. // We could potentially specialize NaN/Inf constants vs. 'normal'
  957. // constants (possibly differently depending on opcode and operand). This
  958. // would allow returning undef sometimes. But it is always safe to fold to
  959. // NaN because we can choose the undef operand as NaN, and any FP opcode
  960. // with a NaN operand will propagate NaN.
  961. return ConstantFP::getNaN(C1->getType());
  962. case Instruction::BinaryOpsEnd:
  963. llvm_unreachable("Invalid BinaryOp");
  964. }
  965. }
  966. // Neither constant should be UndefValue, unless these are vector constants.
  967. assert(!HasScalarUndef && "Unexpected UndefValue");
  968. // Handle simplifications when the RHS is a constant int.
  969. if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
  970. switch (Opcode) {
  971. case Instruction::Add:
  972. if (CI2->isZero()) return C1; // X + 0 == X
  973. break;
  974. case Instruction::Sub:
  975. if (CI2->isZero()) return C1; // X - 0 == X
  976. break;
  977. case Instruction::Mul:
  978. if (CI2->isZero()) return C2; // X * 0 == 0
  979. if (CI2->isOne())
  980. return C1; // X * 1 == X
  981. break;
  982. case Instruction::UDiv:
  983. case Instruction::SDiv:
  984. if (CI2->isOne())
  985. return C1; // X / 1 == X
  986. if (CI2->isZero())
  987. return UndefValue::get(CI2->getType()); // X / 0 == undef
  988. break;
  989. case Instruction::URem:
  990. case Instruction::SRem:
  991. if (CI2->isOne())
  992. return Constant::getNullValue(CI2->getType()); // X % 1 == 0
  993. if (CI2->isZero())
  994. return UndefValue::get(CI2->getType()); // X % 0 == undef
  995. break;
  996. case Instruction::And:
  997. if (CI2->isZero()) return C2; // X & 0 == 0
  998. if (CI2->isMinusOne())
  999. return C1; // X & -1 == X
  1000. if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
  1001. // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
  1002. if (CE1->getOpcode() == Instruction::ZExt) {
  1003. unsigned DstWidth = CI2->getType()->getBitWidth();
  1004. unsigned SrcWidth =
  1005. CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
  1006. APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
  1007. if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
  1008. return C1;
  1009. }
  1010. // If and'ing the address of a global with a constant, fold it.
  1011. if (CE1->getOpcode() == Instruction::PtrToInt &&
  1012. isa<GlobalValue>(CE1->getOperand(0))) {
  1013. GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
  1014. unsigned GVAlign;
  1015. if (Module *TheModule = GV->getParent()) {
  1016. GVAlign = GV->getPointerAlignment(TheModule->getDataLayout());
  1017. // If the function alignment is not specified then assume that it
  1018. // is 4.
  1019. // This is dangerous; on x86, the alignment of the pointer
  1020. // corresponds to the alignment of the function, but might be less
  1021. // than 4 if it isn't explicitly specified.
  1022. // However, a fix for this behaviour was reverted because it
  1023. // increased code size (see https://reviews.llvm.org/D55115)
  1024. // FIXME: This code should be deleted once existing targets have
  1025. // appropriate defaults
  1026. if (GVAlign == 0U && isa<Function>(GV))
  1027. GVAlign = 4U;
  1028. } else if (isa<Function>(GV)) {
  1029. // Without a datalayout we have to assume the worst case: that the
  1030. // function pointer isn't aligned at all.
  1031. GVAlign = 0U;
  1032. } else {
  1033. GVAlign = GV->getAlignment();
  1034. }
  1035. if (GVAlign > 1) {
  1036. unsigned DstWidth = CI2->getType()->getBitWidth();
  1037. unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
  1038. APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
  1039. // If checking bits we know are clear, return zero.
  1040. if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
  1041. return Constant::getNullValue(CI2->getType());
  1042. }
  1043. }
  1044. }
  1045. break;
  1046. case Instruction::Or:
  1047. if (CI2->isZero()) return C1; // X | 0 == X
  1048. if (CI2->isMinusOne())
  1049. return C2; // X | -1 == -1
  1050. break;
  1051. case Instruction::Xor:
  1052. if (CI2->isZero()) return C1; // X ^ 0 == X
  1053. if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
  1054. switch (CE1->getOpcode()) {
  1055. default: break;
  1056. case Instruction::ICmp:
  1057. case Instruction::FCmp:
  1058. // cmp pred ^ true -> cmp !pred
  1059. assert(CI2->isOne());
  1060. CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
  1061. pred = CmpInst::getInversePredicate(pred);
  1062. return ConstantExpr::getCompare(pred, CE1->getOperand(0),
  1063. CE1->getOperand(1));
  1064. }
  1065. }
  1066. break;
  1067. case Instruction::AShr:
  1068. // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
  1069. if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
  1070. if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
  1071. return ConstantExpr::getLShr(C1, C2);
  1072. break;
  1073. }
  1074. } else if (isa<ConstantInt>(C1)) {
  1075. // If C1 is a ConstantInt and C2 is not, swap the operands.
  1076. if (Instruction::isCommutative(Opcode))
  1077. return ConstantExpr::get(Opcode, C2, C1);
  1078. }
  1079. if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
  1080. if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
  1081. const APInt &C1V = CI1->getValue();
  1082. const APInt &C2V = CI2->getValue();
  1083. switch (Opcode) {
  1084. default:
  1085. break;
  1086. case Instruction::Add:
  1087. return ConstantInt::get(CI1->getContext(), C1V + C2V);
  1088. case Instruction::Sub:
  1089. return ConstantInt::get(CI1->getContext(), C1V - C2V);
  1090. case Instruction::Mul:
  1091. return ConstantInt::get(CI1->getContext(), C1V * C2V);
  1092. case Instruction::UDiv:
  1093. assert(!CI2->isZero() && "Div by zero handled above");
  1094. return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
  1095. case Instruction::SDiv:
  1096. assert(!CI2->isZero() && "Div by zero handled above");
  1097. if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
  1098. return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
  1099. return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
  1100. case Instruction::URem:
  1101. assert(!CI2->isZero() && "Div by zero handled above");
  1102. return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
  1103. case Instruction::SRem:
  1104. assert(!CI2->isZero() && "Div by zero handled above");
  1105. if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
  1106. return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
  1107. return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
  1108. case Instruction::And:
  1109. return ConstantInt::get(CI1->getContext(), C1V & C2V);
  1110. case Instruction::Or:
  1111. return ConstantInt::get(CI1->getContext(), C1V | C2V);
  1112. case Instruction::Xor:
  1113. return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
  1114. case Instruction::Shl:
  1115. if (C2V.ult(C1V.getBitWidth()))
  1116. return ConstantInt::get(CI1->getContext(), C1V.shl(C2V));
  1117. return UndefValue::get(C1->getType()); // too big shift is undef
  1118. case Instruction::LShr:
  1119. if (C2V.ult(C1V.getBitWidth()))
  1120. return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V));
  1121. return UndefValue::get(C1->getType()); // too big shift is undef
  1122. case Instruction::AShr:
  1123. if (C2V.ult(C1V.getBitWidth()))
  1124. return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V));
  1125. return UndefValue::get(C1->getType()); // too big shift is undef
  1126. }
  1127. }
  1128. switch (Opcode) {
  1129. case Instruction::SDiv:
  1130. case Instruction::UDiv:
  1131. case Instruction::URem:
  1132. case Instruction::SRem:
  1133. case Instruction::LShr:
  1134. case Instruction::AShr:
  1135. case Instruction::Shl:
  1136. if (CI1->isZero()) return C1;
  1137. break;
  1138. default:
  1139. break;
  1140. }
  1141. } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
  1142. if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
  1143. const APFloat &C1V = CFP1->getValueAPF();
  1144. const APFloat &C2V = CFP2->getValueAPF();
  1145. APFloat C3V = C1V; // copy for modification
  1146. switch (Opcode) {
  1147. default:
  1148. break;
  1149. case Instruction::FAdd:
  1150. (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
  1151. return ConstantFP::get(C1->getContext(), C3V);
  1152. case Instruction::FSub:
  1153. (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
  1154. return ConstantFP::get(C1->getContext(), C3V);
  1155. case Instruction::FMul:
  1156. (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
  1157. return ConstantFP::get(C1->getContext(), C3V);
  1158. case Instruction::FDiv:
  1159. (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
  1160. return ConstantFP::get(C1->getContext(), C3V);
  1161. case Instruction::FRem:
  1162. (void)C3V.mod(C2V);
  1163. return ConstantFP::get(C1->getContext(), C3V);
  1164. }
  1165. }
  1166. } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
  1167. // Fold each element and create a vector constant from those constants.
  1168. SmallVector<Constant*, 16> Result;
  1169. Type *Ty = IntegerType::get(VTy->getContext(), 32);
  1170. for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
  1171. Constant *ExtractIdx = ConstantInt::get(Ty, i);
  1172. Constant *LHS = ConstantExpr::getExtractElement(C1, ExtractIdx);
  1173. Constant *RHS = ConstantExpr::getExtractElement(C2, ExtractIdx);
  1174. // If any element of a divisor vector is zero, the whole op is undef.
  1175. if (Instruction::isIntDivRem(Opcode) && RHS->isNullValue())
  1176. return UndefValue::get(VTy);
  1177. Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
  1178. }
  1179. return ConstantVector::get(Result);
  1180. }
  1181. if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
  1182. // There are many possible foldings we could do here. We should probably
  1183. // at least fold add of a pointer with an integer into the appropriate
  1184. // getelementptr. This will improve alias analysis a bit.
  1185. // Given ((a + b) + c), if (b + c) folds to something interesting, return
  1186. // (a + (b + c)).
  1187. if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
  1188. Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
  1189. if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
  1190. return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
  1191. }
  1192. } else if (isa<ConstantExpr>(C2)) {
  1193. // If C2 is a constant expr and C1 isn't, flop them around and fold the
  1194. // other way if possible.
  1195. if (Instruction::isCommutative(Opcode))
  1196. return ConstantFoldBinaryInstruction(Opcode, C2, C1);
  1197. }
  1198. // i1 can be simplified in many cases.
  1199. if (C1->getType()->isIntegerTy(1)) {
  1200. switch (Opcode) {
  1201. case Instruction::Add:
  1202. case Instruction::Sub:
  1203. return ConstantExpr::getXor(C1, C2);
  1204. case Instruction::Mul:
  1205. return ConstantExpr::getAnd(C1, C2);
  1206. case Instruction::Shl:
  1207. case Instruction::LShr:
  1208. case Instruction::AShr:
  1209. // We can assume that C2 == 0. If it were one the result would be
  1210. // undefined because the shift value is as large as the bitwidth.
  1211. return C1;
  1212. case Instruction::SDiv:
  1213. case Instruction::UDiv:
  1214. // We can assume that C2 == 1. If it were zero the result would be
  1215. // undefined through division by zero.
  1216. return C1;
  1217. case Instruction::URem:
  1218. case Instruction::SRem:
  1219. // We can assume that C2 == 1. If it were zero the result would be
  1220. // undefined through division by zero.
  1221. return ConstantInt::getFalse(C1->getContext());
  1222. default:
  1223. break;
  1224. }
  1225. }
  1226. // We don't know how to fold this.
  1227. return nullptr;
  1228. }
  1229. /// This type is zero-sized if it's an array or structure of zero-sized types.
  1230. /// The only leaf zero-sized type is an empty structure.
  1231. static bool isMaybeZeroSizedType(Type *Ty) {
  1232. if (StructType *STy = dyn_cast<StructType>(Ty)) {
  1233. if (STy->isOpaque()) return true; // Can't say.
  1234. // If all of elements have zero size, this does too.
  1235. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
  1236. if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
  1237. return true;
  1238. } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  1239. return isMaybeZeroSizedType(ATy->getElementType());
  1240. }
  1241. return false;
  1242. }
  1243. /// Compare the two constants as though they were getelementptr indices.
  1244. /// This allows coercion of the types to be the same thing.
  1245. ///
  1246. /// If the two constants are the "same" (after coercion), return 0. If the
  1247. /// first is less than the second, return -1, if the second is less than the
  1248. /// first, return 1. If the constants are not integral, return -2.
  1249. ///
  1250. static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
  1251. if (C1 == C2) return 0;
  1252. // Ok, we found a different index. If they are not ConstantInt, we can't do
  1253. // anything with them.
  1254. if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
  1255. return -2; // don't know!
  1256. // We cannot compare the indices if they don't fit in an int64_t.
  1257. if (cast<ConstantInt>(C1)->getValue().getActiveBits() > 64 ||
  1258. cast<ConstantInt>(C2)->getValue().getActiveBits() > 64)
  1259. return -2; // don't know!
  1260. // Ok, we have two differing integer indices. Sign extend them to be the same
  1261. // type.
  1262. int64_t C1Val = cast<ConstantInt>(C1)->getSExtValue();
  1263. int64_t C2Val = cast<ConstantInt>(C2)->getSExtValue();
  1264. if (C1Val == C2Val) return 0; // They are equal
  1265. // If the type being indexed over is really just a zero sized type, there is
  1266. // no pointer difference being made here.
  1267. if (isMaybeZeroSizedType(ElTy))
  1268. return -2; // dunno.
  1269. // If they are really different, now that they are the same type, then we
  1270. // found a difference!
  1271. if (C1Val < C2Val)
  1272. return -1;
  1273. else
  1274. return 1;
  1275. }
  1276. /// This function determines if there is anything we can decide about the two
  1277. /// constants provided. This doesn't need to handle simple things like
  1278. /// ConstantFP comparisons, but should instead handle ConstantExprs.
  1279. /// If we can determine that the two constants have a particular relation to
  1280. /// each other, we should return the corresponding FCmpInst predicate,
  1281. /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
  1282. /// ConstantFoldCompareInstruction.
  1283. ///
  1284. /// To simplify this code we canonicalize the relation so that the first
  1285. /// operand is always the most "complex" of the two. We consider ConstantFP
  1286. /// to be the simplest, and ConstantExprs to be the most complex.
  1287. static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
  1288. assert(V1->getType() == V2->getType() &&
  1289. "Cannot compare values of different types!");
  1290. // We do not know if a constant expression will evaluate to a number or NaN.
  1291. // Therefore, we can only say that the relation is unordered or equal.
  1292. if (V1 == V2) return FCmpInst::FCMP_UEQ;
  1293. if (!isa<ConstantExpr>(V1)) {
  1294. if (!isa<ConstantExpr>(V2)) {
  1295. // Simple case, use the standard constant folder.
  1296. ConstantInt *R = nullptr;
  1297. R = dyn_cast<ConstantInt>(
  1298. ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
  1299. if (R && !R->isZero())
  1300. return FCmpInst::FCMP_OEQ;
  1301. R = dyn_cast<ConstantInt>(
  1302. ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
  1303. if (R && !R->isZero())
  1304. return FCmpInst::FCMP_OLT;
  1305. R = dyn_cast<ConstantInt>(
  1306. ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
  1307. if (R && !R->isZero())
  1308. return FCmpInst::FCMP_OGT;
  1309. // Nothing more we can do
  1310. return FCmpInst::BAD_FCMP_PREDICATE;
  1311. }
  1312. // If the first operand is simple and second is ConstantExpr, swap operands.
  1313. FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
  1314. if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
  1315. return FCmpInst::getSwappedPredicate(SwappedRelation);
  1316. } else {
  1317. // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
  1318. // constantexpr or a simple constant.
  1319. ConstantExpr *CE1 = cast<ConstantExpr>(V1);
  1320. switch (CE1->getOpcode()) {
  1321. case Instruction::FPTrunc:
  1322. case Instruction::FPExt:
  1323. case Instruction::UIToFP:
  1324. case Instruction::SIToFP:
  1325. // We might be able to do something with these but we don't right now.
  1326. break;
  1327. default:
  1328. break;
  1329. }
  1330. }
  1331. // There are MANY other foldings that we could perform here. They will
  1332. // probably be added on demand, as they seem needed.
  1333. return FCmpInst::BAD_FCMP_PREDICATE;
  1334. }
  1335. static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1,
  1336. const GlobalValue *GV2) {
  1337. auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) {
  1338. if (GV->hasExternalWeakLinkage() || GV->hasWeakAnyLinkage())
  1339. return true;
  1340. if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
  1341. Type *Ty = GVar->getValueType();
  1342. // A global with opaque type might end up being zero sized.
  1343. if (!Ty->isSized())
  1344. return true;
  1345. // A global with an empty type might lie at the address of any other
  1346. // global.
  1347. if (Ty->isEmptyTy())
  1348. return true;
  1349. }
  1350. return false;
  1351. };
  1352. // Don't try to decide equality of aliases.
  1353. if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
  1354. if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))
  1355. return ICmpInst::ICMP_NE;
  1356. return ICmpInst::BAD_ICMP_PREDICATE;
  1357. }
  1358. /// This function determines if there is anything we can decide about the two
  1359. /// constants provided. This doesn't need to handle simple things like integer
  1360. /// comparisons, but should instead handle ConstantExprs and GlobalValues.
  1361. /// If we can determine that the two constants have a particular relation to
  1362. /// each other, we should return the corresponding ICmp predicate, otherwise
  1363. /// return ICmpInst::BAD_ICMP_PREDICATE.
  1364. ///
  1365. /// To simplify this code we canonicalize the relation so that the first
  1366. /// operand is always the most "complex" of the two. We consider simple
  1367. /// constants (like ConstantInt) to be the simplest, followed by
  1368. /// GlobalValues, followed by ConstantExpr's (the most complex).
  1369. ///
  1370. static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
  1371. bool isSigned) {
  1372. assert(V1->getType() == V2->getType() &&
  1373. "Cannot compare different types of values!");
  1374. if (V1 == V2) return ICmpInst::ICMP_EQ;
  1375. if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
  1376. !isa<BlockAddress>(V1)) {
  1377. if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
  1378. !isa<BlockAddress>(V2)) {
  1379. // We distilled this down to a simple case, use the standard constant
  1380. // folder.
  1381. ConstantInt *R = nullptr;
  1382. ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
  1383. R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
  1384. if (R && !R->isZero())
  1385. return pred;
  1386. pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
  1387. R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
  1388. if (R && !R->isZero())
  1389. return pred;
  1390. pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
  1391. R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
  1392. if (R && !R->isZero())
  1393. return pred;
  1394. // If we couldn't figure it out, bail.
  1395. return ICmpInst::BAD_ICMP_PREDICATE;
  1396. }
  1397. // If the first operand is simple, swap operands.
  1398. ICmpInst::Predicate SwappedRelation =
  1399. evaluateICmpRelation(V2, V1, isSigned);
  1400. if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
  1401. return ICmpInst::getSwappedPredicate(SwappedRelation);
  1402. } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
  1403. if (isa<ConstantExpr>(V2)) { // Swap as necessary.
  1404. ICmpInst::Predicate SwappedRelation =
  1405. evaluateICmpRelation(V2, V1, isSigned);
  1406. if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
  1407. return ICmpInst::getSwappedPredicate(SwappedRelation);
  1408. return ICmpInst::BAD_ICMP_PREDICATE;
  1409. }
  1410. // Now we know that the RHS is a GlobalValue, BlockAddress or simple
  1411. // constant (which, since the types must match, means that it's a
  1412. // ConstantPointerNull).
  1413. if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
  1414. return areGlobalsPotentiallyEqual(GV, GV2);
  1415. } else if (isa<BlockAddress>(V2)) {
  1416. return ICmpInst::ICMP_NE; // Globals never equal labels.
  1417. } else {
  1418. assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
  1419. // GlobalVals can never be null unless they have external weak linkage.
  1420. // We don't try to evaluate aliases here.
  1421. // NOTE: We should not be doing this constant folding if null pointer
  1422. // is considered valid for the function. But currently there is no way to
  1423. // query it from the Constant type.
  1424. if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV) &&
  1425. !NullPointerIsDefined(nullptr /* F */,
  1426. GV->getType()->getAddressSpace()))
  1427. return ICmpInst::ICMP_NE;
  1428. }
  1429. } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
  1430. if (isa<ConstantExpr>(V2)) { // Swap as necessary.
  1431. ICmpInst::Predicate SwappedRelation =
  1432. evaluateICmpRelation(V2, V1, isSigned);
  1433. if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
  1434. return ICmpInst::getSwappedPredicate(SwappedRelation);
  1435. return ICmpInst::BAD_ICMP_PREDICATE;
  1436. }
  1437. // Now we know that the RHS is a GlobalValue, BlockAddress or simple
  1438. // constant (which, since the types must match, means that it is a
  1439. // ConstantPointerNull).
  1440. if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
  1441. // Block address in another function can't equal this one, but block
  1442. // addresses in the current function might be the same if blocks are
  1443. // empty.
  1444. if (BA2->getFunction() != BA->getFunction())
  1445. return ICmpInst::ICMP_NE;
  1446. } else {
  1447. // Block addresses aren't null, don't equal the address of globals.
  1448. assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
  1449. "Canonicalization guarantee!");
  1450. return ICmpInst::ICMP_NE;
  1451. }
  1452. } else {
  1453. // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
  1454. // constantexpr, a global, block address, or a simple constant.
  1455. ConstantExpr *CE1 = cast<ConstantExpr>(V1);
  1456. Constant *CE1Op0 = CE1->getOperand(0);
  1457. switch (CE1->getOpcode()) {
  1458. case Instruction::Trunc:
  1459. case Instruction::FPTrunc:
  1460. case Instruction::FPExt:
  1461. case Instruction::FPToUI:
  1462. case Instruction::FPToSI:
  1463. break; // We can't evaluate floating point casts or truncations.
  1464. case Instruction::UIToFP:
  1465. case Instruction::SIToFP:
  1466. case Instruction::BitCast:
  1467. case Instruction::ZExt:
  1468. case Instruction::SExt:
  1469. // We can't evaluate floating point casts or truncations.
  1470. if (CE1Op0->getType()->isFPOrFPVectorTy())
  1471. break;
  1472. // If the cast is not actually changing bits, and the second operand is a
  1473. // null pointer, do the comparison with the pre-casted value.
  1474. if (V2->isNullValue() && CE1->getType()->isIntOrPtrTy()) {
  1475. if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
  1476. if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
  1477. return evaluateICmpRelation(CE1Op0,
  1478. Constant::getNullValue(CE1Op0->getType()),
  1479. isSigned);
  1480. }
  1481. break;
  1482. case Instruction::GetElementPtr: {
  1483. GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
  1484. // Ok, since this is a getelementptr, we know that the constant has a
  1485. // pointer type. Check the various cases.
  1486. if (isa<ConstantPointerNull>(V2)) {
  1487. // If we are comparing a GEP to a null pointer, check to see if the base
  1488. // of the GEP equals the null pointer.
  1489. if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
  1490. if (GV->hasExternalWeakLinkage())
  1491. // Weak linkage GVals could be zero or not. We're comparing that
  1492. // to null pointer so its greater-or-equal
  1493. return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
  1494. else
  1495. // If its not weak linkage, the GVal must have a non-zero address
  1496. // so the result is greater-than
  1497. return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
  1498. } else if (isa<ConstantPointerNull>(CE1Op0)) {
  1499. // If we are indexing from a null pointer, check to see if we have any
  1500. // non-zero indices.
  1501. for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
  1502. if (!CE1->getOperand(i)->isNullValue())
  1503. // Offsetting from null, must not be equal.
  1504. return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
  1505. // Only zero indexes from null, must still be zero.
  1506. return ICmpInst::ICMP_EQ;
  1507. }
  1508. // Otherwise, we can't really say if the first operand is null or not.
  1509. } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
  1510. if (isa<ConstantPointerNull>(CE1Op0)) {
  1511. if (GV2->hasExternalWeakLinkage())
  1512. // Weak linkage GVals could be zero or not. We're comparing it to
  1513. // a null pointer, so its less-or-equal
  1514. return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
  1515. else
  1516. // If its not weak linkage, the GVal must have a non-zero address
  1517. // so the result is less-than
  1518. return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
  1519. } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
  1520. if (GV == GV2) {
  1521. // If this is a getelementptr of the same global, then it must be
  1522. // different. Because the types must match, the getelementptr could
  1523. // only have at most one index, and because we fold getelementptr's
  1524. // with a single zero index, it must be nonzero.
  1525. assert(CE1->getNumOperands() == 2 &&
  1526. !CE1->getOperand(1)->isNullValue() &&
  1527. "Surprising getelementptr!");
  1528. return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
  1529. } else {
  1530. if (CE1GEP->hasAllZeroIndices())
  1531. return areGlobalsPotentiallyEqual(GV, GV2);
  1532. return ICmpInst::BAD_ICMP_PREDICATE;
  1533. }
  1534. }
  1535. } else {
  1536. ConstantExpr *CE2 = cast<ConstantExpr>(V2);
  1537. Constant *CE2Op0 = CE2->getOperand(0);
  1538. // There are MANY other foldings that we could perform here. They will
  1539. // probably be added on demand, as they seem needed.
  1540. switch (CE2->getOpcode()) {
  1541. default: break;
  1542. case Instruction::GetElementPtr:
  1543. // By far the most common case to handle is when the base pointers are
  1544. // obviously to the same global.
  1545. if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
  1546. // Don't know relative ordering, but check for inequality.
  1547. if (CE1Op0 != CE2Op0) {
  1548. GEPOperator *CE2GEP = cast<GEPOperator>(CE2);
  1549. if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
  1550. return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
  1551. cast<GlobalValue>(CE2Op0));
  1552. return ICmpInst::BAD_ICMP_PREDICATE;
  1553. }
  1554. // Ok, we know that both getelementptr instructions are based on the
  1555. // same global. From this, we can precisely determine the relative
  1556. // ordering of the resultant pointers.
  1557. unsigned i = 1;
  1558. // The logic below assumes that the result of the comparison
  1559. // can be determined by finding the first index that differs.
  1560. // This doesn't work if there is over-indexing in any
  1561. // subsequent indices, so check for that case first.
  1562. if (!CE1->isGEPWithNoNotionalOverIndexing() ||
  1563. !CE2->isGEPWithNoNotionalOverIndexing())
  1564. return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
  1565. // Compare all of the operands the GEP's have in common.
  1566. gep_type_iterator GTI = gep_type_begin(CE1);
  1567. for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
  1568. ++i, ++GTI)
  1569. switch (IdxCompare(CE1->getOperand(i),
  1570. CE2->getOperand(i), GTI.getIndexedType())) {
  1571. case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
  1572. case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
  1573. case -2: return ICmpInst::BAD_ICMP_PREDICATE;
  1574. }
  1575. // Ok, we ran out of things they have in common. If any leftovers
  1576. // are non-zero then we have a difference, otherwise we are equal.
  1577. for (; i < CE1->getNumOperands(); ++i)
  1578. if (!CE1->getOperand(i)->isNullValue()) {
  1579. if (isa<ConstantInt>(CE1->getOperand(i)))
  1580. return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
  1581. else
  1582. return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
  1583. }
  1584. for (; i < CE2->getNumOperands(); ++i)
  1585. if (!CE2->getOperand(i)->isNullValue()) {
  1586. if (isa<ConstantInt>(CE2->getOperand(i)))
  1587. return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
  1588. else
  1589. return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
  1590. }
  1591. return ICmpInst::ICMP_EQ;
  1592. }
  1593. }
  1594. }
  1595. break;
  1596. }
  1597. default:
  1598. break;
  1599. }
  1600. }
  1601. return ICmpInst::BAD_ICMP_PREDICATE;
  1602. }
  1603. Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
  1604. Constant *C1, Constant *C2) {
  1605. Type *ResultTy;
  1606. if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
  1607. ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
  1608. VT->getNumElements());
  1609. else
  1610. ResultTy = Type::getInt1Ty(C1->getContext());
  1611. // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
  1612. if (pred == FCmpInst::FCMP_FALSE)
  1613. return Constant::getNullValue(ResultTy);
  1614. if (pred == FCmpInst::FCMP_TRUE)
  1615. return Constant::getAllOnesValue(ResultTy);
  1616. // Handle some degenerate cases first
  1617. if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
  1618. CmpInst::Predicate Predicate = CmpInst::Predicate(pred);
  1619. bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate);
  1620. // For EQ and NE, we can always pick a value for the undef to make the
  1621. // predicate pass or fail, so we can return undef.
  1622. // Also, if both operands are undef, we can return undef for int comparison.
  1623. if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2))
  1624. return UndefValue::get(ResultTy);
  1625. // Otherwise, for integer compare, pick the same value as the non-undef
  1626. // operand, and fold it to true or false.
  1627. if (isIntegerPredicate)
  1628. return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(Predicate));
  1629. // Choosing NaN for the undef will always make unordered comparison succeed
  1630. // and ordered comparison fails.
  1631. return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate));
  1632. }
  1633. // icmp eq/ne(null,GV) -> false/true
  1634. if (C1->isNullValue()) {
  1635. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
  1636. // Don't try to evaluate aliases. External weak GV can be null.
  1637. if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() &&
  1638. !NullPointerIsDefined(nullptr /* F */,
  1639. GV->getType()->getAddressSpace())) {
  1640. if (pred == ICmpInst::ICMP_EQ)
  1641. return ConstantInt::getFalse(C1->getContext());
  1642. else if (pred == ICmpInst::ICMP_NE)
  1643. return ConstantInt::getTrue(C1->getContext());
  1644. }
  1645. // icmp eq/ne(GV,null) -> false/true
  1646. } else if (C2->isNullValue()) {
  1647. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
  1648. // Don't try to evaluate aliases. External weak GV can be null.
  1649. if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() &&
  1650. !NullPointerIsDefined(nullptr /* F */,
  1651. GV->getType()->getAddressSpace())) {
  1652. if (pred == ICmpInst::ICMP_EQ)
  1653. return ConstantInt::getFalse(C1->getContext());
  1654. else if (pred == ICmpInst::ICMP_NE)
  1655. return ConstantInt::getTrue(C1->getContext());
  1656. }
  1657. }
  1658. // If the comparison is a comparison between two i1's, simplify it.
  1659. if (C1->getType()->isIntegerTy(1)) {
  1660. switch(pred) {
  1661. case ICmpInst::ICMP_EQ:
  1662. if (isa<ConstantInt>(C2))
  1663. return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
  1664. return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
  1665. case ICmpInst::ICMP_NE:
  1666. return ConstantExpr::getXor(C1, C2);
  1667. default:
  1668. break;
  1669. }
  1670. }
  1671. if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
  1672. const APInt &V1 = cast<ConstantInt>(C1)->getValue();
  1673. const APInt &V2 = cast<ConstantInt>(C2)->getValue();
  1674. switch (pred) {
  1675. default: llvm_unreachable("Invalid ICmp Predicate");
  1676. case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2);
  1677. case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2);
  1678. case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
  1679. case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
  1680. case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
  1681. case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
  1682. case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
  1683. case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
  1684. case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
  1685. case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
  1686. }
  1687. } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
  1688. const APFloat &C1V = cast<ConstantFP>(C1)->getValueAPF();
  1689. const APFloat &C2V = cast<ConstantFP>(C2)->getValueAPF();
  1690. APFloat::cmpResult R = C1V.compare(C2V);
  1691. switch (pred) {
  1692. default: llvm_unreachable("Invalid FCmp Predicate");
  1693. case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
  1694. case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy);
  1695. case FCmpInst::FCMP_UNO:
  1696. return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
  1697. case FCmpInst::FCMP_ORD:
  1698. return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
  1699. case FCmpInst::FCMP_UEQ:
  1700. return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
  1701. R==APFloat::cmpEqual);
  1702. case FCmpInst::FCMP_OEQ:
  1703. return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
  1704. case FCmpInst::FCMP_UNE:
  1705. return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
  1706. case FCmpInst::FCMP_ONE:
  1707. return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
  1708. R==APFloat::cmpGreaterThan);
  1709. case FCmpInst::FCMP_ULT:
  1710. return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
  1711. R==APFloat::cmpLessThan);
  1712. case FCmpInst::FCMP_OLT:
  1713. return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
  1714. case FCmpInst::FCMP_UGT:
  1715. return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
  1716. R==APFloat::cmpGreaterThan);
  1717. case FCmpInst::FCMP_OGT:
  1718. return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
  1719. case FCmpInst::FCMP_ULE:
  1720. return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
  1721. case FCmpInst::FCMP_OLE:
  1722. return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
  1723. R==APFloat::cmpEqual);
  1724. case FCmpInst::FCMP_UGE:
  1725. return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
  1726. case FCmpInst::FCMP_OGE:
  1727. return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
  1728. R==APFloat::cmpEqual);
  1729. }
  1730. } else if (C1->getType()->isVectorTy()) {
  1731. // If we can constant fold the comparison of each element, constant fold
  1732. // the whole vector comparison.
  1733. SmallVector<Constant*, 4> ResElts;
  1734. Type *Ty = IntegerType::get(C1->getContext(), 32);
  1735. // Compare the elements, producing an i1 result or constant expr.
  1736. for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
  1737. Constant *C1E =
  1738. ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
  1739. Constant *C2E =
  1740. ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
  1741. ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
  1742. }
  1743. return ConstantVector::get(ResElts);
  1744. }
  1745. if (C1->getType()->isFloatingPointTy() &&
  1746. // Only call evaluateFCmpRelation if we have a constant expr to avoid
  1747. // infinite recursive loop
  1748. (isa<ConstantExpr>(C1) || isa<ConstantExpr>(C2))) {
  1749. int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
  1750. switch (evaluateFCmpRelation(C1, C2)) {
  1751. default: llvm_unreachable("Unknown relation!");
  1752. case FCmpInst::FCMP_UNO:
  1753. case FCmpInst::FCMP_ORD:
  1754. case FCmpInst::FCMP_UNE:
  1755. case FCmpInst::FCMP_ULT:
  1756. case FCmpInst::FCMP_UGT:
  1757. case FCmpInst::FCMP_ULE:
  1758. case FCmpInst::FCMP_UGE:
  1759. case FCmpInst::FCMP_TRUE:
  1760. case FCmpInst::FCMP_FALSE:
  1761. case FCmpInst::BAD_FCMP_PREDICATE:
  1762. break; // Couldn't determine anything about these constants.
  1763. case FCmpInst::FCMP_OEQ: // We know that C1 == C2
  1764. Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
  1765. pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
  1766. pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
  1767. break;
  1768. case FCmpInst::FCMP_OLT: // We know that C1 < C2
  1769. Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
  1770. pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
  1771. pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
  1772. break;
  1773. case FCmpInst::FCMP_OGT: // We know that C1 > C2
  1774. Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
  1775. pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
  1776. pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
  1777. break;
  1778. case FCmpInst::FCMP_OLE: // We know that C1 <= C2
  1779. // We can only partially decide this relation.
  1780. if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
  1781. Result = 0;
  1782. else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
  1783. Result = 1;
  1784. break;
  1785. case FCmpInst::FCMP_OGE: // We known that C1 >= C2
  1786. // We can only partially decide this relation.
  1787. if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
  1788. Result = 0;
  1789. else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
  1790. Result = 1;
  1791. break;
  1792. case FCmpInst::FCMP_ONE: // We know that C1 != C2
  1793. // We can only partially decide this relation.
  1794. if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
  1795. Result = 0;
  1796. else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
  1797. Result = 1;
  1798. break;
  1799. case FCmpInst::FCMP_UEQ: // We know that C1 == C2 || isUnordered(C1, C2).
  1800. // We can only partially decide this relation.
  1801. if (pred == FCmpInst::FCMP_ONE)
  1802. Result = 0;
  1803. else if (pred == FCmpInst::FCMP_UEQ)
  1804. Result = 1;
  1805. break;
  1806. }
  1807. // If we evaluated the result, return it now.
  1808. if (Result != -1)
  1809. return ConstantInt::get(ResultTy, Result);
  1810. } else {
  1811. // Evaluate the relation between the two constants, per the predicate.
  1812. int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
  1813. switch (evaluateICmpRelation(C1, C2,
  1814. CmpInst::isSigned((CmpInst::Predicate)pred))) {
  1815. default: llvm_unreachable("Unknown relational!");
  1816. case ICmpInst::BAD_ICMP_PREDICATE:
  1817. break; // Couldn't determine anything about these constants.
  1818. case ICmpInst::ICMP_EQ: // We know the constants are equal!
  1819. // If we know the constants are equal, we can decide the result of this
  1820. // computation precisely.
  1821. Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
  1822. break;
  1823. case ICmpInst::ICMP_ULT:
  1824. switch (pred) {
  1825. case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
  1826. Result = 1; break;
  1827. case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
  1828. Result = 0; break;
  1829. }
  1830. break;
  1831. case ICmpInst::ICMP_SLT:
  1832. switch (pred) {
  1833. case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
  1834. Result = 1; break;
  1835. case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
  1836. Result = 0; break;
  1837. }
  1838. break;
  1839. case ICmpInst::ICMP_UGT:
  1840. switch (pred) {
  1841. case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
  1842. Result = 1; break;
  1843. case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
  1844. Result = 0; break;
  1845. }
  1846. break;
  1847. case ICmpInst::ICMP_SGT:
  1848. switch (pred) {
  1849. case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
  1850. Result = 1; break;
  1851. case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
  1852. Result = 0; break;
  1853. }
  1854. break;
  1855. case ICmpInst::ICMP_ULE:
  1856. if (pred == ICmpInst::ICMP_UGT) Result = 0;
  1857. if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
  1858. break;
  1859. case ICmpInst::ICMP_SLE:
  1860. if (pred == ICmpInst::ICMP_SGT) Result = 0;
  1861. if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
  1862. break;
  1863. case ICmpInst::ICMP_UGE:
  1864. if (pred == ICmpInst::ICMP_ULT) Result = 0;
  1865. if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
  1866. break;
  1867. case ICmpInst::ICMP_SGE:
  1868. if (pred == ICmpInst::ICMP_SLT) Result = 0;
  1869. if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
  1870. break;
  1871. case ICmpInst::ICMP_NE:
  1872. if (pred == ICmpInst::ICMP_EQ) Result = 0;
  1873. if (pred == ICmpInst::ICMP_NE) Result = 1;
  1874. break;
  1875. }
  1876. // If we evaluated the result, return it now.
  1877. if (Result != -1)
  1878. return ConstantInt::get(ResultTy, Result);
  1879. // If the right hand side is a bitcast, try using its inverse to simplify
  1880. // it by moving it to the left hand side. We can't do this if it would turn
  1881. // a vector compare into a scalar compare or visa versa, or if it would turn
  1882. // the operands into FP values.
  1883. if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
  1884. Constant *CE2Op0 = CE2->getOperand(0);
  1885. if (CE2->getOpcode() == Instruction::BitCast &&
  1886. CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy() &&
  1887. !CE2Op0->getType()->isFPOrFPVectorTy()) {
  1888. Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
  1889. return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
  1890. }
  1891. }
  1892. // If the left hand side is an extension, try eliminating it.
  1893. if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
  1894. if ((CE1->getOpcode() == Instruction::SExt &&
  1895. ICmpInst::isSigned((ICmpInst::Predicate)pred)) ||
  1896. (CE1->getOpcode() == Instruction::ZExt &&
  1897. !ICmpInst::isSigned((ICmpInst::Predicate)pred))){
  1898. Constant *CE1Op0 = CE1->getOperand(0);
  1899. Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
  1900. if (CE1Inverse == CE1Op0) {
  1901. // Check whether we can safely truncate the right hand side.
  1902. Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
  1903. if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse,
  1904. C2->getType()) == C2)
  1905. return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
  1906. }
  1907. }
  1908. }
  1909. if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
  1910. (C1->isNullValue() && !C2->isNullValue())) {
  1911. // If C2 is a constant expr and C1 isn't, flip them around and fold the
  1912. // other way if possible.
  1913. // Also, if C1 is null and C2 isn't, flip them around.
  1914. pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
  1915. return ConstantExpr::getICmp(pred, C2, C1);
  1916. }
  1917. }
  1918. return nullptr;
  1919. }
  1920. /// Test whether the given sequence of *normalized* indices is "inbounds".
  1921. template<typename IndexTy>
  1922. static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
  1923. // No indices means nothing that could be out of bounds.
  1924. if (Idxs.empty()) return true;
  1925. // If the first index is zero, it's in bounds.
  1926. if (cast<Constant>(Idxs[0])->isNullValue()) return true;
  1927. // If the first index is one and all the rest are zero, it's in bounds,
  1928. // by the one-past-the-end rule.
  1929. if (auto *CI = dyn_cast<ConstantInt>(Idxs[0])) {
  1930. if (!CI->isOne())
  1931. return false;
  1932. } else {
  1933. auto *CV = cast<ConstantDataVector>(Idxs[0]);
  1934. CI = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
  1935. if (!CI || !CI->isOne())
  1936. return false;
  1937. }
  1938. for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
  1939. if (!cast<Constant>(Idxs[i])->isNullValue())
  1940. return false;
  1941. return true;
  1942. }
  1943. /// Test whether a given ConstantInt is in-range for a SequentialType.
  1944. static bool isIndexInRangeOfArrayType(uint64_t NumElements,
  1945. const ConstantInt *CI) {
  1946. // We cannot bounds check the index if it doesn't fit in an int64_t.
  1947. if (CI->getValue().getMinSignedBits() > 64)
  1948. return false;
  1949. // A negative index or an index past the end of our sequential type is
  1950. // considered out-of-range.
  1951. int64_t IndexVal = CI->getSExtValue();
  1952. if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements))
  1953. return false;
  1954. // Otherwise, it is in-range.
  1955. return true;
  1956. }
  1957. Constant *llvm::ConstantFoldGetElementPtr(Type *PointeeTy, Constant *C,
  1958. bool InBounds,
  1959. Optional<unsigned> InRangeIndex,
  1960. ArrayRef<Value *> Idxs) {
  1961. if (Idxs.empty()) return C;
  1962. Type *GEPTy = GetElementPtrInst::getGEPReturnType(
  1963. PointeeTy, C, makeArrayRef((Value *const *)Idxs.data(), Idxs.size()));
  1964. if (isa<UndefValue>(C))
  1965. return UndefValue::get(GEPTy);
  1966. Constant *Idx0 = cast<Constant>(Idxs[0]);
  1967. if (Idxs.size() == 1 && (Idx0->isNullValue() || isa<UndefValue>(Idx0)))
  1968. return GEPTy->isVectorTy() && !C->getType()->isVectorTy()
  1969. ? ConstantVector::getSplat(
  1970. cast<VectorType>(GEPTy)->getNumElements(), C)
  1971. : C;
  1972. if (C->isNullValue()) {
  1973. bool isNull = true;
  1974. for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
  1975. if (!isa<UndefValue>(Idxs[i]) &&
  1976. !cast<Constant>(Idxs[i])->isNullValue()) {
  1977. isNull = false;
  1978. break;
  1979. }
  1980. if (isNull) {
  1981. PointerType *PtrTy = cast<PointerType>(C->getType()->getScalarType());
  1982. Type *Ty = GetElementPtrInst::getIndexedType(PointeeTy, Idxs);
  1983. assert(Ty && "Invalid indices for GEP!");
  1984. Type *OrigGEPTy = PointerType::get(Ty, PtrTy->getAddressSpace());
  1985. Type *GEPTy = PointerType::get(Ty, PtrTy->getAddressSpace());
  1986. if (VectorType *VT = dyn_cast<VectorType>(C->getType()))
  1987. GEPTy = VectorType::get(OrigGEPTy, VT->getNumElements());
  1988. // The GEP returns a vector of pointers when one of more of
  1989. // its arguments is a vector.
  1990. for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
  1991. if (auto *VT = dyn_cast<VectorType>(Idxs[i]->getType())) {
  1992. GEPTy = VectorType::get(OrigGEPTy, VT->getNumElements());
  1993. break;
  1994. }
  1995. }
  1996. return Constant::getNullValue(GEPTy);
  1997. }
  1998. }
  1999. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  2000. // Combine Indices - If the source pointer to this getelementptr instruction
  2001. // is a getelementptr instruction, combine the indices of the two
  2002. // getelementptr instructions into a single instruction.
  2003. //
  2004. if (CE->getOpcode() == Instruction::GetElementPtr) {
  2005. gep_type_iterator LastI = gep_type_end(CE);
  2006. for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
  2007. I != E; ++I)
  2008. LastI = I;
  2009. // We cannot combine indices if doing so would take us outside of an
  2010. // array or vector. Doing otherwise could trick us if we evaluated such a
  2011. // GEP as part of a load.
  2012. //
  2013. // e.g. Consider if the original GEP was:
  2014. // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
  2015. // i32 0, i32 0, i64 0)
  2016. //
  2017. // If we then tried to offset it by '8' to get to the third element,
  2018. // an i8, we should *not* get:
  2019. // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
  2020. // i32 0, i32 0, i64 8)
  2021. //
  2022. // This GEP tries to index array element '8 which runs out-of-bounds.
  2023. // Subsequent evaluation would get confused and produce erroneous results.
  2024. //
  2025. // The following prohibits such a GEP from being formed by checking to see
  2026. // if the index is in-range with respect to an array.
  2027. // TODO: This code may be extended to handle vectors as well.
  2028. bool PerformFold = false;
  2029. if (Idx0->isNullValue())
  2030. PerformFold = true;
  2031. else if (LastI.isSequential())
  2032. if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx0))
  2033. PerformFold = (!LastI.isBoundedSequential() ||
  2034. isIndexInRangeOfArrayType(
  2035. LastI.getSequentialNumElements(), CI)) &&
  2036. !CE->getOperand(CE->getNumOperands() - 1)
  2037. ->getType()
  2038. ->isVectorTy();
  2039. if (PerformFold) {
  2040. SmallVector<Value*, 16> NewIndices;
  2041. NewIndices.reserve(Idxs.size() + CE->getNumOperands());
  2042. NewIndices.append(CE->op_begin() + 1, CE->op_end() - 1);
  2043. // Add the last index of the source with the first index of the new GEP.
  2044. // Make sure to handle the case when they are actually different types.
  2045. Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
  2046. // Otherwise it must be an array.
  2047. if (!Idx0->isNullValue()) {
  2048. Type *IdxTy = Combined->getType();
  2049. if (IdxTy != Idx0->getType()) {
  2050. unsigned CommonExtendedWidth =
  2051. std::max(IdxTy->getIntegerBitWidth(),
  2052. Idx0->getType()->getIntegerBitWidth());
  2053. CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
  2054. Type *CommonTy =
  2055. Type::getIntNTy(IdxTy->getContext(), CommonExtendedWidth);
  2056. Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, CommonTy);
  2057. Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, CommonTy);
  2058. Combined = ConstantExpr::get(Instruction::Add, C1, C2);
  2059. } else {
  2060. Combined =
  2061. ConstantExpr::get(Instruction::Add, Idx0, Combined);
  2062. }
  2063. }
  2064. NewIndices.push_back(Combined);
  2065. NewIndices.append(Idxs.begin() + 1, Idxs.end());
  2066. // The combined GEP normally inherits its index inrange attribute from
  2067. // the inner GEP, but if the inner GEP's last index was adjusted by the
  2068. // outer GEP, any inbounds attribute on that index is invalidated.
  2069. Optional<unsigned> IRIndex = cast<GEPOperator>(CE)->getInRangeIndex();
  2070. if (IRIndex && *IRIndex == CE->getNumOperands() - 2 && !Idx0->isNullValue())
  2071. IRIndex = None;
  2072. return ConstantExpr::getGetElementPtr(
  2073. cast<GEPOperator>(CE)->getSourceElementType(), CE->getOperand(0),
  2074. NewIndices, InBounds && cast<GEPOperator>(CE)->isInBounds(),
  2075. IRIndex);
  2076. }
  2077. }
  2078. // Attempt to fold casts to the same type away. For example, folding:
  2079. //
  2080. // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
  2081. // i64 0, i64 0)
  2082. // into:
  2083. //
  2084. // i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
  2085. //
  2086. // Don't fold if the cast is changing address spaces.
  2087. if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
  2088. PointerType *SrcPtrTy =
  2089. dyn_cast<PointerType>(CE->getOperand(0)->getType());
  2090. PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
  2091. if (SrcPtrTy && DstPtrTy) {
  2092. ArrayType *SrcArrayTy =
  2093. dyn_cast<ArrayType>(SrcPtrTy->getElementType());
  2094. ArrayType *DstArrayTy =
  2095. dyn_cast<ArrayType>(DstPtrTy->getElementType());
  2096. if (SrcArrayTy && DstArrayTy
  2097. && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
  2098. && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
  2099. return ConstantExpr::getGetElementPtr(SrcArrayTy,
  2100. (Constant *)CE->getOperand(0),
  2101. Idxs, InBounds, InRangeIndex);
  2102. }
  2103. }
  2104. }
  2105. // Check to see if any array indices are not within the corresponding
  2106. // notional array or vector bounds. If so, try to determine if they can be
  2107. // factored out into preceding dimensions.
  2108. SmallVector<Constant *, 8> NewIdxs;
  2109. Type *Ty = PointeeTy;
  2110. Type *Prev = C->getType();
  2111. bool Unknown =
  2112. !isa<ConstantInt>(Idxs[0]) && !isa<ConstantDataVector>(Idxs[0]);
  2113. for (unsigned i = 1, e = Idxs.size(); i != e;
  2114. Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
  2115. if (!isa<ConstantInt>(Idxs[i]) && !isa<ConstantDataVector>(Idxs[i])) {
  2116. // We don't know if it's in range or not.
  2117. Unknown = true;
  2118. continue;
  2119. }
  2120. if (!isa<ConstantInt>(Idxs[i - 1]) && !isa<ConstantDataVector>(Idxs[i - 1]))
  2121. // Skip if the type of the previous index is not supported.
  2122. continue;
  2123. if (InRangeIndex && i == *InRangeIndex + 1) {
  2124. // If an index is marked inrange, we cannot apply this canonicalization to
  2125. // the following index, as that will cause the inrange index to point to
  2126. // the wrong element.
  2127. continue;
  2128. }
  2129. if (isa<StructType>(Ty)) {
  2130. // The verify makes sure that GEPs into a struct are in range.
  2131. continue;
  2132. }
  2133. auto *STy = cast<SequentialType>(Ty);
  2134. if (isa<VectorType>(STy)) {
  2135. // There can be awkward padding in after a non-power of two vector.
  2136. Unknown = true;
  2137. continue;
  2138. }
  2139. if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
  2140. if (isIndexInRangeOfArrayType(STy->getNumElements(), CI))
  2141. // It's in range, skip to the next index.
  2142. continue;
  2143. if (CI->getSExtValue() < 0) {
  2144. // It's out of range and negative, don't try to factor it.
  2145. Unknown = true;
  2146. continue;
  2147. }
  2148. } else {
  2149. auto *CV = cast<ConstantDataVector>(Idxs[i]);
  2150. bool InRange = true;
  2151. for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
  2152. auto *CI = cast<ConstantInt>(CV->getElementAsConstant(I));
  2153. InRange &= isIndexInRangeOfArrayType(STy->getNumElements(), CI);
  2154. if (CI->getSExtValue() < 0) {
  2155. Unknown = true;
  2156. break;
  2157. }
  2158. }
  2159. if (InRange || Unknown)
  2160. // It's in range, skip to the next index.
  2161. // It's out of range and negative, don't try to factor it.
  2162. continue;
  2163. }
  2164. if (isa<StructType>(Prev)) {
  2165. // It's out of range, but the prior dimension is a struct
  2166. // so we can't do anything about it.
  2167. Unknown = true;
  2168. continue;
  2169. }
  2170. // It's out of range, but we can factor it into the prior
  2171. // dimension.
  2172. NewIdxs.resize(Idxs.size());
  2173. // Determine the number of elements in our sequential type.
  2174. uint64_t NumElements = STy->getArrayNumElements();
  2175. // Expand the current index or the previous index to a vector from a scalar
  2176. // if necessary.
  2177. Constant *CurrIdx = cast<Constant>(Idxs[i]);
  2178. auto *PrevIdx =
  2179. NewIdxs[i - 1] ? NewIdxs[i - 1] : cast<Constant>(Idxs[i - 1]);
  2180. bool IsCurrIdxVector = CurrIdx->getType()->isVectorTy();
  2181. bool IsPrevIdxVector = PrevIdx->getType()->isVectorTy();
  2182. bool UseVector = IsCurrIdxVector || IsPrevIdxVector;
  2183. if (!IsCurrIdxVector && IsPrevIdxVector)
  2184. CurrIdx = ConstantDataVector::getSplat(
  2185. PrevIdx->getType()->getVectorNumElements(), CurrIdx);
  2186. if (!IsPrevIdxVector && IsCurrIdxVector)
  2187. PrevIdx = ConstantDataVector::getSplat(
  2188. CurrIdx->getType()->getVectorNumElements(), PrevIdx);
  2189. Constant *Factor =
  2190. ConstantInt::get(CurrIdx->getType()->getScalarType(), NumElements);
  2191. if (UseVector)
  2192. Factor = ConstantDataVector::getSplat(
  2193. IsPrevIdxVector ? PrevIdx->getType()->getVectorNumElements()
  2194. : CurrIdx->getType()->getVectorNumElements(),
  2195. Factor);
  2196. NewIdxs[i] = ConstantExpr::getSRem(CurrIdx, Factor);
  2197. Constant *Div = ConstantExpr::getSDiv(CurrIdx, Factor);
  2198. unsigned CommonExtendedWidth =
  2199. std::max(PrevIdx->getType()->getScalarSizeInBits(),
  2200. Div->getType()->getScalarSizeInBits());
  2201. CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
  2202. // Before adding, extend both operands to i64 to avoid
  2203. // overflow trouble.
  2204. Type *ExtendedTy = Type::getIntNTy(Div->getContext(), CommonExtendedWidth);
  2205. if (UseVector)
  2206. ExtendedTy = VectorType::get(
  2207. ExtendedTy, IsPrevIdxVector
  2208. ? PrevIdx->getType()->getVectorNumElements()
  2209. : CurrIdx->getType()->getVectorNumElements());
  2210. if (!PrevIdx->getType()->isIntOrIntVectorTy(CommonExtendedWidth))
  2211. PrevIdx = ConstantExpr::getSExt(PrevIdx, ExtendedTy);
  2212. if (!Div->getType()->isIntOrIntVectorTy(CommonExtendedWidth))
  2213. Div = ConstantExpr::getSExt(Div, ExtendedTy);
  2214. NewIdxs[i - 1] = ConstantExpr::getAdd(PrevIdx, Div);
  2215. }
  2216. // If we did any factoring, start over with the adjusted indices.
  2217. if (!NewIdxs.empty()) {
  2218. for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
  2219. if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
  2220. return ConstantExpr::getGetElementPtr(PointeeTy, C, NewIdxs, InBounds,
  2221. InRangeIndex);
  2222. }
  2223. // If all indices are known integers and normalized, we can do a simple
  2224. // check for the "inbounds" property.
  2225. if (!Unknown && !InBounds)
  2226. if (auto *GV = dyn_cast<GlobalVariable>(C))
  2227. if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs))
  2228. return ConstantExpr::getGetElementPtr(PointeeTy, C, Idxs,
  2229. /*InBounds=*/true, InRangeIndex);
  2230. return nullptr;
  2231. }