InductiveRangeCheckElimination.cpp 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003
  1. //===- InductiveRangeCheckElimination.cpp - -------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // The InductiveRangeCheckElimination pass splits a loop's iteration space into
  10. // three disjoint ranges. It does that in a way such that the loop running in
  11. // the middle loop provably does not need range checks. As an example, it will
  12. // convert
  13. //
  14. // len = < known positive >
  15. // for (i = 0; i < n; i++) {
  16. // if (0 <= i && i < len) {
  17. // do_something();
  18. // } else {
  19. // throw_out_of_bounds();
  20. // }
  21. // }
  22. //
  23. // to
  24. //
  25. // len = < known positive >
  26. // limit = smin(n, len)
  27. // // no first segment
  28. // for (i = 0; i < limit; i++) {
  29. // if (0 <= i && i < len) { // this check is fully redundant
  30. // do_something();
  31. // } else {
  32. // throw_out_of_bounds();
  33. // }
  34. // }
  35. // for (i = limit; i < n; i++) {
  36. // if (0 <= i && i < len) {
  37. // do_something();
  38. // } else {
  39. // throw_out_of_bounds();
  40. // }
  41. // }
  42. //
  43. //===----------------------------------------------------------------------===//
  44. #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
  45. #include "llvm/ADT/APInt.h"
  46. #include "llvm/ADT/ArrayRef.h"
  47. #include "llvm/ADT/PriorityWorklist.h"
  48. #include "llvm/ADT/SmallPtrSet.h"
  49. #include "llvm/ADT/SmallVector.h"
  50. #include "llvm/ADT/StringRef.h"
  51. #include "llvm/ADT/Twine.h"
  52. #include "llvm/Analysis/BlockFrequencyInfo.h"
  53. #include "llvm/Analysis/BranchProbabilityInfo.h"
  54. #include "llvm/Analysis/LoopAnalysisManager.h"
  55. #include "llvm/Analysis/LoopInfo.h"
  56. #include "llvm/Analysis/ScalarEvolution.h"
  57. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  58. #include "llvm/IR/BasicBlock.h"
  59. #include "llvm/IR/CFG.h"
  60. #include "llvm/IR/Constants.h"
  61. #include "llvm/IR/DerivedTypes.h"
  62. #include "llvm/IR/Dominators.h"
  63. #include "llvm/IR/Function.h"
  64. #include "llvm/IR/IRBuilder.h"
  65. #include "llvm/IR/InstrTypes.h"
  66. #include "llvm/IR/Instructions.h"
  67. #include "llvm/IR/Metadata.h"
  68. #include "llvm/IR/Module.h"
  69. #include "llvm/IR/PatternMatch.h"
  70. #include "llvm/IR/Type.h"
  71. #include "llvm/IR/Use.h"
  72. #include "llvm/IR/User.h"
  73. #include "llvm/IR/Value.h"
  74. #include "llvm/InitializePasses.h"
  75. #include "llvm/Pass.h"
  76. #include "llvm/Support/BranchProbability.h"
  77. #include "llvm/Support/Casting.h"
  78. #include "llvm/Support/CommandLine.h"
  79. #include "llvm/Support/Compiler.h"
  80. #include "llvm/Support/Debug.h"
  81. #include "llvm/Support/ErrorHandling.h"
  82. #include "llvm/Support/raw_ostream.h"
  83. #include "llvm/Transforms/Scalar.h"
  84. #include "llvm/Transforms/Utils/Cloning.h"
  85. #include "llvm/Transforms/Utils/LoopSimplify.h"
  86. #include "llvm/Transforms/Utils/LoopUtils.h"
  87. #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
  88. #include "llvm/Transforms/Utils/ValueMapper.h"
  89. #include <algorithm>
  90. #include <cassert>
  91. #include <iterator>
  92. #include <limits>
  93. #include <optional>
  94. #include <utility>
  95. #include <vector>
  96. using namespace llvm;
  97. using namespace llvm::PatternMatch;
  98. static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
  99. cl::init(64));
  100. static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
  101. cl::init(false));
  102. static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
  103. cl::init(false));
  104. static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
  105. cl::Hidden, cl::init(false));
  106. static cl::opt<unsigned> MinRuntimeIterations("irce-min-runtime-iterations",
  107. cl::Hidden, cl::init(10));
  108. static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch",
  109. cl::Hidden, cl::init(true));
  110. static cl::opt<bool> AllowNarrowLatchCondition(
  111. "irce-allow-narrow-latch", cl::Hidden, cl::init(true),
  112. cl::desc("If set to true, IRCE may eliminate wide range checks in loops "
  113. "with narrow latch condition."));
  114. static const char *ClonedLoopTag = "irce.loop.clone";
  115. #define DEBUG_TYPE "irce"
  116. namespace {
  117. /// An inductive range check is conditional branch in a loop with
  118. ///
  119. /// 1. a very cold successor (i.e. the branch jumps to that successor very
  120. /// rarely)
  121. ///
  122. /// and
  123. ///
  124. /// 2. a condition that is provably true for some contiguous range of values
  125. /// taken by the containing loop's induction variable.
  126. ///
  127. class InductiveRangeCheck {
  128. const SCEV *Begin = nullptr;
  129. const SCEV *Step = nullptr;
  130. const SCEV *End = nullptr;
  131. Use *CheckUse = nullptr;
  132. static bool parseRangeCheckICmp(Loop *L, ICmpInst *ICI, ScalarEvolution &SE,
  133. Value *&Index, Value *&Length,
  134. bool &IsSigned);
  135. static void
  136. extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
  137. SmallVectorImpl<InductiveRangeCheck> &Checks,
  138. SmallPtrSetImpl<Value *> &Visited);
  139. public:
  140. const SCEV *getBegin() const { return Begin; }
  141. const SCEV *getStep() const { return Step; }
  142. const SCEV *getEnd() const { return End; }
  143. void print(raw_ostream &OS) const {
  144. OS << "InductiveRangeCheck:\n";
  145. OS << " Begin: ";
  146. Begin->print(OS);
  147. OS << " Step: ";
  148. Step->print(OS);
  149. OS << " End: ";
  150. End->print(OS);
  151. OS << "\n CheckUse: ";
  152. getCheckUse()->getUser()->print(OS);
  153. OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
  154. }
  155. LLVM_DUMP_METHOD
  156. void dump() {
  157. print(dbgs());
  158. }
  159. Use *getCheckUse() const { return CheckUse; }
  160. /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
  161. /// R.getEnd() le R.getBegin(), then R denotes the empty range.
  162. class Range {
  163. const SCEV *Begin;
  164. const SCEV *End;
  165. public:
  166. Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
  167. assert(Begin->getType() == End->getType() && "ill-typed range!");
  168. }
  169. Type *getType() const { return Begin->getType(); }
  170. const SCEV *getBegin() const { return Begin; }
  171. const SCEV *getEnd() const { return End; }
  172. bool isEmpty(ScalarEvolution &SE, bool IsSigned) const {
  173. if (Begin == End)
  174. return true;
  175. if (IsSigned)
  176. return SE.isKnownPredicate(ICmpInst::ICMP_SGE, Begin, End);
  177. else
  178. return SE.isKnownPredicate(ICmpInst::ICMP_UGE, Begin, End);
  179. }
  180. };
  181. /// This is the value the condition of the branch needs to evaluate to for the
  182. /// branch to take the hot successor (see (1) above).
  183. bool getPassingDirection() { return true; }
  184. /// Computes a range for the induction variable (IndVar) in which the range
  185. /// check is redundant and can be constant-folded away. The induction
  186. /// variable is not required to be the canonical {0,+,1} induction variable.
  187. std::optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
  188. const SCEVAddRecExpr *IndVar,
  189. bool IsLatchSigned) const;
  190. /// Parse out a set of inductive range checks from \p BI and append them to \p
  191. /// Checks.
  192. ///
  193. /// NB! There may be conditions feeding into \p BI that aren't inductive range
  194. /// checks, and hence don't end up in \p Checks.
  195. static void
  196. extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
  197. BranchProbabilityInfo *BPI,
  198. SmallVectorImpl<InductiveRangeCheck> &Checks);
  199. };
  200. struct LoopStructure;
  201. class InductiveRangeCheckElimination {
  202. ScalarEvolution &SE;
  203. BranchProbabilityInfo *BPI;
  204. DominatorTree &DT;
  205. LoopInfo &LI;
  206. using GetBFIFunc =
  207. std::optional<llvm::function_ref<llvm::BlockFrequencyInfo &()>>;
  208. GetBFIFunc GetBFI;
  209. // Returns true if it is profitable to do a transform basing on estimation of
  210. // number of iterations.
  211. bool isProfitableToTransform(const Loop &L, LoopStructure &LS);
  212. public:
  213. InductiveRangeCheckElimination(ScalarEvolution &SE,
  214. BranchProbabilityInfo *BPI, DominatorTree &DT,
  215. LoopInfo &LI, GetBFIFunc GetBFI = std::nullopt)
  216. : SE(SE), BPI(BPI), DT(DT), LI(LI), GetBFI(GetBFI) {}
  217. bool run(Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop);
  218. };
  219. class IRCELegacyPass : public FunctionPass {
  220. public:
  221. static char ID;
  222. IRCELegacyPass() : FunctionPass(ID) {
  223. initializeIRCELegacyPassPass(*PassRegistry::getPassRegistry());
  224. }
  225. void getAnalysisUsage(AnalysisUsage &AU) const override {
  226. AU.addRequired<BranchProbabilityInfoWrapperPass>();
  227. AU.addRequired<DominatorTreeWrapperPass>();
  228. AU.addPreserved<DominatorTreeWrapperPass>();
  229. AU.addRequired<LoopInfoWrapperPass>();
  230. AU.addPreserved<LoopInfoWrapperPass>();
  231. AU.addRequired<ScalarEvolutionWrapperPass>();
  232. AU.addPreserved<ScalarEvolutionWrapperPass>();
  233. }
  234. bool runOnFunction(Function &F) override;
  235. };
  236. } // end anonymous namespace
  237. char IRCELegacyPass::ID = 0;
  238. INITIALIZE_PASS_BEGIN(IRCELegacyPass, "irce",
  239. "Inductive range check elimination", false, false)
  240. INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
  241. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  242. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  243. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  244. INITIALIZE_PASS_END(IRCELegacyPass, "irce", "Inductive range check elimination",
  245. false, false)
  246. /// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
  247. /// be interpreted as a range check, return false and set `Index` and `Length`
  248. /// to `nullptr`. Otherwise set `Index` to the value being range checked, and
  249. /// set `Length` to the upper limit `Index` is being range checked.
  250. bool
  251. InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
  252. ScalarEvolution &SE, Value *&Index,
  253. Value *&Length, bool &IsSigned) {
  254. auto IsLoopInvariant = [&SE, L](Value *V) {
  255. return SE.isLoopInvariant(SE.getSCEV(V), L);
  256. };
  257. ICmpInst::Predicate Pred = ICI->getPredicate();
  258. Value *LHS = ICI->getOperand(0);
  259. Value *RHS = ICI->getOperand(1);
  260. switch (Pred) {
  261. default:
  262. return false;
  263. case ICmpInst::ICMP_SLE:
  264. std::swap(LHS, RHS);
  265. [[fallthrough]];
  266. case ICmpInst::ICMP_SGE:
  267. IsSigned = true;
  268. if (match(RHS, m_ConstantInt<0>())) {
  269. Index = LHS;
  270. return true; // Lower.
  271. }
  272. return false;
  273. case ICmpInst::ICMP_SLT:
  274. std::swap(LHS, RHS);
  275. [[fallthrough]];
  276. case ICmpInst::ICMP_SGT:
  277. IsSigned = true;
  278. if (match(RHS, m_ConstantInt<-1>())) {
  279. Index = LHS;
  280. return true; // Lower.
  281. }
  282. if (IsLoopInvariant(LHS)) {
  283. Index = RHS;
  284. Length = LHS;
  285. return true; // Upper.
  286. }
  287. return false;
  288. case ICmpInst::ICMP_ULT:
  289. std::swap(LHS, RHS);
  290. [[fallthrough]];
  291. case ICmpInst::ICMP_UGT:
  292. IsSigned = false;
  293. if (IsLoopInvariant(LHS)) {
  294. Index = RHS;
  295. Length = LHS;
  296. return true; // Both lower and upper.
  297. }
  298. return false;
  299. }
  300. llvm_unreachable("default clause returns!");
  301. }
  302. void InductiveRangeCheck::extractRangeChecksFromCond(
  303. Loop *L, ScalarEvolution &SE, Use &ConditionUse,
  304. SmallVectorImpl<InductiveRangeCheck> &Checks,
  305. SmallPtrSetImpl<Value *> &Visited) {
  306. Value *Condition = ConditionUse.get();
  307. if (!Visited.insert(Condition).second)
  308. return;
  309. // TODO: Do the same for OR, XOR, NOT etc?
  310. if (match(Condition, m_LogicalAnd(m_Value(), m_Value()))) {
  311. extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
  312. Checks, Visited);
  313. extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
  314. Checks, Visited);
  315. return;
  316. }
  317. ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
  318. if (!ICI)
  319. return;
  320. Value *Length = nullptr, *Index;
  321. bool IsSigned;
  322. if (!parseRangeCheckICmp(L, ICI, SE, Index, Length, IsSigned))
  323. return;
  324. const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
  325. bool IsAffineIndex =
  326. IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
  327. if (!IsAffineIndex)
  328. return;
  329. const SCEV *End = nullptr;
  330. // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
  331. // We can potentially do much better here.
  332. if (Length)
  333. End = SE.getSCEV(Length);
  334. else {
  335. // So far we can only reach this point for Signed range check. This may
  336. // change in future. In this case we will need to pick Unsigned max for the
  337. // unsigned range check.
  338. unsigned BitWidth = cast<IntegerType>(IndexAddRec->getType())->getBitWidth();
  339. const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
  340. End = SIntMax;
  341. }
  342. InductiveRangeCheck IRC;
  343. IRC.End = End;
  344. IRC.Begin = IndexAddRec->getStart();
  345. IRC.Step = IndexAddRec->getStepRecurrence(SE);
  346. IRC.CheckUse = &ConditionUse;
  347. Checks.push_back(IRC);
  348. }
  349. void InductiveRangeCheck::extractRangeChecksFromBranch(
  350. BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo *BPI,
  351. SmallVectorImpl<InductiveRangeCheck> &Checks) {
  352. if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
  353. return;
  354. BranchProbability LikelyTaken(15, 16);
  355. if (!SkipProfitabilityChecks && BPI &&
  356. BPI->getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
  357. return;
  358. SmallPtrSet<Value *, 8> Visited;
  359. InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
  360. Checks, Visited);
  361. }
  362. // Add metadata to the loop L to disable loop optimizations. Callers need to
  363. // confirm that optimizing loop L is not beneficial.
  364. static void DisableAllLoopOptsOnLoop(Loop &L) {
  365. // We do not care about any existing loopID related metadata for L, since we
  366. // are setting all loop metadata to false.
  367. LLVMContext &Context = L.getHeader()->getContext();
  368. // Reserve first location for self reference to the LoopID metadata node.
  369. MDNode *Dummy = MDNode::get(Context, {});
  370. MDNode *DisableUnroll = MDNode::get(
  371. Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
  372. Metadata *FalseVal =
  373. ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
  374. MDNode *DisableVectorize = MDNode::get(
  375. Context,
  376. {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
  377. MDNode *DisableLICMVersioning = MDNode::get(
  378. Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
  379. MDNode *DisableDistribution= MDNode::get(
  380. Context,
  381. {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal});
  382. MDNode *NewLoopID =
  383. MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
  384. DisableLICMVersioning, DisableDistribution});
  385. // Set operand 0 to refer to the loop id itself.
  386. NewLoopID->replaceOperandWith(0, NewLoopID);
  387. L.setLoopID(NewLoopID);
  388. }
  389. namespace {
  390. // Keeps track of the structure of a loop. This is similar to llvm::Loop,
  391. // except that it is more lightweight and can track the state of a loop through
  392. // changing and potentially invalid IR. This structure also formalizes the
  393. // kinds of loops we can deal with -- ones that have a single latch that is also
  394. // an exiting block *and* have a canonical induction variable.
  395. struct LoopStructure {
  396. const char *Tag = "";
  397. BasicBlock *Header = nullptr;
  398. BasicBlock *Latch = nullptr;
  399. // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
  400. // successor is `LatchExit', the exit block of the loop.
  401. BranchInst *LatchBr = nullptr;
  402. BasicBlock *LatchExit = nullptr;
  403. unsigned LatchBrExitIdx = std::numeric_limits<unsigned>::max();
  404. // The loop represented by this instance of LoopStructure is semantically
  405. // equivalent to:
  406. //
  407. // intN_ty inc = IndVarIncreasing ? 1 : -1;
  408. // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT;
  409. //
  410. // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase)
  411. // ... body ...
  412. Value *IndVarBase = nullptr;
  413. Value *IndVarStart = nullptr;
  414. Value *IndVarStep = nullptr;
  415. Value *LoopExitAt = nullptr;
  416. bool IndVarIncreasing = false;
  417. bool IsSignedPredicate = true;
  418. LoopStructure() = default;
  419. template <typename M> LoopStructure map(M Map) const {
  420. LoopStructure Result;
  421. Result.Tag = Tag;
  422. Result.Header = cast<BasicBlock>(Map(Header));
  423. Result.Latch = cast<BasicBlock>(Map(Latch));
  424. Result.LatchBr = cast<BranchInst>(Map(LatchBr));
  425. Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
  426. Result.LatchBrExitIdx = LatchBrExitIdx;
  427. Result.IndVarBase = Map(IndVarBase);
  428. Result.IndVarStart = Map(IndVarStart);
  429. Result.IndVarStep = Map(IndVarStep);
  430. Result.LoopExitAt = Map(LoopExitAt);
  431. Result.IndVarIncreasing = IndVarIncreasing;
  432. Result.IsSignedPredicate = IsSignedPredicate;
  433. return Result;
  434. }
  435. static std::optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
  436. Loop &, const char *&);
  437. };
  438. /// This class is used to constrain loops to run within a given iteration space.
  439. /// The algorithm this class implements is given a Loop and a range [Begin,
  440. /// End). The algorithm then tries to break out a "main loop" out of the loop
  441. /// it is given in a way that the "main loop" runs with the induction variable
  442. /// in a subset of [Begin, End). The algorithm emits appropriate pre and post
  443. /// loops to run any remaining iterations. The pre loop runs any iterations in
  444. /// which the induction variable is < Begin, and the post loop runs any
  445. /// iterations in which the induction variable is >= End.
  446. class LoopConstrainer {
  447. // The representation of a clone of the original loop we started out with.
  448. struct ClonedLoop {
  449. // The cloned blocks
  450. std::vector<BasicBlock *> Blocks;
  451. // `Map` maps values in the clonee into values in the cloned version
  452. ValueToValueMapTy Map;
  453. // An instance of `LoopStructure` for the cloned loop
  454. LoopStructure Structure;
  455. };
  456. // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
  457. // more details on what these fields mean.
  458. struct RewrittenRangeInfo {
  459. BasicBlock *PseudoExit = nullptr;
  460. BasicBlock *ExitSelector = nullptr;
  461. std::vector<PHINode *> PHIValuesAtPseudoExit;
  462. PHINode *IndVarEnd = nullptr;
  463. RewrittenRangeInfo() = default;
  464. };
  465. // Calculated subranges we restrict the iteration space of the main loop to.
  466. // See the implementation of `calculateSubRanges' for more details on how
  467. // these fields are computed. `LowLimit` is std::nullopt if there is no
  468. // restriction on low end of the restricted iteration space of the main loop.
  469. // `HighLimit` is std::nullopt if there is no restriction on high end of the
  470. // restricted iteration space of the main loop.
  471. struct SubRanges {
  472. std::optional<const SCEV *> LowLimit;
  473. std::optional<const SCEV *> HighLimit;
  474. };
  475. // Compute a safe set of limits for the main loop to run in -- effectively the
  476. // intersection of `Range' and the iteration space of the original loop.
  477. // Return std::nullopt if unable to compute the set of subranges.
  478. std::optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const;
  479. // Clone `OriginalLoop' and return the result in CLResult. The IR after
  480. // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
  481. // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
  482. // but there is no such edge.
  483. void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
  484. // Create the appropriate loop structure needed to describe a cloned copy of
  485. // `Original`. The clone is described by `VM`.
  486. Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
  487. ValueToValueMapTy &VM, bool IsSubloop);
  488. // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
  489. // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
  490. // iteration space is not changed. `ExitLoopAt' is assumed to be slt
  491. // `OriginalHeaderCount'.
  492. //
  493. // If there are iterations left to execute, control is made to jump to
  494. // `ContinuationBlock', otherwise they take the normal loop exit. The
  495. // returned `RewrittenRangeInfo' object is populated as follows:
  496. //
  497. // .PseudoExit is a basic block that unconditionally branches to
  498. // `ContinuationBlock'.
  499. //
  500. // .ExitSelector is a basic block that decides, on exit from the loop,
  501. // whether to branch to the "true" exit or to `PseudoExit'.
  502. //
  503. // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
  504. // for each PHINode in the loop header on taking the pseudo exit.
  505. //
  506. // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
  507. // preheader because it is made to branch to the loop header only
  508. // conditionally.
  509. RewrittenRangeInfo
  510. changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
  511. Value *ExitLoopAt,
  512. BasicBlock *ContinuationBlock) const;
  513. // The loop denoted by `LS' has `OldPreheader' as its preheader. This
  514. // function creates a new preheader for `LS' and returns it.
  515. BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
  516. const char *Tag) const;
  517. // `ContinuationBlockAndPreheader' was the continuation block for some call to
  518. // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
  519. // This function rewrites the PHI nodes in `LS.Header' to start with the
  520. // correct value.
  521. void rewriteIncomingValuesForPHIs(
  522. LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
  523. const LoopConstrainer::RewrittenRangeInfo &RRI) const;
  524. // Even though we do not preserve any passes at this time, we at least need to
  525. // keep the parent loop structure consistent. The `LPPassManager' seems to
  526. // verify this after running a loop pass. This function adds the list of
  527. // blocks denoted by BBs to this loops parent loop if required.
  528. void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
  529. // Some global state.
  530. Function &F;
  531. LLVMContext &Ctx;
  532. ScalarEvolution &SE;
  533. DominatorTree &DT;
  534. LoopInfo &LI;
  535. function_ref<void(Loop *, bool)> LPMAddNewLoop;
  536. // Information about the original loop we started out with.
  537. Loop &OriginalLoop;
  538. const SCEV *LatchTakenCount = nullptr;
  539. BasicBlock *OriginalPreheader = nullptr;
  540. // The preheader of the main loop. This may or may not be different from
  541. // `OriginalPreheader'.
  542. BasicBlock *MainLoopPreheader = nullptr;
  543. // The range we need to run the main loop in.
  544. InductiveRangeCheck::Range Range;
  545. // The structure of the main loop (see comment at the beginning of this class
  546. // for a definition)
  547. LoopStructure MainLoopStructure;
  548. public:
  549. LoopConstrainer(Loop &L, LoopInfo &LI,
  550. function_ref<void(Loop *, bool)> LPMAddNewLoop,
  551. const LoopStructure &LS, ScalarEvolution &SE,
  552. DominatorTree &DT, InductiveRangeCheck::Range R)
  553. : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
  554. SE(SE), DT(DT), LI(LI), LPMAddNewLoop(LPMAddNewLoop), OriginalLoop(L),
  555. Range(R), MainLoopStructure(LS) {}
  556. // Entry point for the algorithm. Returns true on success.
  557. bool run();
  558. };
  559. } // end anonymous namespace
  560. /// Given a loop with an deccreasing induction variable, is it possible to
  561. /// safely calculate the bounds of a new loop using the given Predicate.
  562. static bool isSafeDecreasingBound(const SCEV *Start,
  563. const SCEV *BoundSCEV, const SCEV *Step,
  564. ICmpInst::Predicate Pred,
  565. unsigned LatchBrExitIdx,
  566. Loop *L, ScalarEvolution &SE) {
  567. if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT &&
  568. Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT)
  569. return false;
  570. if (!SE.isAvailableAtLoopEntry(BoundSCEV, L))
  571. return false;
  572. assert(SE.isKnownNegative(Step) && "expecting negative step");
  573. LLVM_DEBUG(dbgs() << "irce: isSafeDecreasingBound with:\n");
  574. LLVM_DEBUG(dbgs() << "irce: Start: " << *Start << "\n");
  575. LLVM_DEBUG(dbgs() << "irce: Step: " << *Step << "\n");
  576. LLVM_DEBUG(dbgs() << "irce: BoundSCEV: " << *BoundSCEV << "\n");
  577. LLVM_DEBUG(dbgs() << "irce: Pred: " << ICmpInst::getPredicateName(Pred)
  578. << "\n");
  579. LLVM_DEBUG(dbgs() << "irce: LatchExitBrIdx: " << LatchBrExitIdx << "\n");
  580. bool IsSigned = ICmpInst::isSigned(Pred);
  581. // The predicate that we need to check that the induction variable lies
  582. // within bounds.
  583. ICmpInst::Predicate BoundPred =
  584. IsSigned ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT;
  585. if (LatchBrExitIdx == 1)
  586. return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, BoundSCEV);
  587. assert(LatchBrExitIdx == 0 &&
  588. "LatchBrExitIdx should be either 0 or 1");
  589. const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType()));
  590. unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth();
  591. APInt Min = IsSigned ? APInt::getSignedMinValue(BitWidth) :
  592. APInt::getMinValue(BitWidth);
  593. const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Min), StepPlusOne);
  594. const SCEV *MinusOne =
  595. SE.getMinusSCEV(BoundSCEV, SE.getOne(BoundSCEV->getType()));
  596. return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, MinusOne) &&
  597. SE.isLoopEntryGuardedByCond(L, BoundPred, BoundSCEV, Limit);
  598. }
  599. /// Given a loop with an increasing induction variable, is it possible to
  600. /// safely calculate the bounds of a new loop using the given Predicate.
  601. static bool isSafeIncreasingBound(const SCEV *Start,
  602. const SCEV *BoundSCEV, const SCEV *Step,
  603. ICmpInst::Predicate Pred,
  604. unsigned LatchBrExitIdx,
  605. Loop *L, ScalarEvolution &SE) {
  606. if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT &&
  607. Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT)
  608. return false;
  609. if (!SE.isAvailableAtLoopEntry(BoundSCEV, L))
  610. return false;
  611. LLVM_DEBUG(dbgs() << "irce: isSafeIncreasingBound with:\n");
  612. LLVM_DEBUG(dbgs() << "irce: Start: " << *Start << "\n");
  613. LLVM_DEBUG(dbgs() << "irce: Step: " << *Step << "\n");
  614. LLVM_DEBUG(dbgs() << "irce: BoundSCEV: " << *BoundSCEV << "\n");
  615. LLVM_DEBUG(dbgs() << "irce: Pred: " << ICmpInst::getPredicateName(Pred)
  616. << "\n");
  617. LLVM_DEBUG(dbgs() << "irce: LatchExitBrIdx: " << LatchBrExitIdx << "\n");
  618. bool IsSigned = ICmpInst::isSigned(Pred);
  619. // The predicate that we need to check that the induction variable lies
  620. // within bounds.
  621. ICmpInst::Predicate BoundPred =
  622. IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
  623. if (LatchBrExitIdx == 1)
  624. return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, BoundSCEV);
  625. assert(LatchBrExitIdx == 0 && "LatchBrExitIdx should be 0 or 1");
  626. const SCEV *StepMinusOne =
  627. SE.getMinusSCEV(Step, SE.getOne(Step->getType()));
  628. unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth();
  629. APInt Max = IsSigned ? APInt::getSignedMaxValue(BitWidth) :
  630. APInt::getMaxValue(BitWidth);
  631. const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Max), StepMinusOne);
  632. return (SE.isLoopEntryGuardedByCond(L, BoundPred, Start,
  633. SE.getAddExpr(BoundSCEV, Step)) &&
  634. SE.isLoopEntryGuardedByCond(L, BoundPred, BoundSCEV, Limit));
  635. }
  636. std::optional<LoopStructure>
  637. LoopStructure::parseLoopStructure(ScalarEvolution &SE, Loop &L,
  638. const char *&FailureReason) {
  639. if (!L.isLoopSimplifyForm()) {
  640. FailureReason = "loop not in LoopSimplify form";
  641. return std::nullopt;
  642. }
  643. BasicBlock *Latch = L.getLoopLatch();
  644. assert(Latch && "Simplified loops only have one latch!");
  645. if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
  646. FailureReason = "loop has already been cloned";
  647. return std::nullopt;
  648. }
  649. if (!L.isLoopExiting(Latch)) {
  650. FailureReason = "no loop latch";
  651. return std::nullopt;
  652. }
  653. BasicBlock *Header = L.getHeader();
  654. BasicBlock *Preheader = L.getLoopPreheader();
  655. if (!Preheader) {
  656. FailureReason = "no preheader";
  657. return std::nullopt;
  658. }
  659. BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
  660. if (!LatchBr || LatchBr->isUnconditional()) {
  661. FailureReason = "latch terminator not conditional branch";
  662. return std::nullopt;
  663. }
  664. unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
  665. ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
  666. if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
  667. FailureReason = "latch terminator branch not conditional on integral icmp";
  668. return std::nullopt;
  669. }
  670. const SCEV *LatchCount = SE.getExitCount(&L, Latch);
  671. if (isa<SCEVCouldNotCompute>(LatchCount)) {
  672. FailureReason = "could not compute latch count";
  673. return std::nullopt;
  674. }
  675. ICmpInst::Predicate Pred = ICI->getPredicate();
  676. Value *LeftValue = ICI->getOperand(0);
  677. const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
  678. IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
  679. Value *RightValue = ICI->getOperand(1);
  680. const SCEV *RightSCEV = SE.getSCEV(RightValue);
  681. // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
  682. if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
  683. if (isa<SCEVAddRecExpr>(RightSCEV)) {
  684. std::swap(LeftSCEV, RightSCEV);
  685. std::swap(LeftValue, RightValue);
  686. Pred = ICmpInst::getSwappedPredicate(Pred);
  687. } else {
  688. FailureReason = "no add recurrences in the icmp";
  689. return std::nullopt;
  690. }
  691. }
  692. auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
  693. if (AR->getNoWrapFlags(SCEV::FlagNSW))
  694. return true;
  695. IntegerType *Ty = cast<IntegerType>(AR->getType());
  696. IntegerType *WideTy =
  697. IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
  698. const SCEVAddRecExpr *ExtendAfterOp =
  699. dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
  700. if (ExtendAfterOp) {
  701. const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
  702. const SCEV *ExtendedStep =
  703. SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
  704. bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
  705. ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
  706. if (NoSignedWrap)
  707. return true;
  708. }
  709. // We may have proved this when computing the sign extension above.
  710. return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
  711. };
  712. // `ICI` is interpreted as taking the backedge if the *next* value of the
  713. // induction variable satisfies some constraint.
  714. const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV);
  715. if (IndVarBase->getLoop() != &L) {
  716. FailureReason = "LHS in cmp is not an AddRec for this loop";
  717. return std::nullopt;
  718. }
  719. if (!IndVarBase->isAffine()) {
  720. FailureReason = "LHS in icmp not induction variable";
  721. return std::nullopt;
  722. }
  723. const SCEV* StepRec = IndVarBase->getStepRecurrence(SE);
  724. if (!isa<SCEVConstant>(StepRec)) {
  725. FailureReason = "LHS in icmp not induction variable";
  726. return std::nullopt;
  727. }
  728. ConstantInt *StepCI = cast<SCEVConstant>(StepRec)->getValue();
  729. if (ICI->isEquality() && !HasNoSignedWrap(IndVarBase)) {
  730. FailureReason = "LHS in icmp needs nsw for equality predicates";
  731. return std::nullopt;
  732. }
  733. assert(!StepCI->isZero() && "Zero step?");
  734. bool IsIncreasing = !StepCI->isNegative();
  735. bool IsSignedPredicate;
  736. const SCEV *StartNext = IndVarBase->getStart();
  737. const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE));
  738. const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
  739. const SCEV *Step = SE.getSCEV(StepCI);
  740. const SCEV *FixedRightSCEV = nullptr;
  741. // If RightValue resides within loop (but still being loop invariant),
  742. // regenerate it as preheader.
  743. if (auto *I = dyn_cast<Instruction>(RightValue))
  744. if (L.contains(I->getParent()))
  745. FixedRightSCEV = RightSCEV;
  746. if (IsIncreasing) {
  747. bool DecreasedRightValueByOne = false;
  748. if (StepCI->isOne()) {
  749. // Try to turn eq/ne predicates to those we can work with.
  750. if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
  751. // while (++i != len) { while (++i < len) {
  752. // ... ---> ...
  753. // } }
  754. // If both parts are known non-negative, it is profitable to use
  755. // unsigned comparison in increasing loop. This allows us to make the
  756. // comparison check against "RightSCEV + 1" more optimistic.
  757. if (isKnownNonNegativeInLoop(IndVarStart, &L, SE) &&
  758. isKnownNonNegativeInLoop(RightSCEV, &L, SE))
  759. Pred = ICmpInst::ICMP_ULT;
  760. else
  761. Pred = ICmpInst::ICMP_SLT;
  762. else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) {
  763. // while (true) { while (true) {
  764. // if (++i == len) ---> if (++i > len - 1)
  765. // break; break;
  766. // ... ...
  767. // } }
  768. if (IndVarBase->getNoWrapFlags(SCEV::FlagNUW) &&
  769. cannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/false)) {
  770. Pred = ICmpInst::ICMP_UGT;
  771. RightSCEV = SE.getMinusSCEV(RightSCEV,
  772. SE.getOne(RightSCEV->getType()));
  773. DecreasedRightValueByOne = true;
  774. } else if (cannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/true)) {
  775. Pred = ICmpInst::ICMP_SGT;
  776. RightSCEV = SE.getMinusSCEV(RightSCEV,
  777. SE.getOne(RightSCEV->getType()));
  778. DecreasedRightValueByOne = true;
  779. }
  780. }
  781. }
  782. bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
  783. bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
  784. bool FoundExpectedPred =
  785. (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
  786. if (!FoundExpectedPred) {
  787. FailureReason = "expected icmp slt semantically, found something else";
  788. return std::nullopt;
  789. }
  790. IsSignedPredicate = ICmpInst::isSigned(Pred);
  791. if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
  792. FailureReason = "unsigned latch conditions are explicitly prohibited";
  793. return std::nullopt;
  794. }
  795. if (!isSafeIncreasingBound(IndVarStart, RightSCEV, Step, Pred,
  796. LatchBrExitIdx, &L, SE)) {
  797. FailureReason = "Unsafe loop bounds";
  798. return std::nullopt;
  799. }
  800. if (LatchBrExitIdx == 0) {
  801. // We need to increase the right value unless we have already decreased
  802. // it virtually when we replaced EQ with SGT.
  803. if (!DecreasedRightValueByOne)
  804. FixedRightSCEV =
  805. SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
  806. } else {
  807. assert(!DecreasedRightValueByOne &&
  808. "Right value can be decreased only for LatchBrExitIdx == 0!");
  809. }
  810. } else {
  811. bool IncreasedRightValueByOne = false;
  812. if (StepCI->isMinusOne()) {
  813. // Try to turn eq/ne predicates to those we can work with.
  814. if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
  815. // while (--i != len) { while (--i > len) {
  816. // ... ---> ...
  817. // } }
  818. // We intentionally don't turn the predicate into UGT even if we know
  819. // that both operands are non-negative, because it will only pessimize
  820. // our check against "RightSCEV - 1".
  821. Pred = ICmpInst::ICMP_SGT;
  822. else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) {
  823. // while (true) { while (true) {
  824. // if (--i == len) ---> if (--i < len + 1)
  825. // break; break;
  826. // ... ...
  827. // } }
  828. if (IndVarBase->getNoWrapFlags(SCEV::FlagNUW) &&
  829. cannotBeMaxInLoop(RightSCEV, &L, SE, /* Signed */ false)) {
  830. Pred = ICmpInst::ICMP_ULT;
  831. RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
  832. IncreasedRightValueByOne = true;
  833. } else if (cannotBeMaxInLoop(RightSCEV, &L, SE, /* Signed */ true)) {
  834. Pred = ICmpInst::ICMP_SLT;
  835. RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
  836. IncreasedRightValueByOne = true;
  837. }
  838. }
  839. }
  840. bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
  841. bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
  842. bool FoundExpectedPred =
  843. (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
  844. if (!FoundExpectedPred) {
  845. FailureReason = "expected icmp sgt semantically, found something else";
  846. return std::nullopt;
  847. }
  848. IsSignedPredicate =
  849. Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
  850. if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
  851. FailureReason = "unsigned latch conditions are explicitly prohibited";
  852. return std::nullopt;
  853. }
  854. if (!isSafeDecreasingBound(IndVarStart, RightSCEV, Step, Pred,
  855. LatchBrExitIdx, &L, SE)) {
  856. FailureReason = "Unsafe bounds";
  857. return std::nullopt;
  858. }
  859. if (LatchBrExitIdx == 0) {
  860. // We need to decrease the right value unless we have already increased
  861. // it virtually when we replaced EQ with SLT.
  862. if (!IncreasedRightValueByOne)
  863. FixedRightSCEV =
  864. SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType()));
  865. } else {
  866. assert(!IncreasedRightValueByOne &&
  867. "Right value can be increased only for LatchBrExitIdx == 0!");
  868. }
  869. }
  870. BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
  871. assert(SE.getLoopDisposition(LatchCount, &L) ==
  872. ScalarEvolution::LoopInvariant &&
  873. "loop variant exit count doesn't make sense!");
  874. assert(!L.contains(LatchExit) && "expected an exit block!");
  875. const DataLayout &DL = Preheader->getModule()->getDataLayout();
  876. SCEVExpander Expander(SE, DL, "irce");
  877. Instruction *Ins = Preheader->getTerminator();
  878. if (FixedRightSCEV)
  879. RightValue =
  880. Expander.expandCodeFor(FixedRightSCEV, FixedRightSCEV->getType(), Ins);
  881. Value *IndVarStartV = Expander.expandCodeFor(IndVarStart, IndVarTy, Ins);
  882. IndVarStartV->setName("indvar.start");
  883. LoopStructure Result;
  884. Result.Tag = "main";
  885. Result.Header = Header;
  886. Result.Latch = Latch;
  887. Result.LatchBr = LatchBr;
  888. Result.LatchExit = LatchExit;
  889. Result.LatchBrExitIdx = LatchBrExitIdx;
  890. Result.IndVarStart = IndVarStartV;
  891. Result.IndVarStep = StepCI;
  892. Result.IndVarBase = LeftValue;
  893. Result.IndVarIncreasing = IsIncreasing;
  894. Result.LoopExitAt = RightValue;
  895. Result.IsSignedPredicate = IsSignedPredicate;
  896. FailureReason = nullptr;
  897. return Result;
  898. }
  899. /// If the type of \p S matches with \p Ty, return \p S. Otherwise, return
  900. /// signed or unsigned extension of \p S to type \p Ty.
  901. static const SCEV *NoopOrExtend(const SCEV *S, Type *Ty, ScalarEvolution &SE,
  902. bool Signed) {
  903. return Signed ? SE.getNoopOrSignExtend(S, Ty) : SE.getNoopOrZeroExtend(S, Ty);
  904. }
  905. std::optional<LoopConstrainer::SubRanges>
  906. LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const {
  907. IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
  908. auto *RTy = cast<IntegerType>(Range.getType());
  909. // We only support wide range checks and narrow latches.
  910. if (!AllowNarrowLatchCondition && RTy != Ty)
  911. return std::nullopt;
  912. if (RTy->getBitWidth() < Ty->getBitWidth())
  913. return std::nullopt;
  914. LoopConstrainer::SubRanges Result;
  915. // I think we can be more aggressive here and make this nuw / nsw if the
  916. // addition that feeds into the icmp for the latch's terminating branch is nuw
  917. // / nsw. In any case, a wrapping 2's complement addition is safe.
  918. const SCEV *Start = NoopOrExtend(SE.getSCEV(MainLoopStructure.IndVarStart),
  919. RTy, SE, IsSignedPredicate);
  920. const SCEV *End = NoopOrExtend(SE.getSCEV(MainLoopStructure.LoopExitAt), RTy,
  921. SE, IsSignedPredicate);
  922. bool Increasing = MainLoopStructure.IndVarIncreasing;
  923. // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or
  924. // [Smallest, GreatestSeen] is the range of values the induction variable
  925. // takes.
  926. const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;
  927. const SCEV *One = SE.getOne(RTy);
  928. if (Increasing) {
  929. Smallest = Start;
  930. Greatest = End;
  931. // No overflow, because the range [Smallest, GreatestSeen] is not empty.
  932. GreatestSeen = SE.getMinusSCEV(End, One);
  933. } else {
  934. // These two computations may sign-overflow. Here is why that is okay:
  935. //
  936. // We know that the induction variable does not sign-overflow on any
  937. // iteration except the last one, and it starts at `Start` and ends at
  938. // `End`, decrementing by one every time.
  939. //
  940. // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
  941. // induction variable is decreasing we know that that the smallest value
  942. // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
  943. //
  944. // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
  945. // that case, `Clamp` will always return `Smallest` and
  946. // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
  947. // will be an empty range. Returning an empty range is always safe.
  948. Smallest = SE.getAddExpr(End, One);
  949. Greatest = SE.getAddExpr(Start, One);
  950. GreatestSeen = Start;
  951. }
  952. auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {
  953. return IsSignedPredicate
  954. ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))
  955. : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));
  956. };
  957. // In some cases we can prove that we don't need a pre or post loop.
  958. ICmpInst::Predicate PredLE =
  959. IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
  960. ICmpInst::Predicate PredLT =
  961. IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
  962. bool ProvablyNoPreloop =
  963. SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);
  964. if (!ProvablyNoPreloop)
  965. Result.LowLimit = Clamp(Range.getBegin());
  966. bool ProvablyNoPostLoop =
  967. SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());
  968. if (!ProvablyNoPostLoop)
  969. Result.HighLimit = Clamp(Range.getEnd());
  970. return Result;
  971. }
  972. void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
  973. const char *Tag) const {
  974. for (BasicBlock *BB : OriginalLoop.getBlocks()) {
  975. BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
  976. Result.Blocks.push_back(Clone);
  977. Result.Map[BB] = Clone;
  978. }
  979. auto GetClonedValue = [&Result](Value *V) {
  980. assert(V && "null values not in domain!");
  981. auto It = Result.Map.find(V);
  982. if (It == Result.Map.end())
  983. return V;
  984. return static_cast<Value *>(It->second);
  985. };
  986. auto *ClonedLatch =
  987. cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
  988. ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
  989. MDNode::get(Ctx, {}));
  990. Result.Structure = MainLoopStructure.map(GetClonedValue);
  991. Result.Structure.Tag = Tag;
  992. for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
  993. BasicBlock *ClonedBB = Result.Blocks[i];
  994. BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
  995. assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
  996. for (Instruction &I : *ClonedBB)
  997. RemapInstruction(&I, Result.Map,
  998. RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
  999. // Exit blocks will now have one more predecessor and their PHI nodes need
  1000. // to be edited to reflect that. No phi nodes need to be introduced because
  1001. // the loop is in LCSSA.
  1002. for (auto *SBB : successors(OriginalBB)) {
  1003. if (OriginalLoop.contains(SBB))
  1004. continue; // not an exit block
  1005. for (PHINode &PN : SBB->phis()) {
  1006. Value *OldIncoming = PN.getIncomingValueForBlock(OriginalBB);
  1007. PN.addIncoming(GetClonedValue(OldIncoming), ClonedBB);
  1008. SE.forgetValue(&PN);
  1009. }
  1010. }
  1011. }
  1012. }
  1013. LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
  1014. const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
  1015. BasicBlock *ContinuationBlock) const {
  1016. // We start with a loop with a single latch:
  1017. //
  1018. // +--------------------+
  1019. // | |
  1020. // | preheader |
  1021. // | |
  1022. // +--------+-----------+
  1023. // | ----------------\
  1024. // | / |
  1025. // +--------v----v------+ |
  1026. // | | |
  1027. // | header | |
  1028. // | | |
  1029. // +--------------------+ |
  1030. // |
  1031. // ..... |
  1032. // |
  1033. // +--------------------+ |
  1034. // | | |
  1035. // | latch >----------/
  1036. // | |
  1037. // +-------v------------+
  1038. // |
  1039. // |
  1040. // | +--------------------+
  1041. // | | |
  1042. // +---> original exit |
  1043. // | |
  1044. // +--------------------+
  1045. //
  1046. // We change the control flow to look like
  1047. //
  1048. //
  1049. // +--------------------+
  1050. // | |
  1051. // | preheader >-------------------------+
  1052. // | | |
  1053. // +--------v-----------+ |
  1054. // | /-------------+ |
  1055. // | / | |
  1056. // +--------v--v--------+ | |
  1057. // | | | |
  1058. // | header | | +--------+ |
  1059. // | | | | | |
  1060. // +--------------------+ | | +-----v-----v-----------+
  1061. // | | | |
  1062. // | | | .pseudo.exit |
  1063. // | | | |
  1064. // | | +-----------v-----------+
  1065. // | | |
  1066. // ..... | | |
  1067. // | | +--------v-------------+
  1068. // +--------------------+ | | | |
  1069. // | | | | | ContinuationBlock |
  1070. // | latch >------+ | | |
  1071. // | | | +----------------------+
  1072. // +---------v----------+ |
  1073. // | |
  1074. // | |
  1075. // | +---------------^-----+
  1076. // | | |
  1077. // +-----> .exit.selector |
  1078. // | |
  1079. // +----------v----------+
  1080. // |
  1081. // +--------------------+ |
  1082. // | | |
  1083. // | original exit <----+
  1084. // | |
  1085. // +--------------------+
  1086. RewrittenRangeInfo RRI;
  1087. BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
  1088. RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
  1089. &F, BBInsertLocation);
  1090. RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
  1091. BBInsertLocation);
  1092. BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
  1093. bool Increasing = LS.IndVarIncreasing;
  1094. bool IsSignedPredicate = LS.IsSignedPredicate;
  1095. IRBuilder<> B(PreheaderJump);
  1096. auto *RangeTy = Range.getBegin()->getType();
  1097. auto NoopOrExt = [&](Value *V) {
  1098. if (V->getType() == RangeTy)
  1099. return V;
  1100. return IsSignedPredicate ? B.CreateSExt(V, RangeTy, "wide." + V->getName())
  1101. : B.CreateZExt(V, RangeTy, "wide." + V->getName());
  1102. };
  1103. // EnterLoopCond - is it okay to start executing this `LS'?
  1104. Value *EnterLoopCond = nullptr;
  1105. auto Pred =
  1106. Increasing
  1107. ? (IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT)
  1108. : (IsSignedPredicate ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
  1109. Value *IndVarStart = NoopOrExt(LS.IndVarStart);
  1110. EnterLoopCond = B.CreateICmp(Pred, IndVarStart, ExitSubloopAt);
  1111. B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
  1112. PreheaderJump->eraseFromParent();
  1113. LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
  1114. B.SetInsertPoint(LS.LatchBr);
  1115. Value *IndVarBase = NoopOrExt(LS.IndVarBase);
  1116. Value *TakeBackedgeLoopCond = B.CreateICmp(Pred, IndVarBase, ExitSubloopAt);
  1117. Value *CondForBranch = LS.LatchBrExitIdx == 1
  1118. ? TakeBackedgeLoopCond
  1119. : B.CreateNot(TakeBackedgeLoopCond);
  1120. LS.LatchBr->setCondition(CondForBranch);
  1121. B.SetInsertPoint(RRI.ExitSelector);
  1122. // IterationsLeft - are there any more iterations left, given the original
  1123. // upper bound on the induction variable? If not, we branch to the "real"
  1124. // exit.
  1125. Value *LoopExitAt = NoopOrExt(LS.LoopExitAt);
  1126. Value *IterationsLeft = B.CreateICmp(Pred, IndVarBase, LoopExitAt);
  1127. B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
  1128. BranchInst *BranchToContinuation =
  1129. BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
  1130. // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
  1131. // each of the PHI nodes in the loop header. This feeds into the initial
  1132. // value of the same PHI nodes if/when we continue execution.
  1133. for (PHINode &PN : LS.Header->phis()) {
  1134. PHINode *NewPHI = PHINode::Create(PN.getType(), 2, PN.getName() + ".copy",
  1135. BranchToContinuation);
  1136. NewPHI->addIncoming(PN.getIncomingValueForBlock(Preheader), Preheader);
  1137. NewPHI->addIncoming(PN.getIncomingValueForBlock(LS.Latch),
  1138. RRI.ExitSelector);
  1139. RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
  1140. }
  1141. RRI.IndVarEnd = PHINode::Create(IndVarBase->getType(), 2, "indvar.end",
  1142. BranchToContinuation);
  1143. RRI.IndVarEnd->addIncoming(IndVarStart, Preheader);
  1144. RRI.IndVarEnd->addIncoming(IndVarBase, RRI.ExitSelector);
  1145. // The latch exit now has a branch from `RRI.ExitSelector' instead of
  1146. // `LS.Latch'. The PHI nodes need to be updated to reflect that.
  1147. LS.LatchExit->replacePhiUsesWith(LS.Latch, RRI.ExitSelector);
  1148. return RRI;
  1149. }
  1150. void LoopConstrainer::rewriteIncomingValuesForPHIs(
  1151. LoopStructure &LS, BasicBlock *ContinuationBlock,
  1152. const LoopConstrainer::RewrittenRangeInfo &RRI) const {
  1153. unsigned PHIIndex = 0;
  1154. for (PHINode &PN : LS.Header->phis())
  1155. PN.setIncomingValueForBlock(ContinuationBlock,
  1156. RRI.PHIValuesAtPseudoExit[PHIIndex++]);
  1157. LS.IndVarStart = RRI.IndVarEnd;
  1158. }
  1159. BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
  1160. BasicBlock *OldPreheader,
  1161. const char *Tag) const {
  1162. BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
  1163. BranchInst::Create(LS.Header, Preheader);
  1164. LS.Header->replacePhiUsesWith(OldPreheader, Preheader);
  1165. return Preheader;
  1166. }
  1167. void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
  1168. Loop *ParentLoop = OriginalLoop.getParentLoop();
  1169. if (!ParentLoop)
  1170. return;
  1171. for (BasicBlock *BB : BBs)
  1172. ParentLoop->addBasicBlockToLoop(BB, LI);
  1173. }
  1174. Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
  1175. ValueToValueMapTy &VM,
  1176. bool IsSubloop) {
  1177. Loop &New = *LI.AllocateLoop();
  1178. if (Parent)
  1179. Parent->addChildLoop(&New);
  1180. else
  1181. LI.addTopLevelLoop(&New);
  1182. LPMAddNewLoop(&New, IsSubloop);
  1183. // Add all of the blocks in Original to the new loop.
  1184. for (auto *BB : Original->blocks())
  1185. if (LI.getLoopFor(BB) == Original)
  1186. New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
  1187. // Add all of the subloops to the new loop.
  1188. for (Loop *SubLoop : *Original)
  1189. createClonedLoopStructure(SubLoop, &New, VM, /* IsSubloop */ true);
  1190. return &New;
  1191. }
  1192. bool LoopConstrainer::run() {
  1193. BasicBlock *Preheader = nullptr;
  1194. LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
  1195. Preheader = OriginalLoop.getLoopPreheader();
  1196. assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
  1197. "preconditions!");
  1198. OriginalPreheader = Preheader;
  1199. MainLoopPreheader = Preheader;
  1200. bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
  1201. std::optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate);
  1202. if (!MaybeSR) {
  1203. LLVM_DEBUG(dbgs() << "irce: could not compute subranges\n");
  1204. return false;
  1205. }
  1206. SubRanges SR = *MaybeSR;
  1207. bool Increasing = MainLoopStructure.IndVarIncreasing;
  1208. IntegerType *IVTy =
  1209. cast<IntegerType>(Range.getBegin()->getType());
  1210. SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
  1211. Instruction *InsertPt = OriginalPreheader->getTerminator();
  1212. // It would have been better to make `PreLoop' and `PostLoop'
  1213. // `std::optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
  1214. // constructor.
  1215. ClonedLoop PreLoop, PostLoop;
  1216. bool NeedsPreLoop =
  1217. Increasing ? SR.LowLimit.has_value() : SR.HighLimit.has_value();
  1218. bool NeedsPostLoop =
  1219. Increasing ? SR.HighLimit.has_value() : SR.LowLimit.has_value();
  1220. Value *ExitPreLoopAt = nullptr;
  1221. Value *ExitMainLoopAt = nullptr;
  1222. const SCEVConstant *MinusOneS =
  1223. cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
  1224. if (NeedsPreLoop) {
  1225. const SCEV *ExitPreLoopAtSCEV = nullptr;
  1226. if (Increasing)
  1227. ExitPreLoopAtSCEV = *SR.LowLimit;
  1228. else if (cannotBeMinInLoop(*SR.HighLimit, &OriginalLoop, SE,
  1229. IsSignedPredicate))
  1230. ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
  1231. else {
  1232. LLVM_DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
  1233. << "preloop exit limit. HighLimit = "
  1234. << *(*SR.HighLimit) << "\n");
  1235. return false;
  1236. }
  1237. if (!Expander.isSafeToExpandAt(ExitPreLoopAtSCEV, InsertPt)) {
  1238. LLVM_DEBUG(dbgs() << "irce: could not prove that it is safe to expand the"
  1239. << " preloop exit limit " << *ExitPreLoopAtSCEV
  1240. << " at block " << InsertPt->getParent()->getName()
  1241. << "\n");
  1242. return false;
  1243. }
  1244. ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
  1245. ExitPreLoopAt->setName("exit.preloop.at");
  1246. }
  1247. if (NeedsPostLoop) {
  1248. const SCEV *ExitMainLoopAtSCEV = nullptr;
  1249. if (Increasing)
  1250. ExitMainLoopAtSCEV = *SR.HighLimit;
  1251. else if (cannotBeMinInLoop(*SR.LowLimit, &OriginalLoop, SE,
  1252. IsSignedPredicate))
  1253. ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
  1254. else {
  1255. LLVM_DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
  1256. << "mainloop exit limit. LowLimit = "
  1257. << *(*SR.LowLimit) << "\n");
  1258. return false;
  1259. }
  1260. if (!Expander.isSafeToExpandAt(ExitMainLoopAtSCEV, InsertPt)) {
  1261. LLVM_DEBUG(dbgs() << "irce: could not prove that it is safe to expand the"
  1262. << " main loop exit limit " << *ExitMainLoopAtSCEV
  1263. << " at block " << InsertPt->getParent()->getName()
  1264. << "\n");
  1265. return false;
  1266. }
  1267. ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
  1268. ExitMainLoopAt->setName("exit.mainloop.at");
  1269. }
  1270. // We clone these ahead of time so that we don't have to deal with changing
  1271. // and temporarily invalid IR as we transform the loops.
  1272. if (NeedsPreLoop)
  1273. cloneLoop(PreLoop, "preloop");
  1274. if (NeedsPostLoop)
  1275. cloneLoop(PostLoop, "postloop");
  1276. RewrittenRangeInfo PreLoopRRI;
  1277. if (NeedsPreLoop) {
  1278. Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
  1279. PreLoop.Structure.Header);
  1280. MainLoopPreheader =
  1281. createPreheader(MainLoopStructure, Preheader, "mainloop");
  1282. PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
  1283. ExitPreLoopAt, MainLoopPreheader);
  1284. rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
  1285. PreLoopRRI);
  1286. }
  1287. BasicBlock *PostLoopPreheader = nullptr;
  1288. RewrittenRangeInfo PostLoopRRI;
  1289. if (NeedsPostLoop) {
  1290. PostLoopPreheader =
  1291. createPreheader(PostLoop.Structure, Preheader, "postloop");
  1292. PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
  1293. ExitMainLoopAt, PostLoopPreheader);
  1294. rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
  1295. PostLoopRRI);
  1296. }
  1297. BasicBlock *NewMainLoopPreheader =
  1298. MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
  1299. BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
  1300. PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
  1301. PostLoopRRI.ExitSelector, NewMainLoopPreheader};
  1302. // Some of the above may be nullptr, filter them out before passing to
  1303. // addToParentLoopIfNeeded.
  1304. auto NewBlocksEnd =
  1305. std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
  1306. addToParentLoopIfNeeded(ArrayRef(std::begin(NewBlocks), NewBlocksEnd));
  1307. DT.recalculate(F);
  1308. // We need to first add all the pre and post loop blocks into the loop
  1309. // structures (as part of createClonedLoopStructure), and then update the
  1310. // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating
  1311. // LI when LoopSimplifyForm is generated.
  1312. Loop *PreL = nullptr, *PostL = nullptr;
  1313. if (!PreLoop.Blocks.empty()) {
  1314. PreL = createClonedLoopStructure(&OriginalLoop,
  1315. OriginalLoop.getParentLoop(), PreLoop.Map,
  1316. /* IsSubLoop */ false);
  1317. }
  1318. if (!PostLoop.Blocks.empty()) {
  1319. PostL =
  1320. createClonedLoopStructure(&OriginalLoop, OriginalLoop.getParentLoop(),
  1321. PostLoop.Map, /* IsSubLoop */ false);
  1322. }
  1323. // This function canonicalizes the loop into Loop-Simplify and LCSSA forms.
  1324. auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) {
  1325. formLCSSARecursively(*L, DT, &LI, &SE);
  1326. simplifyLoop(L, &DT, &LI, &SE, nullptr, nullptr, true);
  1327. // Pre/post loops are slow paths, we do not need to perform any loop
  1328. // optimizations on them.
  1329. if (!IsOriginalLoop)
  1330. DisableAllLoopOptsOnLoop(*L);
  1331. };
  1332. if (PreL)
  1333. CanonicalizeLoop(PreL, false);
  1334. if (PostL)
  1335. CanonicalizeLoop(PostL, false);
  1336. CanonicalizeLoop(&OriginalLoop, true);
  1337. return true;
  1338. }
  1339. /// Computes and returns a range of values for the induction variable (IndVar)
  1340. /// in which the range check can be safely elided. If it cannot compute such a
  1341. /// range, returns std::nullopt.
  1342. std::optional<InductiveRangeCheck::Range>
  1343. InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,
  1344. const SCEVAddRecExpr *IndVar,
  1345. bool IsLatchSigned) const {
  1346. // We can deal when types of latch check and range checks don't match in case
  1347. // if latch check is more narrow.
  1348. auto *IVType = dyn_cast<IntegerType>(IndVar->getType());
  1349. auto *RCType = dyn_cast<IntegerType>(getBegin()->getType());
  1350. // Do not work with pointer types.
  1351. if (!IVType || !RCType)
  1352. return std::nullopt;
  1353. if (IVType->getBitWidth() > RCType->getBitWidth())
  1354. return std::nullopt;
  1355. // IndVar is of the form "A + B * I" (where "I" is the canonical induction
  1356. // variable, that may or may not exist as a real llvm::Value in the loop) and
  1357. // this inductive range check is a range check on the "C + D * I" ("C" is
  1358. // getBegin() and "D" is getStep()). We rewrite the value being range
  1359. // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
  1360. //
  1361. // The actual inequalities we solve are of the form
  1362. //
  1363. // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
  1364. //
  1365. // Here L stands for upper limit of the safe iteration space.
  1366. // The inequality is satisfied by (0 - M) <= IndVar < (L - M). To avoid
  1367. // overflows when calculating (0 - M) and (L - M) we, depending on type of
  1368. // IV's iteration space, limit the calculations by borders of the iteration
  1369. // space. For example, if IndVar is unsigned, (0 - M) overflows for any M > 0.
  1370. // If we figured out that "anything greater than (-M) is safe", we strengthen
  1371. // this to "everything greater than 0 is safe", assuming that values between
  1372. // -M and 0 just do not exist in unsigned iteration space, and we don't want
  1373. // to deal with overflown values.
  1374. if (!IndVar->isAffine())
  1375. return std::nullopt;
  1376. const SCEV *A = NoopOrExtend(IndVar->getStart(), RCType, SE, IsLatchSigned);
  1377. const SCEVConstant *B = dyn_cast<SCEVConstant>(
  1378. NoopOrExtend(IndVar->getStepRecurrence(SE), RCType, SE, IsLatchSigned));
  1379. if (!B)
  1380. return std::nullopt;
  1381. assert(!B->isZero() && "Recurrence with zero step?");
  1382. const SCEV *C = getBegin();
  1383. const SCEVConstant *D = dyn_cast<SCEVConstant>(getStep());
  1384. if (D != B)
  1385. return std::nullopt;
  1386. assert(!D->getValue()->isZero() && "Recurrence with zero step?");
  1387. unsigned BitWidth = RCType->getBitWidth();
  1388. const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
  1389. // Subtract Y from X so that it does not go through border of the IV
  1390. // iteration space. Mathematically, it is equivalent to:
  1391. //
  1392. // ClampedSubtract(X, Y) = min(max(X - Y, INT_MIN), INT_MAX). [1]
  1393. //
  1394. // In [1], 'X - Y' is a mathematical subtraction (result is not bounded to
  1395. // any width of bit grid). But after we take min/max, the result is
  1396. // guaranteed to be within [INT_MIN, INT_MAX].
  1397. //
  1398. // In [1], INT_MAX and INT_MIN are respectively signed and unsigned max/min
  1399. // values, depending on type of latch condition that defines IV iteration
  1400. // space.
  1401. auto ClampedSubtract = [&](const SCEV *X, const SCEV *Y) {
  1402. // FIXME: The current implementation assumes that X is in [0, SINT_MAX].
  1403. // This is required to ensure that SINT_MAX - X does not overflow signed and
  1404. // that X - Y does not overflow unsigned if Y is negative. Can we lift this
  1405. // restriction and make it work for negative X either?
  1406. if (IsLatchSigned) {
  1407. // X is a number from signed range, Y is interpreted as signed.
  1408. // Even if Y is SINT_MAX, (X - Y) does not reach SINT_MIN. So the only
  1409. // thing we should care about is that we didn't cross SINT_MAX.
  1410. // So, if Y is positive, we subtract Y safely.
  1411. // Rule 1: Y > 0 ---> Y.
  1412. // If 0 <= -Y <= (SINT_MAX - X), we subtract Y safely.
  1413. // Rule 2: Y >=s (X - SINT_MAX) ---> Y.
  1414. // If 0 <= (SINT_MAX - X) < -Y, we can only subtract (X - SINT_MAX).
  1415. // Rule 3: Y <s (X - SINT_MAX) ---> (X - SINT_MAX).
  1416. // It gives us smax(Y, X - SINT_MAX) to subtract in all cases.
  1417. const SCEV *XMinusSIntMax = SE.getMinusSCEV(X, SIntMax);
  1418. return SE.getMinusSCEV(X, SE.getSMaxExpr(Y, XMinusSIntMax),
  1419. SCEV::FlagNSW);
  1420. } else
  1421. // X is a number from unsigned range, Y is interpreted as signed.
  1422. // Even if Y is SINT_MIN, (X - Y) does not reach UINT_MAX. So the only
  1423. // thing we should care about is that we didn't cross zero.
  1424. // So, if Y is negative, we subtract Y safely.
  1425. // Rule 1: Y <s 0 ---> Y.
  1426. // If 0 <= Y <= X, we subtract Y safely.
  1427. // Rule 2: Y <=s X ---> Y.
  1428. // If 0 <= X < Y, we should stop at 0 and can only subtract X.
  1429. // Rule 3: Y >s X ---> X.
  1430. // It gives us smin(X, Y) to subtract in all cases.
  1431. return SE.getMinusSCEV(X, SE.getSMinExpr(X, Y), SCEV::FlagNUW);
  1432. };
  1433. const SCEV *M = SE.getMinusSCEV(C, A);
  1434. const SCEV *Zero = SE.getZero(M->getType());
  1435. // This function returns SCEV equal to 1 if X is non-negative 0 otherwise.
  1436. auto SCEVCheckNonNegative = [&](const SCEV *X) {
  1437. const Loop *L = IndVar->getLoop();
  1438. const SCEV *One = SE.getOne(X->getType());
  1439. // Can we trivially prove that X is a non-negative or negative value?
  1440. if (isKnownNonNegativeInLoop(X, L, SE))
  1441. return One;
  1442. else if (isKnownNegativeInLoop(X, L, SE))
  1443. return Zero;
  1444. // If not, we will have to figure it out during the execution.
  1445. // Function smax(smin(X, 0), -1) + 1 equals to 1 if X >= 0 and 0 if X < 0.
  1446. const SCEV *NegOne = SE.getNegativeSCEV(One);
  1447. return SE.getAddExpr(SE.getSMaxExpr(SE.getSMinExpr(X, Zero), NegOne), One);
  1448. };
  1449. // FIXME: Current implementation of ClampedSubtract implicitly assumes that
  1450. // X is non-negative (in sense of a signed value). We need to re-implement
  1451. // this function in a way that it will correctly handle negative X as well.
  1452. // We use it twice: for X = 0 everything is fine, but for X = getEnd() we can
  1453. // end up with a negative X and produce wrong results. So currently we ensure
  1454. // that if getEnd() is negative then both ends of the safe range are zero.
  1455. // Note that this may pessimize elimination of unsigned range checks against
  1456. // negative values.
  1457. const SCEV *REnd = getEnd();
  1458. const SCEV *EndIsNonNegative = SCEVCheckNonNegative(REnd);
  1459. const SCEV *Begin = SE.getMulExpr(ClampedSubtract(Zero, M), EndIsNonNegative);
  1460. const SCEV *End = SE.getMulExpr(ClampedSubtract(REnd, M), EndIsNonNegative);
  1461. return InductiveRangeCheck::Range(Begin, End);
  1462. }
  1463. static std::optional<InductiveRangeCheck::Range>
  1464. IntersectSignedRange(ScalarEvolution &SE,
  1465. const std::optional<InductiveRangeCheck::Range> &R1,
  1466. const InductiveRangeCheck::Range &R2) {
  1467. if (R2.isEmpty(SE, /* IsSigned */ true))
  1468. return std::nullopt;
  1469. if (!R1)
  1470. return R2;
  1471. auto &R1Value = *R1;
  1472. // We never return empty ranges from this function, and R1 is supposed to be
  1473. // a result of intersection. Thus, R1 is never empty.
  1474. assert(!R1Value.isEmpty(SE, /* IsSigned */ true) &&
  1475. "We should never have empty R1!");
  1476. // TODO: we could widen the smaller range and have this work; but for now we
  1477. // bail out to keep things simple.
  1478. if (R1Value.getType() != R2.getType())
  1479. return std::nullopt;
  1480. const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
  1481. const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
  1482. // If the resulting range is empty, just return std::nullopt.
  1483. auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
  1484. if (Ret.isEmpty(SE, /* IsSigned */ true))
  1485. return std::nullopt;
  1486. return Ret;
  1487. }
  1488. static std::optional<InductiveRangeCheck::Range>
  1489. IntersectUnsignedRange(ScalarEvolution &SE,
  1490. const std::optional<InductiveRangeCheck::Range> &R1,
  1491. const InductiveRangeCheck::Range &R2) {
  1492. if (R2.isEmpty(SE, /* IsSigned */ false))
  1493. return std::nullopt;
  1494. if (!R1)
  1495. return R2;
  1496. auto &R1Value = *R1;
  1497. // We never return empty ranges from this function, and R1 is supposed to be
  1498. // a result of intersection. Thus, R1 is never empty.
  1499. assert(!R1Value.isEmpty(SE, /* IsSigned */ false) &&
  1500. "We should never have empty R1!");
  1501. // TODO: we could widen the smaller range and have this work; but for now we
  1502. // bail out to keep things simple.
  1503. if (R1Value.getType() != R2.getType())
  1504. return std::nullopt;
  1505. const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin());
  1506. const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd());
  1507. // If the resulting range is empty, just return std::nullopt.
  1508. auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
  1509. if (Ret.isEmpty(SE, /* IsSigned */ false))
  1510. return std::nullopt;
  1511. return Ret;
  1512. }
  1513. PreservedAnalyses IRCEPass::run(Function &F, FunctionAnalysisManager &AM) {
  1514. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  1515. LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
  1516. // There are no loops in the function. Return before computing other expensive
  1517. // analyses.
  1518. if (LI.empty())
  1519. return PreservedAnalyses::all();
  1520. auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
  1521. auto &BPI = AM.getResult<BranchProbabilityAnalysis>(F);
  1522. // Get BFI analysis result on demand. Please note that modification of
  1523. // CFG invalidates this analysis and we should handle it.
  1524. auto getBFI = [&F, &AM ]()->BlockFrequencyInfo & {
  1525. return AM.getResult<BlockFrequencyAnalysis>(F);
  1526. };
  1527. InductiveRangeCheckElimination IRCE(SE, &BPI, DT, LI, { getBFI });
  1528. bool Changed = false;
  1529. {
  1530. bool CFGChanged = false;
  1531. for (const auto &L : LI) {
  1532. CFGChanged |= simplifyLoop(L, &DT, &LI, &SE, nullptr, nullptr,
  1533. /*PreserveLCSSA=*/false);
  1534. Changed |= formLCSSARecursively(*L, DT, &LI, &SE);
  1535. }
  1536. Changed |= CFGChanged;
  1537. if (CFGChanged && !SkipProfitabilityChecks) {
  1538. PreservedAnalyses PA = PreservedAnalyses::all();
  1539. PA.abandon<BlockFrequencyAnalysis>();
  1540. AM.invalidate(F, PA);
  1541. }
  1542. }
  1543. SmallPriorityWorklist<Loop *, 4> Worklist;
  1544. appendLoopsToWorklist(LI, Worklist);
  1545. auto LPMAddNewLoop = [&Worklist](Loop *NL, bool IsSubloop) {
  1546. if (!IsSubloop)
  1547. appendLoopsToWorklist(*NL, Worklist);
  1548. };
  1549. while (!Worklist.empty()) {
  1550. Loop *L = Worklist.pop_back_val();
  1551. if (IRCE.run(L, LPMAddNewLoop)) {
  1552. Changed = true;
  1553. if (!SkipProfitabilityChecks) {
  1554. PreservedAnalyses PA = PreservedAnalyses::all();
  1555. PA.abandon<BlockFrequencyAnalysis>();
  1556. AM.invalidate(F, PA);
  1557. }
  1558. }
  1559. }
  1560. if (!Changed)
  1561. return PreservedAnalyses::all();
  1562. return getLoopPassPreservedAnalyses();
  1563. }
  1564. bool IRCELegacyPass::runOnFunction(Function &F) {
  1565. if (skipFunction(F))
  1566. return false;
  1567. ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  1568. BranchProbabilityInfo &BPI =
  1569. getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
  1570. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1571. auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  1572. InductiveRangeCheckElimination IRCE(SE, &BPI, DT, LI);
  1573. bool Changed = false;
  1574. for (const auto &L : LI) {
  1575. Changed |= simplifyLoop(L, &DT, &LI, &SE, nullptr, nullptr,
  1576. /*PreserveLCSSA=*/false);
  1577. Changed |= formLCSSARecursively(*L, DT, &LI, &SE);
  1578. }
  1579. SmallPriorityWorklist<Loop *, 4> Worklist;
  1580. appendLoopsToWorklist(LI, Worklist);
  1581. auto LPMAddNewLoop = [&](Loop *NL, bool IsSubloop) {
  1582. if (!IsSubloop)
  1583. appendLoopsToWorklist(*NL, Worklist);
  1584. };
  1585. while (!Worklist.empty()) {
  1586. Loop *L = Worklist.pop_back_val();
  1587. Changed |= IRCE.run(L, LPMAddNewLoop);
  1588. }
  1589. return Changed;
  1590. }
  1591. bool
  1592. InductiveRangeCheckElimination::isProfitableToTransform(const Loop &L,
  1593. LoopStructure &LS) {
  1594. if (SkipProfitabilityChecks)
  1595. return true;
  1596. if (GetBFI) {
  1597. BlockFrequencyInfo &BFI = (*GetBFI)();
  1598. uint64_t hFreq = BFI.getBlockFreq(LS.Header).getFrequency();
  1599. uint64_t phFreq = BFI.getBlockFreq(L.getLoopPreheader()).getFrequency();
  1600. if (phFreq != 0 && hFreq != 0 && (hFreq / phFreq < MinRuntimeIterations)) {
  1601. LLVM_DEBUG(dbgs() << "irce: could not prove profitability: "
  1602. << "the estimated number of iterations basing on "
  1603. "frequency info is " << (hFreq / phFreq) << "\n";);
  1604. return false;
  1605. }
  1606. return true;
  1607. }
  1608. if (!BPI)
  1609. return true;
  1610. BranchProbability ExitProbability =
  1611. BPI->getEdgeProbability(LS.Latch, LS.LatchBrExitIdx);
  1612. if (ExitProbability > BranchProbability(1, MinRuntimeIterations)) {
  1613. LLVM_DEBUG(dbgs() << "irce: could not prove profitability: "
  1614. << "the exit probability is too big " << ExitProbability
  1615. << "\n";);
  1616. return false;
  1617. }
  1618. return true;
  1619. }
  1620. bool InductiveRangeCheckElimination::run(
  1621. Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop) {
  1622. if (L->getBlocks().size() >= LoopSizeCutoff) {
  1623. LLVM_DEBUG(dbgs() << "irce: giving up constraining loop, too large\n");
  1624. return false;
  1625. }
  1626. BasicBlock *Preheader = L->getLoopPreheader();
  1627. if (!Preheader) {
  1628. LLVM_DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
  1629. return false;
  1630. }
  1631. LLVMContext &Context = Preheader->getContext();
  1632. SmallVector<InductiveRangeCheck, 16> RangeChecks;
  1633. for (auto *BBI : L->getBlocks())
  1634. if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
  1635. InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
  1636. RangeChecks);
  1637. if (RangeChecks.empty())
  1638. return false;
  1639. auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
  1640. OS << "irce: looking at loop "; L->print(OS);
  1641. OS << "irce: loop has " << RangeChecks.size()
  1642. << " inductive range checks: \n";
  1643. for (InductiveRangeCheck &IRC : RangeChecks)
  1644. IRC.print(OS);
  1645. };
  1646. LLVM_DEBUG(PrintRecognizedRangeChecks(dbgs()));
  1647. if (PrintRangeChecks)
  1648. PrintRecognizedRangeChecks(errs());
  1649. const char *FailureReason = nullptr;
  1650. std::optional<LoopStructure> MaybeLoopStructure =
  1651. LoopStructure::parseLoopStructure(SE, *L, FailureReason);
  1652. if (!MaybeLoopStructure) {
  1653. LLVM_DEBUG(dbgs() << "irce: could not parse loop structure: "
  1654. << FailureReason << "\n";);
  1655. return false;
  1656. }
  1657. LoopStructure LS = *MaybeLoopStructure;
  1658. if (!isProfitableToTransform(*L, LS))
  1659. return false;
  1660. const SCEVAddRecExpr *IndVar =
  1661. cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep)));
  1662. std::optional<InductiveRangeCheck::Range> SafeIterRange;
  1663. Instruction *ExprInsertPt = Preheader->getTerminator();
  1664. SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
  1665. // Basing on the type of latch predicate, we interpret the IV iteration range
  1666. // as signed or unsigned range. We use different min/max functions (signed or
  1667. // unsigned) when intersecting this range with safe iteration ranges implied
  1668. // by range checks.
  1669. auto IntersectRange =
  1670. LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange;
  1671. IRBuilder<> B(ExprInsertPt);
  1672. for (InductiveRangeCheck &IRC : RangeChecks) {
  1673. auto Result = IRC.computeSafeIterationSpace(SE, IndVar,
  1674. LS.IsSignedPredicate);
  1675. if (Result) {
  1676. auto MaybeSafeIterRange = IntersectRange(SE, SafeIterRange, *Result);
  1677. if (MaybeSafeIterRange) {
  1678. assert(!MaybeSafeIterRange->isEmpty(SE, LS.IsSignedPredicate) &&
  1679. "We should never return empty ranges!");
  1680. RangeChecksToEliminate.push_back(IRC);
  1681. SafeIterRange = *MaybeSafeIterRange;
  1682. }
  1683. }
  1684. }
  1685. if (!SafeIterRange)
  1686. return false;
  1687. LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT, *SafeIterRange);
  1688. bool Changed = LC.run();
  1689. if (Changed) {
  1690. auto PrintConstrainedLoopInfo = [L]() {
  1691. dbgs() << "irce: in function ";
  1692. dbgs() << L->getHeader()->getParent()->getName() << ": ";
  1693. dbgs() << "constrained ";
  1694. L->print(dbgs());
  1695. };
  1696. LLVM_DEBUG(PrintConstrainedLoopInfo());
  1697. if (PrintChangedLoops)
  1698. PrintConstrainedLoopInfo();
  1699. // Optimize away the now-redundant range checks.
  1700. for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
  1701. ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
  1702. ? ConstantInt::getTrue(Context)
  1703. : ConstantInt::getFalse(Context);
  1704. IRC.getCheckUse()->set(FoldedRangeCheck);
  1705. }
  1706. }
  1707. return Changed;
  1708. }
  1709. Pass *llvm::createInductiveRangeCheckEliminationPass() {
  1710. return new IRCELegacyPass();
  1711. }