ScalarEvolutionExpander.cpp 91 KB

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