LoopAccessAnalysis.h 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. //===- llvm/Analysis/LoopAccessAnalysis.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. // This file defines the interface for the loop memory dependence framework that
  10. // was originally developed for the Loop Vectorizer.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
  14. #define LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
  15. #include "llvm/ADT/EquivalenceClasses.h"
  16. #include "llvm/Analysis/LoopAnalysisManager.h"
  17. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  18. #include "llvm/IR/DiagnosticInfo.h"
  19. #include "llvm/Pass.h"
  20. namespace llvm {
  21. class AAResults;
  22. class DataLayout;
  23. class Loop;
  24. class LoopAccessInfo;
  25. class OptimizationRemarkEmitter;
  26. class raw_ostream;
  27. class SCEV;
  28. class SCEVUnionPredicate;
  29. class Value;
  30. /// Collection of parameters shared beetween the Loop Vectorizer and the
  31. /// Loop Access Analysis.
  32. struct VectorizerParams {
  33. /// Maximum SIMD width.
  34. static const unsigned MaxVectorWidth;
  35. /// VF as overridden by the user.
  36. static unsigned VectorizationFactor;
  37. /// Interleave factor as overridden by the user.
  38. static unsigned VectorizationInterleave;
  39. /// True if force-vector-interleave was specified by the user.
  40. static bool isInterleaveForced();
  41. /// \When performing memory disambiguation checks at runtime do not
  42. /// make more than this number of comparisons.
  43. static unsigned RuntimeMemoryCheckThreshold;
  44. };
  45. /// Checks memory dependences among accesses to the same underlying
  46. /// object to determine whether there vectorization is legal or not (and at
  47. /// which vectorization factor).
  48. ///
  49. /// Note: This class will compute a conservative dependence for access to
  50. /// different underlying pointers. Clients, such as the loop vectorizer, will
  51. /// sometimes deal these potential dependencies by emitting runtime checks.
  52. ///
  53. /// We use the ScalarEvolution framework to symbolically evalutate access
  54. /// functions pairs. Since we currently don't restructure the loop we can rely
  55. /// on the program order of memory accesses to determine their safety.
  56. /// At the moment we will only deem accesses as safe for:
  57. /// * A negative constant distance assuming program order.
  58. ///
  59. /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
  60. /// a[i] = tmp; y = a[i];
  61. ///
  62. /// The latter case is safe because later checks guarantuee that there can't
  63. /// be a cycle through a phi node (that is, we check that "x" and "y" is not
  64. /// the same variable: a header phi can only be an induction or a reduction, a
  65. /// reduction can't have a memory sink, an induction can't have a memory
  66. /// source). This is important and must not be violated (or we have to
  67. /// resort to checking for cycles through memory).
  68. ///
  69. /// * A positive constant distance assuming program order that is bigger
  70. /// than the biggest memory access.
  71. ///
  72. /// tmp = a[i] OR b[i] = x
  73. /// a[i+2] = tmp y = b[i+2];
  74. ///
  75. /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
  76. ///
  77. /// * Zero distances and all accesses have the same size.
  78. ///
  79. class MemoryDepChecker {
  80. public:
  81. typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
  82. typedef SmallVector<MemAccessInfo, 8> MemAccessInfoList;
  83. /// Set of potential dependent memory accesses.
  84. typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
  85. /// Type to keep track of the status of the dependence check. The order of
  86. /// the elements is important and has to be from most permissive to least
  87. /// permissive.
  88. enum class VectorizationSafetyStatus {
  89. // Can vectorize safely without RT checks. All dependences are known to be
  90. // safe.
  91. Safe,
  92. // Can possibly vectorize with RT checks to overcome unknown dependencies.
  93. PossiblySafeWithRtChecks,
  94. // Cannot vectorize due to known unsafe dependencies.
  95. Unsafe,
  96. };
  97. /// Dependece between memory access instructions.
  98. struct Dependence {
  99. /// The type of the dependence.
  100. enum DepType {
  101. // No dependence.
  102. NoDep,
  103. // We couldn't determine the direction or the distance.
  104. Unknown,
  105. // Lexically forward.
  106. //
  107. // FIXME: If we only have loop-independent forward dependences (e.g. a
  108. // read and write of A[i]), LAA will locally deem the dependence "safe"
  109. // without querying the MemoryDepChecker. Therefore we can miss
  110. // enumerating loop-independent forward dependences in
  111. // getDependences. Note that as soon as there are different
  112. // indices used to access the same array, the MemoryDepChecker *is*
  113. // queried and the dependence list is complete.
  114. Forward,
  115. // Forward, but if vectorized, is likely to prevent store-to-load
  116. // forwarding.
  117. ForwardButPreventsForwarding,
  118. // Lexically backward.
  119. Backward,
  120. // Backward, but the distance allows a vectorization factor of
  121. // MaxSafeDepDistBytes.
  122. BackwardVectorizable,
  123. // Same, but may prevent store-to-load forwarding.
  124. BackwardVectorizableButPreventsForwarding
  125. };
  126. /// String version of the types.
  127. static const char *DepName[];
  128. /// Index of the source of the dependence in the InstMap vector.
  129. unsigned Source;
  130. /// Index of the destination of the dependence in the InstMap vector.
  131. unsigned Destination;
  132. /// The type of the dependence.
  133. DepType Type;
  134. Dependence(unsigned Source, unsigned Destination, DepType Type)
  135. : Source(Source), Destination(Destination), Type(Type) {}
  136. /// Return the source instruction of the dependence.
  137. Instruction *getSource(const LoopAccessInfo &LAI) const;
  138. /// Return the destination instruction of the dependence.
  139. Instruction *getDestination(const LoopAccessInfo &LAI) const;
  140. /// Dependence types that don't prevent vectorization.
  141. static VectorizationSafetyStatus isSafeForVectorization(DepType Type);
  142. /// Lexically forward dependence.
  143. bool isForward() const;
  144. /// Lexically backward dependence.
  145. bool isBackward() const;
  146. /// May be a lexically backward dependence type (includes Unknown).
  147. bool isPossiblyBackward() const;
  148. /// Print the dependence. \p Instr is used to map the instruction
  149. /// indices to instructions.
  150. void print(raw_ostream &OS, unsigned Depth,
  151. const SmallVectorImpl<Instruction *> &Instrs) const;
  152. };
  153. MemoryDepChecker(PredicatedScalarEvolution &PSE, const Loop *L)
  154. : PSE(PSE), InnermostLoop(L), AccessIdx(0), MaxSafeDepDistBytes(0),
  155. MaxSafeVectorWidthInBits(-1U),
  156. FoundNonConstantDistanceDependence(false),
  157. Status(VectorizationSafetyStatus::Safe), RecordDependences(true) {}
  158. /// Register the location (instructions are given increasing numbers)
  159. /// of a write access.
  160. void addAccess(StoreInst *SI) {
  161. Value *Ptr = SI->getPointerOperand();
  162. Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
  163. InstMap.push_back(SI);
  164. ++AccessIdx;
  165. }
  166. /// Register the location (instructions are given increasing numbers)
  167. /// of a write access.
  168. void addAccess(LoadInst *LI) {
  169. Value *Ptr = LI->getPointerOperand();
  170. Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
  171. InstMap.push_back(LI);
  172. ++AccessIdx;
  173. }
  174. /// Check whether the dependencies between the accesses are safe.
  175. ///
  176. /// Only checks sets with elements in \p CheckDeps.
  177. bool areDepsSafe(DepCandidates &AccessSets, MemAccessInfoList &CheckDeps,
  178. const ValueToValueMap &Strides);
  179. /// No memory dependence was encountered that would inhibit
  180. /// vectorization.
  181. bool isSafeForVectorization() const {
  182. return Status == VectorizationSafetyStatus::Safe;
  183. }
  184. /// Return true if the number of elements that are safe to operate on
  185. /// simultaneously is not bounded.
  186. bool isSafeForAnyVectorWidth() const {
  187. return MaxSafeVectorWidthInBits == UINT_MAX;
  188. }
  189. /// The maximum number of bytes of a vector register we can vectorize
  190. /// the accesses safely with.
  191. uint64_t getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
  192. /// Return the number of elements that are safe to operate on
  193. /// simultaneously, multiplied by the size of the element in bits.
  194. uint64_t getMaxSafeVectorWidthInBits() const {
  195. return MaxSafeVectorWidthInBits;
  196. }
  197. /// In same cases when the dependency check fails we can still
  198. /// vectorize the loop with a dynamic array access check.
  199. bool shouldRetryWithRuntimeCheck() const {
  200. return FoundNonConstantDistanceDependence &&
  201. Status == VectorizationSafetyStatus::PossiblySafeWithRtChecks;
  202. }
  203. /// Returns the memory dependences. If null is returned we exceeded
  204. /// the MaxDependences threshold and this information is not
  205. /// available.
  206. const SmallVectorImpl<Dependence> *getDependences() const {
  207. return RecordDependences ? &Dependences : nullptr;
  208. }
  209. void clearDependences() { Dependences.clear(); }
  210. /// The vector of memory access instructions. The indices are used as
  211. /// instruction identifiers in the Dependence class.
  212. const SmallVectorImpl<Instruction *> &getMemoryInstructions() const {
  213. return InstMap;
  214. }
  215. /// Generate a mapping between the memory instructions and their
  216. /// indices according to program order.
  217. DenseMap<Instruction *, unsigned> generateInstructionOrderMap() const {
  218. DenseMap<Instruction *, unsigned> OrderMap;
  219. for (unsigned I = 0; I < InstMap.size(); ++I)
  220. OrderMap[InstMap[I]] = I;
  221. return OrderMap;
  222. }
  223. /// Find the set of instructions that read or write via \p Ptr.
  224. SmallVector<Instruction *, 4> getInstructionsForAccess(Value *Ptr,
  225. bool isWrite) const;
  226. private:
  227. /// A wrapper around ScalarEvolution, used to add runtime SCEV checks, and
  228. /// applies dynamic knowledge to simplify SCEV expressions and convert them
  229. /// to a more usable form. We need this in case assumptions about SCEV
  230. /// expressions need to be made in order to avoid unknown dependences. For
  231. /// example we might assume a unit stride for a pointer in order to prove
  232. /// that a memory access is strided and doesn't wrap.
  233. PredicatedScalarEvolution &PSE;
  234. const Loop *InnermostLoop;
  235. /// Maps access locations (ptr, read/write) to program order.
  236. DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
  237. /// Memory access instructions in program order.
  238. SmallVector<Instruction *, 16> InstMap;
  239. /// The program order index to be used for the next instruction.
  240. unsigned AccessIdx;
  241. // We can access this many bytes in parallel safely.
  242. uint64_t MaxSafeDepDistBytes;
  243. /// Number of elements (from consecutive iterations) that are safe to
  244. /// operate on simultaneously, multiplied by the size of the element in bits.
  245. /// The size of the element is taken from the memory access that is most
  246. /// restrictive.
  247. uint64_t MaxSafeVectorWidthInBits;
  248. /// If we see a non-constant dependence distance we can still try to
  249. /// vectorize this loop with runtime checks.
  250. bool FoundNonConstantDistanceDependence;
  251. /// Result of the dependence checks, indicating whether the checked
  252. /// dependences are safe for vectorization, require RT checks or are known to
  253. /// be unsafe.
  254. VectorizationSafetyStatus Status;
  255. //// True if Dependences reflects the dependences in the
  256. //// loop. If false we exceeded MaxDependences and
  257. //// Dependences is invalid.
  258. bool RecordDependences;
  259. /// Memory dependences collected during the analysis. Only valid if
  260. /// RecordDependences is true.
  261. SmallVector<Dependence, 8> Dependences;
  262. /// Check whether there is a plausible dependence between the two
  263. /// accesses.
  264. ///
  265. /// Access \p A must happen before \p B in program order. The two indices
  266. /// identify the index into the program order map.
  267. ///
  268. /// This function checks whether there is a plausible dependence (or the
  269. /// absence of such can't be proved) between the two accesses. If there is a
  270. /// plausible dependence but the dependence distance is bigger than one
  271. /// element access it records this distance in \p MaxSafeDepDistBytes (if this
  272. /// distance is smaller than any other distance encountered so far).
  273. /// Otherwise, this function returns true signaling a possible dependence.
  274. Dependence::DepType isDependent(const MemAccessInfo &A, unsigned AIdx,
  275. const MemAccessInfo &B, unsigned BIdx,
  276. const ValueToValueMap &Strides);
  277. /// Check whether the data dependence could prevent store-load
  278. /// forwarding.
  279. ///
  280. /// \return false if we shouldn't vectorize at all or avoid larger
  281. /// vectorization factors by limiting MaxSafeDepDistBytes.
  282. bool couldPreventStoreLoadForward(uint64_t Distance, uint64_t TypeByteSize);
  283. /// Updates the current safety status with \p S. We can go from Safe to
  284. /// either PossiblySafeWithRtChecks or Unsafe and from
  285. /// PossiblySafeWithRtChecks to Unsafe.
  286. void mergeInStatus(VectorizationSafetyStatus S);
  287. };
  288. class RuntimePointerChecking;
  289. /// A grouping of pointers. A single memcheck is required between
  290. /// two groups.
  291. struct RuntimeCheckingPtrGroup {
  292. /// Create a new pointer checking group containing a single
  293. /// pointer, with index \p Index in RtCheck.
  294. RuntimeCheckingPtrGroup(unsigned Index, RuntimePointerChecking &RtCheck);
  295. /// Tries to add the pointer recorded in RtCheck at index
  296. /// \p Index to this pointer checking group. We can only add a pointer
  297. /// to a checking group if we will still be able to get
  298. /// the upper and lower bounds of the check. Returns true in case
  299. /// of success, false otherwise.
  300. bool addPointer(unsigned Index);
  301. /// Constitutes the context of this pointer checking group. For each
  302. /// pointer that is a member of this group we will retain the index
  303. /// at which it appears in RtCheck.
  304. RuntimePointerChecking &RtCheck;
  305. /// The SCEV expression which represents the upper bound of all the
  306. /// pointers in this group.
  307. const SCEV *High;
  308. /// The SCEV expression which represents the lower bound of all the
  309. /// pointers in this group.
  310. const SCEV *Low;
  311. /// Indices of all the pointers that constitute this grouping.
  312. SmallVector<unsigned, 2> Members;
  313. };
  314. /// A memcheck which made up of a pair of grouped pointers.
  315. typedef std::pair<const RuntimeCheckingPtrGroup *,
  316. const RuntimeCheckingPtrGroup *>
  317. RuntimePointerCheck;
  318. /// Holds information about the memory runtime legality checks to verify
  319. /// that a group of pointers do not overlap.
  320. class RuntimePointerChecking {
  321. friend struct RuntimeCheckingPtrGroup;
  322. public:
  323. struct PointerInfo {
  324. /// Holds the pointer value that we need to check.
  325. TrackingVH<Value> PointerValue;
  326. /// Holds the smallest byte address accessed by the pointer throughout all
  327. /// iterations of the loop.
  328. const SCEV *Start;
  329. /// Holds the largest byte address accessed by the pointer throughout all
  330. /// iterations of the loop, plus 1.
  331. const SCEV *End;
  332. /// Holds the information if this pointer is used for writing to memory.
  333. bool IsWritePtr;
  334. /// Holds the id of the set of pointers that could be dependent because of a
  335. /// shared underlying object.
  336. unsigned DependencySetId;
  337. /// Holds the id of the disjoint alias set to which this pointer belongs.
  338. unsigned AliasSetId;
  339. /// SCEV for the access.
  340. const SCEV *Expr;
  341. PointerInfo(Value *PointerValue, const SCEV *Start, const SCEV *End,
  342. bool IsWritePtr, unsigned DependencySetId, unsigned AliasSetId,
  343. const SCEV *Expr)
  344. : PointerValue(PointerValue), Start(Start), End(End),
  345. IsWritePtr(IsWritePtr), DependencySetId(DependencySetId),
  346. AliasSetId(AliasSetId), Expr(Expr) {}
  347. };
  348. RuntimePointerChecking(ScalarEvolution *SE) : Need(false), SE(SE) {}
  349. /// Reset the state of the pointer runtime information.
  350. void reset() {
  351. Need = false;
  352. Pointers.clear();
  353. Checks.clear();
  354. }
  355. /// Insert a pointer and calculate the start and end SCEVs.
  356. /// We need \p PSE in order to compute the SCEV expression of the pointer
  357. /// according to the assumptions that we've made during the analysis.
  358. /// The method might also version the pointer stride according to \p Strides,
  359. /// and add new predicates to \p PSE.
  360. void insert(Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
  361. unsigned ASId, const ValueToValueMap &Strides,
  362. PredicatedScalarEvolution &PSE);
  363. /// No run-time memory checking is necessary.
  364. bool empty() const { return Pointers.empty(); }
  365. /// Generate the checks and store it. This also performs the grouping
  366. /// of pointers to reduce the number of memchecks necessary.
  367. void generateChecks(MemoryDepChecker::DepCandidates &DepCands,
  368. bool UseDependencies);
  369. /// Returns the checks that generateChecks created.
  370. const SmallVectorImpl<RuntimePointerCheck> &getChecks() const {
  371. return Checks;
  372. }
  373. /// Decide if we need to add a check between two groups of pointers,
  374. /// according to needsChecking.
  375. bool needsChecking(const RuntimeCheckingPtrGroup &M,
  376. const RuntimeCheckingPtrGroup &N) const;
  377. /// Returns the number of run-time checks required according to
  378. /// needsChecking.
  379. unsigned getNumberOfChecks() const { return Checks.size(); }
  380. /// Print the list run-time memory checks necessary.
  381. void print(raw_ostream &OS, unsigned Depth = 0) const;
  382. /// Print \p Checks.
  383. void printChecks(raw_ostream &OS,
  384. const SmallVectorImpl<RuntimePointerCheck> &Checks,
  385. unsigned Depth = 0) const;
  386. /// This flag indicates if we need to add the runtime check.
  387. bool Need;
  388. /// Information about the pointers that may require checking.
  389. SmallVector<PointerInfo, 2> Pointers;
  390. /// Holds a partitioning of pointers into "check groups".
  391. SmallVector<RuntimeCheckingPtrGroup, 2> CheckingGroups;
  392. /// Check if pointers are in the same partition
  393. ///
  394. /// \p PtrToPartition contains the partition number for pointers (-1 if the
  395. /// pointer belongs to multiple partitions).
  396. static bool
  397. arePointersInSamePartition(const SmallVectorImpl<int> &PtrToPartition,
  398. unsigned PtrIdx1, unsigned PtrIdx2);
  399. /// Decide whether we need to issue a run-time check for pointer at
  400. /// index \p I and \p J to prove their independence.
  401. bool needsChecking(unsigned I, unsigned J) const;
  402. /// Return PointerInfo for pointer at index \p PtrIdx.
  403. const PointerInfo &getPointerInfo(unsigned PtrIdx) const {
  404. return Pointers[PtrIdx];
  405. }
  406. ScalarEvolution *getSE() const { return SE; }
  407. private:
  408. /// Groups pointers such that a single memcheck is required
  409. /// between two different groups. This will clear the CheckingGroups vector
  410. /// and re-compute it. We will only group dependecies if \p UseDependencies
  411. /// is true, otherwise we will create a separate group for each pointer.
  412. void groupChecks(MemoryDepChecker::DepCandidates &DepCands,
  413. bool UseDependencies);
  414. /// Generate the checks and return them.
  415. SmallVector<RuntimePointerCheck, 4> generateChecks() const;
  416. /// Holds a pointer to the ScalarEvolution analysis.
  417. ScalarEvolution *SE;
  418. /// Set of run-time checks required to establish independence of
  419. /// otherwise may-aliasing pointers in the loop.
  420. SmallVector<RuntimePointerCheck, 4> Checks;
  421. };
  422. /// Drive the analysis of memory accesses in the loop
  423. ///
  424. /// This class is responsible for analyzing the memory accesses of a loop. It
  425. /// collects the accesses and then its main helper the AccessAnalysis class
  426. /// finds and categorizes the dependences in buildDependenceSets.
  427. ///
  428. /// For memory dependences that can be analyzed at compile time, it determines
  429. /// whether the dependence is part of cycle inhibiting vectorization. This work
  430. /// is delegated to the MemoryDepChecker class.
  431. ///
  432. /// For memory dependences that cannot be determined at compile time, it
  433. /// generates run-time checks to prove independence. This is done by
  434. /// AccessAnalysis::canCheckPtrAtRT and the checks are maintained by the
  435. /// RuntimePointerCheck class.
  436. ///
  437. /// If pointers can wrap or can't be expressed as affine AddRec expressions by
  438. /// ScalarEvolution, we will generate run-time checks by emitting a
  439. /// SCEVUnionPredicate.
  440. ///
  441. /// Checks for both memory dependences and the SCEV predicates contained in the
  442. /// PSE must be emitted in order for the results of this analysis to be valid.
  443. class LoopAccessInfo {
  444. public:
  445. LoopAccessInfo(Loop *L, ScalarEvolution *SE, const TargetLibraryInfo *TLI,
  446. AAResults *AA, DominatorTree *DT, LoopInfo *LI);
  447. /// Return true we can analyze the memory accesses in the loop and there are
  448. /// no memory dependence cycles.
  449. bool canVectorizeMemory() const { return CanVecMem; }
  450. /// Return true if there is a convergent operation in the loop. There may
  451. /// still be reported runtime pointer checks that would be required, but it is
  452. /// not legal to insert them.
  453. bool hasConvergentOp() const { return HasConvergentOp; }
  454. const RuntimePointerChecking *getRuntimePointerChecking() const {
  455. return PtrRtChecking.get();
  456. }
  457. /// Number of memchecks required to prove independence of otherwise
  458. /// may-alias pointers.
  459. unsigned getNumRuntimePointerChecks() const {
  460. return PtrRtChecking->getNumberOfChecks();
  461. }
  462. /// Return true if the block BB needs to be predicated in order for the loop
  463. /// to be vectorized.
  464. static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
  465. DominatorTree *DT);
  466. /// Returns true if the value V is uniform within the loop.
  467. bool isUniform(Value *V) const;
  468. uint64_t getMaxSafeDepDistBytes() const { return MaxSafeDepDistBytes; }
  469. unsigned getNumStores() const { return NumStores; }
  470. unsigned getNumLoads() const { return NumLoads;}
  471. /// The diagnostics report generated for the analysis. E.g. why we
  472. /// couldn't analyze the loop.
  473. const OptimizationRemarkAnalysis *getReport() const { return Report.get(); }
  474. /// the Memory Dependence Checker which can determine the
  475. /// loop-independent and loop-carried dependences between memory accesses.
  476. const MemoryDepChecker &getDepChecker() const { return *DepChecker; }
  477. /// Return the list of instructions that use \p Ptr to read or write
  478. /// memory.
  479. SmallVector<Instruction *, 4> getInstructionsForAccess(Value *Ptr,
  480. bool isWrite) const {
  481. return DepChecker->getInstructionsForAccess(Ptr, isWrite);
  482. }
  483. /// If an access has a symbolic strides, this maps the pointer value to
  484. /// the stride symbol.
  485. const ValueToValueMap &getSymbolicStrides() const { return SymbolicStrides; }
  486. /// Pointer has a symbolic stride.
  487. bool hasStride(Value *V) const { return StrideSet.count(V); }
  488. /// Print the information about the memory accesses in the loop.
  489. void print(raw_ostream &OS, unsigned Depth = 0) const;
  490. /// If the loop has memory dependence involving an invariant address, i.e. two
  491. /// stores or a store and a load, then return true, else return false.
  492. bool hasDependenceInvolvingLoopInvariantAddress() const {
  493. return HasDependenceInvolvingLoopInvariantAddress;
  494. }
  495. /// Used to add runtime SCEV checks. Simplifies SCEV expressions and converts
  496. /// them to a more usable form. All SCEV expressions during the analysis
  497. /// should be re-written (and therefore simplified) according to PSE.
  498. /// A user of LoopAccessAnalysis will need to emit the runtime checks
  499. /// associated with this predicate.
  500. const PredicatedScalarEvolution &getPSE() const { return *PSE; }
  501. private:
  502. /// Analyze the loop.
  503. void analyzeLoop(AAResults *AA, LoopInfo *LI,
  504. const TargetLibraryInfo *TLI, DominatorTree *DT);
  505. /// Check if the structure of the loop allows it to be analyzed by this
  506. /// pass.
  507. bool canAnalyzeLoop();
  508. /// Save the analysis remark.
  509. ///
  510. /// LAA does not directly emits the remarks. Instead it stores it which the
  511. /// client can retrieve and presents as its own analysis
  512. /// (e.g. -Rpass-analysis=loop-vectorize).
  513. OptimizationRemarkAnalysis &recordAnalysis(StringRef RemarkName,
  514. Instruction *Instr = nullptr);
  515. /// Collect memory access with loop invariant strides.
  516. ///
  517. /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
  518. /// invariant.
  519. void collectStridedAccess(Value *LoadOrStoreInst);
  520. std::unique_ptr<PredicatedScalarEvolution> PSE;
  521. /// We need to check that all of the pointers in this list are disjoint
  522. /// at runtime. Using std::unique_ptr to make using move ctor simpler.
  523. std::unique_ptr<RuntimePointerChecking> PtrRtChecking;
  524. /// the Memory Dependence Checker which can determine the
  525. /// loop-independent and loop-carried dependences between memory accesses.
  526. std::unique_ptr<MemoryDepChecker> DepChecker;
  527. Loop *TheLoop;
  528. unsigned NumLoads;
  529. unsigned NumStores;
  530. uint64_t MaxSafeDepDistBytes;
  531. /// Cache the result of analyzeLoop.
  532. bool CanVecMem;
  533. bool HasConvergentOp;
  534. /// Indicator that there are non vectorizable stores to a uniform address.
  535. bool HasDependenceInvolvingLoopInvariantAddress;
  536. /// The diagnostics report generated for the analysis. E.g. why we
  537. /// couldn't analyze the loop.
  538. std::unique_ptr<OptimizationRemarkAnalysis> Report;
  539. /// If an access has a symbolic strides, this maps the pointer value to
  540. /// the stride symbol.
  541. ValueToValueMap SymbolicStrides;
  542. /// Set of symbolic strides values.
  543. SmallPtrSet<Value *, 8> StrideSet;
  544. };
  545. Value *stripIntegerCast(Value *V);
  546. /// Return the SCEV corresponding to a pointer with the symbolic stride
  547. /// replaced with constant one, assuming the SCEV predicate associated with
  548. /// \p PSE is true.
  549. ///
  550. /// If necessary this method will version the stride of the pointer according
  551. /// to \p PtrToStride and therefore add further predicates to \p PSE.
  552. ///
  553. /// If \p OrigPtr is not null, use it to look up the stride value instead of \p
  554. /// Ptr. \p PtrToStride provides the mapping between the pointer value and its
  555. /// stride as collected by LoopVectorizationLegality::collectStridedAccess.
  556. const SCEV *replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
  557. const ValueToValueMap &PtrToStride,
  558. Value *Ptr, Value *OrigPtr = nullptr);
  559. /// If the pointer has a constant stride return it in units of its
  560. /// element size. Otherwise return zero.
  561. ///
  562. /// Ensure that it does not wrap in the address space, assuming the predicate
  563. /// associated with \p PSE is true.
  564. ///
  565. /// If necessary this method will version the stride of the pointer according
  566. /// to \p PtrToStride and therefore add further predicates to \p PSE.
  567. /// The \p Assume parameter indicates if we are allowed to make additional
  568. /// run-time assumptions.
  569. int64_t getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr, const Loop *Lp,
  570. const ValueToValueMap &StridesMap = ValueToValueMap(),
  571. bool Assume = false, bool ShouldCheckWrap = true);
  572. /// Returns the distance between the pointers \p PtrA and \p PtrB iff they are
  573. /// compatible and it is possible to calculate the distance between them. This
  574. /// is a simple API that does not depend on the analysis pass.
  575. /// \param StrictCheck Ensure that the calculated distance matches the
  576. /// type-based one after all the bitcasts removal in the provided pointers.
  577. Optional<int> getPointersDiff(Value *PtrA, Value *PtrB, const DataLayout &DL,
  578. ScalarEvolution &SE, bool StrictCheck = false,
  579. bool CheckType = true);
  580. /// Attempt to sort the pointers in \p VL and return the sorted indices
  581. /// in \p SortedIndices, if reordering is required.
  582. ///
  583. /// Returns 'true' if sorting is legal, otherwise returns 'false'.
  584. ///
  585. /// For example, for a given \p VL of memory accesses in program order, a[i+4],
  586. /// a[i+0], a[i+1] and a[i+7], this function will sort the \p VL and save the
  587. /// sorted indices in \p SortedIndices as a[i+0], a[i+1], a[i+4], a[i+7] and
  588. /// saves the mask for actual memory accesses in program order in
  589. /// \p SortedIndices as <1,2,0,3>
  590. bool sortPtrAccesses(ArrayRef<Value *> VL, const DataLayout &DL,
  591. ScalarEvolution &SE,
  592. SmallVectorImpl<unsigned> &SortedIndices);
  593. /// Returns true if the memory operations \p A and \p B are consecutive.
  594. /// This is a simple API that does not depend on the analysis pass.
  595. bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
  596. ScalarEvolution &SE, bool CheckType = true);
  597. /// This analysis provides dependence information for the memory accesses
  598. /// of a loop.
  599. ///
  600. /// It runs the analysis for a loop on demand. This can be initiated by
  601. /// querying the loop access info via LAA::getInfo. getInfo return a
  602. /// LoopAccessInfo object. See this class for the specifics of what information
  603. /// is provided.
  604. class LoopAccessLegacyAnalysis : public FunctionPass {
  605. public:
  606. static char ID;
  607. LoopAccessLegacyAnalysis();
  608. bool runOnFunction(Function &F) override;
  609. void getAnalysisUsage(AnalysisUsage &AU) const override;
  610. /// Query the result of the loop access information for the loop \p L.
  611. ///
  612. /// If there is no cached result available run the analysis.
  613. const LoopAccessInfo &getInfo(Loop *L);
  614. void releaseMemory() override {
  615. // Invalidate the cache when the pass is freed.
  616. LoopAccessInfoMap.clear();
  617. }
  618. /// Print the result of the analysis when invoked with -analyze.
  619. void print(raw_ostream &OS, const Module *M = nullptr) const override;
  620. private:
  621. /// The cache.
  622. DenseMap<Loop *, std::unique_ptr<LoopAccessInfo>> LoopAccessInfoMap;
  623. // The used analysis passes.
  624. ScalarEvolution *SE = nullptr;
  625. const TargetLibraryInfo *TLI = nullptr;
  626. AAResults *AA = nullptr;
  627. DominatorTree *DT = nullptr;
  628. LoopInfo *LI = nullptr;
  629. };
  630. /// This analysis provides dependence information for the memory
  631. /// accesses of a loop.
  632. ///
  633. /// It runs the analysis for a loop on demand. This can be initiated by
  634. /// querying the loop access info via AM.getResult<LoopAccessAnalysis>.
  635. /// getResult return a LoopAccessInfo object. See this class for the
  636. /// specifics of what information is provided.
  637. class LoopAccessAnalysis
  638. : public AnalysisInfoMixin<LoopAccessAnalysis> {
  639. friend AnalysisInfoMixin<LoopAccessAnalysis>;
  640. static AnalysisKey Key;
  641. public:
  642. typedef LoopAccessInfo Result;
  643. Result run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR);
  644. };
  645. inline Instruction *MemoryDepChecker::Dependence::getSource(
  646. const LoopAccessInfo &LAI) const {
  647. return LAI.getDepChecker().getMemoryInstructions()[Source];
  648. }
  649. inline Instruction *MemoryDepChecker::Dependence::getDestination(
  650. const LoopAccessInfo &LAI) const {
  651. return LAI.getDepChecker().getMemoryInstructions()[Destination];
  652. }
  653. } // End llvm namespace
  654. #endif