ScopInfo.h 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898
  1. //===- polly/ScopInfo.h -----------------------------------------*- 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. // Store the polyhedral model representation of a static control flow region,
  10. // also called SCoP (Static Control Part).
  11. //
  12. // This representation is shared among several tools in the polyhedral
  13. // community, which are e.g. CLooG, Pluto, Loopo, Graphite.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #ifndef POLLY_SCOPINFO_H
  17. #define POLLY_SCOPINFO_H
  18. #include "polly/ScopDetection.h"
  19. #include "polly/Support/SCEVAffinator.h"
  20. #include "polly/Support/ScopHelper.h"
  21. #include "llvm/ADT/ArrayRef.h"
  22. #include "llvm/ADT/MapVector.h"
  23. #include "llvm/ADT/SetVector.h"
  24. #include "llvm/Analysis/RegionPass.h"
  25. #include "llvm/IR/DebugLoc.h"
  26. #include "llvm/IR/Instruction.h"
  27. #include "llvm/IR/Instructions.h"
  28. #include "llvm/IR/PassManager.h"
  29. #include "llvm/IR/ValueHandle.h"
  30. #include "llvm/Pass.h"
  31. #include "isl/isl-noexceptions.h"
  32. #include <cassert>
  33. #include <cstddef>
  34. #include <forward_list>
  35. namespace llvm {
  36. void initializeScopInfoRegionPassPass(PassRegistry &);
  37. void initializeScopInfoWrapperPassPass(PassRegistry &);
  38. } // end namespace llvm
  39. namespace polly {
  40. using llvm::AnalysisInfoMixin;
  41. using llvm::ArrayRef;
  42. using llvm::AssertingVH;
  43. using llvm::AssumptionCache;
  44. using llvm::cast;
  45. using llvm::DataLayout;
  46. using llvm::DenseMap;
  47. using llvm::DenseSet;
  48. using llvm::function_ref;
  49. using llvm::isa;
  50. using llvm::iterator_range;
  51. using llvm::LoadInst;
  52. using llvm::make_range;
  53. using llvm::MapVector;
  54. using llvm::MemIntrinsic;
  55. using llvm::Optional;
  56. using llvm::PassInfoMixin;
  57. using llvm::PHINode;
  58. using llvm::RegionNode;
  59. using llvm::RegionPass;
  60. using llvm::RGPassManager;
  61. using llvm::SetVector;
  62. using llvm::SmallPtrSetImpl;
  63. using llvm::SmallVector;
  64. using llvm::SmallVectorImpl;
  65. using llvm::StringMap;
  66. using llvm::Type;
  67. using llvm::Use;
  68. using llvm::Value;
  69. using llvm::ValueToValueMap;
  70. class MemoryAccess;
  71. //===---------------------------------------------------------------------===//
  72. extern bool UseInstructionNames;
  73. // The maximal number of basic sets we allow during domain construction to
  74. // be created. More complex scops will result in very high compile time and
  75. // are also unlikely to result in good code.
  76. extern int const MaxDisjunctsInDomain;
  77. /// The different memory kinds used in Polly.
  78. ///
  79. /// We distinguish between arrays and various scalar memory objects. We use
  80. /// the term ``array'' to describe memory objects that consist of a set of
  81. /// individual data elements arranged in a multi-dimensional grid. A scalar
  82. /// memory object describes an individual data element and is used to model
  83. /// the definition and uses of llvm::Values.
  84. ///
  85. /// The polyhedral model does traditionally not reason about SSA values. To
  86. /// reason about llvm::Values we model them "as if" they were zero-dimensional
  87. /// memory objects, even though they were not actually allocated in (main)
  88. /// memory. Memory for such objects is only alloca[ed] at CodeGeneration
  89. /// time. To relate the memory slots used during code generation with the
  90. /// llvm::Values they belong to the new names for these corresponding stack
  91. /// slots are derived by appending suffixes (currently ".s2a" and ".phiops")
  92. /// to the name of the original llvm::Value. To describe how def/uses are
  93. /// modeled exactly we use these suffixes here as well.
  94. ///
  95. /// There are currently four different kinds of memory objects:
  96. enum class MemoryKind {
  97. /// MemoryKind::Array: Models a one or multi-dimensional array
  98. ///
  99. /// A memory object that can be described by a multi-dimensional array.
  100. /// Memory objects of this type are used to model actual multi-dimensional
  101. /// arrays as they exist in LLVM-IR, but they are also used to describe
  102. /// other objects:
  103. /// - A single data element allocated on the stack using 'alloca' is
  104. /// modeled as a one-dimensional, single-element array.
  105. /// - A single data element allocated as a global variable is modeled as
  106. /// one-dimensional, single-element array.
  107. /// - Certain multi-dimensional arrays with variable size, which in
  108. /// LLVM-IR are commonly expressed as a single-dimensional access with a
  109. /// complicated access function, are modeled as multi-dimensional
  110. /// memory objects (grep for "delinearization").
  111. Array,
  112. /// MemoryKind::Value: Models an llvm::Value
  113. ///
  114. /// Memory objects of type MemoryKind::Value are used to model the data flow
  115. /// induced by llvm::Values. For each llvm::Value that is used across
  116. /// BasicBlocks, one ScopArrayInfo object is created. A single memory WRITE
  117. /// stores the llvm::Value at its definition into the memory object and at
  118. /// each use of the llvm::Value (ignoring trivial intra-block uses) a
  119. /// corresponding READ is added. For instance, the use/def chain of a
  120. /// llvm::Value %V depicted below
  121. /// ______________________
  122. /// |DefBB: |
  123. /// | %V = float op ... |
  124. /// ----------------------
  125. /// | |
  126. /// _________________ _________________
  127. /// |UseBB1: | |UseBB2: |
  128. /// | use float %V | | use float %V |
  129. /// ----------------- -----------------
  130. ///
  131. /// is modeled as if the following memory accesses occurred:
  132. ///
  133. /// __________________________
  134. /// |entry: |
  135. /// | %V.s2a = alloca float |
  136. /// --------------------------
  137. /// |
  138. /// ___________________________________
  139. /// |DefBB: |
  140. /// | store %float %V, float* %V.s2a |
  141. /// -----------------------------------
  142. /// | |
  143. /// ____________________________________ ___________________________________
  144. /// |UseBB1: | |UseBB2: |
  145. /// | %V.reload1 = load float* %V.s2a | | %V.reload2 = load float* %V.s2a|
  146. /// | use float %V.reload1 | | use float %V.reload2 |
  147. /// ------------------------------------ -----------------------------------
  148. ///
  149. Value,
  150. /// MemoryKind::PHI: Models PHI nodes within the SCoP
  151. ///
  152. /// Besides the MemoryKind::Value memory object used to model the normal
  153. /// llvm::Value dependences described above, PHI nodes require an additional
  154. /// memory object of type MemoryKind::PHI to describe the forwarding of values
  155. /// to
  156. /// the PHI node.
  157. ///
  158. /// As an example, a PHIInst instructions
  159. ///
  160. /// %PHI = phi float [ %Val1, %IncomingBlock1 ], [ %Val2, %IncomingBlock2 ]
  161. ///
  162. /// is modeled as if the accesses occurred this way:
  163. ///
  164. /// _______________________________
  165. /// |entry: |
  166. /// | %PHI.phiops = alloca float |
  167. /// -------------------------------
  168. /// | |
  169. /// __________________________________ __________________________________
  170. /// |IncomingBlock1: | |IncomingBlock2: |
  171. /// | ... | | ... |
  172. /// | store float %Val1 %PHI.phiops | | store float %Val2 %PHI.phiops |
  173. /// | br label % JoinBlock | | br label %JoinBlock |
  174. /// ---------------------------------- ----------------------------------
  175. /// \ /
  176. /// \ /
  177. /// _________________________________________
  178. /// |JoinBlock: |
  179. /// | %PHI = load float, float* PHI.phiops |
  180. /// -----------------------------------------
  181. ///
  182. /// Note that there can also be a scalar write access for %PHI if used in a
  183. /// different BasicBlock, i.e. there can be a memory object %PHI.phiops as
  184. /// well as a memory object %PHI.s2a.
  185. PHI,
  186. /// MemoryKind::ExitPHI: Models PHI nodes in the SCoP's exit block
  187. ///
  188. /// For PHI nodes in the Scop's exit block a special memory object kind is
  189. /// used. The modeling used is identical to MemoryKind::PHI, with the
  190. /// exception
  191. /// that there are no READs from these memory objects. The PHINode's
  192. /// llvm::Value is treated as a value escaping the SCoP. WRITE accesses
  193. /// write directly to the escaping value's ".s2a" alloca.
  194. ExitPHI
  195. };
  196. /// Maps from a loop to the affine function expressing its backedge taken count.
  197. /// The backedge taken count already enough to express iteration domain as we
  198. /// only allow loops with canonical induction variable.
  199. /// A canonical induction variable is:
  200. /// an integer recurrence that starts at 0 and increments by one each time
  201. /// through the loop.
  202. using LoopBoundMapType = std::map<const Loop *, const SCEV *>;
  203. using AccFuncVector = std::vector<std::unique_ptr<MemoryAccess>>;
  204. /// A class to store information about arrays in the SCoP.
  205. ///
  206. /// Objects are accessible via the ScoP, MemoryAccess or the id associated with
  207. /// the MemoryAccess access function.
  208. ///
  209. class ScopArrayInfo {
  210. public:
  211. /// Construct a ScopArrayInfo object.
  212. ///
  213. /// @param BasePtr The array base pointer.
  214. /// @param ElementType The type of the elements stored in the array.
  215. /// @param IslCtx The isl context used to create the base pointer id.
  216. /// @param DimensionSizes A vector containing the size of each dimension.
  217. /// @param Kind The kind of the array object.
  218. /// @param DL The data layout of the module.
  219. /// @param S The scop this array object belongs to.
  220. /// @param BaseName The optional name of this memory reference.
  221. ScopArrayInfo(Value *BasePtr, Type *ElementType, isl::ctx IslCtx,
  222. ArrayRef<const SCEV *> DimensionSizes, MemoryKind Kind,
  223. const DataLayout &DL, Scop *S, const char *BaseName = nullptr);
  224. /// Destructor to free the isl id of the base pointer.
  225. ~ScopArrayInfo();
  226. /// Update the element type of the ScopArrayInfo object.
  227. ///
  228. /// Memory accesses referencing this ScopArrayInfo object may use
  229. /// different element sizes. This function ensures the canonical element type
  230. /// stored is small enough to model accesses to the current element type as
  231. /// well as to @p NewElementType.
  232. ///
  233. /// @param NewElementType An element type that is used to access this array.
  234. void updateElementType(Type *NewElementType);
  235. /// Update the sizes of the ScopArrayInfo object.
  236. ///
  237. /// A ScopArrayInfo object may be created without all outer dimensions being
  238. /// available. This function is called when new memory accesses are added for
  239. /// this ScopArrayInfo object. It verifies that sizes are compatible and adds
  240. /// additional outer array dimensions, if needed.
  241. ///
  242. /// @param Sizes A vector of array sizes where the rightmost array
  243. /// sizes need to match the innermost array sizes already
  244. /// defined in SAI.
  245. /// @param CheckConsistency Update sizes, even if new sizes are inconsistent
  246. /// with old sizes
  247. bool updateSizes(ArrayRef<const SCEV *> Sizes, bool CheckConsistency = true);
  248. /// Make the ScopArrayInfo model a Fortran array.
  249. /// It receives the Fortran array descriptor and stores this.
  250. /// It also adds a piecewise expression for the outermost dimension
  251. /// since this information is available for Fortran arrays at runtime.
  252. void applyAndSetFAD(Value *FAD);
  253. /// Get the FortranArrayDescriptor corresponding to this array if it exists,
  254. /// nullptr otherwise.
  255. Value *getFortranArrayDescriptor() const { return this->FAD; }
  256. /// Set the base pointer to @p BP.
  257. void setBasePtr(Value *BP) { BasePtr = BP; }
  258. /// Return the base pointer.
  259. Value *getBasePtr() const { return BasePtr; }
  260. // Set IsOnHeap to the value in parameter.
  261. void setIsOnHeap(bool value) { IsOnHeap = value; }
  262. /// For indirect accesses return the origin SAI of the BP, else null.
  263. const ScopArrayInfo *getBasePtrOriginSAI() const { return BasePtrOriginSAI; }
  264. /// The set of derived indirect SAIs for this origin SAI.
  265. const SmallSetVector<ScopArrayInfo *, 2> &getDerivedSAIs() const {
  266. return DerivedSAIs;
  267. }
  268. /// Return the number of dimensions.
  269. unsigned getNumberOfDimensions() const {
  270. if (Kind == MemoryKind::PHI || Kind == MemoryKind::ExitPHI ||
  271. Kind == MemoryKind::Value)
  272. return 0;
  273. return DimensionSizes.size();
  274. }
  275. /// Return the size of dimension @p dim as SCEV*.
  276. //
  277. // Scalars do not have array dimensions and the first dimension of
  278. // a (possibly multi-dimensional) array also does not carry any size
  279. // information, in case the array is not newly created.
  280. const SCEV *getDimensionSize(unsigned Dim) const {
  281. assert(Dim < getNumberOfDimensions() && "Invalid dimension");
  282. return DimensionSizes[Dim];
  283. }
  284. /// Return the size of dimension @p dim as isl::pw_aff.
  285. //
  286. // Scalars do not have array dimensions and the first dimension of
  287. // a (possibly multi-dimensional) array also does not carry any size
  288. // information, in case the array is not newly created.
  289. isl::pw_aff getDimensionSizePw(unsigned Dim) const {
  290. assert(Dim < getNumberOfDimensions() && "Invalid dimension");
  291. return DimensionSizesPw[Dim];
  292. }
  293. /// Get the canonical element type of this array.
  294. ///
  295. /// @returns The canonical element type of this array.
  296. Type *getElementType() const { return ElementType; }
  297. /// Get element size in bytes.
  298. int getElemSizeInBytes() const;
  299. /// Get the name of this memory reference.
  300. std::string getName() const;
  301. /// Return the isl id for the base pointer.
  302. isl::id getBasePtrId() const;
  303. /// Return what kind of memory this represents.
  304. MemoryKind getKind() const { return Kind; }
  305. /// Is this array info modeling an llvm::Value?
  306. bool isValueKind() const { return Kind == MemoryKind::Value; }
  307. /// Is this array info modeling special PHI node memory?
  308. ///
  309. /// During code generation of PHI nodes, there is a need for two kinds of
  310. /// virtual storage. The normal one as it is used for all scalar dependences,
  311. /// where the result of the PHI node is stored and later loaded from as well
  312. /// as a second one where the incoming values of the PHI nodes are stored
  313. /// into and reloaded when the PHI is executed. As both memories use the
  314. /// original PHI node as virtual base pointer, we have this additional
  315. /// attribute to distinguish the PHI node specific array modeling from the
  316. /// normal scalar array modeling.
  317. bool isPHIKind() const { return Kind == MemoryKind::PHI; }
  318. /// Is this array info modeling an MemoryKind::ExitPHI?
  319. bool isExitPHIKind() const { return Kind == MemoryKind::ExitPHI; }
  320. /// Is this array info modeling an array?
  321. bool isArrayKind() const { return Kind == MemoryKind::Array; }
  322. /// Is this array allocated on heap
  323. ///
  324. /// This property is only relevant if the array is allocated by Polly instead
  325. /// of pre-existing. If false, it is allocated using alloca instead malloca.
  326. bool isOnHeap() const { return IsOnHeap; }
  327. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  328. /// Dump a readable representation to stderr.
  329. void dump() const;
  330. #endif
  331. /// Print a readable representation to @p OS.
  332. ///
  333. /// @param SizeAsPwAff Print the size as isl::pw_aff
  334. void print(raw_ostream &OS, bool SizeAsPwAff = false) const;
  335. /// Access the ScopArrayInfo associated with an access function.
  336. static const ScopArrayInfo *getFromAccessFunction(isl::pw_multi_aff PMA);
  337. /// Access the ScopArrayInfo associated with an isl Id.
  338. static const ScopArrayInfo *getFromId(isl::id Id);
  339. /// Get the space of this array access.
  340. isl::space getSpace() const;
  341. /// If the array is read only
  342. bool isReadOnly();
  343. /// Verify that @p Array is compatible to this ScopArrayInfo.
  344. ///
  345. /// Two arrays are compatible if their dimensionality, the sizes of their
  346. /// dimensions, and their element sizes match.
  347. ///
  348. /// @param Array The array to compare against.
  349. ///
  350. /// @returns True, if the arrays are compatible, False otherwise.
  351. bool isCompatibleWith(const ScopArrayInfo *Array) const;
  352. private:
  353. void addDerivedSAI(ScopArrayInfo *DerivedSAI) {
  354. DerivedSAIs.insert(DerivedSAI);
  355. }
  356. /// For indirect accesses this is the SAI of the BP origin.
  357. const ScopArrayInfo *BasePtrOriginSAI;
  358. /// For origin SAIs the set of derived indirect SAIs.
  359. SmallSetVector<ScopArrayInfo *, 2> DerivedSAIs;
  360. /// The base pointer.
  361. AssertingVH<Value> BasePtr;
  362. /// The canonical element type of this array.
  363. ///
  364. /// The canonical element type describes the minimal accessible element in
  365. /// this array. Not all elements accessed, need to be of the very same type,
  366. /// but the allocation size of the type of the elements loaded/stored from/to
  367. /// this array needs to be a multiple of the allocation size of the canonical
  368. /// type.
  369. Type *ElementType;
  370. /// The isl id for the base pointer.
  371. isl::id Id;
  372. /// True if the newly allocated array is on heap.
  373. bool IsOnHeap = false;
  374. /// The sizes of each dimension as SCEV*.
  375. SmallVector<const SCEV *, 4> DimensionSizes;
  376. /// The sizes of each dimension as isl::pw_aff.
  377. SmallVector<isl::pw_aff, 4> DimensionSizesPw;
  378. /// The type of this scop array info object.
  379. ///
  380. /// We distinguish between SCALAR, PHI and ARRAY objects.
  381. MemoryKind Kind;
  382. /// The data layout of the module.
  383. const DataLayout &DL;
  384. /// The scop this SAI object belongs to.
  385. Scop &S;
  386. /// If this array models a Fortran array, then this points
  387. /// to the Fortran array descriptor.
  388. Value *FAD = nullptr;
  389. };
  390. /// Represent memory accesses in statements.
  391. class MemoryAccess {
  392. friend class Scop;
  393. friend class ScopStmt;
  394. friend class ScopBuilder;
  395. public:
  396. /// The access type of a memory access
  397. ///
  398. /// There are three kind of access types:
  399. ///
  400. /// * A read access
  401. ///
  402. /// A certain set of memory locations are read and may be used for internal
  403. /// calculations.
  404. ///
  405. /// * A must-write access
  406. ///
  407. /// A certain set of memory locations is definitely written. The old value is
  408. /// replaced by a newly calculated value. The old value is not read or used at
  409. /// all.
  410. ///
  411. /// * A may-write access
  412. ///
  413. /// A certain set of memory locations may be written. The memory location may
  414. /// contain a new value if there is actually a write or the old value may
  415. /// remain, if no write happens.
  416. enum AccessType {
  417. READ = 0x1,
  418. MUST_WRITE = 0x2,
  419. MAY_WRITE = 0x3,
  420. };
  421. /// Reduction access type
  422. ///
  423. /// Commutative and associative binary operations suitable for reductions
  424. enum ReductionType {
  425. RT_NONE, ///< Indicate no reduction at all
  426. RT_ADD, ///< Addition
  427. RT_MUL, ///< Multiplication
  428. RT_BOR, ///< Bitwise Or
  429. RT_BXOR, ///< Bitwise XOr
  430. RT_BAND, ///< Bitwise And
  431. };
  432. using SubscriptsTy = SmallVector<const SCEV *, 4>;
  433. private:
  434. /// A unique identifier for this memory access.
  435. ///
  436. /// The identifier is unique between all memory accesses belonging to the same
  437. /// scop statement.
  438. isl::id Id;
  439. /// What is modeled by this MemoryAccess.
  440. /// @see MemoryKind
  441. MemoryKind Kind;
  442. /// Whether it a reading or writing access, and if writing, whether it
  443. /// is conditional (MAY_WRITE).
  444. enum AccessType AccType;
  445. /// Reduction type for reduction like accesses, RT_NONE otherwise
  446. ///
  447. /// An access is reduction like if it is part of a load-store chain in which
  448. /// both access the same memory location (use the same LLVM-IR value
  449. /// as pointer reference). Furthermore, between the load and the store there
  450. /// is exactly one binary operator which is known to be associative and
  451. /// commutative.
  452. ///
  453. /// TODO:
  454. ///
  455. /// We can later lift the constraint that the same LLVM-IR value defines the
  456. /// memory location to handle scops such as the following:
  457. ///
  458. /// for i
  459. /// for j
  460. /// sum[i+j] = sum[i] + 3;
  461. ///
  462. /// Here not all iterations access the same memory location, but iterations
  463. /// for which j = 0 holds do. After lifting the equality check in ScopBuilder,
  464. /// subsequent transformations do not only need check if a statement is
  465. /// reduction like, but they also need to verify that that the reduction
  466. /// property is only exploited for statement instances that load from and
  467. /// store to the same data location. Doing so at dependence analysis time
  468. /// could allow us to handle the above example.
  469. ReductionType RedType = RT_NONE;
  470. /// Parent ScopStmt of this access.
  471. ScopStmt *Statement;
  472. /// The domain under which this access is not modeled precisely.
  473. ///
  474. /// The invalid domain for an access describes all parameter combinations
  475. /// under which the statement looks to be executed but is in fact not because
  476. /// some assumption/restriction makes the access invalid.
  477. isl::set InvalidDomain;
  478. // Properties describing the accessed array.
  479. // TODO: It might be possible to move them to ScopArrayInfo.
  480. // @{
  481. /// The base address (e.g., A for A[i+j]).
  482. ///
  483. /// The #BaseAddr of a memory access of kind MemoryKind::Array is the base
  484. /// pointer of the memory access.
  485. /// The #BaseAddr of a memory access of kind MemoryKind::PHI or
  486. /// MemoryKind::ExitPHI is the PHI node itself.
  487. /// The #BaseAddr of a memory access of kind MemoryKind::Value is the
  488. /// instruction defining the value.
  489. AssertingVH<Value> BaseAddr;
  490. /// Type a single array element wrt. this access.
  491. Type *ElementType;
  492. /// Size of each dimension of the accessed array.
  493. SmallVector<const SCEV *, 4> Sizes;
  494. // @}
  495. // Properties describing the accessed element.
  496. // @{
  497. /// The access instruction of this memory access.
  498. ///
  499. /// For memory accesses of kind MemoryKind::Array the access instruction is
  500. /// the Load or Store instruction performing the access.
  501. ///
  502. /// For memory accesses of kind MemoryKind::PHI or MemoryKind::ExitPHI the
  503. /// access instruction of a load access is the PHI instruction. The access
  504. /// instruction of a PHI-store is the incoming's block's terminator
  505. /// instruction.
  506. ///
  507. /// For memory accesses of kind MemoryKind::Value the access instruction of a
  508. /// load access is nullptr because generally there can be multiple
  509. /// instructions in the statement using the same llvm::Value. The access
  510. /// instruction of a write access is the instruction that defines the
  511. /// llvm::Value.
  512. Instruction *AccessInstruction = nullptr;
  513. /// Incoming block and value of a PHINode.
  514. SmallVector<std::pair<BasicBlock *, Value *>, 4> Incoming;
  515. /// The value associated with this memory access.
  516. ///
  517. /// - For array memory accesses (MemoryKind::Array) it is the loaded result
  518. /// or the stored value. If the access instruction is a memory intrinsic it
  519. /// the access value is also the memory intrinsic.
  520. /// - For accesses of kind MemoryKind::Value it is the access instruction
  521. /// itself.
  522. /// - For accesses of kind MemoryKind::PHI or MemoryKind::ExitPHI it is the
  523. /// PHI node itself (for both, READ and WRITE accesses).
  524. ///
  525. AssertingVH<Value> AccessValue;
  526. /// Are all the subscripts affine expression?
  527. bool IsAffine = true;
  528. /// Subscript expression for each dimension.
  529. SubscriptsTy Subscripts;
  530. /// Relation from statement instances to the accessed array elements.
  531. ///
  532. /// In the common case this relation is a function that maps a set of loop
  533. /// indices to the memory address from which a value is loaded/stored:
  534. ///
  535. /// for i
  536. /// for j
  537. /// S: A[i + 3 j] = ...
  538. ///
  539. /// => { S[i,j] -> A[i + 3j] }
  540. ///
  541. /// In case the exact access function is not known, the access relation may
  542. /// also be a one to all mapping { S[i,j] -> A[o] } describing that any
  543. /// element accessible through A might be accessed.
  544. ///
  545. /// In case of an access to a larger element belonging to an array that also
  546. /// contains smaller elements, the access relation models the larger access
  547. /// with multiple smaller accesses of the size of the minimal array element
  548. /// type:
  549. ///
  550. /// short *A;
  551. ///
  552. /// for i
  553. /// S: A[i] = *((double*)&A[4 * i]);
  554. ///
  555. /// => { S[i] -> A[i]; S[i] -> A[o] : 4i <= o <= 4i + 3 }
  556. isl::map AccessRelation;
  557. /// Updated access relation read from JSCOP file.
  558. isl::map NewAccessRelation;
  559. /// Fortran arrays whose sizes are not statically known are stored in terms
  560. /// of a descriptor struct. This maintains a raw pointer to the memory,
  561. /// along with auxiliary fields with information such as dimensions.
  562. /// We hold a reference to the descriptor corresponding to a MemoryAccess
  563. /// into a Fortran array. FAD for "Fortran Array Descriptor"
  564. AssertingVH<Value> FAD;
  565. // @}
  566. isl::basic_map createBasicAccessMap(ScopStmt *Statement);
  567. isl::set assumeNoOutOfBound();
  568. /// Compute bounds on an over approximated access relation.
  569. ///
  570. /// @param ElementSize The size of one element accessed.
  571. void computeBoundsOnAccessRelation(unsigned ElementSize);
  572. /// Get the original access function as read from IR.
  573. isl::map getOriginalAccessRelation() const;
  574. /// Return the space in which the access relation lives in.
  575. isl::space getOriginalAccessRelationSpace() const;
  576. /// Get the new access function imported or set by a pass
  577. isl::map getNewAccessRelation() const;
  578. /// Fold the memory access to consider parametric offsets
  579. ///
  580. /// To recover memory accesses with array size parameters in the subscript
  581. /// expression we post-process the delinearization results.
  582. ///
  583. /// We would normally recover from an access A[exp0(i) * N + exp1(i)] into an
  584. /// array A[][N] the 2D access A[exp0(i)][exp1(i)]. However, another valid
  585. /// delinearization is A[exp0(i) - 1][exp1(i) + N] which - depending on the
  586. /// range of exp1(i) - may be preferable. Specifically, for cases where we
  587. /// know exp1(i) is negative, we want to choose the latter expression.
  588. ///
  589. /// As we commonly do not have any information about the range of exp1(i),
  590. /// we do not choose one of the two options, but instead create a piecewise
  591. /// access function that adds the (-1, N) offsets as soon as exp1(i) becomes
  592. /// negative. For a 2D array such an access function is created by applying
  593. /// the piecewise map:
  594. ///
  595. /// [i,j] -> [i, j] : j >= 0
  596. /// [i,j] -> [i-1, j+N] : j < 0
  597. ///
  598. /// We can generalize this mapping to arbitrary dimensions by applying this
  599. /// piecewise mapping pairwise from the rightmost to the leftmost access
  600. /// dimension. It would also be possible to cover a wider range by introducing
  601. /// more cases and adding multiple of Ns to these cases. However, this has
  602. /// not yet been necessary.
  603. /// The introduction of different cases necessarily complicates the memory
  604. /// access function, but cases that can be statically proven to not happen
  605. /// will be eliminated later on.
  606. void foldAccessRelation();
  607. /// Create the access relation for the underlying memory intrinsic.
  608. void buildMemIntrinsicAccessRelation();
  609. /// Assemble the access relation from all available information.
  610. ///
  611. /// In particular, used the information passes in the constructor and the
  612. /// parent ScopStmt set by setStatment().
  613. ///
  614. /// @param SAI Info object for the accessed array.
  615. void buildAccessRelation(const ScopArrayInfo *SAI);
  616. /// Carry index overflows of dimensions with constant size to the next higher
  617. /// dimension.
  618. ///
  619. /// For dimensions that have constant size, modulo the index by the size and
  620. /// add up the carry (floored division) to the next higher dimension. This is
  621. /// how overflow is defined in row-major order.
  622. /// It happens e.g. when ScalarEvolution computes the offset to the base
  623. /// pointer and would algebraically sum up all lower dimensions' indices of
  624. /// constant size.
  625. ///
  626. /// Example:
  627. /// float (*A)[4];
  628. /// A[1][6] -> A[2][2]
  629. void wrapConstantDimensions();
  630. public:
  631. /// Create a new MemoryAccess.
  632. ///
  633. /// @param Stmt The parent statement.
  634. /// @param AccessInst The instruction doing the access.
  635. /// @param BaseAddr The accessed array's address.
  636. /// @param ElemType The type of the accessed array elements.
  637. /// @param AccType Whether read or write access.
  638. /// @param IsAffine Whether the subscripts are affine expressions.
  639. /// @param Kind The kind of memory accessed.
  640. /// @param Subscripts Subscript expressions
  641. /// @param Sizes Dimension lengths of the accessed array.
  642. MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst, AccessType AccType,
  643. Value *BaseAddress, Type *ElemType, bool Affine,
  644. ArrayRef<const SCEV *> Subscripts, ArrayRef<const SCEV *> Sizes,
  645. Value *AccessValue, MemoryKind Kind);
  646. /// Create a new MemoryAccess that corresponds to @p AccRel.
  647. ///
  648. /// Along with @p Stmt and @p AccType it uses information about dimension
  649. /// lengths of the accessed array, the type of the accessed array elements,
  650. /// the name of the accessed array that is derived from the object accessible
  651. /// via @p AccRel.
  652. ///
  653. /// @param Stmt The parent statement.
  654. /// @param AccType Whether read or write access.
  655. /// @param AccRel The access relation that describes the memory access.
  656. MemoryAccess(ScopStmt *Stmt, AccessType AccType, isl::map AccRel);
  657. MemoryAccess(const MemoryAccess &) = delete;
  658. MemoryAccess &operator=(const MemoryAccess &) = delete;
  659. ~MemoryAccess();
  660. /// Add a new incoming block/value pairs for this PHI/ExitPHI access.
  661. ///
  662. /// @param IncomingBlock The PHI's incoming block.
  663. /// @param IncomingValue The value when reaching the PHI from the @p
  664. /// IncomingBlock.
  665. void addIncoming(BasicBlock *IncomingBlock, Value *IncomingValue) {
  666. assert(!isRead());
  667. assert(isAnyPHIKind());
  668. Incoming.emplace_back(std::make_pair(IncomingBlock, IncomingValue));
  669. }
  670. /// Return the list of possible PHI/ExitPHI values.
  671. ///
  672. /// After code generation moves some PHIs around during region simplification,
  673. /// we cannot reliably locate the original PHI node and its incoming values
  674. /// anymore. For this reason we remember these explicitly for all PHI-kind
  675. /// accesses.
  676. ArrayRef<std::pair<BasicBlock *, Value *>> getIncoming() const {
  677. assert(isAnyPHIKind());
  678. return Incoming;
  679. }
  680. /// Get the type of a memory access.
  681. enum AccessType getType() { return AccType; }
  682. /// Is this a reduction like access?
  683. bool isReductionLike() const { return RedType != RT_NONE; }
  684. /// Is this a read memory access?
  685. bool isRead() const { return AccType == MemoryAccess::READ; }
  686. /// Is this a must-write memory access?
  687. bool isMustWrite() const { return AccType == MemoryAccess::MUST_WRITE; }
  688. /// Is this a may-write memory access?
  689. bool isMayWrite() const { return AccType == MemoryAccess::MAY_WRITE; }
  690. /// Is this a write memory access?
  691. bool isWrite() const { return isMustWrite() || isMayWrite(); }
  692. /// Is this a memory intrinsic access (memcpy, memset, memmove)?
  693. bool isMemoryIntrinsic() const {
  694. return isa<MemIntrinsic>(getAccessInstruction());
  695. }
  696. /// Check if a new access relation was imported or set by a pass.
  697. bool hasNewAccessRelation() const { return !NewAccessRelation.is_null(); }
  698. /// Return the newest access relation of this access.
  699. ///
  700. /// There are two possibilities:
  701. /// 1) The original access relation read from the LLVM-IR.
  702. /// 2) A new access relation imported from a json file or set by another
  703. /// pass (e.g., for privatization).
  704. ///
  705. /// As 2) is by construction "newer" than 1) we return the new access
  706. /// relation if present.
  707. ///
  708. isl::map getLatestAccessRelation() const {
  709. return hasNewAccessRelation() ? getNewAccessRelation()
  710. : getOriginalAccessRelation();
  711. }
  712. /// Old name of getLatestAccessRelation().
  713. isl::map getAccessRelation() const { return getLatestAccessRelation(); }
  714. /// Get an isl map describing the memory address accessed.
  715. ///
  716. /// In most cases the memory address accessed is well described by the access
  717. /// relation obtained with getAccessRelation. However, in case of arrays
  718. /// accessed with types of different size the access relation maps one access
  719. /// to multiple smaller address locations. This method returns an isl map that
  720. /// relates each dynamic statement instance to the unique memory location
  721. /// that is loaded from / stored to.
  722. ///
  723. /// For an access relation { S[i] -> A[o] : 4i <= o <= 4i + 3 } this method
  724. /// will return the address function { S[i] -> A[4i] }.
  725. ///
  726. /// @returns The address function for this memory access.
  727. isl::map getAddressFunction() const;
  728. /// Return the access relation after the schedule was applied.
  729. isl::pw_multi_aff
  730. applyScheduleToAccessRelation(isl::union_map Schedule) const;
  731. /// Get an isl string representing the access function read from IR.
  732. std::string getOriginalAccessRelationStr() const;
  733. /// Get an isl string representing a new access function, if available.
  734. std::string getNewAccessRelationStr() const;
  735. /// Get an isl string representing the latest access relation.
  736. std::string getAccessRelationStr() const;
  737. /// Get the original base address of this access (e.g. A for A[i+j]) when
  738. /// detected.
  739. ///
  740. /// This address may differ from the base address referenced by the original
  741. /// ScopArrayInfo to which this array belongs, as this memory access may
  742. /// have been canonicalized to a ScopArrayInfo which has a different but
  743. /// identically-valued base pointer in case invariant load hoisting is
  744. /// enabled.
  745. Value *getOriginalBaseAddr() const { return BaseAddr; }
  746. /// Get the detection-time base array isl::id for this access.
  747. isl::id getOriginalArrayId() const;
  748. /// Get the base array isl::id for this access, modifiable through
  749. /// setNewAccessRelation().
  750. isl::id getLatestArrayId() const;
  751. /// Old name of getOriginalArrayId().
  752. isl::id getArrayId() const { return getOriginalArrayId(); }
  753. /// Get the detection-time ScopArrayInfo object for the base address.
  754. const ScopArrayInfo *getOriginalScopArrayInfo() const;
  755. /// Get the ScopArrayInfo object for the base address, or the one set
  756. /// by setNewAccessRelation().
  757. const ScopArrayInfo *getLatestScopArrayInfo() const;
  758. /// Legacy name of getOriginalScopArrayInfo().
  759. const ScopArrayInfo *getScopArrayInfo() const {
  760. return getOriginalScopArrayInfo();
  761. }
  762. /// Return a string representation of the access's reduction type.
  763. const std::string getReductionOperatorStr() const;
  764. /// Return a string representation of the reduction type @p RT.
  765. static const std::string getReductionOperatorStr(ReductionType RT);
  766. /// Return the element type of the accessed array wrt. this access.
  767. Type *getElementType() const { return ElementType; }
  768. /// Return the access value of this memory access.
  769. Value *getAccessValue() const { return AccessValue; }
  770. /// Return llvm::Value that is stored by this access, if available.
  771. ///
  772. /// PHI nodes may not have a unique value available that is stored, as in
  773. /// case of region statements one out of possibly several llvm::Values
  774. /// might be stored. In this case nullptr is returned.
  775. Value *tryGetValueStored() {
  776. assert(isWrite() && "Only write statement store values");
  777. if (isAnyPHIKind()) {
  778. if (Incoming.size() == 1)
  779. return Incoming[0].second;
  780. return nullptr;
  781. }
  782. return AccessValue;
  783. }
  784. /// Return the access instruction of this memory access.
  785. Instruction *getAccessInstruction() const { return AccessInstruction; }
  786. /// Return an iterator range containing the subscripts.
  787. iterator_range<SubscriptsTy::const_iterator> subscripts() const {
  788. return make_range(Subscripts.begin(), Subscripts.end());
  789. }
  790. /// Return the number of access function subscript.
  791. unsigned getNumSubscripts() const { return Subscripts.size(); }
  792. /// Return the access function subscript in the dimension @p Dim.
  793. const SCEV *getSubscript(unsigned Dim) const { return Subscripts[Dim]; }
  794. /// Compute the isl representation for the SCEV @p E wrt. this access.
  795. ///
  796. /// Note that this function will also adjust the invalid context accordingly.
  797. isl::pw_aff getPwAff(const SCEV *E);
  798. /// Get the invalid domain for this access.
  799. isl::set getInvalidDomain() const { return InvalidDomain; }
  800. /// Get the invalid context for this access.
  801. isl::set getInvalidContext() const { return getInvalidDomain().params(); }
  802. /// Get the stride of this memory access in the specified Schedule. Schedule
  803. /// is a map from the statement to a schedule where the innermost dimension is
  804. /// the dimension of the innermost loop containing the statement.
  805. isl::set getStride(isl::map Schedule) const;
  806. /// Get the FortranArrayDescriptor corresponding to this memory access if
  807. /// it exists, and nullptr otherwise.
  808. Value *getFortranArrayDescriptor() const { return this->FAD; }
  809. /// Is the stride of the access equal to a certain width? Schedule is a map
  810. /// from the statement to a schedule where the innermost dimension is the
  811. /// dimension of the innermost loop containing the statement.
  812. bool isStrideX(isl::map Schedule, int StrideWidth) const;
  813. /// Is consecutive memory accessed for a given statement instance set?
  814. /// Schedule is a map from the statement to a schedule where the innermost
  815. /// dimension is the dimension of the innermost loop containing the
  816. /// statement.
  817. bool isStrideOne(isl::map Schedule) const;
  818. /// Is always the same memory accessed for a given statement instance set?
  819. /// Schedule is a map from the statement to a schedule where the innermost
  820. /// dimension is the dimension of the innermost loop containing the
  821. /// statement.
  822. bool isStrideZero(isl::map Schedule) const;
  823. /// Return the kind when this access was first detected.
  824. MemoryKind getOriginalKind() const {
  825. assert(!getOriginalScopArrayInfo() /* not yet initialized */ ||
  826. getOriginalScopArrayInfo()->getKind() == Kind);
  827. return Kind;
  828. }
  829. /// Return the kind considering a potential setNewAccessRelation.
  830. MemoryKind getLatestKind() const {
  831. return getLatestScopArrayInfo()->getKind();
  832. }
  833. /// Whether this is an access of an explicit load or store in the IR.
  834. bool isOriginalArrayKind() const {
  835. return getOriginalKind() == MemoryKind::Array;
  836. }
  837. /// Whether storage memory is either an custom .s2a/.phiops alloca
  838. /// (false) or an existing pointer into an array (true).
  839. bool isLatestArrayKind() const {
  840. return getLatestKind() == MemoryKind::Array;
  841. }
  842. /// Old name of isOriginalArrayKind.
  843. bool isArrayKind() const { return isOriginalArrayKind(); }
  844. /// Whether this access is an array to a scalar memory object, without
  845. /// considering changes by setNewAccessRelation.
  846. ///
  847. /// Scalar accesses are accesses to MemoryKind::Value, MemoryKind::PHI or
  848. /// MemoryKind::ExitPHI.
  849. bool isOriginalScalarKind() const {
  850. return getOriginalKind() != MemoryKind::Array;
  851. }
  852. /// Whether this access is an array to a scalar memory object, also
  853. /// considering changes by setNewAccessRelation.
  854. bool isLatestScalarKind() const {
  855. return getLatestKind() != MemoryKind::Array;
  856. }
  857. /// Old name of isOriginalScalarKind.
  858. bool isScalarKind() const { return isOriginalScalarKind(); }
  859. /// Was this MemoryAccess detected as a scalar dependences?
  860. bool isOriginalValueKind() const {
  861. return getOriginalKind() == MemoryKind::Value;
  862. }
  863. /// Is this MemoryAccess currently modeling scalar dependences?
  864. bool isLatestValueKind() const {
  865. return getLatestKind() == MemoryKind::Value;
  866. }
  867. /// Old name of isOriginalValueKind().
  868. bool isValueKind() const { return isOriginalValueKind(); }
  869. /// Was this MemoryAccess detected as a special PHI node access?
  870. bool isOriginalPHIKind() const {
  871. return getOriginalKind() == MemoryKind::PHI;
  872. }
  873. /// Is this MemoryAccess modeling special PHI node accesses, also
  874. /// considering a potential change by setNewAccessRelation?
  875. bool isLatestPHIKind() const { return getLatestKind() == MemoryKind::PHI; }
  876. /// Old name of isOriginalPHIKind.
  877. bool isPHIKind() const { return isOriginalPHIKind(); }
  878. /// Was this MemoryAccess detected as the accesses of a PHI node in the
  879. /// SCoP's exit block?
  880. bool isOriginalExitPHIKind() const {
  881. return getOriginalKind() == MemoryKind::ExitPHI;
  882. }
  883. /// Is this MemoryAccess modeling the accesses of a PHI node in the
  884. /// SCoP's exit block? Can be changed to an array access using
  885. /// setNewAccessRelation().
  886. bool isLatestExitPHIKind() const {
  887. return getLatestKind() == MemoryKind::ExitPHI;
  888. }
  889. /// Old name of isOriginalExitPHIKind().
  890. bool isExitPHIKind() const { return isOriginalExitPHIKind(); }
  891. /// Was this access detected as one of the two PHI types?
  892. bool isOriginalAnyPHIKind() const {
  893. return isOriginalPHIKind() || isOriginalExitPHIKind();
  894. }
  895. /// Does this access originate from one of the two PHI types? Can be
  896. /// changed to an array access using setNewAccessRelation().
  897. bool isLatestAnyPHIKind() const {
  898. return isLatestPHIKind() || isLatestExitPHIKind();
  899. }
  900. /// Old name of isOriginalAnyPHIKind().
  901. bool isAnyPHIKind() const { return isOriginalAnyPHIKind(); }
  902. /// Get the statement that contains this memory access.
  903. ScopStmt *getStatement() const { return Statement; }
  904. /// Get the reduction type of this access
  905. ReductionType getReductionType() const { return RedType; }
  906. /// Set the array descriptor corresponding to the Array on which the
  907. /// memory access is performed.
  908. void setFortranArrayDescriptor(Value *FAD);
  909. /// Update the original access relation.
  910. ///
  911. /// We need to update the original access relation during scop construction,
  912. /// when unifying the memory accesses that access the same scop array info
  913. /// object. After the scop has been constructed, the original access relation
  914. /// should not be changed any more. Instead setNewAccessRelation should
  915. /// be called.
  916. void setAccessRelation(isl::map AccessRelation);
  917. /// Set the updated access relation read from JSCOP file.
  918. void setNewAccessRelation(isl::map NewAccessRelation);
  919. /// Return whether the MemoryyAccess is a partial access. That is, the access
  920. /// is not executed in some instances of the parent statement's domain.
  921. bool isLatestPartialAccess() const;
  922. /// Mark this a reduction like access
  923. void markAsReductionLike(ReductionType RT) { RedType = RT; }
  924. /// Align the parameters in the access relation to the scop context
  925. void realignParams();
  926. /// Update the dimensionality of the memory access.
  927. ///
  928. /// During scop construction some memory accesses may not be constructed with
  929. /// their full dimensionality, but outer dimensions may have been omitted if
  930. /// they took the value 'zero'. By updating the dimensionality of the
  931. /// statement we add additional zero-valued dimensions to match the
  932. /// dimensionality of the ScopArrayInfo object that belongs to this memory
  933. /// access.
  934. void updateDimensionality();
  935. /// Get identifier for the memory access.
  936. ///
  937. /// This identifier is unique for all accesses that belong to the same scop
  938. /// statement.
  939. isl::id getId() const;
  940. /// Print the MemoryAccess.
  941. ///
  942. /// @param OS The output stream the MemoryAccess is printed to.
  943. void print(raw_ostream &OS) const;
  944. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  945. /// Print the MemoryAccess to stderr.
  946. void dump() const;
  947. #endif
  948. /// Is the memory access affine?
  949. bool isAffine() const { return IsAffine; }
  950. };
  951. raw_ostream &operator<<(raw_ostream &OS, MemoryAccess::ReductionType RT);
  952. /// Ordered list type to hold accesses.
  953. using MemoryAccessList = std::forward_list<MemoryAccess *>;
  954. /// Helper structure for invariant memory accesses.
  955. struct InvariantAccess {
  956. /// The memory access that is (partially) invariant.
  957. MemoryAccess *MA;
  958. /// The context under which the access is not invariant.
  959. isl::set NonHoistableCtx;
  960. };
  961. /// Ordered container type to hold invariant accesses.
  962. using InvariantAccessesTy = SmallVector<InvariantAccess, 8>;
  963. /// Type for equivalent invariant accesses and their domain context.
  964. struct InvariantEquivClassTy {
  965. /// The pointer that identifies this equivalence class
  966. const SCEV *IdentifyingPointer;
  967. /// Memory accesses now treated invariant
  968. ///
  969. /// These memory accesses access the pointer location that identifies
  970. /// this equivalence class. They are treated as invariant and hoisted during
  971. /// code generation.
  972. MemoryAccessList InvariantAccesses;
  973. /// The execution context under which the memory location is accessed
  974. ///
  975. /// It is the union of the execution domains of the memory accesses in the
  976. /// InvariantAccesses list.
  977. isl::set ExecutionContext;
  978. /// The type of the invariant access
  979. ///
  980. /// It is used to differentiate between differently typed invariant loads from
  981. /// the same location.
  982. Type *AccessType;
  983. };
  984. /// Type for invariant accesses equivalence classes.
  985. using InvariantEquivClassesTy = SmallVector<InvariantEquivClassTy, 8>;
  986. /// Statement of the Scop
  987. ///
  988. /// A Scop statement represents an instruction in the Scop.
  989. ///
  990. /// It is further described by its iteration domain, its schedule and its data
  991. /// accesses.
  992. /// At the moment every statement represents a single basic block of LLVM-IR.
  993. class ScopStmt {
  994. friend class ScopBuilder;
  995. public:
  996. /// Create the ScopStmt from a BasicBlock.
  997. ScopStmt(Scop &parent, BasicBlock &bb, StringRef Name, Loop *SurroundingLoop,
  998. std::vector<Instruction *> Instructions);
  999. /// Create an overapproximating ScopStmt for the region @p R.
  1000. ///
  1001. /// @param EntryBlockInstructions The list of instructions that belong to the
  1002. /// entry block of the region statement.
  1003. /// Instructions are only tracked for entry
  1004. /// blocks for now. We currently do not allow
  1005. /// to modify the instructions of blocks later
  1006. /// in the region statement.
  1007. ScopStmt(Scop &parent, Region &R, StringRef Name, Loop *SurroundingLoop,
  1008. std::vector<Instruction *> EntryBlockInstructions);
  1009. /// Create a copy statement.
  1010. ///
  1011. /// @param Stmt The parent statement.
  1012. /// @param SourceRel The source location.
  1013. /// @param TargetRel The target location.
  1014. /// @param Domain The original domain under which the copy statement would
  1015. /// be executed.
  1016. ScopStmt(Scop &parent, isl::map SourceRel, isl::map TargetRel,
  1017. isl::set Domain);
  1018. ScopStmt(const ScopStmt &) = delete;
  1019. const ScopStmt &operator=(const ScopStmt &) = delete;
  1020. ~ScopStmt();
  1021. private:
  1022. /// Polyhedral description
  1023. //@{
  1024. /// The Scop containing this ScopStmt.
  1025. Scop &Parent;
  1026. /// The domain under which this statement is not modeled precisely.
  1027. ///
  1028. /// The invalid domain for a statement describes all parameter combinations
  1029. /// under which the statement looks to be executed but is in fact not because
  1030. /// some assumption/restriction makes the statement/scop invalid.
  1031. isl::set InvalidDomain;
  1032. /// The iteration domain describes the set of iterations for which this
  1033. /// statement is executed.
  1034. ///
  1035. /// Example:
  1036. /// for (i = 0; i < 100 + b; ++i)
  1037. /// for (j = 0; j < i; ++j)
  1038. /// S(i,j);
  1039. ///
  1040. /// 'S' is executed for different values of i and j. A vector of all
  1041. /// induction variables around S (i, j) is called iteration vector.
  1042. /// The domain describes the set of possible iteration vectors.
  1043. ///
  1044. /// In this case it is:
  1045. ///
  1046. /// Domain: 0 <= i <= 100 + b
  1047. /// 0 <= j <= i
  1048. ///
  1049. /// A pair of statement and iteration vector (S, (5,3)) is called statement
  1050. /// instance.
  1051. isl::set Domain;
  1052. /// The memory accesses of this statement.
  1053. ///
  1054. /// The only side effects of a statement are its memory accesses.
  1055. using MemoryAccessVec = llvm::SmallVector<MemoryAccess *, 8>;
  1056. MemoryAccessVec MemAccs;
  1057. /// Mapping from instructions to (scalar) memory accesses.
  1058. DenseMap<const Instruction *, MemoryAccessList> InstructionToAccess;
  1059. /// The set of values defined elsewhere required in this ScopStmt and
  1060. /// their MemoryKind::Value READ MemoryAccesses.
  1061. DenseMap<Value *, MemoryAccess *> ValueReads;
  1062. /// The set of values defined in this ScopStmt that are required
  1063. /// elsewhere, mapped to their MemoryKind::Value WRITE MemoryAccesses.
  1064. DenseMap<Instruction *, MemoryAccess *> ValueWrites;
  1065. /// Map from PHI nodes to its incoming value when coming from this
  1066. /// statement.
  1067. ///
  1068. /// Non-affine subregions can have multiple exiting blocks that are incoming
  1069. /// blocks of the PHI nodes. This map ensures that there is only one write
  1070. /// operation for the complete subregion. A PHI selecting the relevant value
  1071. /// will be inserted.
  1072. DenseMap<PHINode *, MemoryAccess *> PHIWrites;
  1073. /// Map from PHI nodes to its read access in this statement.
  1074. DenseMap<PHINode *, MemoryAccess *> PHIReads;
  1075. //@}
  1076. /// A SCoP statement represents either a basic block (affine/precise case) or
  1077. /// a whole region (non-affine case).
  1078. ///
  1079. /// Only one of the following two members will therefore be set and indicate
  1080. /// which kind of statement this is.
  1081. ///
  1082. ///{
  1083. /// The BasicBlock represented by this statement (in the affine case).
  1084. BasicBlock *BB = nullptr;
  1085. /// The region represented by this statement (in the non-affine case).
  1086. Region *R = nullptr;
  1087. ///}
  1088. /// The isl AST build for the new generated AST.
  1089. isl::ast_build Build;
  1090. SmallVector<Loop *, 4> NestLoops;
  1091. std::string BaseName;
  1092. /// The closest loop that contains this statement.
  1093. Loop *SurroundingLoop;
  1094. /// Vector for Instructions in this statement.
  1095. std::vector<Instruction *> Instructions;
  1096. /// Remove @p MA from dictionaries pointing to them.
  1097. void removeAccessData(MemoryAccess *MA);
  1098. public:
  1099. /// Get an isl_ctx pointer.
  1100. isl::ctx getIslCtx() const;
  1101. /// Get the iteration domain of this ScopStmt.
  1102. ///
  1103. /// @return The iteration domain of this ScopStmt.
  1104. isl::set getDomain() const;
  1105. /// Get the space of the iteration domain
  1106. ///
  1107. /// @return The space of the iteration domain
  1108. isl::space getDomainSpace() const;
  1109. /// Get the id of the iteration domain space
  1110. ///
  1111. /// @return The id of the iteration domain space
  1112. isl::id getDomainId() const;
  1113. /// Get an isl string representing this domain.
  1114. std::string getDomainStr() const;
  1115. /// Get the schedule function of this ScopStmt.
  1116. ///
  1117. /// @return The schedule function of this ScopStmt, if it does not contain
  1118. /// extension nodes, and nullptr, otherwise.
  1119. isl::map getSchedule() const;
  1120. /// Get an isl string representing this schedule.
  1121. ///
  1122. /// @return An isl string representing this schedule, if it does not contain
  1123. /// extension nodes, and an empty string, otherwise.
  1124. std::string getScheduleStr() const;
  1125. /// Get the invalid domain for this statement.
  1126. isl::set getInvalidDomain() const { return InvalidDomain; }
  1127. /// Get the invalid context for this statement.
  1128. isl::set getInvalidContext() const { return getInvalidDomain().params(); }
  1129. /// Set the invalid context for this statement to @p ID.
  1130. void setInvalidDomain(isl::set ID);
  1131. /// Get the BasicBlock represented by this ScopStmt (if any).
  1132. ///
  1133. /// @return The BasicBlock represented by this ScopStmt, or null if the
  1134. /// statement represents a region.
  1135. BasicBlock *getBasicBlock() const { return BB; }
  1136. /// Return true if this statement represents a single basic block.
  1137. bool isBlockStmt() const { return BB != nullptr; }
  1138. /// Return true if this is a copy statement.
  1139. bool isCopyStmt() const { return BB == nullptr && R == nullptr; }
  1140. /// Get the region represented by this ScopStmt (if any).
  1141. ///
  1142. /// @return The region represented by this ScopStmt, or null if the statement
  1143. /// represents a basic block.
  1144. Region *getRegion() const { return R; }
  1145. /// Return true if this statement represents a whole region.
  1146. bool isRegionStmt() const { return R != nullptr; }
  1147. /// Return a BasicBlock from this statement.
  1148. ///
  1149. /// For block statements, it returns the BasicBlock itself. For subregion
  1150. /// statements, return its entry block.
  1151. BasicBlock *getEntryBlock() const;
  1152. /// Return whether @p L is boxed within this statement.
  1153. bool contains(const Loop *L) const {
  1154. // Block statements never contain loops.
  1155. if (isBlockStmt())
  1156. return false;
  1157. return getRegion()->contains(L);
  1158. }
  1159. /// Return whether this statement represents @p BB.
  1160. bool represents(BasicBlock *BB) const {
  1161. if (isCopyStmt())
  1162. return false;
  1163. if (isBlockStmt())
  1164. return BB == getBasicBlock();
  1165. return getRegion()->contains(BB);
  1166. }
  1167. /// Return whether this statement contains @p Inst.
  1168. bool contains(Instruction *Inst) const {
  1169. if (!Inst)
  1170. return false;
  1171. if (isBlockStmt())
  1172. return std::find(Instructions.begin(), Instructions.end(), Inst) !=
  1173. Instructions.end();
  1174. return represents(Inst->getParent());
  1175. }
  1176. /// Return the closest innermost loop that contains this statement, but is not
  1177. /// contained in it.
  1178. ///
  1179. /// For block statement, this is just the loop that contains the block. Region
  1180. /// statements can contain boxed loops, so getting the loop of one of the
  1181. /// region's BBs might return such an inner loop. For instance, the region's
  1182. /// entry could be a header of a loop, but the region might extend to BBs
  1183. /// after the loop exit. Similarly, the region might only contain parts of the
  1184. /// loop body and still include the loop header.
  1185. ///
  1186. /// Most of the time the surrounding loop is the top element of #NestLoops,
  1187. /// except when it is empty. In that case it return the loop that the whole
  1188. /// SCoP is contained in. That can be nullptr if there is no such loop.
  1189. Loop *getSurroundingLoop() const {
  1190. assert(!isCopyStmt() &&
  1191. "No surrounding loop for artificially created statements");
  1192. return SurroundingLoop;
  1193. }
  1194. /// Return true if this statement does not contain any accesses.
  1195. bool isEmpty() const { return MemAccs.empty(); }
  1196. /// Find all array accesses for @p Inst.
  1197. ///
  1198. /// @param Inst The instruction accessing an array.
  1199. ///
  1200. /// @return A list of array accesses (MemoryKind::Array) accessed by @p Inst.
  1201. /// If there is no such access, it returns nullptr.
  1202. const MemoryAccessList *
  1203. lookupArrayAccessesFor(const Instruction *Inst) const {
  1204. auto It = InstructionToAccess.find(Inst);
  1205. if (It == InstructionToAccess.end())
  1206. return nullptr;
  1207. if (It->second.empty())
  1208. return nullptr;
  1209. return &It->second;
  1210. }
  1211. /// Return the only array access for @p Inst, if existing.
  1212. ///
  1213. /// @param Inst The instruction for which to look up the access.
  1214. /// @returns The unique array memory access related to Inst or nullptr if
  1215. /// no array access exists
  1216. MemoryAccess *getArrayAccessOrNULLFor(const Instruction *Inst) const {
  1217. auto It = InstructionToAccess.find(Inst);
  1218. if (It == InstructionToAccess.end())
  1219. return nullptr;
  1220. MemoryAccess *ArrayAccess = nullptr;
  1221. for (auto Access : It->getSecond()) {
  1222. if (!Access->isArrayKind())
  1223. continue;
  1224. assert(!ArrayAccess && "More then one array access for instruction");
  1225. ArrayAccess = Access;
  1226. }
  1227. return ArrayAccess;
  1228. }
  1229. /// Return the only array access for @p Inst.
  1230. ///
  1231. /// @param Inst The instruction for which to look up the access.
  1232. /// @returns The unique array memory access related to Inst.
  1233. MemoryAccess &getArrayAccessFor(const Instruction *Inst) const {
  1234. MemoryAccess *ArrayAccess = getArrayAccessOrNULLFor(Inst);
  1235. assert(ArrayAccess && "No array access found for instruction!");
  1236. return *ArrayAccess;
  1237. }
  1238. /// Return the MemoryAccess that writes the value of an instruction
  1239. /// defined in this statement, or nullptr if not existing, respectively
  1240. /// not yet added.
  1241. MemoryAccess *lookupValueWriteOf(Instruction *Inst) const {
  1242. assert((isRegionStmt() && R->contains(Inst)) ||
  1243. (!isRegionStmt() && Inst->getParent() == BB));
  1244. return ValueWrites.lookup(Inst);
  1245. }
  1246. /// Return the MemoryAccess that reloads a value, or nullptr if not
  1247. /// existing, respectively not yet added.
  1248. MemoryAccess *lookupValueReadOf(Value *Inst) const {
  1249. return ValueReads.lookup(Inst);
  1250. }
  1251. /// Return the MemoryAccess that loads a PHINode value, or nullptr if not
  1252. /// existing, respectively not yet added.
  1253. MemoryAccess *lookupPHIReadOf(PHINode *PHI) const {
  1254. return PHIReads.lookup(PHI);
  1255. }
  1256. /// Return the PHI write MemoryAccess for the incoming values from any
  1257. /// basic block in this ScopStmt, or nullptr if not existing,
  1258. /// respectively not yet added.
  1259. MemoryAccess *lookupPHIWriteOf(PHINode *PHI) const {
  1260. assert(isBlockStmt() || R->getExit() == PHI->getParent());
  1261. return PHIWrites.lookup(PHI);
  1262. }
  1263. /// Return the input access of the value, or null if no such MemoryAccess
  1264. /// exists.
  1265. ///
  1266. /// The input access is the MemoryAccess that makes an inter-statement value
  1267. /// available in this statement by reading it at the start of this statement.
  1268. /// This can be a MemoryKind::Value if defined in another statement or a
  1269. /// MemoryKind::PHI if the value is a PHINode in this statement.
  1270. MemoryAccess *lookupInputAccessOf(Value *Val) const {
  1271. if (isa<PHINode>(Val))
  1272. if (auto InputMA = lookupPHIReadOf(cast<PHINode>(Val))) {
  1273. assert(!lookupValueReadOf(Val) && "input accesses must be unique; a "
  1274. "statement cannot read a .s2a and "
  1275. ".phiops simultaneously");
  1276. return InputMA;
  1277. }
  1278. if (auto *InputMA = lookupValueReadOf(Val))
  1279. return InputMA;
  1280. return nullptr;
  1281. }
  1282. /// Add @p Access to this statement's list of accesses.
  1283. ///
  1284. /// @param Access The access to add.
  1285. /// @param Prepend If true, will add @p Access before all other instructions
  1286. /// (instead of appending it).
  1287. void addAccess(MemoryAccess *Access, bool Preprend = false);
  1288. /// Remove a MemoryAccess from this statement.
  1289. ///
  1290. /// Note that scalar accesses that are caused by MA will
  1291. /// be eliminated too.
  1292. void removeMemoryAccess(MemoryAccess *MA);
  1293. /// Remove @p MA from this statement.
  1294. ///
  1295. /// In contrast to removeMemoryAccess(), no other access will be eliminated.
  1296. ///
  1297. /// @param MA The MemoryAccess to be removed.
  1298. /// @param AfterHoisting If true, also remove from data access lists.
  1299. /// These lists are filled during
  1300. /// ScopBuilder::buildAccessRelations. Therefore, if this
  1301. /// method is called before buildAccessRelations, false
  1302. /// must be passed.
  1303. void removeSingleMemoryAccess(MemoryAccess *MA, bool AfterHoisting = true);
  1304. using iterator = MemoryAccessVec::iterator;
  1305. using const_iterator = MemoryAccessVec::const_iterator;
  1306. iterator begin() { return MemAccs.begin(); }
  1307. iterator end() { return MemAccs.end(); }
  1308. const_iterator begin() const { return MemAccs.begin(); }
  1309. const_iterator end() const { return MemAccs.end(); }
  1310. size_t size() const { return MemAccs.size(); }
  1311. unsigned getNumIterators() const;
  1312. Scop *getParent() { return &Parent; }
  1313. const Scop *getParent() const { return &Parent; }
  1314. const std::vector<Instruction *> &getInstructions() const {
  1315. return Instructions;
  1316. }
  1317. /// Set the list of instructions for this statement. It replaces the current
  1318. /// list.
  1319. void setInstructions(ArrayRef<Instruction *> Range) {
  1320. Instructions.assign(Range.begin(), Range.end());
  1321. }
  1322. std::vector<Instruction *>::const_iterator insts_begin() const {
  1323. return Instructions.begin();
  1324. }
  1325. std::vector<Instruction *>::const_iterator insts_end() const {
  1326. return Instructions.end();
  1327. }
  1328. /// The range of instructions in this statement.
  1329. iterator_range<std::vector<Instruction *>::const_iterator> insts() const {
  1330. return {insts_begin(), insts_end()};
  1331. }
  1332. /// Insert an instruction before all other instructions in this statement.
  1333. void prependInstruction(Instruction *Inst) {
  1334. Instructions.insert(Instructions.begin(), Inst);
  1335. }
  1336. const char *getBaseName() const;
  1337. /// Set the isl AST build.
  1338. void setAstBuild(isl::ast_build B) { Build = B; }
  1339. /// Get the isl AST build.
  1340. isl::ast_build getAstBuild() const { return Build; }
  1341. /// Restrict the domain of the statement.
  1342. ///
  1343. /// @param NewDomain The new statement domain.
  1344. void restrictDomain(isl::set NewDomain);
  1345. /// Get the loop for a dimension.
  1346. ///
  1347. /// @param Dimension The dimension of the induction variable
  1348. /// @return The loop at a certain dimension.
  1349. Loop *getLoopForDimension(unsigned Dimension) const;
  1350. /// Align the parameters in the statement to the scop context
  1351. void realignParams();
  1352. /// Print the ScopStmt.
  1353. ///
  1354. /// @param OS The output stream the ScopStmt is printed to.
  1355. /// @param PrintInstructions Whether to print the statement's instructions as
  1356. /// well.
  1357. void print(raw_ostream &OS, bool PrintInstructions) const;
  1358. /// Print the instructions in ScopStmt.
  1359. ///
  1360. void printInstructions(raw_ostream &OS) const;
  1361. /// Check whether there is a value read access for @p V in this statement, and
  1362. /// if not, create one.
  1363. ///
  1364. /// This allows to add MemoryAccesses after the initial creation of the Scop
  1365. /// by ScopBuilder.
  1366. ///
  1367. /// @return The already existing or newly created MemoryKind::Value READ
  1368. /// MemoryAccess.
  1369. ///
  1370. /// @see ScopBuilder::ensureValueRead(Value*,ScopStmt*)
  1371. MemoryAccess *ensureValueRead(Value *V);
  1372. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1373. /// Print the ScopStmt to stderr.
  1374. void dump() const;
  1375. #endif
  1376. };
  1377. /// Print ScopStmt S to raw_ostream OS.
  1378. raw_ostream &operator<<(raw_ostream &OS, const ScopStmt &S);
  1379. /// Build the conditions sets for the branch condition @p Condition in
  1380. /// the @p Domain.
  1381. ///
  1382. /// This will fill @p ConditionSets with the conditions under which control
  1383. /// will be moved from @p TI to its successors. Hence, @p ConditionSets will
  1384. /// have as many elements as @p TI has successors. If @p TI is nullptr the
  1385. /// context under which @p Condition is true/false will be returned as the
  1386. /// new elements of @p ConditionSets.
  1387. bool buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
  1388. Instruction *TI, Loop *L, __isl_keep isl_set *Domain,
  1389. DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
  1390. SmallVectorImpl<__isl_give isl_set *> &ConditionSets);
  1391. /// Build condition sets for unsigned ICmpInst(s).
  1392. /// Special handling is required for unsigned operands to ensure that if
  1393. /// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
  1394. /// it should wrap around.
  1395. ///
  1396. /// @param IsStrictUpperBound holds information on the predicate relation
  1397. /// between TestVal and UpperBound, i.e,
  1398. /// TestVal < UpperBound OR TestVal <= UpperBound
  1399. __isl_give isl_set *
  1400. buildUnsignedConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
  1401. __isl_keep isl_set *Domain, const SCEV *SCEV_TestVal,
  1402. const SCEV *SCEV_UpperBound,
  1403. DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
  1404. bool IsStrictUpperBound);
  1405. /// Build the conditions sets for the terminator @p TI in the @p Domain.
  1406. ///
  1407. /// This will fill @p ConditionSets with the conditions under which control
  1408. /// will be moved from @p TI to its successors. Hence, @p ConditionSets will
  1409. /// have as many elements as @p TI has successors.
  1410. bool buildConditionSets(Scop &S, BasicBlock *BB, Instruction *TI, Loop *L,
  1411. __isl_keep isl_set *Domain,
  1412. DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
  1413. SmallVectorImpl<__isl_give isl_set *> &ConditionSets);
  1414. /// Static Control Part
  1415. ///
  1416. /// A Scop is the polyhedral representation of a control flow region detected
  1417. /// by the Scop detection. It is generated by translating the LLVM-IR and
  1418. /// abstracting its effects.
  1419. ///
  1420. /// A Scop consists of a set of:
  1421. ///
  1422. /// * A set of statements executed in the Scop.
  1423. ///
  1424. /// * A set of global parameters
  1425. /// Those parameters are scalar integer values, which are constant during
  1426. /// execution.
  1427. ///
  1428. /// * A context
  1429. /// This context contains information about the values the parameters
  1430. /// can take and relations between different parameters.
  1431. class Scop {
  1432. public:
  1433. /// Type to represent a pair of minimal/maximal access to an array.
  1434. using MinMaxAccessTy = std::pair<isl::pw_multi_aff, isl::pw_multi_aff>;
  1435. /// Vector of minimal/maximal accesses to different arrays.
  1436. using MinMaxVectorTy = SmallVector<MinMaxAccessTy, 4>;
  1437. /// Pair of minimal/maximal access vectors representing
  1438. /// read write and read only accesses
  1439. using MinMaxVectorPairTy = std::pair<MinMaxVectorTy, MinMaxVectorTy>;
  1440. /// Vector of pair of minimal/maximal access vectors representing
  1441. /// non read only and read only accesses for each alias group.
  1442. using MinMaxVectorPairVectorTy = SmallVector<MinMaxVectorPairTy, 4>;
  1443. private:
  1444. friend class ScopBuilder;
  1445. /// Isl context.
  1446. ///
  1447. /// We need a shared_ptr with reference counter to delete the context when all
  1448. /// isl objects are deleted. We will distribute the shared_ptr to all objects
  1449. /// that use the context to create isl objects, and increase the reference
  1450. /// counter. By doing this, we guarantee that the context is deleted when we
  1451. /// delete the last object that creates isl objects with the context. This
  1452. /// declaration needs to be the first in class to gracefully destroy all isl
  1453. /// objects before the context.
  1454. std::shared_ptr<isl_ctx> IslCtx;
  1455. ScalarEvolution *SE;
  1456. DominatorTree *DT;
  1457. /// The underlying Region.
  1458. Region &R;
  1459. /// The name of the SCoP (identical to the regions name)
  1460. Optional<std::string> name;
  1461. // Access functions of the SCoP.
  1462. //
  1463. // This owns all the MemoryAccess objects of the Scop created in this pass.
  1464. AccFuncVector AccessFunctions;
  1465. /// Flag to indicate that the scheduler actually optimized the SCoP.
  1466. bool IsOptimized = false;
  1467. /// True if the underlying region has a single exiting block.
  1468. bool HasSingleExitEdge;
  1469. /// Flag to remember if the SCoP contained an error block or not.
  1470. bool HasErrorBlock = false;
  1471. /// Max loop depth.
  1472. unsigned MaxLoopDepth = 0;
  1473. /// Number of copy statements.
  1474. unsigned CopyStmtsNum = 0;
  1475. /// Flag to indicate if the Scop is to be skipped.
  1476. bool SkipScop = false;
  1477. using StmtSet = std::list<ScopStmt>;
  1478. /// The statements in this Scop.
  1479. StmtSet Stmts;
  1480. /// Parameters of this Scop
  1481. ParameterSetTy Parameters;
  1482. /// Mapping from parameters to their ids.
  1483. DenseMap<const SCEV *, isl::id> ParameterIds;
  1484. /// The context of the SCoP created during SCoP detection.
  1485. ScopDetection::DetectionContext &DC;
  1486. /// OptimizationRemarkEmitter object for displaying diagnostic remarks
  1487. OptimizationRemarkEmitter &ORE;
  1488. /// A map from basic blocks to vector of SCoP statements. Currently this
  1489. /// vector comprises only of a single statement.
  1490. DenseMap<BasicBlock *, std::vector<ScopStmt *>> StmtMap;
  1491. /// A map from instructions to SCoP statements.
  1492. DenseMap<Instruction *, ScopStmt *> InstStmtMap;
  1493. /// A map from basic blocks to their domains.
  1494. DenseMap<BasicBlock *, isl::set> DomainMap;
  1495. /// Constraints on parameters.
  1496. isl::set Context = nullptr;
  1497. /// The affinator used to translate SCEVs to isl expressions.
  1498. SCEVAffinator Affinator;
  1499. using ArrayInfoMapTy =
  1500. std::map<std::pair<AssertingVH<const Value>, MemoryKind>,
  1501. std::unique_ptr<ScopArrayInfo>>;
  1502. using ArrayNameMapTy = StringMap<std::unique_ptr<ScopArrayInfo>>;
  1503. using ArrayInfoSetTy = SetVector<ScopArrayInfo *>;
  1504. /// A map to remember ScopArrayInfo objects for all base pointers.
  1505. ///
  1506. /// As PHI nodes may have two array info objects associated, we add a flag
  1507. /// that distinguishes between the PHI node specific ArrayInfo object
  1508. /// and the normal one.
  1509. ArrayInfoMapTy ScopArrayInfoMap;
  1510. /// A map to remember ScopArrayInfo objects for all names of memory
  1511. /// references.
  1512. ArrayNameMapTy ScopArrayNameMap;
  1513. /// A set to remember ScopArrayInfo objects.
  1514. /// @see Scop::ScopArrayInfoMap
  1515. ArrayInfoSetTy ScopArrayInfoSet;
  1516. /// The assumptions under which this scop was built.
  1517. ///
  1518. /// When constructing a scop sometimes the exact representation of a statement
  1519. /// or condition would be very complex, but there is a common case which is a
  1520. /// lot simpler, but which is only valid under certain assumptions. The
  1521. /// assumed context records the assumptions taken during the construction of
  1522. /// this scop and that need to be code generated as a run-time test.
  1523. isl::set AssumedContext;
  1524. /// The restrictions under which this SCoP was built.
  1525. ///
  1526. /// The invalid context is similar to the assumed context as it contains
  1527. /// constraints over the parameters. However, while we need the constraints
  1528. /// in the assumed context to be "true" the constraints in the invalid context
  1529. /// need to be "false". Otherwise they behave the same.
  1530. isl::set InvalidContext;
  1531. /// The context under which the SCoP must have defined behavior. Optimizer and
  1532. /// code generator can assume that the SCoP will only be executed with
  1533. /// parameter values within this context. This might be either because we can
  1534. /// prove that other values are impossible or explicitly have undefined
  1535. /// behavior, such as due to no-wrap flags. If this becomes too complex, can
  1536. /// also be nullptr.
  1537. ///
  1538. /// In contrast to Scop::AssumedContext and Scop::InvalidContext, these do not
  1539. /// need to be checked at runtime.
  1540. ///
  1541. /// Scop::Context on the other side is an overapproximation and does not
  1542. /// include all requirements, but is always defined. However, there is still
  1543. /// no guarantee that there is no undefined behavior in
  1544. /// DefinedBehaviorContext.
  1545. isl::set DefinedBehaviorContext;
  1546. /// The schedule of the SCoP
  1547. ///
  1548. /// The schedule of the SCoP describes the execution order of the statements
  1549. /// in the scop by assigning each statement instance a possibly
  1550. /// multi-dimensional execution time. The schedule is stored as a tree of
  1551. /// schedule nodes.
  1552. ///
  1553. /// The most common nodes in a schedule tree are so-called band nodes. Band
  1554. /// nodes map statement instances into a multi dimensional schedule space.
  1555. /// This space can be seen as a multi-dimensional clock.
  1556. ///
  1557. /// Example:
  1558. ///
  1559. /// <S,(5,4)> may be mapped to (5,4) by this schedule:
  1560. ///
  1561. /// s0 = i (Year of execution)
  1562. /// s1 = j (Day of execution)
  1563. ///
  1564. /// or to (9, 20) by this schedule:
  1565. ///
  1566. /// s0 = i + j (Year of execution)
  1567. /// s1 = 20 (Day of execution)
  1568. ///
  1569. /// The order statement instances are executed is defined by the
  1570. /// schedule vectors they are mapped to. A statement instance
  1571. /// <A, (i, j, ..)> is executed before a statement instance <B, (i', ..)>, if
  1572. /// the schedule vector of A is lexicographic smaller than the schedule
  1573. /// vector of B.
  1574. ///
  1575. /// Besides band nodes, schedule trees contain additional nodes that specify
  1576. /// a textual ordering between two subtrees or filter nodes that filter the
  1577. /// set of statement instances that will be scheduled in a subtree. There
  1578. /// are also several other nodes. A full description of the different nodes
  1579. /// in a schedule tree is given in the isl manual.
  1580. isl::schedule Schedule = nullptr;
  1581. /// Is this Scop marked as not to be transformed by an optimization heuristic?
  1582. bool HasDisableHeuristicsHint = false;
  1583. /// Whether the schedule has been modified after derived from the CFG by
  1584. /// ScopBuilder.
  1585. bool ScheduleModified = false;
  1586. /// The set of minimal/maximal accesses for each alias group.
  1587. ///
  1588. /// When building runtime alias checks we look at all memory instructions and
  1589. /// build so called alias groups. Each group contains a set of accesses to
  1590. /// different base arrays which might alias with each other. However, between
  1591. /// alias groups there is no aliasing possible.
  1592. ///
  1593. /// In a program with int and float pointers annotated with tbaa information
  1594. /// we would probably generate two alias groups, one for the int pointers and
  1595. /// one for the float pointers.
  1596. ///
  1597. /// During code generation we will create a runtime alias check for each alias
  1598. /// group to ensure the SCoP is executed in an alias free environment.
  1599. MinMaxVectorPairVectorTy MinMaxAliasGroups;
  1600. /// Mapping from invariant loads to the representing invariant load of
  1601. /// their equivalence class.
  1602. ValueToValueMap InvEquivClassVMap;
  1603. /// List of invariant accesses.
  1604. InvariantEquivClassesTy InvariantEquivClasses;
  1605. /// The smallest array index not yet assigned.
  1606. long ArrayIdx = 0;
  1607. /// The smallest statement index not yet assigned.
  1608. long StmtIdx = 0;
  1609. /// A number that uniquely represents a Scop within its function
  1610. const int ID;
  1611. /// Map of values to the MemoryAccess that writes its definition.
  1612. ///
  1613. /// There must be at most one definition per llvm::Instruction in a SCoP.
  1614. DenseMap<Value *, MemoryAccess *> ValueDefAccs;
  1615. /// Map of values to the MemoryAccess that reads a PHI.
  1616. DenseMap<PHINode *, MemoryAccess *> PHIReadAccs;
  1617. /// List of all uses (i.e. read MemoryAccesses) for a MemoryKind::Value
  1618. /// scalar.
  1619. DenseMap<const ScopArrayInfo *, SmallVector<MemoryAccess *, 4>> ValueUseAccs;
  1620. /// List of all incoming values (write MemoryAccess) of a MemoryKind::PHI or
  1621. /// MemoryKind::ExitPHI scalar.
  1622. DenseMap<const ScopArrayInfo *, SmallVector<MemoryAccess *, 4>>
  1623. PHIIncomingAccs;
  1624. /// Scop constructor; invoked from ScopBuilder::buildScop.
  1625. Scop(Region &R, ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT,
  1626. ScopDetection::DetectionContext &DC, OptimizationRemarkEmitter &ORE,
  1627. int ID);
  1628. //@}
  1629. /// Initialize this ScopBuilder.
  1630. void init(AAResults &AA, AssumptionCache &AC, DominatorTree &DT,
  1631. LoopInfo &LI);
  1632. /// Return the access for the base ptr of @p MA if any.
  1633. MemoryAccess *lookupBasePtrAccess(MemoryAccess *MA);
  1634. /// Create an id for @p Param and store it in the ParameterIds map.
  1635. void createParameterId(const SCEV *Param);
  1636. /// Build the Context of the Scop.
  1637. void buildContext();
  1638. /// Add the bounds of the parameters to the context.
  1639. void addParameterBounds();
  1640. /// Simplify the assumed and invalid context.
  1641. void simplifyContexts();
  1642. /// Create a new SCoP statement for @p BB.
  1643. ///
  1644. /// A new statement for @p BB will be created and added to the statement
  1645. /// vector
  1646. /// and map.
  1647. ///
  1648. /// @param BB The basic block we build the statement for.
  1649. /// @param Name The name of the new statement.
  1650. /// @param SurroundingLoop The loop the created statement is contained in.
  1651. /// @param Instructions The instructions in the statement.
  1652. void addScopStmt(BasicBlock *BB, StringRef Name, Loop *SurroundingLoop,
  1653. std::vector<Instruction *> Instructions);
  1654. /// Create a new SCoP statement for @p R.
  1655. ///
  1656. /// A new statement for @p R will be created and added to the statement vector
  1657. /// and map.
  1658. ///
  1659. /// @param R The region we build the statement for.
  1660. /// @param Name The name of the new statement.
  1661. /// @param SurroundingLoop The loop the created statement is contained
  1662. /// in.
  1663. /// @param EntryBlockInstructions The (interesting) instructions in the
  1664. /// entry block of the region statement.
  1665. void addScopStmt(Region *R, StringRef Name, Loop *SurroundingLoop,
  1666. std::vector<Instruction *> EntryBlockInstructions);
  1667. /// Removes @p Stmt from the StmtMap.
  1668. void removeFromStmtMap(ScopStmt &Stmt);
  1669. /// Removes all statements where the entry block of the statement does not
  1670. /// have a corresponding domain in the domain map (or it is empty).
  1671. void removeStmtNotInDomainMap();
  1672. /// Collect all memory access relations of a given type.
  1673. ///
  1674. /// @param Predicate A predicate function that returns true if an access is
  1675. /// of a given type.
  1676. ///
  1677. /// @returns The set of memory accesses in the scop that match the predicate.
  1678. isl::union_map
  1679. getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate);
  1680. /// @name Helper functions for printing the Scop.
  1681. ///
  1682. //@{
  1683. void printContext(raw_ostream &OS) const;
  1684. void printArrayInfo(raw_ostream &OS) const;
  1685. void printStatements(raw_ostream &OS, bool PrintInstructions) const;
  1686. void printAliasAssumptions(raw_ostream &OS) const;
  1687. //@}
  1688. public:
  1689. Scop(const Scop &) = delete;
  1690. Scop &operator=(const Scop &) = delete;
  1691. ~Scop();
  1692. /// Increment actual number of aliasing assumptions taken
  1693. ///
  1694. /// @param Step Number of new aliasing assumptions which should be added to
  1695. /// the number of already taken assumptions.
  1696. static void incrementNumberOfAliasingAssumptions(unsigned Step);
  1697. /// Get the count of copy statements added to this Scop.
  1698. ///
  1699. /// @return The count of copy statements added to this Scop.
  1700. unsigned getCopyStmtsNum() { return CopyStmtsNum; }
  1701. /// Create a new copy statement.
  1702. ///
  1703. /// A new statement will be created and added to the statement vector.
  1704. ///
  1705. /// @param SourceRel The source location.
  1706. /// @param TargetRel The target location.
  1707. /// @param Domain The original domain under which the copy statement would
  1708. /// be executed.
  1709. ScopStmt *addScopStmt(isl::map SourceRel, isl::map TargetRel,
  1710. isl::set Domain);
  1711. /// Add the access function to all MemoryAccess objects of the Scop
  1712. /// created in this pass.
  1713. void addAccessFunction(MemoryAccess *Access) {
  1714. AccessFunctions.emplace_back(Access);
  1715. // Register value definitions.
  1716. if (Access->isWrite() && Access->isOriginalValueKind()) {
  1717. assert(!ValueDefAccs.count(Access->getAccessValue()) &&
  1718. "there can be just one definition per value");
  1719. ValueDefAccs[Access->getAccessValue()] = Access;
  1720. } else if (Access->isRead() && Access->isOriginalPHIKind()) {
  1721. PHINode *PHI = cast<PHINode>(Access->getAccessInstruction());
  1722. assert(!PHIReadAccs.count(PHI) &&
  1723. "there can be just one PHI read per PHINode");
  1724. PHIReadAccs[PHI] = Access;
  1725. }
  1726. }
  1727. /// Add metadata for @p Access.
  1728. void addAccessData(MemoryAccess *Access);
  1729. /// Add new invariant access equivalence class
  1730. void
  1731. addInvariantEquivClass(const InvariantEquivClassTy &InvariantEquivClass) {
  1732. InvariantEquivClasses.emplace_back(InvariantEquivClass);
  1733. }
  1734. /// Add mapping from invariant loads to the representing invariant load of
  1735. /// their equivalence class.
  1736. void addInvariantLoadMapping(const Value *LoadInst, Value *ClassRep) {
  1737. InvEquivClassVMap[LoadInst] = ClassRep;
  1738. }
  1739. /// Remove the metadata stored for @p Access.
  1740. void removeAccessData(MemoryAccess *Access);
  1741. /// Return the scalar evolution.
  1742. ScalarEvolution *getSE() const;
  1743. /// Return the dominator tree.
  1744. DominatorTree *getDT() const { return DT; }
  1745. /// Return the LoopInfo used for this Scop.
  1746. LoopInfo *getLI() const { return Affinator.getLI(); }
  1747. /// Get the count of parameters used in this Scop.
  1748. ///
  1749. /// @return The count of parameters used in this Scop.
  1750. size_t getNumParams() const { return Parameters.size(); }
  1751. /// Return whether given SCEV is used as the parameter in this Scop.
  1752. bool isParam(const SCEV *Param) const { return Parameters.count(Param); }
  1753. /// Take a list of parameters and add the new ones to the scop.
  1754. void addParams(const ParameterSetTy &NewParameters);
  1755. /// Return an iterator range containing the scop parameters.
  1756. iterator_range<ParameterSetTy::iterator> parameters() const {
  1757. return make_range(Parameters.begin(), Parameters.end());
  1758. }
  1759. /// Return an iterator range containing invariant accesses.
  1760. iterator_range<InvariantEquivClassesTy::iterator> invariantEquivClasses() {
  1761. return make_range(InvariantEquivClasses.begin(),
  1762. InvariantEquivClasses.end());
  1763. }
  1764. /// Return an iterator range containing all the MemoryAccess objects of the
  1765. /// Scop.
  1766. iterator_range<AccFuncVector::iterator> access_functions() {
  1767. return make_range(AccessFunctions.begin(), AccessFunctions.end());
  1768. }
  1769. /// Return whether this scop is empty, i.e. contains no statements that
  1770. /// could be executed.
  1771. bool isEmpty() const { return Stmts.empty(); }
  1772. StringRef getName() {
  1773. if (!name)
  1774. name = R.getNameStr();
  1775. return *name;
  1776. }
  1777. using array_iterator = ArrayInfoSetTy::iterator;
  1778. using const_array_iterator = ArrayInfoSetTy::const_iterator;
  1779. using array_range = iterator_range<ArrayInfoSetTy::iterator>;
  1780. using const_array_range = iterator_range<ArrayInfoSetTy::const_iterator>;
  1781. inline array_iterator array_begin() { return ScopArrayInfoSet.begin(); }
  1782. inline array_iterator array_end() { return ScopArrayInfoSet.end(); }
  1783. inline const_array_iterator array_begin() const {
  1784. return ScopArrayInfoSet.begin();
  1785. }
  1786. inline const_array_iterator array_end() const {
  1787. return ScopArrayInfoSet.end();
  1788. }
  1789. inline array_range arrays() {
  1790. return array_range(array_begin(), array_end());
  1791. }
  1792. inline const_array_range arrays() const {
  1793. return const_array_range(array_begin(), array_end());
  1794. }
  1795. /// Return the isl_id that represents a certain parameter.
  1796. ///
  1797. /// @param Parameter A SCEV that was recognized as a Parameter.
  1798. ///
  1799. /// @return The corresponding isl_id or NULL otherwise.
  1800. isl::id getIdForParam(const SCEV *Parameter) const;
  1801. /// Get the maximum region of this static control part.
  1802. ///
  1803. /// @return The maximum region of this static control part.
  1804. inline const Region &getRegion() const { return R; }
  1805. inline Region &getRegion() { return R; }
  1806. /// Return the function this SCoP is in.
  1807. Function &getFunction() const { return *R.getEntry()->getParent(); }
  1808. /// Check if @p L is contained in the SCoP.
  1809. bool contains(const Loop *L) const { return R.contains(L); }
  1810. /// Check if @p BB is contained in the SCoP.
  1811. bool contains(const BasicBlock *BB) const { return R.contains(BB); }
  1812. /// Check if @p I is contained in the SCoP.
  1813. bool contains(const Instruction *I) const { return R.contains(I); }
  1814. /// Return the unique exit block of the SCoP.
  1815. BasicBlock *getExit() const { return R.getExit(); }
  1816. /// Return the unique exiting block of the SCoP if any.
  1817. BasicBlock *getExitingBlock() const { return R.getExitingBlock(); }
  1818. /// Return the unique entry block of the SCoP.
  1819. BasicBlock *getEntry() const { return R.getEntry(); }
  1820. /// Return the unique entering block of the SCoP if any.
  1821. BasicBlock *getEnteringBlock() const { return R.getEnteringBlock(); }
  1822. /// Return true if @p BB is the exit block of the SCoP.
  1823. bool isExit(BasicBlock *BB) const { return getExit() == BB; }
  1824. /// Return a range of all basic blocks in the SCoP.
  1825. Region::block_range blocks() const { return R.blocks(); }
  1826. /// Return true if and only if @p BB dominates the SCoP.
  1827. bool isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const;
  1828. /// Get the maximum depth of the loop.
  1829. ///
  1830. /// @return The maximum depth of the loop.
  1831. inline unsigned getMaxLoopDepth() const { return MaxLoopDepth; }
  1832. /// Return the invariant equivalence class for @p Val if any.
  1833. InvariantEquivClassTy *lookupInvariantEquivClass(Value *Val);
  1834. /// Return the set of invariant accesses.
  1835. InvariantEquivClassesTy &getInvariantAccesses() {
  1836. return InvariantEquivClasses;
  1837. }
  1838. /// Check if the scop has any invariant access.
  1839. bool hasInvariantAccesses() { return !InvariantEquivClasses.empty(); }
  1840. /// Mark the SCoP as optimized by the scheduler.
  1841. void markAsOptimized() { IsOptimized = true; }
  1842. /// Check if the SCoP has been optimized by the scheduler.
  1843. bool isOptimized() const { return IsOptimized; }
  1844. /// Mark the SCoP to be skipped by ScopPass passes.
  1845. void markAsToBeSkipped() { SkipScop = true; }
  1846. /// Check if the SCoP is to be skipped by ScopPass passes.
  1847. bool isToBeSkipped() const { return SkipScop; }
  1848. /// Return the ID of the Scop
  1849. int getID() const { return ID; }
  1850. /// Get the name of the entry and exit blocks of this Scop.
  1851. ///
  1852. /// These along with the function name can uniquely identify a Scop.
  1853. ///
  1854. /// @return std::pair whose first element is the entry name & second element
  1855. /// is the exit name.
  1856. std::pair<std::string, std::string> getEntryExitStr() const;
  1857. /// Get the name of this Scop.
  1858. std::string getNameStr() const;
  1859. /// Get the constraint on parameter of this Scop.
  1860. ///
  1861. /// @return The constraint on parameter of this Scop.
  1862. isl::set getContext() const;
  1863. /// Return the context where execution behavior is defined. Might return
  1864. /// nullptr.
  1865. isl::set getDefinedBehaviorContext() const { return DefinedBehaviorContext; }
  1866. /// Return the define behavior context, or if not available, its approximation
  1867. /// from all other contexts.
  1868. isl::set getBestKnownDefinedBehaviorContext() const {
  1869. if (DefinedBehaviorContext)
  1870. return DefinedBehaviorContext;
  1871. return Context.intersect_params(AssumedContext).subtract(InvalidContext);
  1872. }
  1873. /// Return space of isl context parameters.
  1874. ///
  1875. /// Returns the set of context parameters that are currently constrained. In
  1876. /// case the full set of parameters is needed, see @getFullParamSpace.
  1877. isl::space getParamSpace() const;
  1878. /// Return the full space of parameters.
  1879. ///
  1880. /// getParamSpace will only return the parameters of the context that are
  1881. /// actually constrained, whereas getFullParamSpace will return all
  1882. // parameters. This is useful in cases, where we need to ensure all
  1883. // parameters are available, as certain isl functions will abort if this is
  1884. // not the case.
  1885. isl::space getFullParamSpace() const;
  1886. /// Get the assumed context for this Scop.
  1887. ///
  1888. /// @return The assumed context of this Scop.
  1889. isl::set getAssumedContext() const;
  1890. /// Return true if the optimized SCoP can be executed.
  1891. ///
  1892. /// In addition to the runtime check context this will also utilize the domain
  1893. /// constraints to decide it the optimized version can actually be executed.
  1894. ///
  1895. /// @returns True if the optimized SCoP can be executed.
  1896. bool hasFeasibleRuntimeContext() const;
  1897. /// Check if the assumption in @p Set is trivial or not.
  1898. ///
  1899. /// @param Set The relations between parameters that are assumed to hold.
  1900. /// @param Sign Enum to indicate if the assumptions in @p Set are positive
  1901. /// (needed/assumptions) or negative (invalid/restrictions).
  1902. ///
  1903. /// @returns True if the assumption @p Set is not trivial.
  1904. bool isEffectiveAssumption(isl::set Set, AssumptionSign Sign);
  1905. /// Track and report an assumption.
  1906. ///
  1907. /// Use 'clang -Rpass-analysis=polly-scops' or 'opt
  1908. /// -pass-remarks-analysis=polly-scops' to output the assumptions.
  1909. ///
  1910. /// @param Kind The assumption kind describing the underlying cause.
  1911. /// @param Set The relations between parameters that are assumed to hold.
  1912. /// @param Loc The location in the source that caused this assumption.
  1913. /// @param Sign Enum to indicate if the assumptions in @p Set are positive
  1914. /// (needed/assumptions) or negative (invalid/restrictions).
  1915. /// @param BB The block in which this assumption was taken. Used to
  1916. /// calculate hotness when emitting remark.
  1917. ///
  1918. /// @returns True if the assumption is not trivial.
  1919. bool trackAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
  1920. AssumptionSign Sign, BasicBlock *BB);
  1921. /// Add the conditions from @p Set (or subtract them if @p Sign is
  1922. /// AS_RESTRICTION) to the defined behaviour context.
  1923. void intersectDefinedBehavior(isl::set Set, AssumptionSign Sign);
  1924. /// Add assumptions to assumed context.
  1925. ///
  1926. /// The assumptions added will be assumed to hold during the execution of the
  1927. /// scop. However, as they are generally not statically provable, at code
  1928. /// generation time run-time checks will be generated that ensure the
  1929. /// assumptions hold.
  1930. ///
  1931. /// WARNING: We currently exploit in simplifyAssumedContext the knowledge
  1932. /// that assumptions do not change the set of statement instances
  1933. /// executed.
  1934. ///
  1935. /// @param Kind The assumption kind describing the underlying cause.
  1936. /// @param Set The relations between parameters that are assumed to hold.
  1937. /// @param Loc The location in the source that caused this assumption.
  1938. /// @param Sign Enum to indicate if the assumptions in @p Set are positive
  1939. /// (needed/assumptions) or negative (invalid/restrictions).
  1940. /// @param BB The block in which this assumption was taken. Used to
  1941. /// calculate hotness when emitting remark.
  1942. /// @param RTC Does the assumption require a runtime check?
  1943. void addAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
  1944. AssumptionSign Sign, BasicBlock *BB, bool RTC = true);
  1945. /// Mark the scop as invalid.
  1946. ///
  1947. /// This method adds an assumption to the scop that is always invalid. As a
  1948. /// result, the scop will not be optimized later on. This function is commonly
  1949. /// called when a condition makes it impossible (or too compile time
  1950. /// expensive) to process this scop any further.
  1951. ///
  1952. /// @param Kind The assumption kind describing the underlying cause.
  1953. /// @param Loc The location in the source that triggered .
  1954. /// @param BB The BasicBlock where it was triggered.
  1955. void invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB = nullptr);
  1956. /// Get the invalid context for this Scop.
  1957. ///
  1958. /// @return The invalid context of this Scop.
  1959. isl::set getInvalidContext() const;
  1960. /// Return true if and only if the InvalidContext is trivial (=empty).
  1961. bool hasTrivialInvalidContext() const { return InvalidContext.is_empty(); }
  1962. /// Return all alias groups for this SCoP.
  1963. const MinMaxVectorPairVectorTy &getAliasGroups() const {
  1964. return MinMaxAliasGroups;
  1965. }
  1966. void addAliasGroup(MinMaxVectorTy &MinMaxAccessesReadWrite,
  1967. MinMaxVectorTy &MinMaxAccessesReadOnly) {
  1968. MinMaxAliasGroups.emplace_back();
  1969. MinMaxAliasGroups.back().first = MinMaxAccessesReadWrite;
  1970. MinMaxAliasGroups.back().second = MinMaxAccessesReadOnly;
  1971. }
  1972. /// Remove statements from the list of scop statements.
  1973. ///
  1974. /// @param ShouldDelete A function that returns true if the statement passed
  1975. /// to it should be deleted.
  1976. /// @param AfterHoisting If true, also remove from data access lists.
  1977. /// These lists are filled during
  1978. /// ScopBuilder::buildAccessRelations. Therefore, if this
  1979. /// method is called before buildAccessRelations, false
  1980. /// must be passed.
  1981. void removeStmts(function_ref<bool(ScopStmt &)> ShouldDelete,
  1982. bool AfterHoisting = true);
  1983. /// Get an isl string representing the context.
  1984. std::string getContextStr() const;
  1985. /// Get an isl string representing the assumed context.
  1986. std::string getAssumedContextStr() const;
  1987. /// Get an isl string representing the invalid context.
  1988. std::string getInvalidContextStr() const;
  1989. /// Return the list of ScopStmts that represent the given @p BB.
  1990. ArrayRef<ScopStmt *> getStmtListFor(BasicBlock *BB) const;
  1991. /// Get the statement to put a PHI WRITE into.
  1992. ///
  1993. /// @param U The operand of a PHINode.
  1994. ScopStmt *getIncomingStmtFor(const Use &U) const;
  1995. /// Return the last statement representing @p BB.
  1996. ///
  1997. /// Of the sequence of statements that represent a @p BB, this is the last one
  1998. /// to be executed. It is typically used to determine which instruction to add
  1999. /// a MemoryKind::PHI WRITE to. For this purpose, it is not strictly required
  2000. /// to be executed last, only that the incoming value is available in it.
  2001. ScopStmt *getLastStmtFor(BasicBlock *BB) const;
  2002. /// Return the ScopStmts that represents the Region @p R, or nullptr if
  2003. /// it is not represented by any statement in this Scop.
  2004. ArrayRef<ScopStmt *> getStmtListFor(Region *R) const;
  2005. /// Return the ScopStmts that represents @p RN; can return nullptr if
  2006. /// the RegionNode is not within the SCoP or has been removed due to
  2007. /// simplifications.
  2008. ArrayRef<ScopStmt *> getStmtListFor(RegionNode *RN) const;
  2009. /// Return the ScopStmt an instruction belongs to, or nullptr if it
  2010. /// does not belong to any statement in this Scop.
  2011. ScopStmt *getStmtFor(Instruction *Inst) const {
  2012. return InstStmtMap.lookup(Inst);
  2013. }
  2014. /// Return the number of statements in the SCoP.
  2015. size_t getSize() const { return Stmts.size(); }
  2016. /// @name Statements Iterators
  2017. ///
  2018. /// These iterators iterate over all statements of this Scop.
  2019. //@{
  2020. using iterator = StmtSet::iterator;
  2021. using const_iterator = StmtSet::const_iterator;
  2022. iterator begin() { return Stmts.begin(); }
  2023. iterator end() { return Stmts.end(); }
  2024. const_iterator begin() const { return Stmts.begin(); }
  2025. const_iterator end() const { return Stmts.end(); }
  2026. using reverse_iterator = StmtSet::reverse_iterator;
  2027. using const_reverse_iterator = StmtSet::const_reverse_iterator;
  2028. reverse_iterator rbegin() { return Stmts.rbegin(); }
  2029. reverse_iterator rend() { return Stmts.rend(); }
  2030. const_reverse_iterator rbegin() const { return Stmts.rbegin(); }
  2031. const_reverse_iterator rend() const { return Stmts.rend(); }
  2032. //@}
  2033. /// Return the set of required invariant loads.
  2034. const InvariantLoadsSetTy &getRequiredInvariantLoads() const {
  2035. return DC.RequiredILS;
  2036. }
  2037. /// Add @p LI to the set of required invariant loads.
  2038. void addRequiredInvariantLoad(LoadInst *LI) { DC.RequiredILS.insert(LI); }
  2039. /// Return the set of boxed (thus overapproximated) loops.
  2040. const BoxedLoopsSetTy &getBoxedLoops() const { return DC.BoxedLoopsSet; }
  2041. /// Return true if and only if @p R is a non-affine subregion.
  2042. bool isNonAffineSubRegion(const Region *R) {
  2043. return DC.NonAffineSubRegionSet.count(R);
  2044. }
  2045. const MapInsnToMemAcc &getInsnToMemAccMap() const { return DC.InsnToMemAcc; }
  2046. /// Return the (possibly new) ScopArrayInfo object for @p Access.
  2047. ///
  2048. /// @param ElementType The type of the elements stored in this array.
  2049. /// @param Kind The kind of the array info object.
  2050. /// @param BaseName The optional name of this memory reference.
  2051. ScopArrayInfo *getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
  2052. ArrayRef<const SCEV *> Sizes,
  2053. MemoryKind Kind,
  2054. const char *BaseName = nullptr);
  2055. /// Create an array and return the corresponding ScopArrayInfo object.
  2056. ///
  2057. /// @param ElementType The type of the elements stored in this array.
  2058. /// @param BaseName The name of this memory reference.
  2059. /// @param Sizes The sizes of dimensions.
  2060. ScopArrayInfo *createScopArrayInfo(Type *ElementType,
  2061. const std::string &BaseName,
  2062. const std::vector<unsigned> &Sizes);
  2063. /// Return the cached ScopArrayInfo object for @p BasePtr.
  2064. ///
  2065. /// @param BasePtr The base pointer the object has been stored for.
  2066. /// @param Kind The kind of array info object.
  2067. ///
  2068. /// @returns The ScopArrayInfo pointer or NULL if no such pointer is
  2069. /// available.
  2070. ScopArrayInfo *getScopArrayInfoOrNull(Value *BasePtr, MemoryKind Kind);
  2071. /// Return the cached ScopArrayInfo object for @p BasePtr.
  2072. ///
  2073. /// @param BasePtr The base pointer the object has been stored for.
  2074. /// @param Kind The kind of array info object.
  2075. ///
  2076. /// @returns The ScopArrayInfo pointer (may assert if no such pointer is
  2077. /// available).
  2078. ScopArrayInfo *getScopArrayInfo(Value *BasePtr, MemoryKind Kind);
  2079. /// Invalidate ScopArrayInfo object for base address.
  2080. ///
  2081. /// @param BasePtr The base pointer of the ScopArrayInfo object to invalidate.
  2082. /// @param Kind The Kind of the ScopArrayInfo object.
  2083. void invalidateScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
  2084. auto It = ScopArrayInfoMap.find(std::make_pair(BasePtr, Kind));
  2085. if (It == ScopArrayInfoMap.end())
  2086. return;
  2087. ScopArrayInfoSet.remove(It->second.get());
  2088. ScopArrayInfoMap.erase(It);
  2089. }
  2090. /// Set new isl context.
  2091. void setContext(isl::set NewContext);
  2092. /// Update maximal loop depth. If @p Depth is smaller than current value,
  2093. /// then maximal loop depth is not updated.
  2094. void updateMaxLoopDepth(unsigned Depth) {
  2095. MaxLoopDepth = std::max(MaxLoopDepth, Depth);
  2096. }
  2097. /// Align the parameters in the statement to the scop context
  2098. void realignParams();
  2099. /// Return true if this SCoP can be profitably optimized.
  2100. ///
  2101. /// @param ScalarsAreUnprofitable Never consider statements with scalar writes
  2102. /// as profitably optimizable.
  2103. ///
  2104. /// @return Whether this SCoP can be profitably optimized.
  2105. bool isProfitable(bool ScalarsAreUnprofitable) const;
  2106. /// Return true if the SCoP contained at least one error block.
  2107. bool hasErrorBlock() const { return HasErrorBlock; }
  2108. /// Notify SCoP that it contains an error block
  2109. void notifyErrorBlock() { HasErrorBlock = true; }
  2110. /// Return true if the underlying region has a single exiting block.
  2111. bool hasSingleExitEdge() const { return HasSingleExitEdge; }
  2112. /// Print the static control part.
  2113. ///
  2114. /// @param OS The output stream the static control part is printed to.
  2115. /// @param PrintInstructions Whether to print the statement's instructions as
  2116. /// well.
  2117. void print(raw_ostream &OS, bool PrintInstructions) const;
  2118. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  2119. /// Print the ScopStmt to stderr.
  2120. void dump() const;
  2121. #endif
  2122. /// Get the isl context of this static control part.
  2123. ///
  2124. /// @return The isl context of this static control part.
  2125. isl::ctx getIslCtx() const;
  2126. /// Directly return the shared_ptr of the context.
  2127. const std::shared_ptr<isl_ctx> &getSharedIslCtx() const { return IslCtx; }
  2128. /// Compute the isl representation for the SCEV @p E
  2129. ///
  2130. /// @param E The SCEV that should be translated.
  2131. /// @param BB An (optional) basic block in which the isl_pw_aff is computed.
  2132. /// SCEVs known to not reference any loops in the SCoP can be
  2133. /// passed without a @p BB.
  2134. /// @param NonNegative Flag to indicate the @p E has to be non-negative.
  2135. ///
  2136. /// Note that this function will always return a valid isl_pw_aff. However, if
  2137. /// the translation of @p E was deemed to complex the SCoP is invalidated and
  2138. /// a dummy value of appropriate dimension is returned. This allows to bail
  2139. /// for complex cases without "error handling code" needed on the users side.
  2140. PWACtx getPwAff(const SCEV *E, BasicBlock *BB = nullptr,
  2141. bool NonNegative = false,
  2142. RecordedAssumptionsTy *RecordedAssumptions = nullptr);
  2143. /// Compute the isl representation for the SCEV @p E
  2144. ///
  2145. /// This function is like @see Scop::getPwAff() but strips away the invalid
  2146. /// domain part associated with the piecewise affine function.
  2147. isl::pw_aff
  2148. getPwAffOnly(const SCEV *E, BasicBlock *BB = nullptr,
  2149. RecordedAssumptionsTy *RecordedAssumptions = nullptr);
  2150. /// Check if an <nsw> AddRec for the loop L is cached.
  2151. bool hasNSWAddRecForLoop(Loop *L) { return Affinator.hasNSWAddRecForLoop(L); }
  2152. /// Return the domain of @p Stmt.
  2153. ///
  2154. /// @param Stmt The statement for which the conditions should be returned.
  2155. isl::set getDomainConditions(const ScopStmt *Stmt) const;
  2156. /// Return the domain of @p BB.
  2157. ///
  2158. /// @param BB The block for which the conditions should be returned.
  2159. isl::set getDomainConditions(BasicBlock *BB) const;
  2160. /// Return the domain of @p BB. If it does not exist, create an empty one.
  2161. isl::set &getOrInitEmptyDomain(BasicBlock *BB) { return DomainMap[BB]; }
  2162. /// Check if domain is determined for @p BB.
  2163. bool isDomainDefined(BasicBlock *BB) const { return DomainMap.count(BB) > 0; }
  2164. /// Set domain for @p BB.
  2165. void setDomain(BasicBlock *BB, isl::set &Domain) { DomainMap[BB] = Domain; }
  2166. /// Get a union set containing the iteration domains of all statements.
  2167. isl::union_set getDomains() const;
  2168. /// Get a union map of all may-writes performed in the SCoP.
  2169. isl::union_map getMayWrites();
  2170. /// Get a union map of all must-writes performed in the SCoP.
  2171. isl::union_map getMustWrites();
  2172. /// Get a union map of all writes performed in the SCoP.
  2173. isl::union_map getWrites();
  2174. /// Get a union map of all reads performed in the SCoP.
  2175. isl::union_map getReads();
  2176. /// Get a union map of all memory accesses performed in the SCoP.
  2177. isl::union_map getAccesses();
  2178. /// Get a union map of all memory accesses performed in the SCoP.
  2179. ///
  2180. /// @param Array The array to which the accesses should belong.
  2181. isl::union_map getAccesses(ScopArrayInfo *Array);
  2182. /// Get the schedule of all the statements in the SCoP.
  2183. ///
  2184. /// @return The schedule of all the statements in the SCoP, if the schedule of
  2185. /// the Scop does not contain extension nodes, and nullptr, otherwise.
  2186. isl::union_map getSchedule() const;
  2187. /// Get a schedule tree describing the schedule of all statements.
  2188. isl::schedule getScheduleTree() const;
  2189. /// Update the current schedule
  2190. ///
  2191. /// NewSchedule The new schedule (given as a flat union-map).
  2192. void setSchedule(isl::union_map NewSchedule);
  2193. /// Update the current schedule
  2194. ///
  2195. /// NewSchedule The new schedule (given as schedule tree).
  2196. void setScheduleTree(isl::schedule NewSchedule);
  2197. /// Whether the schedule is the original schedule as derived from the CFG by
  2198. /// ScopBuilder.
  2199. bool isOriginalSchedule() const { return !ScheduleModified; }
  2200. /// Intersects the domains of all statements in the SCoP.
  2201. ///
  2202. /// @return true if a change was made
  2203. bool restrictDomains(isl::union_set Domain);
  2204. /// Get the depth of a loop relative to the outermost loop in the Scop.
  2205. ///
  2206. /// This will return
  2207. /// 0 if @p L is an outermost loop in the SCoP
  2208. /// >0 for other loops in the SCoP
  2209. /// -1 if @p L is nullptr or there is no outermost loop in the SCoP
  2210. int getRelativeLoopDepth(const Loop *L) const;
  2211. /// Find the ScopArrayInfo associated with an isl Id
  2212. /// that has name @p Name.
  2213. ScopArrayInfo *getArrayInfoByName(const std::string BaseName);
  2214. /// Simplify the SCoP representation.
  2215. ///
  2216. /// @param AfterHoisting Whether it is called after invariant load hoisting.
  2217. /// When true, also removes statements without
  2218. /// side-effects.
  2219. void simplifySCoP(bool AfterHoisting);
  2220. /// Get the next free array index.
  2221. ///
  2222. /// This function returns a unique index which can be used to identify an
  2223. /// array.
  2224. long getNextArrayIdx() { return ArrayIdx++; }
  2225. /// Get the next free statement index.
  2226. ///
  2227. /// This function returns a unique index which can be used to identify a
  2228. /// statement.
  2229. long getNextStmtIdx() { return StmtIdx++; }
  2230. /// Get the representing SCEV for @p S if applicable, otherwise @p S.
  2231. ///
  2232. /// Invariant loads of the same location are put in an equivalence class and
  2233. /// only one of them is chosen as a representing element that will be
  2234. /// modeled as a parameter. The others have to be normalized, i.e.,
  2235. /// replaced by the representing element of their equivalence class, in order
  2236. /// to get the correct parameter value, e.g., in the SCEVAffinator.
  2237. ///
  2238. /// @param S The SCEV to normalize.
  2239. ///
  2240. /// @return The representing SCEV for invariant loads or @p S if none.
  2241. const SCEV *getRepresentingInvariantLoadSCEV(const SCEV *S) const;
  2242. /// Return the MemoryAccess that writes an llvm::Value, represented by a
  2243. /// ScopArrayInfo.
  2244. ///
  2245. /// There can be at most one such MemoryAccess per llvm::Value in the SCoP.
  2246. /// Zero is possible for read-only values.
  2247. MemoryAccess *getValueDef(const ScopArrayInfo *SAI) const;
  2248. /// Return all MemoryAccesses that us an llvm::Value, represented by a
  2249. /// ScopArrayInfo.
  2250. ArrayRef<MemoryAccess *> getValueUses(const ScopArrayInfo *SAI) const;
  2251. /// Return the MemoryAccess that represents an llvm::PHINode.
  2252. ///
  2253. /// ExitPHIs's PHINode is not within the SCoPs. This function returns nullptr
  2254. /// for them.
  2255. MemoryAccess *getPHIRead(const ScopArrayInfo *SAI) const;
  2256. /// Return all MemoryAccesses for all incoming statements of a PHINode,
  2257. /// represented by a ScopArrayInfo.
  2258. ArrayRef<MemoryAccess *> getPHIIncomings(const ScopArrayInfo *SAI) const;
  2259. /// Return whether @p Inst has a use outside of this SCoP.
  2260. bool isEscaping(Instruction *Inst);
  2261. struct ScopStatistics {
  2262. int NumAffineLoops = 0;
  2263. int NumBoxedLoops = 0;
  2264. int NumValueWrites = 0;
  2265. int NumValueWritesInLoops = 0;
  2266. int NumPHIWrites = 0;
  2267. int NumPHIWritesInLoops = 0;
  2268. int NumSingletonWrites = 0;
  2269. int NumSingletonWritesInLoops = 0;
  2270. };
  2271. /// Collect statistic about this SCoP.
  2272. ///
  2273. /// These are most commonly used for LLVM's static counters (Statistic.h) in
  2274. /// various places. If statistics are disabled, only zeros are returned to
  2275. /// avoid the overhead.
  2276. ScopStatistics getStatistics() const;
  2277. /// Is this Scop marked as not to be transformed by an optimization heuristic?
  2278. /// In this case, only user-directed transformations are allowed.
  2279. bool hasDisableHeuristicsHint() const { return HasDisableHeuristicsHint; }
  2280. /// Mark this Scop to not apply an optimization heuristic.
  2281. void markDisableHeuristics() { HasDisableHeuristicsHint = true; }
  2282. };
  2283. /// Print Scop scop to raw_ostream OS.
  2284. raw_ostream &operator<<(raw_ostream &OS, const Scop &scop);
  2285. /// The legacy pass manager's analysis pass to compute scop information
  2286. /// for a region.
  2287. class ScopInfoRegionPass : public RegionPass {
  2288. /// The Scop pointer which is used to construct a Scop.
  2289. std::unique_ptr<Scop> S;
  2290. public:
  2291. static char ID; // Pass identification, replacement for typeid
  2292. ScopInfoRegionPass() : RegionPass(ID) {}
  2293. ~ScopInfoRegionPass() override = default;
  2294. /// Build Scop object, the Polly IR of static control
  2295. /// part for the current SESE-Region.
  2296. ///
  2297. /// @return If the current region is a valid for a static control part,
  2298. /// return the Polly IR representing this static control part,
  2299. /// return null otherwise.
  2300. Scop *getScop() { return S.get(); }
  2301. const Scop *getScop() const { return S.get(); }
  2302. /// Calculate the polyhedral scop information for a given Region.
  2303. bool runOnRegion(Region *R, RGPassManager &RGM) override;
  2304. void releaseMemory() override { S.reset(); }
  2305. void print(raw_ostream &O, const Module *M = nullptr) const override;
  2306. void getAnalysisUsage(AnalysisUsage &AU) const override;
  2307. };
  2308. class ScopInfo {
  2309. public:
  2310. using RegionToScopMapTy = MapVector<Region *, std::unique_ptr<Scop>>;
  2311. using reverse_iterator = RegionToScopMapTy::reverse_iterator;
  2312. using const_reverse_iterator = RegionToScopMapTy::const_reverse_iterator;
  2313. using iterator = RegionToScopMapTy::iterator;
  2314. using const_iterator = RegionToScopMapTy::const_iterator;
  2315. private:
  2316. /// A map of Region to its Scop object containing
  2317. /// Polly IR of static control part.
  2318. RegionToScopMapTy RegionToScopMap;
  2319. const DataLayout &DL;
  2320. ScopDetection &SD;
  2321. ScalarEvolution &SE;
  2322. LoopInfo &LI;
  2323. AAResults &AA;
  2324. DominatorTree &DT;
  2325. AssumptionCache &AC;
  2326. OptimizationRemarkEmitter &ORE;
  2327. public:
  2328. ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
  2329. LoopInfo &LI, AAResults &AA, DominatorTree &DT, AssumptionCache &AC,
  2330. OptimizationRemarkEmitter &ORE);
  2331. /// Get the Scop object for the given Region.
  2332. ///
  2333. /// @return If the given region is the maximal region within a scop, return
  2334. /// the scop object. If the given region is a subregion, return a
  2335. /// nullptr. Top level region containing the entry block of a function
  2336. /// is not considered in the scop creation.
  2337. Scop *getScop(Region *R) const {
  2338. auto MapIt = RegionToScopMap.find(R);
  2339. if (MapIt != RegionToScopMap.end())
  2340. return MapIt->second.get();
  2341. return nullptr;
  2342. }
  2343. /// Recompute the Scop-Information for a function.
  2344. ///
  2345. /// This invalidates any iterators.
  2346. void recompute();
  2347. /// Handle invalidation explicitly
  2348. bool invalidate(Function &F, const PreservedAnalyses &PA,
  2349. FunctionAnalysisManager::Invalidator &Inv);
  2350. iterator begin() { return RegionToScopMap.begin(); }
  2351. iterator end() { return RegionToScopMap.end(); }
  2352. const_iterator begin() const { return RegionToScopMap.begin(); }
  2353. const_iterator end() const { return RegionToScopMap.end(); }
  2354. reverse_iterator rbegin() { return RegionToScopMap.rbegin(); }
  2355. reverse_iterator rend() { return RegionToScopMap.rend(); }
  2356. const_reverse_iterator rbegin() const { return RegionToScopMap.rbegin(); }
  2357. const_reverse_iterator rend() const { return RegionToScopMap.rend(); }
  2358. bool empty() const { return RegionToScopMap.empty(); }
  2359. };
  2360. struct ScopInfoAnalysis : public AnalysisInfoMixin<ScopInfoAnalysis> {
  2361. static AnalysisKey Key;
  2362. using Result = ScopInfo;
  2363. Result run(Function &, FunctionAnalysisManager &);
  2364. };
  2365. struct ScopInfoPrinterPass : public PassInfoMixin<ScopInfoPrinterPass> {
  2366. ScopInfoPrinterPass(raw_ostream &OS) : Stream(OS) {}
  2367. PreservedAnalyses run(Function &, FunctionAnalysisManager &);
  2368. raw_ostream &Stream;
  2369. };
  2370. //===----------------------------------------------------------------------===//
  2371. /// The legacy pass manager's analysis pass to compute scop information
  2372. /// for the whole function.
  2373. ///
  2374. /// This pass will maintain a map of the maximal region within a scop to its
  2375. /// scop object for all the feasible scops present in a function.
  2376. /// This pass is an alternative to the ScopInfoRegionPass in order to avoid a
  2377. /// region pass manager.
  2378. class ScopInfoWrapperPass : public FunctionPass {
  2379. std::unique_ptr<ScopInfo> Result;
  2380. public:
  2381. ScopInfoWrapperPass() : FunctionPass(ID) {}
  2382. ~ScopInfoWrapperPass() override = default;
  2383. static char ID; // Pass identification, replacement for typeid
  2384. ScopInfo *getSI() { return Result.get(); }
  2385. const ScopInfo *getSI() const { return Result.get(); }
  2386. /// Calculate all the polyhedral scops for a given function.
  2387. bool runOnFunction(Function &F) override;
  2388. void releaseMemory() override { Result.reset(); }
  2389. void print(raw_ostream &O, const Module *M = nullptr) const override;
  2390. void getAnalysisUsage(AnalysisUsage &AU) const override;
  2391. };
  2392. } // end namespace polly
  2393. #endif // POLLY_SCOPINFO_H