ScalarEvolution.h 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237
  1. //===- llvm/Analysis/ScalarEvolution.h - Scalar Evolution -------*- C++ -*-===//
  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 ScalarEvolution class is an LLVM pass which can be used to analyze and
  10. // categorize scalar expressions in loops. It specializes in recognizing
  11. // general induction variables, representing them with the abstract and opaque
  12. // SCEV class. Given this analysis, trip counts of loops and other important
  13. // properties can be obtained.
  14. //
  15. // This analysis is primarily useful for induction variable substitution and
  16. // strength reduction.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_ANALYSIS_SCALAREVOLUTION_H
  20. #define LLVM_ANALYSIS_SCALAREVOLUTION_H
  21. #include "llvm/ADT/APInt.h"
  22. #include "llvm/ADT/ArrayRef.h"
  23. #include "llvm/ADT/DenseMap.h"
  24. #include "llvm/ADT/DenseMapInfo.h"
  25. #include "llvm/ADT/FoldingSet.h"
  26. #include "llvm/ADT/Hashing.h"
  27. #include "llvm/ADT/Optional.h"
  28. #include "llvm/ADT/PointerIntPair.h"
  29. #include "llvm/ADT/SetVector.h"
  30. #include "llvm/ADT/SmallPtrSet.h"
  31. #include "llvm/ADT/SmallVector.h"
  32. #include "llvm/IR/ConstantRange.h"
  33. #include "llvm/IR/Function.h"
  34. #include "llvm/IR/InstrTypes.h"
  35. #include "llvm/IR/Instructions.h"
  36. #include "llvm/IR/Operator.h"
  37. #include "llvm/IR/PassManager.h"
  38. #include "llvm/IR/ValueHandle.h"
  39. #include "llvm/IR/ValueMap.h"
  40. #include "llvm/Pass.h"
  41. #include "llvm/Support/Allocator.h"
  42. #include "llvm/Support/Casting.h"
  43. #include "llvm/Support/Compiler.h"
  44. #include <algorithm>
  45. #include <cassert>
  46. #include <cstdint>
  47. #include <memory>
  48. #include <utility>
  49. namespace llvm {
  50. class AssumptionCache;
  51. class BasicBlock;
  52. class Constant;
  53. class ConstantInt;
  54. class DataLayout;
  55. class DominatorTree;
  56. class GEPOperator;
  57. class Instruction;
  58. class LLVMContext;
  59. class Loop;
  60. class LoopInfo;
  61. class raw_ostream;
  62. class ScalarEvolution;
  63. class SCEVAddRecExpr;
  64. class SCEVUnknown;
  65. class StructType;
  66. class TargetLibraryInfo;
  67. class Type;
  68. class Value;
  69. enum SCEVTypes : unsigned short;
  70. /// This class represents an analyzed expression in the program. These are
  71. /// opaque objects that the client is not allowed to do much with directly.
  72. ///
  73. class SCEV : public FoldingSetNode {
  74. friend struct FoldingSetTrait<SCEV>;
  75. /// A reference to an Interned FoldingSetNodeID for this node. The
  76. /// ScalarEvolution's BumpPtrAllocator holds the data.
  77. FoldingSetNodeIDRef FastID;
  78. // The SCEV baseclass this node corresponds to
  79. const SCEVTypes SCEVType;
  80. protected:
  81. // Estimated complexity of this node's expression tree size.
  82. const unsigned short ExpressionSize;
  83. /// This field is initialized to zero and may be used in subclasses to store
  84. /// miscellaneous information.
  85. unsigned short SubclassData = 0;
  86. public:
  87. /// NoWrapFlags are bitfield indices into SubclassData.
  88. ///
  89. /// Add and Mul expressions may have no-unsigned-wrap <NUW> or
  90. /// no-signed-wrap <NSW> properties, which are derived from the IR
  91. /// operator. NSW is a misnomer that we use to mean no signed overflow or
  92. /// underflow.
  93. ///
  94. /// AddRec expressions may have a no-self-wraparound <NW> property if, in
  95. /// the integer domain, abs(step) * max-iteration(loop) <=
  96. /// unsigned-max(bitwidth). This means that the recurrence will never reach
  97. /// its start value if the step is non-zero. Computing the same value on
  98. /// each iteration is not considered wrapping, and recurrences with step = 0
  99. /// are trivially <NW>. <NW> is independent of the sign of step and the
  100. /// value the add recurrence starts with.
  101. ///
  102. /// Note that NUW and NSW are also valid properties of a recurrence, and
  103. /// either implies NW. For convenience, NW will be set for a recurrence
  104. /// whenever either NUW or NSW are set.
  105. enum NoWrapFlags {
  106. FlagAnyWrap = 0, // No guarantee.
  107. FlagNW = (1 << 0), // No self-wrap.
  108. FlagNUW = (1 << 1), // No unsigned wrap.
  109. FlagNSW = (1 << 2), // No signed wrap.
  110. NoWrapMask = (1 << 3) - 1
  111. };
  112. explicit SCEV(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
  113. unsigned short ExpressionSize)
  114. : FastID(ID), SCEVType(SCEVTy), ExpressionSize(ExpressionSize) {}
  115. SCEV(const SCEV &) = delete;
  116. SCEV &operator=(const SCEV &) = delete;
  117. SCEVTypes getSCEVType() const { return SCEVType; }
  118. /// Return the LLVM type of this SCEV expression.
  119. Type *getType() const;
  120. /// Return true if the expression is a constant zero.
  121. bool isZero() const;
  122. /// Return true if the expression is a constant one.
  123. bool isOne() const;
  124. /// Return true if the expression is a constant all-ones value.
  125. bool isAllOnesValue() const;
  126. /// Return true if the specified scev is negated, but not a constant.
  127. bool isNonConstantNegative() const;
  128. // Returns estimated size of the mathematical expression represented by this
  129. // SCEV. The rules of its calculation are following:
  130. // 1) Size of a SCEV without operands (like constants and SCEVUnknown) is 1;
  131. // 2) Size SCEV with operands Op1, Op2, ..., OpN is calculated by formula:
  132. // (1 + Size(Op1) + ... + Size(OpN)).
  133. // This value gives us an estimation of time we need to traverse through this
  134. // SCEV and all its operands recursively. We may use it to avoid performing
  135. // heavy transformations on SCEVs of excessive size for sake of saving the
  136. // compilation time.
  137. unsigned short getExpressionSize() const {
  138. return ExpressionSize;
  139. }
  140. /// Print out the internal representation of this scalar to the specified
  141. /// stream. This should really only be used for debugging purposes.
  142. void print(raw_ostream &OS) const;
  143. /// This method is used for debugging.
  144. void dump() const;
  145. };
  146. // Specialize FoldingSetTrait for SCEV to avoid needing to compute
  147. // temporary FoldingSetNodeID values.
  148. template <> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
  149. static void Profile(const SCEV &X, FoldingSetNodeID &ID) { ID = X.FastID; }
  150. static bool Equals(const SCEV &X, const FoldingSetNodeID &ID, unsigned IDHash,
  151. FoldingSetNodeID &TempID) {
  152. return ID == X.FastID;
  153. }
  154. static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
  155. return X.FastID.ComputeHash();
  156. }
  157. };
  158. inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
  159. S.print(OS);
  160. return OS;
  161. }
  162. /// An object of this class is returned by queries that could not be answered.
  163. /// For example, if you ask for the number of iterations of a linked-list
  164. /// traversal loop, you will get one of these. None of the standard SCEV
  165. /// operations are valid on this class, it is just a marker.
  166. struct SCEVCouldNotCompute : public SCEV {
  167. SCEVCouldNotCompute();
  168. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  169. static bool classof(const SCEV *S);
  170. };
  171. /// This class represents an assumption made using SCEV expressions which can
  172. /// be checked at run-time.
  173. class SCEVPredicate : public FoldingSetNode {
  174. friend struct FoldingSetTrait<SCEVPredicate>;
  175. /// A reference to an Interned FoldingSetNodeID for this node. The
  176. /// ScalarEvolution's BumpPtrAllocator holds the data.
  177. FoldingSetNodeIDRef FastID;
  178. public:
  179. enum SCEVPredicateKind { P_Union, P_Equal, P_Wrap };
  180. protected:
  181. SCEVPredicateKind Kind;
  182. ~SCEVPredicate() = default;
  183. SCEVPredicate(const SCEVPredicate &) = default;
  184. SCEVPredicate &operator=(const SCEVPredicate &) = default;
  185. public:
  186. SCEVPredicate(const FoldingSetNodeIDRef ID, SCEVPredicateKind Kind);
  187. SCEVPredicateKind getKind() const { return Kind; }
  188. /// Returns the estimated complexity of this predicate. This is roughly
  189. /// measured in the number of run-time checks required.
  190. virtual unsigned getComplexity() const { return 1; }
  191. /// Returns true if the predicate is always true. This means that no
  192. /// assumptions were made and nothing needs to be checked at run-time.
  193. virtual bool isAlwaysTrue() const = 0;
  194. /// Returns true if this predicate implies \p N.
  195. virtual bool implies(const SCEVPredicate *N) const = 0;
  196. /// Prints a textual representation of this predicate with an indentation of
  197. /// \p Depth.
  198. virtual void print(raw_ostream &OS, unsigned Depth = 0) const = 0;
  199. /// Returns the SCEV to which this predicate applies, or nullptr if this is
  200. /// a SCEVUnionPredicate.
  201. virtual const SCEV *getExpr() const = 0;
  202. };
  203. inline raw_ostream &operator<<(raw_ostream &OS, const SCEVPredicate &P) {
  204. P.print(OS);
  205. return OS;
  206. }
  207. // Specialize FoldingSetTrait for SCEVPredicate to avoid needing to compute
  208. // temporary FoldingSetNodeID values.
  209. template <>
  210. struct FoldingSetTrait<SCEVPredicate> : DefaultFoldingSetTrait<SCEVPredicate> {
  211. static void Profile(const SCEVPredicate &X, FoldingSetNodeID &ID) {
  212. ID = X.FastID;
  213. }
  214. static bool Equals(const SCEVPredicate &X, const FoldingSetNodeID &ID,
  215. unsigned IDHash, FoldingSetNodeID &TempID) {
  216. return ID == X.FastID;
  217. }
  218. static unsigned ComputeHash(const SCEVPredicate &X,
  219. FoldingSetNodeID &TempID) {
  220. return X.FastID.ComputeHash();
  221. }
  222. };
  223. /// This class represents an assumption that two SCEV expressions are equal,
  224. /// and this can be checked at run-time.
  225. class SCEVEqualPredicate final : public SCEVPredicate {
  226. /// We assume that LHS == RHS.
  227. const SCEV *LHS;
  228. const SCEV *RHS;
  229. public:
  230. SCEVEqualPredicate(const FoldingSetNodeIDRef ID, const SCEV *LHS,
  231. const SCEV *RHS);
  232. /// Implementation of the SCEVPredicate interface
  233. bool implies(const SCEVPredicate *N) const override;
  234. void print(raw_ostream &OS, unsigned Depth = 0) const override;
  235. bool isAlwaysTrue() const override;
  236. const SCEV *getExpr() const override;
  237. /// Returns the left hand side of the equality.
  238. const SCEV *getLHS() const { return LHS; }
  239. /// Returns the right hand side of the equality.
  240. const SCEV *getRHS() const { return RHS; }
  241. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  242. static bool classof(const SCEVPredicate *P) {
  243. return P->getKind() == P_Equal;
  244. }
  245. };
  246. /// This class represents an assumption made on an AddRec expression. Given an
  247. /// affine AddRec expression {a,+,b}, we assume that it has the nssw or nusw
  248. /// flags (defined below) in the first X iterations of the loop, where X is a
  249. /// SCEV expression returned by getPredicatedBackedgeTakenCount).
  250. ///
  251. /// Note that this does not imply that X is equal to the backedge taken
  252. /// count. This means that if we have a nusw predicate for i32 {0,+,1} with a
  253. /// predicated backedge taken count of X, we only guarantee that {0,+,1} has
  254. /// nusw in the first X iterations. {0,+,1} may still wrap in the loop if we
  255. /// have more than X iterations.
  256. class SCEVWrapPredicate final : public SCEVPredicate {
  257. public:
  258. /// Similar to SCEV::NoWrapFlags, but with slightly different semantics
  259. /// for FlagNUSW. The increment is considered to be signed, and a + b
  260. /// (where b is the increment) is considered to wrap if:
  261. /// zext(a + b) != zext(a) + sext(b)
  262. ///
  263. /// If Signed is a function that takes an n-bit tuple and maps to the
  264. /// integer domain as the tuples value interpreted as twos complement,
  265. /// and Unsigned a function that takes an n-bit tuple and maps to the
  266. /// integer domain as as the base two value of input tuple, then a + b
  267. /// has IncrementNUSW iff:
  268. ///
  269. /// 0 <= Unsigned(a) + Signed(b) < 2^n
  270. ///
  271. /// The IncrementNSSW flag has identical semantics with SCEV::FlagNSW.
  272. ///
  273. /// Note that the IncrementNUSW flag is not commutative: if base + inc
  274. /// has IncrementNUSW, then inc + base doesn't neccessarily have this
  275. /// property. The reason for this is that this is used for sign/zero
  276. /// extending affine AddRec SCEV expressions when a SCEVWrapPredicate is
  277. /// assumed. A {base,+,inc} expression is already non-commutative with
  278. /// regards to base and inc, since it is interpreted as:
  279. /// (((base + inc) + inc) + inc) ...
  280. enum IncrementWrapFlags {
  281. IncrementAnyWrap = 0, // No guarantee.
  282. IncrementNUSW = (1 << 0), // No unsigned with signed increment wrap.
  283. IncrementNSSW = (1 << 1), // No signed with signed increment wrap
  284. // (equivalent with SCEV::NSW)
  285. IncrementNoWrapMask = (1 << 2) - 1
  286. };
  287. /// Convenient IncrementWrapFlags manipulation methods.
  288. LLVM_NODISCARD static SCEVWrapPredicate::IncrementWrapFlags
  289. clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags,
  290. SCEVWrapPredicate::IncrementWrapFlags OffFlags) {
  291. assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!");
  292. assert((OffFlags & IncrementNoWrapMask) == OffFlags &&
  293. "Invalid flags value!");
  294. return (SCEVWrapPredicate::IncrementWrapFlags)(Flags & ~OffFlags);
  295. }
  296. LLVM_NODISCARD static SCEVWrapPredicate::IncrementWrapFlags
  297. maskFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, int Mask) {
  298. assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!");
  299. assert((Mask & IncrementNoWrapMask) == Mask && "Invalid mask value!");
  300. return (SCEVWrapPredicate::IncrementWrapFlags)(Flags & Mask);
  301. }
  302. LLVM_NODISCARD static SCEVWrapPredicate::IncrementWrapFlags
  303. setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags,
  304. SCEVWrapPredicate::IncrementWrapFlags OnFlags) {
  305. assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!");
  306. assert((OnFlags & IncrementNoWrapMask) == OnFlags &&
  307. "Invalid flags value!");
  308. return (SCEVWrapPredicate::IncrementWrapFlags)(Flags | OnFlags);
  309. }
  310. /// Returns the set of SCEVWrapPredicate no wrap flags implied by a
  311. /// SCEVAddRecExpr.
  312. LLVM_NODISCARD static SCEVWrapPredicate::IncrementWrapFlags
  313. getImpliedFlags(const SCEVAddRecExpr *AR, ScalarEvolution &SE);
  314. private:
  315. const SCEVAddRecExpr *AR;
  316. IncrementWrapFlags Flags;
  317. public:
  318. explicit SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
  319. const SCEVAddRecExpr *AR,
  320. IncrementWrapFlags Flags);
  321. /// Returns the set assumed no overflow flags.
  322. IncrementWrapFlags getFlags() const { return Flags; }
  323. /// Implementation of the SCEVPredicate interface
  324. const SCEV *getExpr() const override;
  325. bool implies(const SCEVPredicate *N) const override;
  326. void print(raw_ostream &OS, unsigned Depth = 0) const override;
  327. bool isAlwaysTrue() const override;
  328. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  329. static bool classof(const SCEVPredicate *P) {
  330. return P->getKind() == P_Wrap;
  331. }
  332. };
  333. /// This class represents a composition of other SCEV predicates, and is the
  334. /// class that most clients will interact with. This is equivalent to a
  335. /// logical "AND" of all the predicates in the union.
  336. ///
  337. /// NB! Unlike other SCEVPredicate sub-classes this class does not live in the
  338. /// ScalarEvolution::Preds folding set. This is why the \c add function is sound.
  339. class SCEVUnionPredicate final : public SCEVPredicate {
  340. private:
  341. using PredicateMap =
  342. DenseMap<const SCEV *, SmallVector<const SCEVPredicate *, 4>>;
  343. /// Vector with references to all predicates in this union.
  344. SmallVector<const SCEVPredicate *, 16> Preds;
  345. /// Maps SCEVs to predicates for quick look-ups.
  346. PredicateMap SCEVToPreds;
  347. public:
  348. SCEVUnionPredicate();
  349. const SmallVectorImpl<const SCEVPredicate *> &getPredicates() const {
  350. return Preds;
  351. }
  352. /// Adds a predicate to this union.
  353. void add(const SCEVPredicate *N);
  354. /// Returns a reference to a vector containing all predicates which apply to
  355. /// \p Expr.
  356. ArrayRef<const SCEVPredicate *> getPredicatesForExpr(const SCEV *Expr);
  357. /// Implementation of the SCEVPredicate interface
  358. bool isAlwaysTrue() const override;
  359. bool implies(const SCEVPredicate *N) const override;
  360. void print(raw_ostream &OS, unsigned Depth) const override;
  361. const SCEV *getExpr() const override;
  362. /// We estimate the complexity of a union predicate as the size number of
  363. /// predicates in the union.
  364. unsigned getComplexity() const override { return Preds.size(); }
  365. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  366. static bool classof(const SCEVPredicate *P) {
  367. return P->getKind() == P_Union;
  368. }
  369. };
  370. /// The main scalar evolution driver. Because client code (intentionally)
  371. /// can't do much with the SCEV objects directly, they must ask this class
  372. /// for services.
  373. class ScalarEvolution {
  374. friend class ScalarEvolutionsTest;
  375. public:
  376. /// An enum describing the relationship between a SCEV and a loop.
  377. enum LoopDisposition {
  378. LoopVariant, ///< The SCEV is loop-variant (unknown).
  379. LoopInvariant, ///< The SCEV is loop-invariant.
  380. LoopComputable ///< The SCEV varies predictably with the loop.
  381. };
  382. /// An enum describing the relationship between a SCEV and a basic block.
  383. enum BlockDisposition {
  384. DoesNotDominateBlock, ///< The SCEV does not dominate the block.
  385. DominatesBlock, ///< The SCEV dominates the block.
  386. ProperlyDominatesBlock ///< The SCEV properly dominates the block.
  387. };
  388. /// Convenient NoWrapFlags manipulation that hides enum casts and is
  389. /// visible in the ScalarEvolution name space.
  390. LLVM_NODISCARD static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags,
  391. int Mask) {
  392. return (SCEV::NoWrapFlags)(Flags & Mask);
  393. }
  394. LLVM_NODISCARD static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags,
  395. SCEV::NoWrapFlags OnFlags) {
  396. return (SCEV::NoWrapFlags)(Flags | OnFlags);
  397. }
  398. LLVM_NODISCARD static SCEV::NoWrapFlags
  399. clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags) {
  400. return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
  401. }
  402. ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC,
  403. DominatorTree &DT, LoopInfo &LI);
  404. ScalarEvolution(ScalarEvolution &&Arg);
  405. ~ScalarEvolution();
  406. LLVMContext &getContext() const { return F.getContext(); }
  407. /// Test if values of the given type are analyzable within the SCEV
  408. /// framework. This primarily includes integer types, and it can optionally
  409. /// include pointer types if the ScalarEvolution class has access to
  410. /// target-specific information.
  411. bool isSCEVable(Type *Ty) const;
  412. /// Return the size in bits of the specified type, for which isSCEVable must
  413. /// return true.
  414. uint64_t getTypeSizeInBits(Type *Ty) const;
  415. /// Return a type with the same bitwidth as the given type and which
  416. /// represents how SCEV will treat the given type, for which isSCEVable must
  417. /// return true. For pointer types, this is the pointer-sized integer type.
  418. Type *getEffectiveSCEVType(Type *Ty) const;
  419. // Returns a wider type among {Ty1, Ty2}.
  420. Type *getWiderType(Type *Ty1, Type *Ty2) const;
  421. /// Return true if the SCEV is a scAddRecExpr or it contains
  422. /// scAddRecExpr. The result will be cached in HasRecMap.
  423. bool containsAddRecurrence(const SCEV *S);
  424. /// Erase Value from ValueExprMap and ExprValueMap.
  425. void eraseValueFromMap(Value *V);
  426. /// Return a SCEV expression for the full generality of the specified
  427. /// expression.
  428. const SCEV *getSCEV(Value *V);
  429. const SCEV *getConstant(ConstantInt *V);
  430. const SCEV *getConstant(const APInt &Val);
  431. const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
  432. const SCEV *getLosslessPtrToIntExpr(const SCEV *Op, unsigned Depth = 0);
  433. const SCEV *getPtrToIntExpr(const SCEV *Op, Type *Ty);
  434. const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty, unsigned Depth = 0);
  435. const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth = 0);
  436. const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth = 0);
  437. const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
  438. const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
  439. SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap,
  440. unsigned Depth = 0);
  441. const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
  442. SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap,
  443. unsigned Depth = 0) {
  444. SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
  445. return getAddExpr(Ops, Flags, Depth);
  446. }
  447. const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
  448. SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap,
  449. unsigned Depth = 0) {
  450. SmallVector<const SCEV *, 3> Ops = {Op0, Op1, Op2};
  451. return getAddExpr(Ops, Flags, Depth);
  452. }
  453. const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
  454. SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap,
  455. unsigned Depth = 0);
  456. const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
  457. SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap,
  458. unsigned Depth = 0) {
  459. SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
  460. return getMulExpr(Ops, Flags, Depth);
  461. }
  462. const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
  463. SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap,
  464. unsigned Depth = 0) {
  465. SmallVector<const SCEV *, 3> Ops = {Op0, Op1, Op2};
  466. return getMulExpr(Ops, Flags, Depth);
  467. }
  468. const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
  469. const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS);
  470. const SCEV *getURemExpr(const SCEV *LHS, const SCEV *RHS);
  471. const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L,
  472. SCEV::NoWrapFlags Flags);
  473. const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
  474. const Loop *L, SCEV::NoWrapFlags Flags);
  475. const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
  476. const Loop *L, SCEV::NoWrapFlags Flags) {
  477. SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
  478. return getAddRecExpr(NewOp, L, Flags);
  479. }
  480. /// Checks if \p SymbolicPHI can be rewritten as an AddRecExpr under some
  481. /// Predicates. If successful return these <AddRecExpr, Predicates>;
  482. /// The function is intended to be called from PSCEV (the caller will decide
  483. /// whether to actually add the predicates and carry out the rewrites).
  484. Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
  485. createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI);
  486. /// Returns an expression for a GEP
  487. ///
  488. /// \p GEP The GEP. The indices contained in the GEP itself are ignored,
  489. /// instead we use IndexExprs.
  490. /// \p IndexExprs The expressions for the indices.
  491. const SCEV *getGEPExpr(GEPOperator *GEP,
  492. const SmallVectorImpl<const SCEV *> &IndexExprs);
  493. const SCEV *getAbsExpr(const SCEV *Op, bool IsNSW);
  494. const SCEV *getMinMaxExpr(SCEVTypes Kind,
  495. SmallVectorImpl<const SCEV *> &Operands);
  496. const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
  497. const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
  498. const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
  499. const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
  500. const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
  501. const SCEV *getSMinExpr(SmallVectorImpl<const SCEV *> &Operands);
  502. const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
  503. const SCEV *getUMinExpr(SmallVectorImpl<const SCEV *> &Operands);
  504. const SCEV *getUnknown(Value *V);
  505. const SCEV *getCouldNotCompute();
  506. /// Return a SCEV for the constant 0 of a specific type.
  507. const SCEV *getZero(Type *Ty) { return getConstant(Ty, 0); }
  508. /// Return a SCEV for the constant 1 of a specific type.
  509. const SCEV *getOne(Type *Ty) { return getConstant(Ty, 1); }
  510. /// Return a SCEV for the constant -1 of a specific type.
  511. const SCEV *getMinusOne(Type *Ty) {
  512. return getConstant(Ty, -1, /*isSigned=*/true);
  513. }
  514. /// Return an expression for sizeof ScalableTy that is type IntTy, where
  515. /// ScalableTy is a scalable vector type.
  516. const SCEV *getSizeOfScalableVectorExpr(Type *IntTy,
  517. ScalableVectorType *ScalableTy);
  518. /// Return an expression for the alloc size of AllocTy that is type IntTy
  519. const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
  520. /// Return an expression for the store size of StoreTy that is type IntTy
  521. const SCEV *getStoreSizeOfExpr(Type *IntTy, Type *StoreTy);
  522. /// Return an expression for offsetof on the given field with type IntTy
  523. const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo);
  524. /// Return the SCEV object corresponding to -V.
  525. const SCEV *getNegativeSCEV(const SCEV *V,
  526. SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
  527. /// Return the SCEV object corresponding to ~V.
  528. const SCEV *getNotSCEV(const SCEV *V);
  529. /// Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
  530. const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
  531. SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap,
  532. unsigned Depth = 0);
  533. /// Return a SCEV corresponding to a conversion of the input value to the
  534. /// specified type. If the type must be extended, it is zero extended.
  535. const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
  536. unsigned Depth = 0);
  537. /// Return a SCEV corresponding to a conversion of the input value to the
  538. /// specified type. If the type must be extended, it is sign extended.
  539. const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty,
  540. unsigned Depth = 0);
  541. /// Return a SCEV corresponding to a conversion of the input value to the
  542. /// specified type. If the type must be extended, it is zero extended. The
  543. /// conversion must not be narrowing.
  544. const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
  545. /// Return a SCEV corresponding to a conversion of the input value to the
  546. /// specified type. If the type must be extended, it is sign extended. The
  547. /// conversion must not be narrowing.
  548. const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
  549. /// Return a SCEV corresponding to a conversion of the input value to the
  550. /// specified type. If the type must be extended, it is extended with
  551. /// unspecified bits. The conversion must not be narrowing.
  552. const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
  553. /// Return a SCEV corresponding to a conversion of the input value to the
  554. /// specified type. The conversion must not be widening.
  555. const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
  556. /// Promote the operands to the wider of the types using zero-extension, and
  557. /// then perform a umax operation with them.
  558. const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS);
  559. /// Promote the operands to the wider of the types using zero-extension, and
  560. /// then perform a umin operation with them.
  561. const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS);
  562. /// Promote the operands to the wider of the types using zero-extension, and
  563. /// then perform a umin operation with them. N-ary function.
  564. const SCEV *getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops);
  565. /// Transitively follow the chain of pointer-type operands until reaching a
  566. /// SCEV that does not have a single pointer operand. This returns a
  567. /// SCEVUnknown pointer for well-formed pointer-type expressions, but corner
  568. /// cases do exist.
  569. const SCEV *getPointerBase(const SCEV *V);
  570. /// Return a SCEV expression for the specified value at the specified scope
  571. /// in the program. The L value specifies a loop nest to evaluate the
  572. /// expression at, where null is the top-level or a specified loop is
  573. /// immediately inside of the loop.
  574. ///
  575. /// This method can be used to compute the exit value for a variable defined
  576. /// in a loop by querying what the value will hold in the parent loop.
  577. ///
  578. /// In the case that a relevant loop exit value cannot be computed, the
  579. /// original value V is returned.
  580. const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
  581. /// This is a convenience function which does getSCEVAtScope(getSCEV(V), L).
  582. const SCEV *getSCEVAtScope(Value *V, const Loop *L);
  583. /// Test whether entry to the loop is protected by a conditional between LHS
  584. /// and RHS. This is used to help avoid max expressions in loop trip
  585. /// counts, and to eliminate casts.
  586. bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
  587. const SCEV *LHS, const SCEV *RHS);
  588. /// Test whether entry to the basic block is protected by a conditional
  589. /// between LHS and RHS.
  590. bool isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
  591. ICmpInst::Predicate Pred, const SCEV *LHS,
  592. const SCEV *RHS);
  593. /// Test whether the backedge of the loop is protected by a conditional
  594. /// between LHS and RHS. This is used to eliminate casts.
  595. bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
  596. const SCEV *LHS, const SCEV *RHS);
  597. /// Convert from an "exit count" (i.e. "backedge taken count") to a "trip
  598. /// count". A "trip count" is the number of times the header of the loop
  599. /// will execute if an exit is taken after the specified number of backedges
  600. /// have been taken. (e.g. TripCount = ExitCount + 1) A zero result
  601. /// must be interpreted as a loop having an unknown trip count.
  602. const SCEV *getTripCountFromExitCount(const SCEV *ExitCount);
  603. /// Returns the exact trip count of the loop if we can compute it, and
  604. /// the result is a small constant. '0' is used to represent an unknown
  605. /// or non-constant trip count. Note that a trip count is simply one more
  606. /// than the backedge taken count for the loop.
  607. unsigned getSmallConstantTripCount(const Loop *L);
  608. /// Return the exact trip count for this loop if we exit through ExitingBlock.
  609. /// '0' is used to represent an unknown or non-constant trip count. Note
  610. /// that a trip count is simply one more than the backedge taken count for
  611. /// the same exit.
  612. /// This "trip count" assumes that control exits via ExitingBlock. More
  613. /// precisely, it is the number of times that control will reach ExitingBlock
  614. /// before taking the branch. For loops with multiple exits, it may not be
  615. /// the number times that the loop header executes if the loop exits
  616. /// prematurely via another branch.
  617. unsigned getSmallConstantTripCount(const Loop *L,
  618. const BasicBlock *ExitingBlock);
  619. /// Returns the upper bound of the loop trip count as a normal unsigned
  620. /// value.
  621. /// Returns 0 if the trip count is unknown or not constant.
  622. unsigned getSmallConstantMaxTripCount(const Loop *L);
  623. /// Returns the largest constant divisor of the trip count as a normal
  624. /// unsigned value, if possible. This means that the actual trip count is
  625. /// always a multiple of the returned value. Returns 1 if the trip count is
  626. /// unknown or not guaranteed to be the multiple of a constant., Will also
  627. /// return 1 if the trip count is very large (>= 2^32).
  628. /// Note that the argument is an exit count for loop L, NOT a trip count.
  629. unsigned getSmallConstantTripMultiple(const Loop *L,
  630. const SCEV *ExitCount);
  631. /// Returns the largest constant divisor of the trip count of the
  632. /// loop. Will return 1 if no trip count could be computed, or if a
  633. /// divisor could not be found.
  634. unsigned getSmallConstantTripMultiple(const Loop *L);
  635. /// Returns the largest constant divisor of the trip count of this loop as a
  636. /// normal unsigned value, if possible. This means that the actual trip
  637. /// count is always a multiple of the returned value (don't forget the trip
  638. /// count could very well be zero as well!). As explained in the comments
  639. /// for getSmallConstantTripCount, this assumes that control exits the loop
  640. /// via ExitingBlock.
  641. unsigned getSmallConstantTripMultiple(const Loop *L,
  642. const BasicBlock *ExitingBlock);
  643. /// The terms "backedge taken count" and "exit count" are used
  644. /// interchangeably to refer to the number of times the backedge of a loop
  645. /// has executed before the loop is exited.
  646. enum ExitCountKind {
  647. /// An expression exactly describing the number of times the backedge has
  648. /// executed when a loop is exited.
  649. Exact,
  650. /// A constant which provides an upper bound on the exact trip count.
  651. ConstantMaximum,
  652. /// An expression which provides an upper bound on the exact trip count.
  653. SymbolicMaximum,
  654. };
  655. /// Return the number of times the backedge executes before the given exit
  656. /// would be taken; if not exactly computable, return SCEVCouldNotCompute.
  657. /// For a single exit loop, this value is equivelent to the result of
  658. /// getBackedgeTakenCount. The loop is guaranteed to exit (via *some* exit)
  659. /// before the backedge is executed (ExitCount + 1) times. Note that there
  660. /// is no guarantee about *which* exit is taken on the exiting iteration.
  661. const SCEV *getExitCount(const Loop *L, const BasicBlock *ExitingBlock,
  662. ExitCountKind Kind = Exact);
  663. /// If the specified loop has a predictable backedge-taken count, return it,
  664. /// otherwise return a SCEVCouldNotCompute object. The backedge-taken count is
  665. /// the number of times the loop header will be branched to from within the
  666. /// loop, assuming there are no abnormal exists like exception throws. This is
  667. /// one less than the trip count of the loop, since it doesn't count the first
  668. /// iteration, when the header is branched to from outside the loop.
  669. ///
  670. /// Note that it is not valid to call this method on a loop without a
  671. /// loop-invariant backedge-taken count (see
  672. /// hasLoopInvariantBackedgeTakenCount).
  673. const SCEV *getBackedgeTakenCount(const Loop *L, ExitCountKind Kind = Exact);
  674. /// Similar to getBackedgeTakenCount, except it will add a set of
  675. /// SCEV predicates to Predicates that are required to be true in order for
  676. /// the answer to be correct. Predicates can be checked with run-time
  677. /// checks and can be used to perform loop versioning.
  678. const SCEV *getPredicatedBackedgeTakenCount(const Loop *L,
  679. SCEVUnionPredicate &Predicates);
  680. /// When successful, this returns a SCEVConstant that is greater than or equal
  681. /// to (i.e. a "conservative over-approximation") of the value returend by
  682. /// getBackedgeTakenCount. If such a value cannot be computed, it returns the
  683. /// SCEVCouldNotCompute object.
  684. const SCEV *getConstantMaxBackedgeTakenCount(const Loop *L) {
  685. return getBackedgeTakenCount(L, ConstantMaximum);
  686. }
  687. /// When successful, this returns a SCEV that is greater than or equal
  688. /// to (i.e. a "conservative over-approximation") of the value returend by
  689. /// getBackedgeTakenCount. If such a value cannot be computed, it returns the
  690. /// SCEVCouldNotCompute object.
  691. const SCEV *getSymbolicMaxBackedgeTakenCount(const Loop *L) {
  692. return getBackedgeTakenCount(L, SymbolicMaximum);
  693. }
  694. /// Return true if the backedge taken count is either the value returned by
  695. /// getConstantMaxBackedgeTakenCount or zero.
  696. bool isBackedgeTakenCountMaxOrZero(const Loop *L);
  697. /// Return true if the specified loop has an analyzable loop-invariant
  698. /// backedge-taken count.
  699. bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
  700. // This method should be called by the client when it made any change that
  701. // would invalidate SCEV's answers, and the client wants to remove all loop
  702. // information held internally by ScalarEvolution. This is intended to be used
  703. // when the alternative to forget a loop is too expensive (i.e. large loop
  704. // bodies).
  705. void forgetAllLoops();
  706. /// This method should be called by the client when it has changed a loop in
  707. /// a way that may effect ScalarEvolution's ability to compute a trip count,
  708. /// or if the loop is deleted. This call is potentially expensive for large
  709. /// loop bodies.
  710. void forgetLoop(const Loop *L);
  711. // This method invokes forgetLoop for the outermost loop of the given loop
  712. // \p L, making ScalarEvolution forget about all this subtree. This needs to
  713. // be done whenever we make a transform that may affect the parameters of the
  714. // outer loop, such as exit counts for branches.
  715. void forgetTopmostLoop(const Loop *L);
  716. /// This method should be called by the client when it has changed a value
  717. /// in a way that may effect its value, or which may disconnect it from a
  718. /// def-use chain linking it to a loop.
  719. void forgetValue(Value *V);
  720. /// Called when the client has changed the disposition of values in
  721. /// this loop.
  722. ///
  723. /// We don't have a way to invalidate per-loop dispositions. Clear and
  724. /// recompute is simpler.
  725. void forgetLoopDispositions(const Loop *L);
  726. /// Determine the minimum number of zero bits that S is guaranteed to end in
  727. /// (at every loop iteration). It is, at the same time, the minimum number
  728. /// of times S is divisible by 2. For example, given {4,+,8} it returns 2.
  729. /// If S is guaranteed to be 0, it returns the bitwidth of S.
  730. uint32_t GetMinTrailingZeros(const SCEV *S);
  731. /// Determine the unsigned range for a particular SCEV.
  732. /// NOTE: This returns a copy of the reference returned by getRangeRef.
  733. ConstantRange getUnsignedRange(const SCEV *S) {
  734. return getRangeRef(S, HINT_RANGE_UNSIGNED);
  735. }
  736. /// Determine the min of the unsigned range for a particular SCEV.
  737. APInt getUnsignedRangeMin(const SCEV *S) {
  738. return getRangeRef(S, HINT_RANGE_UNSIGNED).getUnsignedMin();
  739. }
  740. /// Determine the max of the unsigned range for a particular SCEV.
  741. APInt getUnsignedRangeMax(const SCEV *S) {
  742. return getRangeRef(S, HINT_RANGE_UNSIGNED).getUnsignedMax();
  743. }
  744. /// Determine the signed range for a particular SCEV.
  745. /// NOTE: This returns a copy of the reference returned by getRangeRef.
  746. ConstantRange getSignedRange(const SCEV *S) {
  747. return getRangeRef(S, HINT_RANGE_SIGNED);
  748. }
  749. /// Determine the min of the signed range for a particular SCEV.
  750. APInt getSignedRangeMin(const SCEV *S) {
  751. return getRangeRef(S, HINT_RANGE_SIGNED).getSignedMin();
  752. }
  753. /// Determine the max of the signed range for a particular SCEV.
  754. APInt getSignedRangeMax(const SCEV *S) {
  755. return getRangeRef(S, HINT_RANGE_SIGNED).getSignedMax();
  756. }
  757. /// Test if the given expression is known to be negative.
  758. bool isKnownNegative(const SCEV *S);
  759. /// Test if the given expression is known to be positive.
  760. bool isKnownPositive(const SCEV *S);
  761. /// Test if the given expression is known to be non-negative.
  762. bool isKnownNonNegative(const SCEV *S);
  763. /// Test if the given expression is known to be non-positive.
  764. bool isKnownNonPositive(const SCEV *S);
  765. /// Test if the given expression is known to be non-zero.
  766. bool isKnownNonZero(const SCEV *S);
  767. /// Splits SCEV expression \p S into two SCEVs. One of them is obtained from
  768. /// \p S by substitution of all AddRec sub-expression related to loop \p L
  769. /// with initial value of that SCEV. The second is obtained from \p S by
  770. /// substitution of all AddRec sub-expressions related to loop \p L with post
  771. /// increment of this AddRec in the loop \p L. In both cases all other AddRec
  772. /// sub-expressions (not related to \p L) remain the same.
  773. /// If the \p S contains non-invariant unknown SCEV the function returns
  774. /// CouldNotCompute SCEV in both values of std::pair.
  775. /// For example, for SCEV S={0, +, 1}<L1> + {0, +, 1}<L2> and loop L=L1
  776. /// the function returns pair:
  777. /// first = {0, +, 1}<L2>
  778. /// second = {1, +, 1}<L1> + {0, +, 1}<L2>
  779. /// We can see that for the first AddRec sub-expression it was replaced with
  780. /// 0 (initial value) for the first element and to {1, +, 1}<L1> (post
  781. /// increment value) for the second one. In both cases AddRec expression
  782. /// related to L2 remains the same.
  783. std::pair<const SCEV *, const SCEV *> SplitIntoInitAndPostInc(const Loop *L,
  784. const SCEV *S);
  785. /// We'd like to check the predicate on every iteration of the most dominated
  786. /// loop between loops used in LHS and RHS.
  787. /// To do this we use the following list of steps:
  788. /// 1. Collect set S all loops on which either LHS or RHS depend.
  789. /// 2. If S is non-empty
  790. /// a. Let PD be the element of S which is dominated by all other elements.
  791. /// b. Let E(LHS) be value of LHS on entry of PD.
  792. /// To get E(LHS), we should just take LHS and replace all AddRecs that are
  793. /// attached to PD on with their entry values.
  794. /// Define E(RHS) in the same way.
  795. /// c. Let B(LHS) be value of L on backedge of PD.
  796. /// To get B(LHS), we should just take LHS and replace all AddRecs that are
  797. /// attached to PD on with their backedge values.
  798. /// Define B(RHS) in the same way.
  799. /// d. Note that E(LHS) and E(RHS) are automatically available on entry of PD,
  800. /// so we can assert on that.
  801. /// e. Return true if isLoopEntryGuardedByCond(Pred, E(LHS), E(RHS)) &&
  802. /// isLoopBackedgeGuardedByCond(Pred, B(LHS), B(RHS))
  803. bool isKnownViaInduction(ICmpInst::Predicate Pred, const SCEV *LHS,
  804. const SCEV *RHS);
  805. /// Test if the given expression is known to satisfy the condition described
  806. /// by Pred, LHS, and RHS.
  807. bool isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *LHS,
  808. const SCEV *RHS);
  809. /// Check whether the condition described by Pred, LHS, and RHS is true or
  810. /// false. If we know it, return the evaluation of this condition. If neither
  811. /// is proved, return None.
  812. Optional<bool> evaluatePredicate(ICmpInst::Predicate Pred, const SCEV *LHS,
  813. const SCEV *RHS);
  814. /// Test if the given expression is known to satisfy the condition described
  815. /// by Pred, LHS, and RHS in the given Context.
  816. bool isKnownPredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS,
  817. const SCEV *RHS, const Instruction *Context);
  818. /// Check whether the condition described by Pred, LHS, and RHS is true or
  819. /// false in the given \p Context. If we know it, return the evaluation of
  820. /// this condition. If neither is proved, return None.
  821. Optional<bool> evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS,
  822. const SCEV *RHS,
  823. const Instruction *Context);
  824. /// Test if the condition described by Pred, LHS, RHS is known to be true on
  825. /// every iteration of the loop of the recurrency LHS.
  826. bool isKnownOnEveryIteration(ICmpInst::Predicate Pred,
  827. const SCEVAddRecExpr *LHS, const SCEV *RHS);
  828. /// A predicate is said to be monotonically increasing if may go from being
  829. /// false to being true as the loop iterates, but never the other way
  830. /// around. A predicate is said to be monotonically decreasing if may go
  831. /// from being true to being false as the loop iterates, but never the other
  832. /// way around.
  833. enum MonotonicPredicateType {
  834. MonotonicallyIncreasing,
  835. MonotonicallyDecreasing
  836. };
  837. /// If, for all loop invariant X, the predicate "LHS `Pred` X" is
  838. /// monotonically increasing or decreasing, returns
  839. /// Some(MonotonicallyIncreasing) and Some(MonotonicallyDecreasing)
  840. /// respectively. If we could not prove either of these facts, returns None.
  841. Optional<MonotonicPredicateType>
  842. getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
  843. ICmpInst::Predicate Pred);
  844. struct LoopInvariantPredicate {
  845. ICmpInst::Predicate Pred;
  846. const SCEV *LHS;
  847. const SCEV *RHS;
  848. LoopInvariantPredicate(ICmpInst::Predicate Pred, const SCEV *LHS,
  849. const SCEV *RHS)
  850. : Pred(Pred), LHS(LHS), RHS(RHS) {}
  851. };
  852. /// If the result of the predicate LHS `Pred` RHS is loop invariant with
  853. /// respect to L, return a LoopInvariantPredicate with LHS and RHS being
  854. /// invariants, available at L's entry. Otherwise, return None.
  855. Optional<LoopInvariantPredicate>
  856. getLoopInvariantPredicate(ICmpInst::Predicate Pred, const SCEV *LHS,
  857. const SCEV *RHS, const Loop *L);
  858. /// If the result of the predicate LHS `Pred` RHS is loop invariant with
  859. /// respect to L at given Context during at least first MaxIter iterations,
  860. /// return a LoopInvariantPredicate with LHS and RHS being invariants,
  861. /// available at L's entry. Otherwise, return None. The predicate should be
  862. /// the loop's exit condition.
  863. Optional<LoopInvariantPredicate>
  864. getLoopInvariantExitCondDuringFirstIterations(ICmpInst::Predicate Pred,
  865. const SCEV *LHS,
  866. const SCEV *RHS, const Loop *L,
  867. const Instruction *Context,
  868. const SCEV *MaxIter);
  869. /// Simplify LHS and RHS in a comparison with predicate Pred. Return true
  870. /// iff any changes were made. If the operands are provably equal or
  871. /// unequal, LHS and RHS are set to the same value and Pred is set to either
  872. /// ICMP_EQ or ICMP_NE.
  873. bool SimplifyICmpOperands(ICmpInst::Predicate &Pred, const SCEV *&LHS,
  874. const SCEV *&RHS, unsigned Depth = 0);
  875. /// Return the "disposition" of the given SCEV with respect to the given
  876. /// loop.
  877. LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
  878. /// Return true if the value of the given SCEV is unchanging in the
  879. /// specified loop.
  880. bool isLoopInvariant(const SCEV *S, const Loop *L);
  881. /// Determine if the SCEV can be evaluated at loop's entry. It is true if it
  882. /// doesn't depend on a SCEVUnknown of an instruction which is dominated by
  883. /// the header of loop L.
  884. bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L);
  885. /// Return true if the given SCEV changes value in a known way in the
  886. /// specified loop. This property being true implies that the value is
  887. /// variant in the loop AND that we can emit an expression to compute the
  888. /// value of the expression at any particular loop iteration.
  889. bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
  890. /// Return the "disposition" of the given SCEV with respect to the given
  891. /// block.
  892. BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
  893. /// Return true if elements that makes up the given SCEV dominate the
  894. /// specified basic block.
  895. bool dominates(const SCEV *S, const BasicBlock *BB);
  896. /// Return true if elements that makes up the given SCEV properly dominate
  897. /// the specified basic block.
  898. bool properlyDominates(const SCEV *S, const BasicBlock *BB);
  899. /// Test whether the given SCEV has Op as a direct or indirect operand.
  900. bool hasOperand(const SCEV *S, const SCEV *Op) const;
  901. /// Return the size of an element read or written by Inst.
  902. const SCEV *getElementSize(Instruction *Inst);
  903. /// Compute the array dimensions Sizes from the set of Terms extracted from
  904. /// the memory access function of this SCEVAddRecExpr (second step of
  905. /// delinearization).
  906. void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
  907. SmallVectorImpl<const SCEV *> &Sizes,
  908. const SCEV *ElementSize);
  909. void print(raw_ostream &OS) const;
  910. void verify() const;
  911. bool invalidate(Function &F, const PreservedAnalyses &PA,
  912. FunctionAnalysisManager::Invalidator &Inv);
  913. /// Collect parametric terms occurring in step expressions (first step of
  914. /// delinearization).
  915. void collectParametricTerms(const SCEV *Expr,
  916. SmallVectorImpl<const SCEV *> &Terms);
  917. /// Return in Subscripts the access functions for each dimension in Sizes
  918. /// (third step of delinearization).
  919. void computeAccessFunctions(const SCEV *Expr,
  920. SmallVectorImpl<const SCEV *> &Subscripts,
  921. SmallVectorImpl<const SCEV *> &Sizes);
  922. /// Gathers the individual index expressions from a GEP instruction.
  923. ///
  924. /// This function optimistically assumes the GEP references into a fixed size
  925. /// array. If this is actually true, this function returns a list of array
  926. /// subscript expressions in \p Subscripts and a list of integers describing
  927. /// the size of the individual array dimensions in \p Sizes. Both lists have
  928. /// either equal length or the size list is one element shorter in case there
  929. /// is no known size available for the outermost array dimension. Returns true
  930. /// if successful and false otherwise.
  931. bool getIndexExpressionsFromGEP(const GetElementPtrInst *GEP,
  932. SmallVectorImpl<const SCEV *> &Subscripts,
  933. SmallVectorImpl<int> &Sizes);
  934. /// Split this SCEVAddRecExpr into two vectors of SCEVs representing the
  935. /// subscripts and sizes of an array access.
  936. ///
  937. /// The delinearization is a 3 step process: the first two steps compute the
  938. /// sizes of each subscript and the third step computes the access functions
  939. /// for the delinearized array:
  940. ///
  941. /// 1. Find the terms in the step functions
  942. /// 2. Compute the array size
  943. /// 3. Compute the access function: divide the SCEV by the array size
  944. /// starting with the innermost dimensions found in step 2. The Quotient
  945. /// is the SCEV to be divided in the next step of the recursion. The
  946. /// Remainder is the subscript of the innermost dimension. Loop over all
  947. /// array dimensions computed in step 2.
  948. ///
  949. /// To compute a uniform array size for several memory accesses to the same
  950. /// object, one can collect in step 1 all the step terms for all the memory
  951. /// accesses, and compute in step 2 a unique array shape. This guarantees
  952. /// that the array shape will be the same across all memory accesses.
  953. ///
  954. /// FIXME: We could derive the result of steps 1 and 2 from a description of
  955. /// the array shape given in metadata.
  956. ///
  957. /// Example:
  958. ///
  959. /// A[][n][m]
  960. ///
  961. /// for i
  962. /// for j
  963. /// for k
  964. /// A[j+k][2i][5i] =
  965. ///
  966. /// The initial SCEV:
  967. ///
  968. /// A[{{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k]
  969. ///
  970. /// 1. Find the different terms in the step functions:
  971. /// -> [2*m, 5, n*m, n*m]
  972. ///
  973. /// 2. Compute the array size: sort and unique them
  974. /// -> [n*m, 2*m, 5]
  975. /// find the GCD of all the terms = 1
  976. /// divide by the GCD and erase constant terms
  977. /// -> [n*m, 2*m]
  978. /// GCD = m
  979. /// divide by GCD -> [n, 2]
  980. /// remove constant terms
  981. /// -> [n]
  982. /// size of the array is A[unknown][n][m]
  983. ///
  984. /// 3. Compute the access function
  985. /// a. Divide {{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k by the innermost size m
  986. /// Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k
  987. /// Remainder: {{{0,+,5}_i, +, 0}_j, +, 0}_k
  988. /// The remainder is the subscript of the innermost array dimension: [5i].
  989. ///
  990. /// b. Divide Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k by next outer size n
  991. /// Quotient: {{{0,+,0}_i, +, 1}_j, +, 1}_k
  992. /// Remainder: {{{0,+,2}_i, +, 0}_j, +, 0}_k
  993. /// The Remainder is the subscript of the next array dimension: [2i].
  994. ///
  995. /// The subscript of the outermost dimension is the Quotient: [j+k].
  996. ///
  997. /// Overall, we have: A[][n][m], and the access function: A[j+k][2i][5i].
  998. void delinearize(const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
  999. SmallVectorImpl<const SCEV *> &Sizes,
  1000. const SCEV *ElementSize);
  1001. /// Return the DataLayout associated with the module this SCEV instance is
  1002. /// operating on.
  1003. const DataLayout &getDataLayout() const {
  1004. return F.getParent()->getDataLayout();
  1005. }
  1006. const SCEVPredicate *getEqualPredicate(const SCEV *LHS, const SCEV *RHS);
  1007. const SCEVPredicate *
  1008. getWrapPredicate(const SCEVAddRecExpr *AR,
  1009. SCEVWrapPredicate::IncrementWrapFlags AddedFlags);
  1010. /// Re-writes the SCEV according to the Predicates in \p A.
  1011. const SCEV *rewriteUsingPredicate(const SCEV *S, const Loop *L,
  1012. SCEVUnionPredicate &A);
  1013. /// Tries to convert the \p S expression to an AddRec expression,
  1014. /// adding additional predicates to \p Preds as required.
  1015. const SCEVAddRecExpr *convertSCEVToAddRecWithPredicates(
  1016. const SCEV *S, const Loop *L,
  1017. SmallPtrSetImpl<const SCEVPredicate *> &Preds);
  1018. /// Compute \p LHS - \p RHS and returns the result as an APInt if it is a
  1019. /// constant, and None if it isn't.
  1020. ///
  1021. /// This is intended to be a cheaper version of getMinusSCEV. We can be
  1022. /// frugal here since we just bail out of actually constructing and
  1023. /// canonicalizing an expression in the cases where the result isn't going
  1024. /// to be a constant.
  1025. Optional<APInt> computeConstantDifference(const SCEV *LHS, const SCEV *RHS);
  1026. /// Update no-wrap flags of an AddRec. This may drop the cached info about
  1027. /// this AddRec (such as range info) in case if new flags may potentially
  1028. /// sharpen it.
  1029. void setNoWrapFlags(SCEVAddRecExpr *AddRec, SCEV::NoWrapFlags Flags);
  1030. /// Try to apply information from loop guards for \p L to \p Expr.
  1031. const SCEV *applyLoopGuards(const SCEV *Expr, const Loop *L);
  1032. private:
  1033. /// A CallbackVH to arrange for ScalarEvolution to be notified whenever a
  1034. /// Value is deleted.
  1035. class SCEVCallbackVH final : public CallbackVH {
  1036. ScalarEvolution *SE;
  1037. void deleted() override;
  1038. void allUsesReplacedWith(Value *New) override;
  1039. public:
  1040. SCEVCallbackVH(Value *V, ScalarEvolution *SE = nullptr);
  1041. };
  1042. friend class SCEVCallbackVH;
  1043. friend class SCEVExpander;
  1044. friend class SCEVUnknown;
  1045. /// The function we are analyzing.
  1046. Function &F;
  1047. /// Does the module have any calls to the llvm.experimental.guard intrinsic
  1048. /// at all? If this is false, we avoid doing work that will only help if
  1049. /// thare are guards present in the IR.
  1050. bool HasGuards;
  1051. /// The target library information for the target we are targeting.
  1052. TargetLibraryInfo &TLI;
  1053. /// The tracker for \@llvm.assume intrinsics in this function.
  1054. AssumptionCache &AC;
  1055. /// The dominator tree.
  1056. DominatorTree &DT;
  1057. /// The loop information for the function we are currently analyzing.
  1058. LoopInfo &LI;
  1059. /// This SCEV is used to represent unknown trip counts and things.
  1060. std::unique_ptr<SCEVCouldNotCompute> CouldNotCompute;
  1061. /// The type for HasRecMap.
  1062. using HasRecMapType = DenseMap<const SCEV *, bool>;
  1063. /// This is a cache to record whether a SCEV contains any scAddRecExpr.
  1064. HasRecMapType HasRecMap;
  1065. /// The type for ExprValueMap.
  1066. using ValueOffsetPair = std::pair<Value *, ConstantInt *>;
  1067. using ExprValueMapType = DenseMap<const SCEV *, SetVector<ValueOffsetPair>>;
  1068. /// ExprValueMap -- This map records the original values from which
  1069. /// the SCEV expr is generated from.
  1070. ///
  1071. /// We want to represent the mapping as SCEV -> ValueOffsetPair instead
  1072. /// of SCEV -> Value:
  1073. /// Suppose we know S1 expands to V1, and
  1074. /// S1 = S2 + C_a
  1075. /// S3 = S2 + C_b
  1076. /// where C_a and C_b are different SCEVConstants. Then we'd like to
  1077. /// expand S3 as V1 - C_a + C_b instead of expanding S2 literally.
  1078. /// It is helpful when S2 is a complex SCEV expr.
  1079. ///
  1080. /// In order to do that, we represent ExprValueMap as a mapping from
  1081. /// SCEV to ValueOffsetPair. We will save both S1->{V1, 0} and
  1082. /// S2->{V1, C_a} into the map when we create SCEV for V1. When S3
  1083. /// is expanded, it will first expand S2 to V1 - C_a because of
  1084. /// S2->{V1, C_a} in the map, then expand S3 to V1 - C_a + C_b.
  1085. ///
  1086. /// Note: S->{V, Offset} in the ExprValueMap means S can be expanded
  1087. /// to V - Offset.
  1088. ExprValueMapType ExprValueMap;
  1089. /// The type for ValueExprMap.
  1090. using ValueExprMapType =
  1091. DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *>>;
  1092. /// This is a cache of the values we have analyzed so far.
  1093. ValueExprMapType ValueExprMap;
  1094. /// Mark predicate values currently being processed by isImpliedCond.
  1095. SmallPtrSet<const Value *, 6> PendingLoopPredicates;
  1096. /// Mark SCEVUnknown Phis currently being processed by getRangeRef.
  1097. SmallPtrSet<const PHINode *, 6> PendingPhiRanges;
  1098. // Mark SCEVUnknown Phis currently being processed by isImpliedViaMerge.
  1099. SmallPtrSet<const PHINode *, 6> PendingMerges;
  1100. /// Set to true by isLoopBackedgeGuardedByCond when we're walking the set of
  1101. /// conditions dominating the backedge of a loop.
  1102. bool WalkingBEDominatingConds = false;
  1103. /// Set to true by isKnownPredicateViaSplitting when we're trying to prove a
  1104. /// predicate by splitting it into a set of independent predicates.
  1105. bool ProvingSplitPredicate = false;
  1106. /// Memoized values for the GetMinTrailingZeros
  1107. DenseMap<const SCEV *, uint32_t> MinTrailingZerosCache;
  1108. /// Return the Value set from which the SCEV expr is generated.
  1109. SetVector<ValueOffsetPair> *getSCEVValues(const SCEV *S);
  1110. /// Private helper method for the GetMinTrailingZeros method
  1111. uint32_t GetMinTrailingZerosImpl(const SCEV *S);
  1112. /// Information about the number of loop iterations for which a loop exit's
  1113. /// branch condition evaluates to the not-taken path. This is a temporary
  1114. /// pair of exact and max expressions that are eventually summarized in
  1115. /// ExitNotTakenInfo and BackedgeTakenInfo.
  1116. struct ExitLimit {
  1117. const SCEV *ExactNotTaken; // The exit is not taken exactly this many times
  1118. const SCEV *MaxNotTaken; // The exit is not taken at most this many times
  1119. // Not taken either exactly MaxNotTaken or zero times
  1120. bool MaxOrZero = false;
  1121. /// A set of predicate guards for this ExitLimit. The result is only valid
  1122. /// if all of the predicates in \c Predicates evaluate to 'true' at
  1123. /// run-time.
  1124. SmallPtrSet<const SCEVPredicate *, 4> Predicates;
  1125. void addPredicate(const SCEVPredicate *P) {
  1126. assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
  1127. Predicates.insert(P);
  1128. }
  1129. /// Construct either an exact exit limit from a constant, or an unknown
  1130. /// one from a SCEVCouldNotCompute. No other types of SCEVs are allowed
  1131. /// as arguments and asserts enforce that internally.
  1132. /*implicit*/ ExitLimit(const SCEV *E);
  1133. ExitLimit(
  1134. const SCEV *E, const SCEV *M, bool MaxOrZero,
  1135. ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList);
  1136. ExitLimit(const SCEV *E, const SCEV *M, bool MaxOrZero,
  1137. const SmallPtrSetImpl<const SCEVPredicate *> &PredSet);
  1138. ExitLimit(const SCEV *E, const SCEV *M, bool MaxOrZero);
  1139. /// Test whether this ExitLimit contains any computed information, or
  1140. /// whether it's all SCEVCouldNotCompute values.
  1141. bool hasAnyInfo() const {
  1142. return !isa<SCEVCouldNotCompute>(ExactNotTaken) ||
  1143. !isa<SCEVCouldNotCompute>(MaxNotTaken);
  1144. }
  1145. /// Test whether this ExitLimit contains all information.
  1146. bool hasFullInfo() const {
  1147. return !isa<SCEVCouldNotCompute>(ExactNotTaken);
  1148. }
  1149. };
  1150. /// Information about the number of times a particular loop exit may be
  1151. /// reached before exiting the loop.
  1152. struct ExitNotTakenInfo {
  1153. PoisoningVH<BasicBlock> ExitingBlock;
  1154. const SCEV *ExactNotTaken;
  1155. const SCEV *MaxNotTaken;
  1156. std::unique_ptr<SCEVUnionPredicate> Predicate;
  1157. explicit ExitNotTakenInfo(PoisoningVH<BasicBlock> ExitingBlock,
  1158. const SCEV *ExactNotTaken,
  1159. const SCEV *MaxNotTaken,
  1160. std::unique_ptr<SCEVUnionPredicate> Predicate)
  1161. : ExitingBlock(ExitingBlock), ExactNotTaken(ExactNotTaken),
  1162. MaxNotTaken(ExactNotTaken), Predicate(std::move(Predicate)) {}
  1163. bool hasAlwaysTruePredicate() const {
  1164. return !Predicate || Predicate->isAlwaysTrue();
  1165. }
  1166. };
  1167. /// Information about the backedge-taken count of a loop. This currently
  1168. /// includes an exact count and a maximum count.
  1169. ///
  1170. class BackedgeTakenInfo {
  1171. /// A list of computable exits and their not-taken counts. Loops almost
  1172. /// never have more than one computable exit.
  1173. SmallVector<ExitNotTakenInfo, 1> ExitNotTaken;
  1174. /// Expression indicating the least constant maximum backedge-taken count of
  1175. /// the loop that is known, or a SCEVCouldNotCompute. This expression is
  1176. /// only valid if the redicates associated with all loop exits are true.
  1177. const SCEV *ConstantMax;
  1178. /// Indicating if \c ExitNotTaken has an element for every exiting block in
  1179. /// the loop.
  1180. bool IsComplete;
  1181. /// Expression indicating the least maximum backedge-taken count of the loop
  1182. /// that is known, or a SCEVCouldNotCompute. Lazily computed on first query.
  1183. const SCEV *SymbolicMax = nullptr;
  1184. /// True iff the backedge is taken either exactly Max or zero times.
  1185. bool MaxOrZero = false;
  1186. /// SCEV expressions used in any of the ExitNotTakenInfo counts.
  1187. SmallPtrSet<const SCEV *, 4> Operands;
  1188. bool isComplete() const { return IsComplete; }
  1189. const SCEV *getConstantMax() const { return ConstantMax; }
  1190. public:
  1191. BackedgeTakenInfo() : ConstantMax(nullptr), IsComplete(false) {}
  1192. BackedgeTakenInfo(BackedgeTakenInfo &&) = default;
  1193. BackedgeTakenInfo &operator=(BackedgeTakenInfo &&) = default;
  1194. using EdgeExitInfo = std::pair<BasicBlock *, ExitLimit>;
  1195. /// Initialize BackedgeTakenInfo from a list of exact exit counts.
  1196. BackedgeTakenInfo(ArrayRef<EdgeExitInfo> ExitCounts, bool IsComplete,
  1197. const SCEV *ConstantMax, bool MaxOrZero);
  1198. /// Test whether this BackedgeTakenInfo contains any computed information,
  1199. /// or whether it's all SCEVCouldNotCompute values.
  1200. bool hasAnyInfo() const {
  1201. return !ExitNotTaken.empty() ||
  1202. !isa<SCEVCouldNotCompute>(getConstantMax());
  1203. }
  1204. /// Test whether this BackedgeTakenInfo contains complete information.
  1205. bool hasFullInfo() const { return isComplete(); }
  1206. /// Return an expression indicating the exact *backedge-taken*
  1207. /// count of the loop if it is known or SCEVCouldNotCompute
  1208. /// otherwise. If execution makes it to the backedge on every
  1209. /// iteration (i.e. there are no abnormal exists like exception
  1210. /// throws and thread exits) then this is the number of times the
  1211. /// loop header will execute minus one.
  1212. ///
  1213. /// If the SCEV predicate associated with the answer can be different
  1214. /// from AlwaysTrue, we must add a (non null) Predicates argument.
  1215. /// The SCEV predicate associated with the answer will be added to
  1216. /// Predicates. A run-time check needs to be emitted for the SCEV
  1217. /// predicate in order for the answer to be valid.
  1218. ///
  1219. /// Note that we should always know if we need to pass a predicate
  1220. /// argument or not from the way the ExitCounts vector was computed.
  1221. /// If we allowed SCEV predicates to be generated when populating this
  1222. /// vector, this information can contain them and therefore a
  1223. /// SCEVPredicate argument should be added to getExact.
  1224. const SCEV *getExact(const Loop *L, ScalarEvolution *SE,
  1225. SCEVUnionPredicate *Predicates = nullptr) const;
  1226. /// Return the number of times this loop exit may fall through to the back
  1227. /// edge, or SCEVCouldNotCompute. The loop is guaranteed not to exit via
  1228. /// this block before this number of iterations, but may exit via another
  1229. /// block.
  1230. const SCEV *getExact(const BasicBlock *ExitingBlock,
  1231. ScalarEvolution *SE) const;
  1232. /// Get the constant max backedge taken count for the loop.
  1233. const SCEV *getConstantMax(ScalarEvolution *SE) const;
  1234. /// Get the constant max backedge taken count for the particular loop exit.
  1235. const SCEV *getConstantMax(const BasicBlock *ExitingBlock,
  1236. ScalarEvolution *SE) const;
  1237. /// Get the symbolic max backedge taken count for the loop.
  1238. const SCEV *getSymbolicMax(const Loop *L, ScalarEvolution *SE);
  1239. /// Return true if the number of times this backedge is taken is either the
  1240. /// value returned by getConstantMax or zero.
  1241. bool isConstantMaxOrZero(ScalarEvolution *SE) const;
  1242. /// Return true if any backedge taken count expressions refer to the given
  1243. /// subexpression.
  1244. bool hasOperand(const SCEV *S) const;
  1245. };
  1246. /// Cache the backedge-taken count of the loops for this function as they
  1247. /// are computed.
  1248. DenseMap<const Loop *, BackedgeTakenInfo> BackedgeTakenCounts;
  1249. /// Cache the predicated backedge-taken count of the loops for this
  1250. /// function as they are computed.
  1251. DenseMap<const Loop *, BackedgeTakenInfo> PredicatedBackedgeTakenCounts;
  1252. /// This map contains entries for all of the PHI instructions that we
  1253. /// attempt to compute constant evolutions for. This allows us to avoid
  1254. /// potentially expensive recomputation of these properties. An instruction
  1255. /// maps to null if we are unable to compute its exit value.
  1256. DenseMap<PHINode *, Constant *> ConstantEvolutionLoopExitValue;
  1257. /// This map contains entries for all the expressions that we attempt to
  1258. /// compute getSCEVAtScope information for, which can be expensive in
  1259. /// extreme cases.
  1260. DenseMap<const SCEV *, SmallVector<std::pair<const Loop *, const SCEV *>, 2>>
  1261. ValuesAtScopes;
  1262. /// Memoized computeLoopDisposition results.
  1263. DenseMap<const SCEV *,
  1264. SmallVector<PointerIntPair<const Loop *, 2, LoopDisposition>, 2>>
  1265. LoopDispositions;
  1266. struct LoopProperties {
  1267. /// Set to true if the loop contains no instruction that can have side
  1268. /// effects (i.e. via throwing an exception, volatile or atomic access).
  1269. bool HasNoAbnormalExits;
  1270. /// Set to true if the loop contains no instruction that can abnormally exit
  1271. /// the loop (i.e. via throwing an exception, by terminating the thread
  1272. /// cleanly or by infinite looping in a called function). Strictly
  1273. /// speaking, the last one is not leaving the loop, but is identical to
  1274. /// leaving the loop for reasoning about undefined behavior.
  1275. bool HasNoSideEffects;
  1276. };
  1277. /// Cache for \c getLoopProperties.
  1278. DenseMap<const Loop *, LoopProperties> LoopPropertiesCache;
  1279. /// Return a \c LoopProperties instance for \p L, creating one if necessary.
  1280. LoopProperties getLoopProperties(const Loop *L);
  1281. bool loopHasNoSideEffects(const Loop *L) {
  1282. return getLoopProperties(L).HasNoSideEffects;
  1283. }
  1284. bool loopHasNoAbnormalExits(const Loop *L) {
  1285. return getLoopProperties(L).HasNoAbnormalExits;
  1286. }
  1287. /// Compute a LoopDisposition value.
  1288. LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
  1289. /// Memoized computeBlockDisposition results.
  1290. DenseMap<
  1291. const SCEV *,
  1292. SmallVector<PointerIntPair<const BasicBlock *, 2, BlockDisposition>, 2>>
  1293. BlockDispositions;
  1294. /// Compute a BlockDisposition value.
  1295. BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
  1296. /// Memoized results from getRange
  1297. DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
  1298. /// Memoized results from getRange
  1299. DenseMap<const SCEV *, ConstantRange> SignedRanges;
  1300. /// Used to parameterize getRange
  1301. enum RangeSignHint { HINT_RANGE_UNSIGNED, HINT_RANGE_SIGNED };
  1302. /// Set the memoized range for the given SCEV.
  1303. const ConstantRange &setRange(const SCEV *S, RangeSignHint Hint,
  1304. ConstantRange CR) {
  1305. DenseMap<const SCEV *, ConstantRange> &Cache =
  1306. Hint == HINT_RANGE_UNSIGNED ? UnsignedRanges : SignedRanges;
  1307. auto Pair = Cache.try_emplace(S, std::move(CR));
  1308. if (!Pair.second)
  1309. Pair.first->second = std::move(CR);
  1310. return Pair.first->second;
  1311. }
  1312. /// Determine the range for a particular SCEV.
  1313. /// NOTE: This returns a reference to an entry in a cache. It must be
  1314. /// copied if its needed for longer.
  1315. const ConstantRange &getRangeRef(const SCEV *S, RangeSignHint Hint);
  1316. /// Determines the range for the affine SCEVAddRecExpr {\p Start,+,\p Stop}.
  1317. /// Helper for \c getRange.
  1318. ConstantRange getRangeForAffineAR(const SCEV *Start, const SCEV *Stop,
  1319. const SCEV *MaxBECount, unsigned BitWidth);
  1320. /// Determines the range for the affine non-self-wrapping SCEVAddRecExpr {\p
  1321. /// Start,+,\p Stop}<nw>.
  1322. ConstantRange getRangeForAffineNoSelfWrappingAR(const SCEVAddRecExpr *AddRec,
  1323. const SCEV *MaxBECount,
  1324. unsigned BitWidth,
  1325. RangeSignHint SignHint);
  1326. /// Try to compute a range for the affine SCEVAddRecExpr {\p Start,+,\p
  1327. /// Stop} by "factoring out" a ternary expression from the add recurrence.
  1328. /// Helper called by \c getRange.
  1329. ConstantRange getRangeViaFactoring(const SCEV *Start, const SCEV *Stop,
  1330. const SCEV *MaxBECount, unsigned BitWidth);
  1331. /// If the unknown expression U corresponds to a simple recurrence, return
  1332. /// a constant range which represents the entire recurrence. Note that
  1333. /// *add* recurrences with loop invariant steps aren't represented by
  1334. /// SCEVUnknowns and thus don't use this mechanism.
  1335. ConstantRange getRangeForUnknownRecurrence(const SCEVUnknown *U);
  1336. /// We know that there is no SCEV for the specified value. Analyze the
  1337. /// expression.
  1338. const SCEV *createSCEV(Value *V);
  1339. /// Provide the special handling we need to analyze PHI SCEVs.
  1340. const SCEV *createNodeForPHI(PHINode *PN);
  1341. /// Helper function called from createNodeForPHI.
  1342. const SCEV *createAddRecFromPHI(PHINode *PN);
  1343. /// A helper function for createAddRecFromPHI to handle simple cases.
  1344. const SCEV *createSimpleAffineAddRec(PHINode *PN, Value *BEValueV,
  1345. Value *StartValueV);
  1346. /// Helper function called from createNodeForPHI.
  1347. const SCEV *createNodeFromSelectLikePHI(PHINode *PN);
  1348. /// Provide special handling for a select-like instruction (currently this
  1349. /// is either a select instruction or a phi node). \p I is the instruction
  1350. /// being processed, and it is assumed equivalent to "Cond ? TrueVal :
  1351. /// FalseVal".
  1352. const SCEV *createNodeForSelectOrPHI(Instruction *I, Value *Cond,
  1353. Value *TrueVal, Value *FalseVal);
  1354. /// Provide the special handling we need to analyze GEP SCEVs.
  1355. const SCEV *createNodeForGEP(GEPOperator *GEP);
  1356. /// Implementation code for getSCEVAtScope; called at most once for each
  1357. /// SCEV+Loop pair.
  1358. const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
  1359. /// This looks up computed SCEV values for all instructions that depend on
  1360. /// the given instruction and removes them from the ValueExprMap map if they
  1361. /// reference SymName. This is used during PHI resolution.
  1362. void forgetSymbolicName(Instruction *I, const SCEV *SymName);
  1363. /// Return the BackedgeTakenInfo for the given loop, lazily computing new
  1364. /// values if the loop hasn't been analyzed yet. The returned result is
  1365. /// guaranteed not to be predicated.
  1366. BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
  1367. /// Similar to getBackedgeTakenInfo, but will add predicates as required
  1368. /// with the purpose of returning complete information.
  1369. const BackedgeTakenInfo &getPredicatedBackedgeTakenInfo(const Loop *L);
  1370. /// Compute the number of times the specified loop will iterate.
  1371. /// If AllowPredicates is set, we will create new SCEV predicates as
  1372. /// necessary in order to return an exact answer.
  1373. BackedgeTakenInfo computeBackedgeTakenCount(const Loop *L,
  1374. bool AllowPredicates = false);
  1375. /// Compute the number of times the backedge of the specified loop will
  1376. /// execute if it exits via the specified block. If AllowPredicates is set,
  1377. /// this call will try to use a minimal set of SCEV predicates in order to
  1378. /// return an exact answer.
  1379. ExitLimit computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
  1380. bool AllowPredicates = false);
  1381. /// Compute the number of times the backedge of the specified loop will
  1382. /// execute if its exit condition were a conditional branch of ExitCond.
  1383. ///
  1384. /// \p ControlsExit is true if ExitCond directly controls the exit
  1385. /// branch. In this case, we can assume that the loop exits only if the
  1386. /// condition is true and can infer that failing to meet the condition prior
  1387. /// to integer wraparound results in undefined behavior.
  1388. ///
  1389. /// If \p AllowPredicates is set, this call will try to use a minimal set of
  1390. /// SCEV predicates in order to return an exact answer.
  1391. ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond,
  1392. bool ExitIfTrue, bool ControlsExit,
  1393. bool AllowPredicates = false);
  1394. /// Return a symbolic upper bound for the backedge taken count of the loop.
  1395. /// This is more general than getConstantMaxBackedgeTakenCount as it returns
  1396. /// an arbitrary expression as opposed to only constants.
  1397. const SCEV *computeSymbolicMaxBackedgeTakenCount(const Loop *L);
  1398. // Helper functions for computeExitLimitFromCond to avoid exponential time
  1399. // complexity.
  1400. class ExitLimitCache {
  1401. // It may look like we need key on the whole (L, ExitIfTrue, ControlsExit,
  1402. // AllowPredicates) tuple, but recursive calls to
  1403. // computeExitLimitFromCondCached from computeExitLimitFromCondImpl only
  1404. // vary the in \c ExitCond and \c ControlsExit parameters. We remember the
  1405. // initial values of the other values to assert our assumption.
  1406. SmallDenseMap<PointerIntPair<Value *, 1>, ExitLimit> TripCountMap;
  1407. const Loop *L;
  1408. bool ExitIfTrue;
  1409. bool AllowPredicates;
  1410. public:
  1411. ExitLimitCache(const Loop *L, bool ExitIfTrue, bool AllowPredicates)
  1412. : L(L), ExitIfTrue(ExitIfTrue), AllowPredicates(AllowPredicates) {}
  1413. Optional<ExitLimit> find(const Loop *L, Value *ExitCond, bool ExitIfTrue,
  1414. bool ControlsExit, bool AllowPredicates);
  1415. void insert(const Loop *L, Value *ExitCond, bool ExitIfTrue,
  1416. bool ControlsExit, bool AllowPredicates, const ExitLimit &EL);
  1417. };
  1418. using ExitLimitCacheTy = ExitLimitCache;
  1419. ExitLimit computeExitLimitFromCondCached(ExitLimitCacheTy &Cache,
  1420. const Loop *L, Value *ExitCond,
  1421. bool ExitIfTrue,
  1422. bool ControlsExit,
  1423. bool AllowPredicates);
  1424. ExitLimit computeExitLimitFromCondImpl(ExitLimitCacheTy &Cache, const Loop *L,
  1425. Value *ExitCond, bool ExitIfTrue,
  1426. bool ControlsExit,
  1427. bool AllowPredicates);
  1428. Optional<ScalarEvolution::ExitLimit>
  1429. computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache, const Loop *L,
  1430. Value *ExitCond, bool ExitIfTrue,
  1431. bool ControlsExit, bool AllowPredicates);
  1432. /// Compute the number of times the backedge of the specified loop will
  1433. /// execute if its exit condition were a conditional branch of the ICmpInst
  1434. /// ExitCond and ExitIfTrue. If AllowPredicates is set, this call will try
  1435. /// to use a minimal set of SCEV predicates in order to return an exact
  1436. /// answer.
  1437. ExitLimit computeExitLimitFromICmp(const Loop *L, ICmpInst *ExitCond,
  1438. bool ExitIfTrue,
  1439. bool IsSubExpr,
  1440. bool AllowPredicates = false);
  1441. /// Compute the number of times the backedge of the specified loop will
  1442. /// execute if its exit condition were a switch with a single exiting case
  1443. /// to ExitingBB.
  1444. ExitLimit computeExitLimitFromSingleExitSwitch(const Loop *L,
  1445. SwitchInst *Switch,
  1446. BasicBlock *ExitingBB,
  1447. bool IsSubExpr);
  1448. /// Given an exit condition of 'icmp op load X, cst', try to see if we can
  1449. /// compute the backedge-taken count.
  1450. ExitLimit computeLoadConstantCompareExitLimit(LoadInst *LI, Constant *RHS,
  1451. const Loop *L,
  1452. ICmpInst::Predicate p);
  1453. /// Compute the exit limit of a loop that is controlled by a
  1454. /// "(IV >> 1) != 0" type comparison. We cannot compute the exact trip
  1455. /// count in these cases (since SCEV has no way of expressing them), but we
  1456. /// can still sometimes compute an upper bound.
  1457. ///
  1458. /// Return an ExitLimit for a loop whose backedge is guarded by `LHS Pred
  1459. /// RHS`.
  1460. ExitLimit computeShiftCompareExitLimit(Value *LHS, Value *RHS, const Loop *L,
  1461. ICmpInst::Predicate Pred);
  1462. /// If the loop is known to execute a constant number of times (the
  1463. /// condition evolves only from constants), try to evaluate a few iterations
  1464. /// of the loop until we get the exit condition gets a value of ExitWhen
  1465. /// (true or false). If we cannot evaluate the exit count of the loop,
  1466. /// return CouldNotCompute.
  1467. const SCEV *computeExitCountExhaustively(const Loop *L, Value *Cond,
  1468. bool ExitWhen);
  1469. /// Return the number of times an exit condition comparing the specified
  1470. /// value to zero will execute. If not computable, return CouldNotCompute.
  1471. /// If AllowPredicates is set, this call will try to use a minimal set of
  1472. /// SCEV predicates in order to return an exact answer.
  1473. ExitLimit howFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr,
  1474. bool AllowPredicates = false);
  1475. /// Return the number of times an exit condition checking the specified
  1476. /// value for nonzero will execute. If not computable, return
  1477. /// CouldNotCompute.
  1478. ExitLimit howFarToNonZero(const SCEV *V, const Loop *L);
  1479. /// Return the number of times an exit condition containing the specified
  1480. /// less-than comparison will execute. If not computable, return
  1481. /// CouldNotCompute.
  1482. ///
  1483. /// \p isSigned specifies whether the less-than is signed.
  1484. ///
  1485. /// \p ControlsExit is true when the LHS < RHS condition directly controls
  1486. /// the branch (loops exits only if condition is true). In this case, we can
  1487. /// use NoWrapFlags to skip overflow checks.
  1488. ///
  1489. /// If \p AllowPredicates is set, this call will try to use a minimal set of
  1490. /// SCEV predicates in order to return an exact answer.
  1491. ExitLimit howManyLessThans(const SCEV *LHS, const SCEV *RHS, const Loop *L,
  1492. bool isSigned, bool ControlsExit,
  1493. bool AllowPredicates = false);
  1494. ExitLimit howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, const Loop *L,
  1495. bool isSigned, bool IsSubExpr,
  1496. bool AllowPredicates = false);
  1497. /// Return a predecessor of BB (which may not be an immediate predecessor)
  1498. /// which has exactly one successor from which BB is reachable, or null if
  1499. /// no such block is found.
  1500. std::pair<const BasicBlock *, const BasicBlock *>
  1501. getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) const;
  1502. /// Test whether the condition described by Pred, LHS, and RHS is true
  1503. /// whenever the given FoundCondValue value evaluates to true in given
  1504. /// Context. If Context is nullptr, then the found predicate is true
  1505. /// everywhere. LHS and FoundLHS may have different type width.
  1506. bool isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
  1507. const Value *FoundCondValue, bool Inverse,
  1508. const Instruction *Context = nullptr);
  1509. /// Test whether the condition described by Pred, LHS, and RHS is true
  1510. /// whenever the given FoundCondValue value evaluates to true in given
  1511. /// Context. If Context is nullptr, then the found predicate is true
  1512. /// everywhere. LHS and FoundLHS must have same type width.
  1513. bool isImpliedCondBalancedTypes(ICmpInst::Predicate Pred, const SCEV *LHS,
  1514. const SCEV *RHS,
  1515. ICmpInst::Predicate FoundPred,
  1516. const SCEV *FoundLHS, const SCEV *FoundRHS,
  1517. const Instruction *Context);
  1518. /// Test whether the condition described by Pred, LHS, and RHS is true
  1519. /// whenever the condition described by FoundPred, FoundLHS, FoundRHS is
  1520. /// true in given Context. If Context is nullptr, then the found predicate is
  1521. /// true everywhere.
  1522. bool isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
  1523. ICmpInst::Predicate FoundPred, const SCEV *FoundLHS,
  1524. const SCEV *FoundRHS,
  1525. const Instruction *Context = nullptr);
  1526. /// Test whether the condition described by Pred, LHS, and RHS is true
  1527. /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
  1528. /// true in given Context. If Context is nullptr, then the found predicate is
  1529. /// true everywhere.
  1530. bool isImpliedCondOperands(ICmpInst::Predicate Pred, const SCEV *LHS,
  1531. const SCEV *RHS, const SCEV *FoundLHS,
  1532. const SCEV *FoundRHS,
  1533. const Instruction *Context = nullptr);
  1534. /// Test whether the condition described by Pred, LHS, and RHS is true
  1535. /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
  1536. /// true. Here LHS is an operation that includes FoundLHS as one of its
  1537. /// arguments.
  1538. bool isImpliedViaOperations(ICmpInst::Predicate Pred,
  1539. const SCEV *LHS, const SCEV *RHS,
  1540. const SCEV *FoundLHS, const SCEV *FoundRHS,
  1541. unsigned Depth = 0);
  1542. /// Test whether the condition described by Pred, LHS, and RHS is true.
  1543. /// Use only simple non-recursive types of checks, such as range analysis etc.
  1544. bool isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
  1545. const SCEV *LHS, const SCEV *RHS);
  1546. /// Test whether the condition described by Pred, LHS, and RHS is true
  1547. /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
  1548. /// true.
  1549. bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, const SCEV *LHS,
  1550. const SCEV *RHS, const SCEV *FoundLHS,
  1551. const SCEV *FoundRHS);
  1552. /// Test whether the condition described by Pred, LHS, and RHS is true
  1553. /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
  1554. /// true. Utility function used by isImpliedCondOperands. Tries to get
  1555. /// cases like "X `sgt` 0 => X - 1 `sgt` -1".
  1556. bool isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, const SCEV *LHS,
  1557. const SCEV *RHS, const SCEV *FoundLHS,
  1558. const SCEV *FoundRHS);
  1559. /// Return true if the condition denoted by \p LHS \p Pred \p RHS is implied
  1560. /// by a call to @llvm.experimental.guard in \p BB.
  1561. bool isImpliedViaGuard(const BasicBlock *BB, ICmpInst::Predicate Pred,
  1562. const SCEV *LHS, const SCEV *RHS);
  1563. /// Test whether the condition described by Pred, LHS, and RHS is true
  1564. /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
  1565. /// true.
  1566. ///
  1567. /// This routine tries to rule out certain kinds of integer overflow, and
  1568. /// then tries to reason about arithmetic properties of the predicates.
  1569. bool isImpliedCondOperandsViaNoOverflow(ICmpInst::Predicate Pred,
  1570. const SCEV *LHS, const SCEV *RHS,
  1571. const SCEV *FoundLHS,
  1572. const SCEV *FoundRHS);
  1573. /// Test whether the condition described by Pred, LHS, and RHS is true
  1574. /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
  1575. /// true.
  1576. ///
  1577. /// This routine tries to weaken the known condition basing on fact that
  1578. /// FoundLHS is an AddRec.
  1579. bool isImpliedCondOperandsViaAddRecStart(ICmpInst::Predicate Pred,
  1580. const SCEV *LHS, const SCEV *RHS,
  1581. const SCEV *FoundLHS,
  1582. const SCEV *FoundRHS,
  1583. const Instruction *Context);
  1584. /// Test whether the condition described by Pred, LHS, and RHS is true
  1585. /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
  1586. /// true.
  1587. ///
  1588. /// This routine tries to figure out predicate for Phis which are SCEVUnknown
  1589. /// if it is true for every possible incoming value from their respective
  1590. /// basic blocks.
  1591. bool isImpliedViaMerge(ICmpInst::Predicate Pred,
  1592. const SCEV *LHS, const SCEV *RHS,
  1593. const SCEV *FoundLHS, const SCEV *FoundRHS,
  1594. unsigned Depth);
  1595. /// If we know that the specified Phi is in the header of its containing
  1596. /// loop, we know the loop executes a constant number of times, and the PHI
  1597. /// node is just a recurrence involving constants, fold it.
  1598. Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt &BEs,
  1599. const Loop *L);
  1600. /// Test if the given expression is known to satisfy the condition described
  1601. /// by Pred and the known constant ranges of LHS and RHS.
  1602. bool isKnownPredicateViaConstantRanges(ICmpInst::Predicate Pred,
  1603. const SCEV *LHS, const SCEV *RHS);
  1604. /// Try to prove the condition described by "LHS Pred RHS" by ruling out
  1605. /// integer overflow.
  1606. ///
  1607. /// For instance, this will return true for "A s< (A + C)<nsw>" if C is
  1608. /// positive.
  1609. bool isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, const SCEV *LHS,
  1610. const SCEV *RHS);
  1611. /// Try to split Pred LHS RHS into logical conjunctions (and's) and try to
  1612. /// prove them individually.
  1613. bool isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, const SCEV *LHS,
  1614. const SCEV *RHS);
  1615. /// Try to match the Expr as "(L + R)<Flags>".
  1616. bool splitBinaryAdd(const SCEV *Expr, const SCEV *&L, const SCEV *&R,
  1617. SCEV::NoWrapFlags &Flags);
  1618. /// Drop memoized information computed for S.
  1619. void forgetMemoizedResults(const SCEV *S);
  1620. /// Return an existing SCEV for V if there is one, otherwise return nullptr.
  1621. const SCEV *getExistingSCEV(Value *V);
  1622. /// Return false iff given SCEV contains a SCEVUnknown with NULL value-
  1623. /// pointer.
  1624. bool checkValidity(const SCEV *S) const;
  1625. /// Return true if `ExtendOpTy`({`Start`,+,`Step`}) can be proved to be
  1626. /// equal to {`ExtendOpTy`(`Start`),+,`ExtendOpTy`(`Step`)}. This is
  1627. /// equivalent to proving no signed (resp. unsigned) wrap in
  1628. /// {`Start`,+,`Step`} if `ExtendOpTy` is `SCEVSignExtendExpr`
  1629. /// (resp. `SCEVZeroExtendExpr`).
  1630. template <typename ExtendOpTy>
  1631. bool proveNoWrapByVaryingStart(const SCEV *Start, const SCEV *Step,
  1632. const Loop *L);
  1633. /// Try to prove NSW or NUW on \p AR relying on ConstantRange manipulation.
  1634. SCEV::NoWrapFlags proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR);
  1635. /// Try to prove NSW on \p AR by proving facts about conditions known on
  1636. /// entry and backedge.
  1637. SCEV::NoWrapFlags proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR);
  1638. /// Try to prove NUW on \p AR by proving facts about conditions known on
  1639. /// entry and backedge.
  1640. SCEV::NoWrapFlags proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR);
  1641. Optional<MonotonicPredicateType>
  1642. getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
  1643. ICmpInst::Predicate Pred);
  1644. /// Return SCEV no-wrap flags that can be proven based on reasoning about
  1645. /// how poison produced from no-wrap flags on this value (e.g. a nuw add)
  1646. /// would trigger undefined behavior on overflow.
  1647. SCEV::NoWrapFlags getNoWrapFlagsFromUB(const Value *V);
  1648. /// Return true if the SCEV corresponding to \p I is never poison. Proving
  1649. /// this is more complex than proving that just \p I is never poison, since
  1650. /// SCEV commons expressions across control flow, and you can have cases
  1651. /// like:
  1652. ///
  1653. /// idx0 = a + b;
  1654. /// ptr[idx0] = 100;
  1655. /// if (<condition>) {
  1656. /// idx1 = a +nsw b;
  1657. /// ptr[idx1] = 200;
  1658. /// }
  1659. ///
  1660. /// where the SCEV expression (+ a b) is guaranteed to not be poison (and
  1661. /// hence not sign-overflow) only if "<condition>" is true. Since both
  1662. /// `idx0` and `idx1` will be mapped to the same SCEV expression, (+ a b),
  1663. /// it is not okay to annotate (+ a b) with <nsw> in the above example.
  1664. bool isSCEVExprNeverPoison(const Instruction *I);
  1665. /// This is like \c isSCEVExprNeverPoison but it specifically works for
  1666. /// instructions that will get mapped to SCEV add recurrences. Return true
  1667. /// if \p I will never generate poison under the assumption that \p I is an
  1668. /// add recurrence on the loop \p L.
  1669. bool isAddRecNeverPoison(const Instruction *I, const Loop *L);
  1670. /// Similar to createAddRecFromPHI, but with the additional flexibility of
  1671. /// suggesting runtime overflow checks in case casts are encountered.
  1672. /// If successful, the analysis records that for this loop, \p SymbolicPHI,
  1673. /// which is the UnknownSCEV currently representing the PHI, can be rewritten
  1674. /// into an AddRec, assuming some predicates; The function then returns the
  1675. /// AddRec and the predicates as a pair, and caches this pair in
  1676. /// PredicatedSCEVRewrites.
  1677. /// If the analysis is not successful, a mapping from the \p SymbolicPHI to
  1678. /// itself (with no predicates) is recorded, and a nullptr with an empty
  1679. /// predicates vector is returned as a pair.
  1680. Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
  1681. createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI);
  1682. /// Compute the backedge taken count knowing the interval difference, and
  1683. /// the stride for an inequality. Result takes the form:
  1684. /// (Delta + (Stride - 1)) udiv Stride.
  1685. /// Caller must ensure that this expression either does not overflow or
  1686. /// that the result is undefined if it does.
  1687. const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride);
  1688. /// Compute the maximum backedge count based on the range of values
  1689. /// permitted by Start, End, and Stride. This is for loops of the form
  1690. /// {Start, +, Stride} LT End.
  1691. ///
  1692. /// Precondition: the induction variable is known to be positive. We *don't*
  1693. /// assert these preconditions so please be careful.
  1694. const SCEV *computeMaxBECountForLT(const SCEV *Start, const SCEV *Stride,
  1695. const SCEV *End, unsigned BitWidth,
  1696. bool IsSigned);
  1697. /// Verify if an linear IV with positive stride can overflow when in a
  1698. /// less-than comparison, knowing the invariant term of the comparison,
  1699. /// the stride.
  1700. bool canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, bool IsSigned);
  1701. /// Verify if an linear IV with negative stride can overflow when in a
  1702. /// greater-than comparison, knowing the invariant term of the comparison,
  1703. /// the stride.
  1704. bool canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, bool IsSigned);
  1705. /// Get add expr already created or create a new one.
  1706. const SCEV *getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
  1707. SCEV::NoWrapFlags Flags);
  1708. /// Get mul expr already created or create a new one.
  1709. const SCEV *getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
  1710. SCEV::NoWrapFlags Flags);
  1711. // Get addrec expr already created or create a new one.
  1712. const SCEV *getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
  1713. const Loop *L, SCEV::NoWrapFlags Flags);
  1714. /// Return x if \p Val is f(x) where f is a 1-1 function.
  1715. const SCEV *stripInjectiveFunctions(const SCEV *Val) const;
  1716. /// Find all of the loops transitively used in \p S, and fill \p LoopsUsed.
  1717. /// A loop is considered "used" by an expression if it contains
  1718. /// an add rec on said loop.
  1719. void getUsedLoops(const SCEV *S, SmallPtrSetImpl<const Loop *> &LoopsUsed);
  1720. /// Find all of the loops transitively used in \p S, and update \c LoopUsers
  1721. /// accordingly.
  1722. void addToLoopUseLists(const SCEV *S);
  1723. /// Try to match the pattern generated by getURemExpr(A, B). If successful,
  1724. /// Assign A and B to LHS and RHS, respectively.
  1725. bool matchURem(const SCEV *Expr, const SCEV *&LHS, const SCEV *&RHS);
  1726. /// Look for a SCEV expression with type `SCEVType` and operands `Ops` in
  1727. /// `UniqueSCEVs`.
  1728. ///
  1729. /// The first component of the returned tuple is the SCEV if found and null
  1730. /// otherwise. The second component is the `FoldingSetNodeID` that was
  1731. /// constructed to look up the SCEV and the third component is the insertion
  1732. /// point.
  1733. std::tuple<SCEV *, FoldingSetNodeID, void *>
  1734. findExistingSCEVInCache(SCEVTypes SCEVType, ArrayRef<const SCEV *> Ops);
  1735. FoldingSet<SCEV> UniqueSCEVs;
  1736. FoldingSet<SCEVPredicate> UniquePreds;
  1737. BumpPtrAllocator SCEVAllocator;
  1738. /// This maps loops to a list of SCEV expressions that (transitively) use said
  1739. /// loop.
  1740. DenseMap<const Loop *, SmallVector<const SCEV *, 4>> LoopUsers;
  1741. /// Cache tentative mappings from UnknownSCEVs in a Loop, to a SCEV expression
  1742. /// they can be rewritten into under certain predicates.
  1743. DenseMap<std::pair<const SCEVUnknown *, const Loop *>,
  1744. std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
  1745. PredicatedSCEVRewrites;
  1746. /// The head of a linked list of all SCEVUnknown values that have been
  1747. /// allocated. This is used by releaseMemory to locate them all and call
  1748. /// their destructors.
  1749. SCEVUnknown *FirstUnknown = nullptr;
  1750. };
  1751. /// Analysis pass that exposes the \c ScalarEvolution for a function.
  1752. class ScalarEvolutionAnalysis
  1753. : public AnalysisInfoMixin<ScalarEvolutionAnalysis> {
  1754. friend AnalysisInfoMixin<ScalarEvolutionAnalysis>;
  1755. static AnalysisKey Key;
  1756. public:
  1757. using Result = ScalarEvolution;
  1758. ScalarEvolution run(Function &F, FunctionAnalysisManager &AM);
  1759. };
  1760. /// Verifier pass for the \c ScalarEvolutionAnalysis results.
  1761. class ScalarEvolutionVerifierPass
  1762. : public PassInfoMixin<ScalarEvolutionVerifierPass> {
  1763. public:
  1764. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  1765. };
  1766. /// Printer pass for the \c ScalarEvolutionAnalysis results.
  1767. class ScalarEvolutionPrinterPass
  1768. : public PassInfoMixin<ScalarEvolutionPrinterPass> {
  1769. raw_ostream &OS;
  1770. public:
  1771. explicit ScalarEvolutionPrinterPass(raw_ostream &OS) : OS(OS) {}
  1772. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  1773. };
  1774. class ScalarEvolutionWrapperPass : public FunctionPass {
  1775. std::unique_ptr<ScalarEvolution> SE;
  1776. public:
  1777. static char ID;
  1778. ScalarEvolutionWrapperPass();
  1779. ScalarEvolution &getSE() { return *SE; }
  1780. const ScalarEvolution &getSE() const { return *SE; }
  1781. bool runOnFunction(Function &F) override;
  1782. void releaseMemory() override;
  1783. void getAnalysisUsage(AnalysisUsage &AU) const override;
  1784. void print(raw_ostream &OS, const Module * = nullptr) const override;
  1785. void verifyAnalysis() const override;
  1786. };
  1787. /// An interface layer with SCEV used to manage how we see SCEV expressions
  1788. /// for values in the context of existing predicates. We can add new
  1789. /// predicates, but we cannot remove them.
  1790. ///
  1791. /// This layer has multiple purposes:
  1792. /// - provides a simple interface for SCEV versioning.
  1793. /// - guarantees that the order of transformations applied on a SCEV
  1794. /// expression for a single Value is consistent across two different
  1795. /// getSCEV calls. This means that, for example, once we've obtained
  1796. /// an AddRec expression for a certain value through expression
  1797. /// rewriting, we will continue to get an AddRec expression for that
  1798. /// Value.
  1799. /// - lowers the number of expression rewrites.
  1800. class PredicatedScalarEvolution {
  1801. public:
  1802. PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L);
  1803. const SCEVUnionPredicate &getUnionPredicate() const;
  1804. /// Returns the SCEV expression of V, in the context of the current SCEV
  1805. /// predicate. The order of transformations applied on the expression of V
  1806. /// returned by ScalarEvolution is guaranteed to be preserved, even when
  1807. /// adding new predicates.
  1808. const SCEV *getSCEV(Value *V);
  1809. /// Get the (predicated) backedge count for the analyzed loop.
  1810. const SCEV *getBackedgeTakenCount();
  1811. /// Adds a new predicate.
  1812. void addPredicate(const SCEVPredicate &Pred);
  1813. /// Attempts to produce an AddRecExpr for V by adding additional SCEV
  1814. /// predicates. If we can't transform the expression into an AddRecExpr we
  1815. /// return nullptr and not add additional SCEV predicates to the current
  1816. /// context.
  1817. const SCEVAddRecExpr *getAsAddRec(Value *V);
  1818. /// Proves that V doesn't overflow by adding SCEV predicate.
  1819. void setNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags);
  1820. /// Returns true if we've proved that V doesn't wrap by means of a SCEV
  1821. /// predicate.
  1822. bool hasNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags);
  1823. /// Returns the ScalarEvolution analysis used.
  1824. ScalarEvolution *getSE() const { return &SE; }
  1825. /// We need to explicitly define the copy constructor because of FlagsMap.
  1826. PredicatedScalarEvolution(const PredicatedScalarEvolution &);
  1827. /// Print the SCEV mappings done by the Predicated Scalar Evolution.
  1828. /// The printed text is indented by \p Depth.
  1829. void print(raw_ostream &OS, unsigned Depth) const;
  1830. /// Check if \p AR1 and \p AR2 are equal, while taking into account
  1831. /// Equal predicates in Preds.
  1832. bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1,
  1833. const SCEVAddRecExpr *AR2) const;
  1834. private:
  1835. /// Increments the version number of the predicate. This needs to be called
  1836. /// every time the SCEV predicate changes.
  1837. void updateGeneration();
  1838. /// Holds a SCEV and the version number of the SCEV predicate used to
  1839. /// perform the rewrite of the expression.
  1840. using RewriteEntry = std::pair<unsigned, const SCEV *>;
  1841. /// Maps a SCEV to the rewrite result of that SCEV at a certain version
  1842. /// number. If this number doesn't match the current Generation, we will
  1843. /// need to do a rewrite. To preserve the transformation order of previous
  1844. /// rewrites, we will rewrite the previous result instead of the original
  1845. /// SCEV.
  1846. DenseMap<const SCEV *, RewriteEntry> RewriteMap;
  1847. /// Records what NoWrap flags we've added to a Value *.
  1848. ValueMap<Value *, SCEVWrapPredicate::IncrementWrapFlags> FlagsMap;
  1849. /// The ScalarEvolution analysis.
  1850. ScalarEvolution &SE;
  1851. /// The analyzed Loop.
  1852. const Loop &L;
  1853. /// The SCEVPredicate that forms our context. We will rewrite all
  1854. /// expressions assuming that this predicate true.
  1855. SCEVUnionPredicate Preds;
  1856. /// Marks the version of the SCEV predicate used. When rewriting a SCEV
  1857. /// expression we mark it with the version of the predicate. We use this to
  1858. /// figure out if the predicate has changed from the last rewrite of the
  1859. /// SCEV. If so, we need to perform a new rewrite.
  1860. unsigned Generation = 0;
  1861. /// The backedge taken count.
  1862. const SCEV *BackedgeCount = nullptr;
  1863. };
  1864. } // end namespace llvm
  1865. #endif // LLVM_ANALYSIS_SCALAREVOLUTION_H