2
0

ScalarEvolutionExpander.cpp 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951
  1. //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains the implementation of the scalar evolution expander,
  11. // which is used to generate the code corresponding to a given scalar evolution
  12. // expression.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/Analysis/InstructionSimplify.h"
  19. #include "llvm/Analysis/LoopInfo.h"
  20. #include "llvm/Analysis/TargetTransformInfo.h"
  21. #include "llvm/IR/DataLayout.h"
  22. #include "llvm/IR/Dominators.h"
  23. #include "llvm/IR/IntrinsicInst.h"
  24. #include "llvm/IR/LLVMContext.h"
  25. #include "llvm/IR/Module.h"
  26. #include "llvm/IR/PatternMatch.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. using namespace llvm;
  30. using namespace PatternMatch;
  31. /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
  32. /// reusing an existing cast if a suitable one exists, moving an existing
  33. /// cast if a suitable one exists but isn't in the right place, or
  34. /// creating a new one.
  35. Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
  36. Instruction::CastOps Op,
  37. BasicBlock::iterator IP) {
  38. // This function must be called with the builder having a valid insertion
  39. // point. It doesn't need to be the actual IP where the uses of the returned
  40. // cast will be added, but it must dominate such IP.
  41. // We use this precondition to produce a cast that will dominate all its
  42. // uses. In particular, this is crucial for the case where the builder's
  43. // insertion point *is* the point where we were asked to put the cast.
  44. // Since we don't know the builder's insertion point is actually
  45. // where the uses will be added (only that it dominates it), we are
  46. // not allowed to move it.
  47. BasicBlock::iterator BIP = Builder.GetInsertPoint();
  48. Instruction *Ret = nullptr;
  49. // Check to see if there is already a cast!
  50. for (User *U : V->users())
  51. if (U->getType() == Ty)
  52. if (CastInst *CI = dyn_cast<CastInst>(U))
  53. if (CI->getOpcode() == Op) {
  54. // If the cast isn't where we want it, create a new cast at IP.
  55. // Likewise, do not reuse a cast at BIP because it must dominate
  56. // instructions that might be inserted before BIP.
  57. if (BasicBlock::iterator(CI) != IP || BIP == IP) {
  58. // Create a new cast, and leave the old cast in place in case
  59. // it is being used as an insert point. Clear its operand
  60. // so that it doesn't hold anything live.
  61. Ret = CastInst::Create(Op, V, Ty, "", IP);
  62. Ret->takeName(CI);
  63. CI->replaceAllUsesWith(Ret);
  64. CI->setOperand(0, UndefValue::get(V->getType()));
  65. break;
  66. }
  67. Ret = CI;
  68. break;
  69. }
  70. // Create a new cast.
  71. if (!Ret)
  72. Ret = CastInst::Create(Op, V, Ty, V->getName(), IP);
  73. // We assert at the end of the function since IP might point to an
  74. // instruction with different dominance properties than a cast
  75. // (an invoke for example) and not dominate BIP (but the cast does).
  76. assert(SE.DT->dominates(Ret, BIP));
  77. rememberInstruction(Ret);
  78. return Ret;
  79. }
  80. /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
  81. /// which must be possible with a noop cast, doing what we can to share
  82. /// the casts.
  83. Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
  84. Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
  85. assert((Op == Instruction::BitCast ||
  86. Op == Instruction::PtrToInt ||
  87. Op == Instruction::IntToPtr) &&
  88. "InsertNoopCastOfTo cannot perform non-noop casts!");
  89. assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
  90. "InsertNoopCastOfTo cannot change sizes!");
  91. // Short-circuit unnecessary bitcasts.
  92. if (Op == Instruction::BitCast) {
  93. if (V->getType() == Ty)
  94. return V;
  95. if (CastInst *CI = dyn_cast<CastInst>(V)) {
  96. if (CI->getOperand(0)->getType() == Ty)
  97. return CI->getOperand(0);
  98. }
  99. }
  100. // Short-circuit unnecessary inttoptr<->ptrtoint casts.
  101. if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
  102. SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
  103. if (CastInst *CI = dyn_cast<CastInst>(V))
  104. if ((CI->getOpcode() == Instruction::PtrToInt ||
  105. CI->getOpcode() == Instruction::IntToPtr) &&
  106. SE.getTypeSizeInBits(CI->getType()) ==
  107. SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
  108. return CI->getOperand(0);
  109. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
  110. if ((CE->getOpcode() == Instruction::PtrToInt ||
  111. CE->getOpcode() == Instruction::IntToPtr) &&
  112. SE.getTypeSizeInBits(CE->getType()) ==
  113. SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
  114. return CE->getOperand(0);
  115. }
  116. // Fold a cast of a constant.
  117. if (Constant *C = dyn_cast<Constant>(V))
  118. return ConstantExpr::getCast(Op, C, Ty);
  119. // Cast the argument at the beginning of the entry block, after
  120. // any bitcasts of other arguments.
  121. if (Argument *A = dyn_cast<Argument>(V)) {
  122. BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
  123. while ((isa<BitCastInst>(IP) &&
  124. isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
  125. cast<BitCastInst>(IP)->getOperand(0) != A) ||
  126. isa<DbgInfoIntrinsic>(IP) ||
  127. isa<LandingPadInst>(IP))
  128. ++IP;
  129. return ReuseOrCreateCast(A, Ty, Op, IP);
  130. }
  131. // Cast the instruction immediately after the instruction.
  132. Instruction *I = cast<Instruction>(V);
  133. BasicBlock::iterator IP = I; ++IP;
  134. if (InvokeInst *II = dyn_cast<InvokeInst>(I))
  135. IP = II->getNormalDest()->begin();
  136. while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
  137. ++IP;
  138. return ReuseOrCreateCast(I, Ty, Op, IP);
  139. }
  140. /// InsertBinop - Insert the specified binary operator, doing a small amount
  141. /// of work to avoid inserting an obviously redundant operation.
  142. Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
  143. Value *LHS, Value *RHS) {
  144. // Fold a binop with constant operands.
  145. if (Constant *CLHS = dyn_cast<Constant>(LHS))
  146. if (Constant *CRHS = dyn_cast<Constant>(RHS))
  147. return ConstantExpr::get(Opcode, CLHS, CRHS);
  148. // Do a quick scan to see if we have this binop nearby. If so, reuse it.
  149. unsigned ScanLimit = 6;
  150. BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
  151. // Scanning starts from the last instruction before the insertion point.
  152. BasicBlock::iterator IP = Builder.GetInsertPoint();
  153. if (IP != BlockBegin) {
  154. --IP;
  155. for (; ScanLimit; --IP, --ScanLimit) {
  156. // Don't count dbg.value against the ScanLimit, to avoid perturbing the
  157. // generated code.
  158. if (isa<DbgInfoIntrinsic>(IP))
  159. ScanLimit++;
  160. if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
  161. IP->getOperand(1) == RHS)
  162. return IP;
  163. if (IP == BlockBegin) break;
  164. }
  165. }
  166. // Save the original insertion point so we can restore it when we're done.
  167. DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
  168. BuilderType::InsertPointGuard Guard(Builder);
  169. // Move the insertion point out of as many loops as we can.
  170. while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
  171. if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
  172. BasicBlock *Preheader = L->getLoopPreheader();
  173. if (!Preheader) break;
  174. // Ok, move up a level.
  175. Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
  176. }
  177. // If we haven't found this binop, insert it.
  178. Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
  179. BO->setDebugLoc(Loc);
  180. rememberInstruction(BO);
  181. return BO;
  182. }
  183. /// FactorOutConstant - Test if S is divisible by Factor, using signed
  184. /// division. If so, update S with Factor divided out and return true.
  185. /// S need not be evenly divisible if a reasonable remainder can be
  186. /// computed.
  187. /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
  188. /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
  189. /// check to see if the divide was folded.
  190. static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
  191. const SCEV *Factor, ScalarEvolution &SE,
  192. const DataLayout &DL) {
  193. // Everything is divisible by one.
  194. if (Factor->isOne())
  195. return true;
  196. // x/x == 1.
  197. if (S == Factor) {
  198. S = SE.getConstant(S->getType(), 1);
  199. return true;
  200. }
  201. // For a Constant, check for a multiple of the given factor.
  202. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
  203. // 0/x == 0.
  204. if (C->isZero())
  205. return true;
  206. // Check for divisibility.
  207. if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
  208. ConstantInt *CI =
  209. ConstantInt::get(SE.getContext(),
  210. C->getValue()->getValue().sdiv(
  211. FC->getValue()->getValue()));
  212. // If the quotient is zero and the remainder is non-zero, reject
  213. // the value at this scale. It will be considered for subsequent
  214. // smaller scales.
  215. if (!CI->isZero()) {
  216. const SCEV *Div = SE.getConstant(CI);
  217. S = Div;
  218. Remainder =
  219. SE.getAddExpr(Remainder,
  220. SE.getConstant(C->getValue()->getValue().srem(
  221. FC->getValue()->getValue())));
  222. return true;
  223. }
  224. }
  225. }
  226. // In a Mul, check if there is a constant operand which is a multiple
  227. // of the given factor.
  228. if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
  229. // Size is known, check if there is a constant operand which is a multiple
  230. // of the given factor. If so, we can factor it.
  231. const SCEVConstant *FC = cast<SCEVConstant>(Factor);
  232. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
  233. if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
  234. SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
  235. NewMulOps[0] = SE.getConstant(
  236. C->getValue()->getValue().sdiv(FC->getValue()->getValue()));
  237. S = SE.getMulExpr(NewMulOps);
  238. return true;
  239. }
  240. }
  241. // In an AddRec, check if both start and step are divisible.
  242. if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
  243. const SCEV *Step = A->getStepRecurrence(SE);
  244. const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
  245. if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
  246. return false;
  247. if (!StepRem->isZero())
  248. return false;
  249. const SCEV *Start = A->getStart();
  250. if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
  251. return false;
  252. S = SE.getAddRecExpr(Start, Step, A->getLoop(),
  253. A->getNoWrapFlags(SCEV::FlagNW));
  254. return true;
  255. }
  256. return false;
  257. }
  258. /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
  259. /// is the number of SCEVAddRecExprs present, which are kept at the end of
  260. /// the list.
  261. ///
  262. static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
  263. Type *Ty,
  264. ScalarEvolution &SE) {
  265. unsigned NumAddRecs = 0;
  266. for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
  267. ++NumAddRecs;
  268. // Group Ops into non-addrecs and addrecs.
  269. SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
  270. SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
  271. // Let ScalarEvolution sort and simplify the non-addrecs list.
  272. const SCEV *Sum = NoAddRecs.empty() ?
  273. SE.getConstant(Ty, 0) :
  274. SE.getAddExpr(NoAddRecs);
  275. // If it returned an add, use the operands. Otherwise it simplified
  276. // the sum into a single value, so just use that.
  277. Ops.clear();
  278. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
  279. Ops.append(Add->op_begin(), Add->op_end());
  280. else if (!Sum->isZero())
  281. Ops.push_back(Sum);
  282. // Then append the addrecs.
  283. Ops.append(AddRecs.begin(), AddRecs.end());
  284. }
  285. /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
  286. /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
  287. /// This helps expose more opportunities for folding parts of the expressions
  288. /// into GEP indices.
  289. ///
  290. static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
  291. Type *Ty,
  292. ScalarEvolution &SE) {
  293. // Find the addrecs.
  294. SmallVector<const SCEV *, 8> AddRecs;
  295. for (unsigned i = 0, e = Ops.size(); i != e; ++i)
  296. while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
  297. const SCEV *Start = A->getStart();
  298. if (Start->isZero()) break;
  299. const SCEV *Zero = SE.getConstant(Ty, 0);
  300. AddRecs.push_back(SE.getAddRecExpr(Zero,
  301. A->getStepRecurrence(SE),
  302. A->getLoop(),
  303. A->getNoWrapFlags(SCEV::FlagNW)));
  304. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
  305. Ops[i] = Zero;
  306. Ops.append(Add->op_begin(), Add->op_end());
  307. e += Add->getNumOperands();
  308. } else {
  309. Ops[i] = Start;
  310. }
  311. }
  312. if (!AddRecs.empty()) {
  313. // Add the addrecs onto the end of the list.
  314. Ops.append(AddRecs.begin(), AddRecs.end());
  315. // Resort the operand list, moving any constants to the front.
  316. SimplifyAddOperands(Ops, Ty, SE);
  317. }
  318. }
  319. /// expandAddToGEP - Expand an addition expression with a pointer type into
  320. /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
  321. /// BasicAliasAnalysis and other passes analyze the result. See the rules
  322. /// for getelementptr vs. inttoptr in
  323. /// http://llvm.org/docs/LangRef.html#pointeraliasing
  324. /// for details.
  325. ///
  326. /// Design note: The correctness of using getelementptr here depends on
  327. /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
  328. /// they may introduce pointer arithmetic which may not be safely converted
  329. /// into getelementptr.
  330. ///
  331. /// Design note: It might seem desirable for this function to be more
  332. /// loop-aware. If some of the indices are loop-invariant while others
  333. /// aren't, it might seem desirable to emit multiple GEPs, keeping the
  334. /// loop-invariant portions of the overall computation outside the loop.
  335. /// However, there are a few reasons this is not done here. Hoisting simple
  336. /// arithmetic is a low-level optimization that often isn't very
  337. /// important until late in the optimization process. In fact, passes
  338. /// like InstructionCombining will combine GEPs, even if it means
  339. /// pushing loop-invariant computation down into loops, so even if the
  340. /// GEPs were split here, the work would quickly be undone. The
  341. /// LoopStrengthReduction pass, which is usually run quite late (and
  342. /// after the last InstructionCombining pass), takes care of hoisting
  343. /// loop-invariant portions of expressions, after considering what
  344. /// can be folded using target addressing modes.
  345. ///
  346. Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
  347. const SCEV *const *op_end,
  348. PointerType *PTy,
  349. Type *Ty,
  350. Value *V) {
  351. Type *OriginalElTy = PTy->getElementType();
  352. Type *ElTy = OriginalElTy;
  353. SmallVector<Value *, 4> GepIndices;
  354. SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
  355. bool AnyNonZeroIndices = false;
  356. // Split AddRecs up into parts as either of the parts may be usable
  357. // without the other.
  358. SplitAddRecs(Ops, Ty, SE);
  359. Type *IntPtrTy = DL.getIntPtrType(PTy);
  360. // Descend down the pointer's type and attempt to convert the other
  361. // operands into GEP indices, at each level. The first index in a GEP
  362. // indexes into the array implied by the pointer operand; the rest of
  363. // the indices index into the element or field type selected by the
  364. // preceding index.
  365. for (;;) {
  366. // If the scale size is not 0, attempt to factor out a scale for
  367. // array indexing.
  368. SmallVector<const SCEV *, 8> ScaledOps;
  369. if (ElTy->isSized()) {
  370. const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
  371. if (!ElSize->isZero()) {
  372. SmallVector<const SCEV *, 8> NewOps;
  373. for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
  374. const SCEV *Op = Ops[i];
  375. const SCEV *Remainder = SE.getConstant(Ty, 0);
  376. if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
  377. // Op now has ElSize factored out.
  378. ScaledOps.push_back(Op);
  379. if (!Remainder->isZero())
  380. NewOps.push_back(Remainder);
  381. AnyNonZeroIndices = true;
  382. } else {
  383. // The operand was not divisible, so add it to the list of operands
  384. // we'll scan next iteration.
  385. NewOps.push_back(Ops[i]);
  386. }
  387. }
  388. // If we made any changes, update Ops.
  389. if (!ScaledOps.empty()) {
  390. Ops = NewOps;
  391. SimplifyAddOperands(Ops, Ty, SE);
  392. }
  393. }
  394. }
  395. // Record the scaled array index for this level of the type. If
  396. // we didn't find any operands that could be factored, tentatively
  397. // assume that element zero was selected (since the zero offset
  398. // would obviously be folded away).
  399. Value *Scaled = ScaledOps.empty() ?
  400. Constant::getNullValue(Ty) :
  401. expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
  402. GepIndices.push_back(Scaled);
  403. // Collect struct field index operands.
  404. while (StructType *STy = dyn_cast<StructType>(ElTy)) {
  405. bool FoundFieldNo = false;
  406. // An empty struct has no fields.
  407. if (STy->getNumElements() == 0) break;
  408. // Field offsets are known. See if a constant offset falls within any of
  409. // the struct fields.
  410. if (Ops.empty())
  411. break;
  412. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
  413. if (SE.getTypeSizeInBits(C->getType()) <= 64) {
  414. const StructLayout &SL = *DL.getStructLayout(STy);
  415. uint64_t FullOffset = C->getValue()->getZExtValue();
  416. if (FullOffset < SL.getSizeInBytes()) {
  417. unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
  418. GepIndices.push_back(
  419. ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
  420. ElTy = STy->getTypeAtIndex(ElIdx);
  421. Ops[0] =
  422. SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
  423. AnyNonZeroIndices = true;
  424. FoundFieldNo = true;
  425. }
  426. }
  427. // If no struct field offsets were found, tentatively assume that
  428. // field zero was selected (since the zero offset would obviously
  429. // be folded away).
  430. if (!FoundFieldNo) {
  431. ElTy = STy->getTypeAtIndex(0u);
  432. GepIndices.push_back(
  433. Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
  434. }
  435. }
  436. if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
  437. ElTy = ATy->getElementType();
  438. else
  439. break;
  440. }
  441. // If none of the operands were convertible to proper GEP indices, cast
  442. // the base to i8* and do an ugly getelementptr with that. It's still
  443. // better than ptrtoint+arithmetic+inttoptr at least.
  444. if (!AnyNonZeroIndices) {
  445. // Cast the base to i8*.
  446. V = InsertNoopCastOfTo(V,
  447. Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
  448. assert(!isa<Instruction>(V) ||
  449. SE.DT->dominates(cast<Instruction>(V), Builder.GetInsertPoint()));
  450. // Expand the operands for a plain byte offset.
  451. Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
  452. // Fold a GEP with constant operands.
  453. if (Constant *CLHS = dyn_cast<Constant>(V))
  454. if (Constant *CRHS = dyn_cast<Constant>(Idx))
  455. return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
  456. CLHS, CRHS);
  457. // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
  458. unsigned ScanLimit = 6;
  459. BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
  460. // Scanning starts from the last instruction before the insertion point.
  461. BasicBlock::iterator IP = Builder.GetInsertPoint();
  462. if (IP != BlockBegin) {
  463. --IP;
  464. for (; ScanLimit; --IP, --ScanLimit) {
  465. // Don't count dbg.value against the ScanLimit, to avoid perturbing the
  466. // generated code.
  467. if (isa<DbgInfoIntrinsic>(IP))
  468. ScanLimit++;
  469. if (IP->getOpcode() == Instruction::GetElementPtr &&
  470. IP->getOperand(0) == V && IP->getOperand(1) == Idx)
  471. return IP;
  472. if (IP == BlockBegin) break;
  473. }
  474. }
  475. // Save the original insertion point so we can restore it when we're done.
  476. BuilderType::InsertPointGuard Guard(Builder);
  477. // Move the insertion point out of as many loops as we can.
  478. while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
  479. if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
  480. BasicBlock *Preheader = L->getLoopPreheader();
  481. if (!Preheader) break;
  482. // Ok, move up a level.
  483. Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
  484. }
  485. // Emit a GEP.
  486. Value *GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
  487. rememberInstruction(GEP);
  488. return GEP;
  489. }
  490. // Save the original insertion point so we can restore it when we're done.
  491. BuilderType::InsertPoint SaveInsertPt = Builder.saveIP();
  492. // Move the insertion point out of as many loops as we can.
  493. while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
  494. if (!L->isLoopInvariant(V)) break;
  495. bool AnyIndexNotLoopInvariant = false;
  496. for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
  497. E = GepIndices.end(); I != E; ++I)
  498. if (!L->isLoopInvariant(*I)) {
  499. AnyIndexNotLoopInvariant = true;
  500. break;
  501. }
  502. if (AnyIndexNotLoopInvariant)
  503. break;
  504. BasicBlock *Preheader = L->getLoopPreheader();
  505. if (!Preheader) break;
  506. // Ok, move up a level.
  507. Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
  508. }
  509. // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
  510. // because ScalarEvolution may have changed the address arithmetic to
  511. // compute a value which is beyond the end of the allocated object.
  512. Value *Casted = V;
  513. if (V->getType() != PTy)
  514. Casted = InsertNoopCastOfTo(Casted, PTy);
  515. Value *GEP = Builder.CreateGEP(OriginalElTy, Casted,
  516. GepIndices,
  517. "scevgep");
  518. Ops.push_back(SE.getUnknown(GEP));
  519. rememberInstruction(GEP);
  520. // Restore the original insert point.
  521. Builder.restoreIP(SaveInsertPt);
  522. return expand(SE.getAddExpr(Ops));
  523. }
  524. /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
  525. /// SCEV expansion. If they are nested, this is the most nested. If they are
  526. /// neighboring, pick the later.
  527. static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
  528. DominatorTree &DT) {
  529. if (!A) return B;
  530. if (!B) return A;
  531. if (A->contains(B)) return B;
  532. if (B->contains(A)) return A;
  533. if (DT.dominates(A->getHeader(), B->getHeader())) return B;
  534. if (DT.dominates(B->getHeader(), A->getHeader())) return A;
  535. return A; // Arbitrarily break the tie.
  536. }
  537. /// getRelevantLoop - Get the most relevant loop associated with the given
  538. /// expression, according to PickMostRelevantLoop.
  539. const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
  540. // Test whether we've already computed the most relevant loop for this SCEV.
  541. std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
  542. RelevantLoops.insert(std::make_pair(S, nullptr));
  543. if (!Pair.second)
  544. return Pair.first->second;
  545. if (isa<SCEVConstant>(S))
  546. // A constant has no relevant loops.
  547. return nullptr;
  548. if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
  549. if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
  550. return Pair.first->second = SE.LI->getLoopFor(I->getParent());
  551. // A non-instruction has no relevant loops.
  552. return nullptr;
  553. }
  554. if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
  555. const Loop *L = nullptr;
  556. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
  557. L = AR->getLoop();
  558. for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
  559. I != E; ++I)
  560. L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
  561. return RelevantLoops[N] = L;
  562. }
  563. if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
  564. const Loop *Result = getRelevantLoop(C->getOperand());
  565. return RelevantLoops[C] = Result;
  566. }
  567. if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
  568. const Loop *Result =
  569. PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
  570. getRelevantLoop(D->getRHS()),
  571. *SE.DT);
  572. return RelevantLoops[D] = Result;
  573. }
  574. llvm_unreachable("Unexpected SCEV type!");
  575. }
  576. namespace {
  577. /// LoopCompare - Compare loops by PickMostRelevantLoop.
  578. class LoopCompare {
  579. DominatorTree &DT;
  580. public:
  581. explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
  582. bool operator()(std::pair<const Loop *, const SCEV *> LHS,
  583. std::pair<const Loop *, const SCEV *> RHS) const {
  584. // Keep pointer operands sorted at the end.
  585. if (LHS.second->getType()->isPointerTy() !=
  586. RHS.second->getType()->isPointerTy())
  587. return LHS.second->getType()->isPointerTy();
  588. // Compare loops with PickMostRelevantLoop.
  589. if (LHS.first != RHS.first)
  590. return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
  591. // If one operand is a non-constant negative and the other is not,
  592. // put the non-constant negative on the right so that a sub can
  593. // be used instead of a negate and add.
  594. if (LHS.second->isNonConstantNegative()) {
  595. if (!RHS.second->isNonConstantNegative())
  596. return false;
  597. } else if (RHS.second->isNonConstantNegative())
  598. return true;
  599. // Otherwise they are equivalent according to this comparison.
  600. return false;
  601. }
  602. };
  603. }
  604. Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
  605. Type *Ty = SE.getEffectiveSCEVType(S->getType());
  606. // Collect all the add operands in a loop, along with their associated loops.
  607. // Iterate in reverse so that constants are emitted last, all else equal, and
  608. // so that pointer operands are inserted first, which the code below relies on
  609. // to form more involved GEPs.
  610. SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
  611. for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
  612. E(S->op_begin()); I != E; ++I)
  613. OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
  614. // Sort by loop. Use a stable sort so that constants follow non-constants and
  615. // pointer operands precede non-pointer operands.
  616. std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
  617. // Emit instructions to add all the operands. Hoist as much as possible
  618. // out of loops, and form meaningful getelementptrs where possible.
  619. Value *Sum = nullptr;
  620. for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
  621. I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
  622. const Loop *CurLoop = I->first;
  623. const SCEV *Op = I->second;
  624. if (!Sum) {
  625. // This is the first operand. Just expand it.
  626. Sum = expand(Op);
  627. ++I;
  628. } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
  629. // The running sum expression is a pointer. Try to form a getelementptr
  630. // at this level with that as the base.
  631. SmallVector<const SCEV *, 4> NewOps;
  632. for (; I != E && I->first == CurLoop; ++I) {
  633. // If the operand is SCEVUnknown and not instructions, peek through
  634. // it, to enable more of it to be folded into the GEP.
  635. const SCEV *X = I->second;
  636. if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
  637. if (!isa<Instruction>(U->getValue()))
  638. X = SE.getSCEV(U->getValue());
  639. NewOps.push_back(X);
  640. }
  641. Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
  642. } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
  643. // The running sum is an integer, and there's a pointer at this level.
  644. // Try to form a getelementptr. If the running sum is instructions,
  645. // use a SCEVUnknown to avoid re-analyzing them.
  646. SmallVector<const SCEV *, 4> NewOps;
  647. NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
  648. SE.getSCEV(Sum));
  649. for (++I; I != E && I->first == CurLoop; ++I)
  650. NewOps.push_back(I->second);
  651. Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
  652. } else if (Op->isNonConstantNegative()) {
  653. // Instead of doing a negate and add, just do a subtract.
  654. Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
  655. Sum = InsertNoopCastOfTo(Sum, Ty);
  656. Sum = InsertBinop(Instruction::Sub, Sum, W);
  657. ++I;
  658. } else {
  659. // A simple add.
  660. Value *W = expandCodeFor(Op, Ty);
  661. Sum = InsertNoopCastOfTo(Sum, Ty);
  662. // Canonicalize a constant to the RHS.
  663. if (isa<Constant>(Sum)) std::swap(Sum, W);
  664. Sum = InsertBinop(Instruction::Add, Sum, W);
  665. ++I;
  666. }
  667. }
  668. return Sum;
  669. }
  670. Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
  671. Type *Ty = SE.getEffectiveSCEVType(S->getType());
  672. // Collect all the mul operands in a loop, along with their associated loops.
  673. // Iterate in reverse so that constants are emitted last, all else equal.
  674. SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
  675. for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
  676. E(S->op_begin()); I != E; ++I)
  677. OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
  678. // Sort by loop. Use a stable sort so that constants follow non-constants.
  679. std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
  680. // Emit instructions to mul all the operands. Hoist as much as possible
  681. // out of loops.
  682. Value *Prod = nullptr;
  683. for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
  684. I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ++I) {
  685. const SCEV *Op = I->second;
  686. if (!Prod) {
  687. // This is the first operand. Just expand it.
  688. Prod = expand(Op);
  689. } else if (Op->isAllOnesValue()) {
  690. // Instead of doing a multiply by negative one, just do a negate.
  691. Prod = InsertNoopCastOfTo(Prod, Ty);
  692. Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
  693. } else {
  694. // A simple mul.
  695. Value *W = expandCodeFor(Op, Ty);
  696. Prod = InsertNoopCastOfTo(Prod, Ty);
  697. // Canonicalize a constant to the RHS.
  698. if (isa<Constant>(Prod)) std::swap(Prod, W);
  699. const APInt *RHS;
  700. if (match(W, m_Power2(RHS))) {
  701. // Canonicalize Prod*(1<<C) to Prod<<C.
  702. assert(!Ty->isVectorTy() && "vector types are not SCEVable");
  703. Prod = InsertBinop(Instruction::Shl, Prod,
  704. ConstantInt::get(Ty, RHS->logBase2()));
  705. } else {
  706. Prod = InsertBinop(Instruction::Mul, Prod, W);
  707. }
  708. }
  709. }
  710. return Prod;
  711. }
  712. Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
  713. Type *Ty = SE.getEffectiveSCEVType(S->getType());
  714. Value *LHS = expandCodeFor(S->getLHS(), Ty);
  715. if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
  716. const APInt &RHS = SC->getValue()->getValue();
  717. if (RHS.isPowerOf2())
  718. return InsertBinop(Instruction::LShr, LHS,
  719. ConstantInt::get(Ty, RHS.logBase2()));
  720. }
  721. Value *RHS = expandCodeFor(S->getRHS(), Ty);
  722. return InsertBinop(Instruction::UDiv, LHS, RHS);
  723. }
  724. /// Move parts of Base into Rest to leave Base with the minimal
  725. /// expression that provides a pointer operand suitable for a
  726. /// GEP expansion.
  727. static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
  728. ScalarEvolution &SE) {
  729. while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
  730. Base = A->getStart();
  731. Rest = SE.getAddExpr(Rest,
  732. SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
  733. A->getStepRecurrence(SE),
  734. A->getLoop(),
  735. A->getNoWrapFlags(SCEV::FlagNW)));
  736. }
  737. if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
  738. Base = A->getOperand(A->getNumOperands()-1);
  739. SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
  740. NewAddOps.back() = Rest;
  741. Rest = SE.getAddExpr(NewAddOps);
  742. ExposePointerBase(Base, Rest, SE);
  743. }
  744. }
  745. /// Determine if this is a well-behaved chain of instructions leading back to
  746. /// the PHI. If so, it may be reused by expanded expressions.
  747. bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
  748. const Loop *L) {
  749. if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
  750. (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
  751. return false;
  752. // If any of the operands don't dominate the insert position, bail.
  753. // Addrec operands are always loop-invariant, so this can only happen
  754. // if there are instructions which haven't been hoisted.
  755. if (L == IVIncInsertLoop) {
  756. for (User::op_iterator OI = IncV->op_begin()+1,
  757. OE = IncV->op_end(); OI != OE; ++OI)
  758. if (Instruction *OInst = dyn_cast<Instruction>(OI))
  759. if (!SE.DT->dominates(OInst, IVIncInsertPos))
  760. return false;
  761. }
  762. // Advance to the next instruction.
  763. IncV = dyn_cast<Instruction>(IncV->getOperand(0));
  764. if (!IncV)
  765. return false;
  766. if (IncV->mayHaveSideEffects())
  767. return false;
  768. if (IncV != PN)
  769. return true;
  770. return isNormalAddRecExprPHI(PN, IncV, L);
  771. }
  772. /// getIVIncOperand returns an induction variable increment's induction
  773. /// variable operand.
  774. ///
  775. /// If allowScale is set, any type of GEP is allowed as long as the nonIV
  776. /// operands dominate InsertPos.
  777. ///
  778. /// If allowScale is not set, ensure that a GEP increment conforms to one of the
  779. /// simple patterns generated by getAddRecExprPHILiterally and
  780. /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
  781. Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
  782. Instruction *InsertPos,
  783. bool allowScale) {
  784. if (IncV == InsertPos)
  785. return nullptr;
  786. switch (IncV->getOpcode()) {
  787. default:
  788. return nullptr;
  789. // Check for a simple Add/Sub or GEP of a loop invariant step.
  790. case Instruction::Add:
  791. case Instruction::Sub: {
  792. Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
  793. if (!OInst || SE.DT->dominates(OInst, InsertPos))
  794. return dyn_cast<Instruction>(IncV->getOperand(0));
  795. return nullptr;
  796. }
  797. case Instruction::BitCast:
  798. return dyn_cast<Instruction>(IncV->getOperand(0));
  799. case Instruction::GetElementPtr:
  800. for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
  801. I != E; ++I) {
  802. if (isa<Constant>(*I))
  803. continue;
  804. if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
  805. if (!SE.DT->dominates(OInst, InsertPos))
  806. return nullptr;
  807. }
  808. if (allowScale) {
  809. // allow any kind of GEP as long as it can be hoisted.
  810. continue;
  811. }
  812. // This must be a pointer addition of constants (pretty), which is already
  813. // handled, or some number of address-size elements (ugly). Ugly geps
  814. // have 2 operands. i1* is used by the expander to represent an
  815. // address-size element.
  816. if (IncV->getNumOperands() != 2)
  817. return nullptr;
  818. unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
  819. if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
  820. && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
  821. return nullptr;
  822. break;
  823. }
  824. return dyn_cast<Instruction>(IncV->getOperand(0));
  825. }
  826. }
  827. /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
  828. /// it available to other uses in this loop. Recursively hoist any operands,
  829. /// until we reach a value that dominates InsertPos.
  830. bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
  831. if (SE.DT->dominates(IncV, InsertPos))
  832. return true;
  833. // InsertPos must itself dominate IncV so that IncV's new position satisfies
  834. // its existing users.
  835. if (isa<PHINode>(InsertPos)
  836. || !SE.DT->dominates(InsertPos->getParent(), IncV->getParent()))
  837. return false;
  838. // Check that the chain of IV operands leading back to Phi can be hoisted.
  839. SmallVector<Instruction*, 4> IVIncs;
  840. for(;;) {
  841. Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
  842. if (!Oper)
  843. return false;
  844. // IncV is safe to hoist.
  845. IVIncs.push_back(IncV);
  846. IncV = Oper;
  847. if (SE.DT->dominates(IncV, InsertPos))
  848. break;
  849. }
  850. for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
  851. E = IVIncs.rend(); I != E; ++I) {
  852. (*I)->moveBefore(InsertPos);
  853. }
  854. return true;
  855. }
  856. /// Determine if this cyclic phi is in a form that would have been generated by
  857. /// LSR. We don't care if the phi was actually expanded in this pass, as long
  858. /// as it is in a low-cost form, for example, no implied multiplication. This
  859. /// should match any patterns generated by getAddRecExprPHILiterally and
  860. /// expandAddtoGEP.
  861. bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
  862. const Loop *L) {
  863. for(Instruction *IVOper = IncV;
  864. (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
  865. /*allowScale=*/false));) {
  866. if (IVOper == PN)
  867. return true;
  868. }
  869. return false;
  870. }
  871. /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
  872. /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
  873. /// need to materialize IV increments elsewhere to handle difficult situations.
  874. Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
  875. Type *ExpandTy, Type *IntTy,
  876. bool useSubtract) {
  877. Value *IncV;
  878. // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
  879. if (ExpandTy->isPointerTy()) {
  880. PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
  881. // If the step isn't constant, don't use an implicitly scaled GEP, because
  882. // that would require a multiply inside the loop.
  883. if (!isa<ConstantInt>(StepV))
  884. GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
  885. GEPPtrTy->getAddressSpace());
  886. const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
  887. IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
  888. if (IncV->getType() != PN->getType()) {
  889. IncV = Builder.CreateBitCast(IncV, PN->getType());
  890. rememberInstruction(IncV);
  891. }
  892. } else {
  893. IncV = useSubtract ?
  894. Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
  895. Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
  896. rememberInstruction(IncV);
  897. }
  898. return IncV;
  899. }
  900. /// \brief Hoist the addrec instruction chain rooted in the loop phi above the
  901. /// position. This routine assumes that this is possible (has been checked).
  902. static void hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
  903. Instruction *Pos, PHINode *LoopPhi) {
  904. do {
  905. if (DT->dominates(InstToHoist, Pos))
  906. break;
  907. // Make sure the increment is where we want it. But don't move it
  908. // down past a potential existing post-inc user.
  909. InstToHoist->moveBefore(Pos);
  910. Pos = InstToHoist;
  911. InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
  912. } while (InstToHoist != LoopPhi);
  913. }
  914. /// \brief Check whether we can cheaply express the requested SCEV in terms of
  915. /// the available PHI SCEV by truncation and/or invertion of the step.
  916. static bool canBeCheaplyTransformed(ScalarEvolution &SE,
  917. const SCEVAddRecExpr *Phi,
  918. const SCEVAddRecExpr *Requested,
  919. bool &InvertStep) {
  920. Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
  921. Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
  922. if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
  923. return false;
  924. // Try truncate it if necessary.
  925. Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
  926. if (!Phi)
  927. return false;
  928. // Check whether truncation will help.
  929. if (Phi == Requested) {
  930. InvertStep = false;
  931. return true;
  932. }
  933. // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
  934. if (SE.getAddExpr(Requested->getStart(),
  935. SE.getNegativeSCEV(Requested)) == Phi) {
  936. InvertStep = true;
  937. return true;
  938. }
  939. return false;
  940. }
  941. static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
  942. if (!isa<IntegerType>(AR->getType()))
  943. return false;
  944. unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
  945. Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
  946. const SCEV *Step = AR->getStepRecurrence(SE);
  947. const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
  948. SE.getSignExtendExpr(AR, WideTy));
  949. const SCEV *ExtendAfterOp =
  950. SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
  951. return ExtendAfterOp == OpAfterExtend;
  952. }
  953. static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
  954. if (!isa<IntegerType>(AR->getType()))
  955. return false;
  956. unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
  957. Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
  958. const SCEV *Step = AR->getStepRecurrence(SE);
  959. const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
  960. SE.getZeroExtendExpr(AR, WideTy));
  961. const SCEV *ExtendAfterOp =
  962. SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
  963. return ExtendAfterOp == OpAfterExtend;
  964. }
  965. /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
  966. /// the base addrec, which is the addrec without any non-loop-dominating
  967. /// values, and return the PHI.
  968. PHINode *
  969. SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
  970. const Loop *L,
  971. Type *ExpandTy,
  972. Type *IntTy,
  973. Type *&TruncTy,
  974. bool &InvertStep) {
  975. assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
  976. // Reuse a previously-inserted PHI, if present.
  977. BasicBlock *LatchBlock = L->getLoopLatch();
  978. if (LatchBlock) {
  979. PHINode *AddRecPhiMatch = nullptr;
  980. Instruction *IncV = nullptr;
  981. TruncTy = nullptr;
  982. InvertStep = false;
  983. // Only try partially matching scevs that need truncation and/or
  984. // step-inversion if we know this loop is outside the current loop.
  985. bool TryNonMatchingSCEV = IVIncInsertLoop &&
  986. SE.DT->properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
  987. for (BasicBlock::iterator I = L->getHeader()->begin();
  988. PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  989. if (!SE.isSCEVable(PN->getType()))
  990. continue;
  991. const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PN));
  992. if (!PhiSCEV)
  993. continue;
  994. bool IsMatchingSCEV = PhiSCEV == Normalized;
  995. // We only handle truncation and inversion of phi recurrences for the
  996. // expanded expression if the expanded expression's loop dominates the
  997. // loop we insert to. Check now, so we can bail out early.
  998. if (!IsMatchingSCEV && !TryNonMatchingSCEV)
  999. continue;
  1000. Instruction *TempIncV =
  1001. cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
  1002. // Check whether we can reuse this PHI node.
  1003. if (LSRMode) {
  1004. if (!isExpandedAddRecExprPHI(PN, TempIncV, L))
  1005. continue;
  1006. if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
  1007. continue;
  1008. } else {
  1009. if (!isNormalAddRecExprPHI(PN, TempIncV, L))
  1010. continue;
  1011. }
  1012. // Stop if we have found an exact match SCEV.
  1013. if (IsMatchingSCEV) {
  1014. IncV = TempIncV;
  1015. TruncTy = nullptr;
  1016. InvertStep = false;
  1017. AddRecPhiMatch = PN;
  1018. break;
  1019. }
  1020. // Try whether the phi can be translated into the requested form
  1021. // (truncated and/or offset by a constant).
  1022. if ((!TruncTy || InvertStep) &&
  1023. canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
  1024. // Record the phi node. But don't stop we might find an exact match
  1025. // later.
  1026. AddRecPhiMatch = PN;
  1027. IncV = TempIncV;
  1028. TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
  1029. }
  1030. }
  1031. if (AddRecPhiMatch) {
  1032. // Potentially, move the increment. We have made sure in
  1033. // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
  1034. if (L == IVIncInsertLoop)
  1035. hoistBeforePos(SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
  1036. // Ok, the add recurrence looks usable.
  1037. // Remember this PHI, even in post-inc mode.
  1038. InsertedValues.insert(AddRecPhiMatch);
  1039. // Remember the increment.
  1040. rememberInstruction(IncV);
  1041. return AddRecPhiMatch;
  1042. }
  1043. }
  1044. // Save the original insertion point so we can restore it when we're done.
  1045. BuilderType::InsertPointGuard Guard(Builder);
  1046. // Another AddRec may need to be recursively expanded below. For example, if
  1047. // this AddRec is quadratic, the StepV may itself be an AddRec in this
  1048. // loop. Remove this loop from the PostIncLoops set before expanding such
  1049. // AddRecs. Otherwise, we cannot find a valid position for the step
  1050. // (i.e. StepV can never dominate its loop header). Ideally, we could do
  1051. // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
  1052. // so it's not worth implementing SmallPtrSet::swap.
  1053. PostIncLoopSet SavedPostIncLoops = PostIncLoops;
  1054. PostIncLoops.clear();
  1055. // Expand code for the start value.
  1056. Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
  1057. L->getHeader()->begin());
  1058. // StartV must be hoisted into L's preheader to dominate the new phi.
  1059. assert(!isa<Instruction>(StartV) ||
  1060. SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
  1061. L->getHeader()));
  1062. // Expand code for the step value. Do this before creating the PHI so that PHI
  1063. // reuse code doesn't see an incomplete PHI.
  1064. const SCEV *Step = Normalized->getStepRecurrence(SE);
  1065. // If the stride is negative, insert a sub instead of an add for the increment
  1066. // (unless it's a constant, because subtracts of constants are canonicalized
  1067. // to adds).
  1068. bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
  1069. if (useSubtract)
  1070. Step = SE.getNegativeSCEV(Step);
  1071. // Expand the step somewhere that dominates the loop header.
  1072. Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
  1073. // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
  1074. // we actually do emit an addition. It does not apply if we emit a
  1075. // subtraction.
  1076. bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
  1077. bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
  1078. // Create the PHI.
  1079. BasicBlock *Header = L->getHeader();
  1080. Builder.SetInsertPoint(Header, Header->begin());
  1081. pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
  1082. PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
  1083. Twine(IVName) + ".iv");
  1084. rememberInstruction(PN);
  1085. // Create the step instructions and populate the PHI.
  1086. for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
  1087. BasicBlock *Pred = *HPI;
  1088. // Add a start value.
  1089. if (!L->contains(Pred)) {
  1090. PN->addIncoming(StartV, Pred);
  1091. continue;
  1092. }
  1093. // Create a step value and add it to the PHI.
  1094. // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
  1095. // instructions at IVIncInsertPos.
  1096. Instruction *InsertPos = L == IVIncInsertLoop ?
  1097. IVIncInsertPos : Pred->getTerminator();
  1098. Builder.SetInsertPoint(InsertPos);
  1099. Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
  1100. if (isa<OverflowingBinaryOperator>(IncV)) {
  1101. if (IncrementIsNUW)
  1102. cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
  1103. if (IncrementIsNSW)
  1104. cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
  1105. }
  1106. PN->addIncoming(IncV, Pred);
  1107. }
  1108. // After expanding subexpressions, restore the PostIncLoops set so the caller
  1109. // can ensure that IVIncrement dominates the current uses.
  1110. PostIncLoops = SavedPostIncLoops;
  1111. // Remember this PHI, even in post-inc mode.
  1112. InsertedValues.insert(PN);
  1113. return PN;
  1114. }
  1115. Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
  1116. Type *STy = S->getType();
  1117. Type *IntTy = SE.getEffectiveSCEVType(STy);
  1118. const Loop *L = S->getLoop();
  1119. // Determine a normalized form of this expression, which is the expression
  1120. // before any post-inc adjustment is made.
  1121. const SCEVAddRecExpr *Normalized = S;
  1122. if (PostIncLoops.count(L)) {
  1123. PostIncLoopSet Loops;
  1124. Loops.insert(L);
  1125. Normalized =
  1126. cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, nullptr,
  1127. nullptr, Loops, SE, *SE.DT));
  1128. }
  1129. // Strip off any non-loop-dominating component from the addrec start.
  1130. const SCEV *Start = Normalized->getStart();
  1131. const SCEV *PostLoopOffset = nullptr;
  1132. if (!SE.properlyDominates(Start, L->getHeader())) {
  1133. PostLoopOffset = Start;
  1134. Start = SE.getConstant(Normalized->getType(), 0);
  1135. Normalized = cast<SCEVAddRecExpr>(
  1136. SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
  1137. Normalized->getLoop(),
  1138. Normalized->getNoWrapFlags(SCEV::FlagNW)));
  1139. }
  1140. // Strip off any non-loop-dominating component from the addrec step.
  1141. const SCEV *Step = Normalized->getStepRecurrence(SE);
  1142. const SCEV *PostLoopScale = nullptr;
  1143. if (!SE.dominates(Step, L->getHeader())) {
  1144. PostLoopScale = Step;
  1145. Step = SE.getConstant(Normalized->getType(), 1);
  1146. Normalized =
  1147. cast<SCEVAddRecExpr>(SE.getAddRecExpr(
  1148. Start, Step, Normalized->getLoop(),
  1149. Normalized->getNoWrapFlags(SCEV::FlagNW)));
  1150. }
  1151. // Expand the core addrec. If we need post-loop scaling, force it to
  1152. // expand to an integer type to avoid the need for additional casting.
  1153. Type *ExpandTy = PostLoopScale ? IntTy : STy;
  1154. // In some cases, we decide to reuse an existing phi node but need to truncate
  1155. // it and/or invert the step.
  1156. Type *TruncTy = nullptr;
  1157. bool InvertStep = false;
  1158. PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
  1159. TruncTy, InvertStep);
  1160. // Accommodate post-inc mode, if necessary.
  1161. Value *Result;
  1162. if (!PostIncLoops.count(L))
  1163. Result = PN;
  1164. else {
  1165. // In PostInc mode, use the post-incremented value.
  1166. BasicBlock *LatchBlock = L->getLoopLatch();
  1167. assert(LatchBlock && "PostInc mode requires a unique loop latch!");
  1168. Result = PN->getIncomingValueForBlock(LatchBlock);
  1169. // For an expansion to use the postinc form, the client must call
  1170. // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
  1171. // or dominated by IVIncInsertPos.
  1172. if (isa<Instruction>(Result)
  1173. && !SE.DT->dominates(cast<Instruction>(Result),
  1174. Builder.GetInsertPoint())) {
  1175. // The induction variable's postinc expansion does not dominate this use.
  1176. // IVUsers tries to prevent this case, so it is rare. However, it can
  1177. // happen when an IVUser outside the loop is not dominated by the latch
  1178. // block. Adjusting IVIncInsertPos before expansion begins cannot handle
  1179. // all cases. Consider a phi outide whose operand is replaced during
  1180. // expansion with the value of the postinc user. Without fundamentally
  1181. // changing the way postinc users are tracked, the only remedy is
  1182. // inserting an extra IV increment. StepV might fold into PostLoopOffset,
  1183. // but hopefully expandCodeFor handles that.
  1184. bool useSubtract =
  1185. !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
  1186. if (useSubtract)
  1187. Step = SE.getNegativeSCEV(Step);
  1188. Value *StepV;
  1189. {
  1190. // Expand the step somewhere that dominates the loop header.
  1191. BuilderType::InsertPointGuard Guard(Builder);
  1192. StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
  1193. }
  1194. Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
  1195. }
  1196. }
  1197. // We have decided to reuse an induction variable of a dominating loop. Apply
  1198. // truncation and/or invertion of the step.
  1199. if (TruncTy) {
  1200. Type *ResTy = Result->getType();
  1201. // Normalize the result type.
  1202. if (ResTy != SE.getEffectiveSCEVType(ResTy))
  1203. Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
  1204. // Truncate the result.
  1205. if (TruncTy != Result->getType()) {
  1206. Result = Builder.CreateTrunc(Result, TruncTy);
  1207. rememberInstruction(Result);
  1208. }
  1209. // Invert the result.
  1210. if (InvertStep) {
  1211. Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
  1212. Result);
  1213. rememberInstruction(Result);
  1214. }
  1215. }
  1216. // Re-apply any non-loop-dominating scale.
  1217. if (PostLoopScale) {
  1218. assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
  1219. Result = InsertNoopCastOfTo(Result, IntTy);
  1220. Result = Builder.CreateMul(Result,
  1221. expandCodeFor(PostLoopScale, IntTy));
  1222. rememberInstruction(Result);
  1223. }
  1224. // Re-apply any non-loop-dominating offset.
  1225. if (PostLoopOffset) {
  1226. if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
  1227. const SCEV *const OffsetArray[1] = { PostLoopOffset };
  1228. Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
  1229. } else {
  1230. Result = InsertNoopCastOfTo(Result, IntTy);
  1231. Result = Builder.CreateAdd(Result,
  1232. expandCodeFor(PostLoopOffset, IntTy));
  1233. rememberInstruction(Result);
  1234. }
  1235. }
  1236. return Result;
  1237. }
  1238. Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
  1239. if (!CanonicalMode) return expandAddRecExprLiterally(S);
  1240. Type *Ty = SE.getEffectiveSCEVType(S->getType());
  1241. const Loop *L = S->getLoop();
  1242. // First check for an existing canonical IV in a suitable type.
  1243. PHINode *CanonicalIV = nullptr;
  1244. if (PHINode *PN = L->getCanonicalInductionVariable())
  1245. if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
  1246. CanonicalIV = PN;
  1247. // Rewrite an AddRec in terms of the canonical induction variable, if
  1248. // its type is more narrow.
  1249. if (CanonicalIV &&
  1250. SE.getTypeSizeInBits(CanonicalIV->getType()) >
  1251. SE.getTypeSizeInBits(Ty)) {
  1252. SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
  1253. for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
  1254. NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
  1255. Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
  1256. S->getNoWrapFlags(SCEV::FlagNW)));
  1257. BasicBlock::iterator NewInsertPt =
  1258. std::next(BasicBlock::iterator(cast<Instruction>(V)));
  1259. BuilderType::InsertPointGuard Guard(Builder);
  1260. while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
  1261. isa<LandingPadInst>(NewInsertPt))
  1262. ++NewInsertPt;
  1263. V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
  1264. NewInsertPt);
  1265. return V;
  1266. }
  1267. // {X,+,F} --> X + {0,+,F}
  1268. if (!S->getStart()->isZero()) {
  1269. SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
  1270. NewOps[0] = SE.getConstant(Ty, 0);
  1271. const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
  1272. S->getNoWrapFlags(SCEV::FlagNW));
  1273. // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
  1274. // comments on expandAddToGEP for details.
  1275. const SCEV *Base = S->getStart();
  1276. const SCEV *RestArray[1] = { Rest };
  1277. // Dig into the expression to find the pointer base for a GEP.
  1278. ExposePointerBase(Base, RestArray[0], SE);
  1279. // If we found a pointer, expand the AddRec with a GEP.
  1280. if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
  1281. // Make sure the Base isn't something exotic, such as a multiplied
  1282. // or divided pointer value. In those cases, the result type isn't
  1283. // actually a pointer type.
  1284. if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
  1285. Value *StartV = expand(Base);
  1286. assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
  1287. return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
  1288. }
  1289. }
  1290. // Just do a normal add. Pre-expand the operands to suppress folding.
  1291. return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
  1292. SE.getUnknown(expand(Rest))));
  1293. }
  1294. // If we don't yet have a canonical IV, create one.
  1295. if (!CanonicalIV) {
  1296. // Create and insert the PHI node for the induction variable in the
  1297. // specified loop.
  1298. BasicBlock *Header = L->getHeader();
  1299. pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
  1300. CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
  1301. Header->begin());
  1302. rememberInstruction(CanonicalIV);
  1303. SmallSet<BasicBlock *, 4> PredSeen;
  1304. Constant *One = ConstantInt::get(Ty, 1);
  1305. for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
  1306. BasicBlock *HP = *HPI;
  1307. if (!PredSeen.insert(HP).second) {
  1308. // There must be an incoming value for each predecessor, even the
  1309. // duplicates!
  1310. CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
  1311. continue;
  1312. }
  1313. if (L->contains(HP)) {
  1314. // Insert a unit add instruction right before the terminator
  1315. // corresponding to the back-edge.
  1316. Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
  1317. "indvar.next",
  1318. HP->getTerminator());
  1319. Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
  1320. rememberInstruction(Add);
  1321. CanonicalIV->addIncoming(Add, HP);
  1322. } else {
  1323. CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
  1324. }
  1325. }
  1326. }
  1327. // {0,+,1} --> Insert a canonical induction variable into the loop!
  1328. if (S->isAffine() && S->getOperand(1)->isOne()) {
  1329. assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
  1330. "IVs with types different from the canonical IV should "
  1331. "already have been handled!");
  1332. return CanonicalIV;
  1333. }
  1334. // {0,+,F} --> {0,+,1} * F
  1335. // If this is a simple linear addrec, emit it now as a special case.
  1336. if (S->isAffine()) // {0,+,F} --> i*F
  1337. return
  1338. expand(SE.getTruncateOrNoop(
  1339. SE.getMulExpr(SE.getUnknown(CanonicalIV),
  1340. SE.getNoopOrAnyExtend(S->getOperand(1),
  1341. CanonicalIV->getType())),
  1342. Ty));
  1343. // If this is a chain of recurrences, turn it into a closed form, using the
  1344. // folders, then expandCodeFor the closed form. This allows the folders to
  1345. // simplify the expression without having to build a bunch of special code
  1346. // into this folder.
  1347. const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
  1348. // Promote S up to the canonical IV type, if the cast is foldable.
  1349. const SCEV *NewS = S;
  1350. const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
  1351. if (isa<SCEVAddRecExpr>(Ext))
  1352. NewS = Ext;
  1353. const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
  1354. //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
  1355. // Truncate the result down to the original type, if needed.
  1356. const SCEV *T = SE.getTruncateOrNoop(V, Ty);
  1357. return expand(T);
  1358. }
  1359. Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
  1360. Type *Ty = SE.getEffectiveSCEVType(S->getType());
  1361. Value *V = expandCodeFor(S->getOperand(),
  1362. SE.getEffectiveSCEVType(S->getOperand()->getType()));
  1363. Value *I = Builder.CreateTrunc(V, Ty);
  1364. rememberInstruction(I);
  1365. return I;
  1366. }
  1367. Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
  1368. Type *Ty = SE.getEffectiveSCEVType(S->getType());
  1369. Value *V = expandCodeFor(S->getOperand(),
  1370. SE.getEffectiveSCEVType(S->getOperand()->getType()));
  1371. Value *I = Builder.CreateZExt(V, Ty);
  1372. rememberInstruction(I);
  1373. return I;
  1374. }
  1375. Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
  1376. Type *Ty = SE.getEffectiveSCEVType(S->getType());
  1377. Value *V = expandCodeFor(S->getOperand(),
  1378. SE.getEffectiveSCEVType(S->getOperand()->getType()));
  1379. Value *I = Builder.CreateSExt(V, Ty);
  1380. rememberInstruction(I);
  1381. return I;
  1382. }
  1383. Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
  1384. Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
  1385. Type *Ty = LHS->getType();
  1386. for (int i = S->getNumOperands()-2; i >= 0; --i) {
  1387. // In the case of mixed integer and pointer types, do the
  1388. // rest of the comparisons as integer.
  1389. if (S->getOperand(i)->getType() != Ty) {
  1390. Ty = SE.getEffectiveSCEVType(Ty);
  1391. LHS = InsertNoopCastOfTo(LHS, Ty);
  1392. }
  1393. Value *RHS = expandCodeFor(S->getOperand(i), Ty);
  1394. Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
  1395. rememberInstruction(ICmp);
  1396. Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
  1397. rememberInstruction(Sel);
  1398. LHS = Sel;
  1399. }
  1400. // In the case of mixed integer and pointer types, cast the
  1401. // final result back to the pointer type.
  1402. if (LHS->getType() != S->getType())
  1403. LHS = InsertNoopCastOfTo(LHS, S->getType());
  1404. return LHS;
  1405. }
  1406. Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
  1407. Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
  1408. Type *Ty = LHS->getType();
  1409. for (int i = S->getNumOperands()-2; i >= 0; --i) {
  1410. // In the case of mixed integer and pointer types, do the
  1411. // rest of the comparisons as integer.
  1412. if (S->getOperand(i)->getType() != Ty) {
  1413. Ty = SE.getEffectiveSCEVType(Ty);
  1414. LHS = InsertNoopCastOfTo(LHS, Ty);
  1415. }
  1416. Value *RHS = expandCodeFor(S->getOperand(i), Ty);
  1417. Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
  1418. rememberInstruction(ICmp);
  1419. Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
  1420. rememberInstruction(Sel);
  1421. LHS = Sel;
  1422. }
  1423. // In the case of mixed integer and pointer types, cast the
  1424. // final result back to the pointer type.
  1425. if (LHS->getType() != S->getType())
  1426. LHS = InsertNoopCastOfTo(LHS, S->getType());
  1427. return LHS;
  1428. }
  1429. Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
  1430. Instruction *IP) {
  1431. Builder.SetInsertPoint(IP->getParent(), IP);
  1432. return expandCodeFor(SH, Ty);
  1433. }
  1434. Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
  1435. // Expand the code for this SCEV.
  1436. Value *V = expand(SH);
  1437. if (Ty) {
  1438. assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
  1439. "non-trivial casts should be done with the SCEVs directly!");
  1440. V = InsertNoopCastOfTo(V, Ty);
  1441. }
  1442. return V;
  1443. }
  1444. Value *SCEVExpander::expand(const SCEV *S) {
  1445. // Compute an insertion point for this SCEV object. Hoist the instructions
  1446. // as far out in the loop nest as possible.
  1447. Instruction *InsertPt = Builder.GetInsertPoint();
  1448. for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
  1449. L = L->getParentLoop())
  1450. if (SE.isLoopInvariant(S, L)) {
  1451. if (!L) break;
  1452. if (BasicBlock *Preheader = L->getLoopPreheader())
  1453. InsertPt = Preheader->getTerminator();
  1454. else {
  1455. // LSR sets the insertion point for AddRec start/step values to the
  1456. // block start to simplify value reuse, even though it's an invalid
  1457. // position. SCEVExpander must correct for this in all cases.
  1458. InsertPt = L->getHeader()->getFirstInsertionPt();
  1459. }
  1460. } else {
  1461. // If the SCEV is computable at this level, insert it into the header
  1462. // after the PHIs (and after any other instructions that we've inserted
  1463. // there) so that it is guaranteed to dominate any user inside the loop.
  1464. if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
  1465. InsertPt = L->getHeader()->getFirstInsertionPt();
  1466. while (InsertPt != Builder.GetInsertPoint()
  1467. && (isInsertedInstruction(InsertPt)
  1468. || isa<DbgInfoIntrinsic>(InsertPt))) {
  1469. InsertPt = std::next(BasicBlock::iterator(InsertPt));
  1470. }
  1471. break;
  1472. }
  1473. // Check to see if we already expanded this here.
  1474. std::map<std::pair<const SCEV *, Instruction *>, TrackingVH<Value> >::iterator
  1475. I = InsertedExpressions.find(std::make_pair(S, InsertPt));
  1476. if (I != InsertedExpressions.end())
  1477. return I->second;
  1478. BuilderType::InsertPointGuard Guard(Builder);
  1479. Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
  1480. // Expand the expression into instructions.
  1481. Value *V = visit(S);
  1482. // Remember the expanded value for this SCEV at this location.
  1483. //
  1484. // This is independent of PostIncLoops. The mapped value simply materializes
  1485. // the expression at this insertion point. If the mapped value happened to be
  1486. // a postinc expansion, it could be reused by a non-postinc user, but only if
  1487. // its insertion point was already at the head of the loop.
  1488. InsertedExpressions[std::make_pair(S, InsertPt)] = V;
  1489. return V;
  1490. }
  1491. void SCEVExpander::rememberInstruction(Value *I) {
  1492. if (!PostIncLoops.empty())
  1493. InsertedPostIncValues.insert(I);
  1494. else
  1495. InsertedValues.insert(I);
  1496. }
  1497. /// getOrInsertCanonicalInductionVariable - This method returns the
  1498. /// canonical induction variable of the specified type for the specified
  1499. /// loop (inserting one if there is none). A canonical induction variable
  1500. /// starts at zero and steps by one on each iteration.
  1501. PHINode *
  1502. SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
  1503. Type *Ty) {
  1504. assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
  1505. // Build a SCEV for {0,+,1}<L>.
  1506. // Conservatively use FlagAnyWrap for now.
  1507. const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
  1508. SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
  1509. // Emit code for it.
  1510. BuilderType::InsertPointGuard Guard(Builder);
  1511. PHINode *V = cast<PHINode>(expandCodeFor(H, nullptr,
  1512. L->getHeader()->begin()));
  1513. return V;
  1514. }
  1515. /// replaceCongruentIVs - Check for congruent phis in this loop header and
  1516. /// replace them with their most canonical representative. Return the number of
  1517. /// phis eliminated.
  1518. ///
  1519. /// This does not depend on any SCEVExpander state but should be used in
  1520. /// the same context that SCEVExpander is used.
  1521. unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
  1522. SmallVectorImpl<WeakVH> &DeadInsts,
  1523. const TargetTransformInfo *TTI) {
  1524. // Find integer phis in order of increasing width.
  1525. SmallVector<PHINode*, 8> Phis;
  1526. for (BasicBlock::iterator I = L->getHeader()->begin();
  1527. PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
  1528. Phis.push_back(Phi);
  1529. }
  1530. if (TTI)
  1531. std::sort(Phis.begin(), Phis.end(), [](Value *LHS, Value *RHS) {
  1532. // Put pointers at the back and make sure pointer < pointer = false.
  1533. if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
  1534. return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
  1535. return RHS->getType()->getPrimitiveSizeInBits() <
  1536. LHS->getType()->getPrimitiveSizeInBits();
  1537. });
  1538. unsigned NumElim = 0;
  1539. DenseMap<const SCEV *, PHINode *> ExprToIVMap;
  1540. // Process phis from wide to narrow. Map wide phis to their truncation
  1541. // so narrow phis can reuse them.
  1542. for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
  1543. PEnd = Phis.end(); PIter != PEnd; ++PIter) {
  1544. PHINode *Phi = *PIter;
  1545. // Fold constant phis. They may be congruent to other constant phis and
  1546. // would confuse the logic below that expects proper IVs.
  1547. if (Value *V = SimplifyInstruction(Phi, DL, SE.TLI, SE.DT, SE.AC)) {
  1548. Phi->replaceAllUsesWith(V);
  1549. DeadInsts.emplace_back(Phi);
  1550. ++NumElim;
  1551. DEBUG_WITH_TYPE(DebugType, dbgs()
  1552. << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
  1553. continue;
  1554. }
  1555. if (!SE.isSCEVable(Phi->getType()))
  1556. continue;
  1557. PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
  1558. if (!OrigPhiRef) {
  1559. OrigPhiRef = Phi;
  1560. if (Phi->getType()->isIntegerTy() && TTI
  1561. && TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
  1562. // This phi can be freely truncated to the narrowest phi type. Map the
  1563. // truncated expression to it so it will be reused for narrow types.
  1564. const SCEV *TruncExpr =
  1565. SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
  1566. ExprToIVMap[TruncExpr] = Phi;
  1567. }
  1568. continue;
  1569. }
  1570. // Replacing a pointer phi with an integer phi or vice-versa doesn't make
  1571. // sense.
  1572. if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
  1573. continue;
  1574. if (BasicBlock *LatchBlock = L->getLoopLatch()) {
  1575. Instruction *OrigInc =
  1576. cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
  1577. Instruction *IsomorphicInc =
  1578. cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
  1579. // If this phi has the same width but is more canonical, replace the
  1580. // original with it. As part of the "more canonical" determination,
  1581. // respect a prior decision to use an IV chain.
  1582. if (OrigPhiRef->getType() == Phi->getType()
  1583. && !(ChainedPhis.count(Phi)
  1584. || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
  1585. && (ChainedPhis.count(Phi)
  1586. || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
  1587. std::swap(OrigPhiRef, Phi);
  1588. std::swap(OrigInc, IsomorphicInc);
  1589. }
  1590. // Replacing the congruent phi is sufficient because acyclic redundancy
  1591. // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
  1592. // that a phi is congruent, it's often the head of an IV user cycle that
  1593. // is isomorphic with the original phi. It's worth eagerly cleaning up the
  1594. // common case of a single IV increment so that DeleteDeadPHIs can remove
  1595. // cycles that had postinc uses.
  1596. const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
  1597. IsomorphicInc->getType());
  1598. if (OrigInc != IsomorphicInc
  1599. && TruncExpr == SE.getSCEV(IsomorphicInc)
  1600. && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
  1601. || hoistIVInc(OrigInc, IsomorphicInc))) {
  1602. DEBUG_WITH_TYPE(DebugType, dbgs()
  1603. << "INDVARS: Eliminated congruent iv.inc: "
  1604. << *IsomorphicInc << '\n');
  1605. Value *NewInc = OrigInc;
  1606. if (OrigInc->getType() != IsomorphicInc->getType()) {
  1607. Instruction *IP = nullptr;
  1608. if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
  1609. IP = PN->getParent()->getFirstInsertionPt();
  1610. else
  1611. IP = OrigInc->getNextNode();
  1612. IRBuilder<> Builder(IP);
  1613. Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
  1614. NewInc = Builder.
  1615. CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
  1616. }
  1617. IsomorphicInc->replaceAllUsesWith(NewInc);
  1618. DeadInsts.emplace_back(IsomorphicInc);
  1619. }
  1620. }
  1621. DEBUG_WITH_TYPE(DebugType, dbgs()
  1622. << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
  1623. ++NumElim;
  1624. Value *NewIV = OrigPhiRef;
  1625. if (OrigPhiRef->getType() != Phi->getType()) {
  1626. IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
  1627. Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
  1628. NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
  1629. }
  1630. Phi->replaceAllUsesWith(NewIV);
  1631. DeadInsts.emplace_back(Phi);
  1632. }
  1633. return NumElim;
  1634. }
  1635. bool SCEVExpander::isHighCostExpansionHelper(
  1636. const SCEV *S, Loop *L, SmallPtrSetImpl<const SCEV *> &Processed) {
  1637. // Zero/One operand expressions
  1638. switch (S->getSCEVType()) {
  1639. case scUnknown:
  1640. case scConstant:
  1641. return false;
  1642. case scTruncate:
  1643. return isHighCostExpansionHelper(cast<SCEVTruncateExpr>(S)->getOperand(), L,
  1644. Processed);
  1645. case scZeroExtend:
  1646. return isHighCostExpansionHelper(cast<SCEVZeroExtendExpr>(S)->getOperand(),
  1647. L, Processed);
  1648. case scSignExtend:
  1649. return isHighCostExpansionHelper(cast<SCEVSignExtendExpr>(S)->getOperand(),
  1650. L, Processed);
  1651. }
  1652. if (!Processed.insert(S).second)
  1653. return false;
  1654. if (auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) {
  1655. // If the divisor is a power of two and the SCEV type fits in a native
  1656. // integer, consider the divison cheap irrespective of whether it occurs in
  1657. // the user code since it can be lowered into a right shift.
  1658. if (auto *SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS()))
  1659. if (SC->getValue()->getValue().isPowerOf2()) {
  1660. const DataLayout &DL =
  1661. L->getHeader()->getParent()->getParent()->getDataLayout();
  1662. unsigned Width = cast<IntegerType>(UDivExpr->getType())->getBitWidth();
  1663. return DL.isIllegalInteger(Width);
  1664. }
  1665. // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
  1666. // HowManyLessThans produced to compute a precise expression, rather than a
  1667. // UDiv from the user's code. If we can't find a UDiv in the code with some
  1668. // simple searching, assume the former consider UDivExpr expensive to
  1669. // compute.
  1670. BasicBlock *ExitingBB = L->getExitingBlock();
  1671. if (!ExitingBB)
  1672. return true;
  1673. BranchInst *ExitingBI = dyn_cast<BranchInst>(ExitingBB->getTerminator());
  1674. if (!ExitingBI || !ExitingBI->isConditional())
  1675. return true;
  1676. ICmpInst *OrigCond = dyn_cast<ICmpInst>(ExitingBI->getCondition());
  1677. if (!OrigCond)
  1678. return true;
  1679. const SCEV *RHS = SE.getSCEV(OrigCond->getOperand(1));
  1680. RHS = SE.getMinusSCEV(RHS, SE.getConstant(RHS->getType(), 1));
  1681. if (RHS != S) {
  1682. const SCEV *LHS = SE.getSCEV(OrigCond->getOperand(0));
  1683. LHS = SE.getMinusSCEV(LHS, SE.getConstant(LHS->getType(), 1));
  1684. if (LHS != S)
  1685. return true;
  1686. }
  1687. }
  1688. // HowManyLessThans uses a Max expression whenever the loop is not guarded by
  1689. // the exit condition.
  1690. if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
  1691. return true;
  1692. // Recurse past nary expressions, which commonly occur in the
  1693. // BackedgeTakenCount. They may already exist in program code, and if not,
  1694. // they are not too expensive rematerialize.
  1695. if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(S)) {
  1696. for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
  1697. I != E; ++I) {
  1698. if (isHighCostExpansionHelper(*I, L, Processed))
  1699. return true;
  1700. }
  1701. }
  1702. // If we haven't recognized an expensive SCEV pattern, assume it's an
  1703. // expression produced by program code.
  1704. return false;
  1705. }
  1706. namespace {
  1707. // Search for a SCEV subexpression that is not safe to expand. Any expression
  1708. // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
  1709. // UDiv expressions. We don't know if the UDiv is derived from an IR divide
  1710. // instruction, but the important thing is that we prove the denominator is
  1711. // nonzero before expansion.
  1712. //
  1713. // IVUsers already checks that IV-derived expressions are safe. So this check is
  1714. // only needed when the expression includes some subexpression that is not IV
  1715. // derived.
  1716. //
  1717. // Currently, we only allow division by a nonzero constant here. If this is
  1718. // inadequate, we could easily allow division by SCEVUnknown by using
  1719. // ValueTracking to check isKnownNonZero().
  1720. //
  1721. // We cannot generally expand recurrences unless the step dominates the loop
  1722. // header. The expander handles the special case of affine recurrences by
  1723. // scaling the recurrence outside the loop, but this technique isn't generally
  1724. // applicable. Expanding a nested recurrence outside a loop requires computing
  1725. // binomial coefficients. This could be done, but the recurrence has to be in a
  1726. // perfectly reduced form, which can't be guaranteed.
  1727. struct SCEVFindUnsafe {
  1728. ScalarEvolution &SE;
  1729. bool IsUnsafe;
  1730. SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
  1731. bool follow(const SCEV *S) {
  1732. if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
  1733. const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
  1734. if (!SC || SC->getValue()->isZero()) {
  1735. IsUnsafe = true;
  1736. return false;
  1737. }
  1738. }
  1739. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
  1740. const SCEV *Step = AR->getStepRecurrence(SE);
  1741. if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
  1742. IsUnsafe = true;
  1743. return false;
  1744. }
  1745. }
  1746. return true;
  1747. }
  1748. bool isDone() const { return IsUnsafe; }
  1749. };
  1750. }
  1751. namespace llvm {
  1752. bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
  1753. SCEVFindUnsafe Search(SE);
  1754. visitAll(S, Search);
  1755. return !Search.IsUnsafe;
  1756. }
  1757. }