blob: 13fbe884eddf9fa02ecb5e35a7c53382f71dabd6 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- llvm/Analysis/LoopAccessAnalysis.h -----------------------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// 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
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
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
14#ifndef LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
15#define LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
16
17#include "llvm/ADT/EquivalenceClasses.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010018#include "llvm/Analysis/LoopAnalysisManager.h"
19#include "llvm/Analysis/ScalarEvolutionExpressions.h"
20#include "llvm/IR/DiagnosticInfo.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010021#include "llvm/Pass.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010022
23namespace llvm {
24
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020025class AAResults;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010026class DataLayout;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010027class Loop;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010028class LoopAccessInfo;
29class OptimizationRemarkEmitter;
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020030class raw_ostream;
31class SCEV;
32class SCEVUnionPredicate;
33class Value;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010034
Andrew Scullcdfcccc2018-10-05 20:58:37 +010035/// Collection of parameters shared beetween the Loop Vectorizer and the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010036/// Loop Access Analysis.
37struct VectorizerParams {
Andrew Scullcdfcccc2018-10-05 20:58:37 +010038 /// Maximum SIMD width.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010039 static const unsigned MaxVectorWidth;
40
Andrew Scullcdfcccc2018-10-05 20:58:37 +010041 /// VF as overridden by the user.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010042 static unsigned VectorizationFactor;
Andrew Scullcdfcccc2018-10-05 20:58:37 +010043 /// Interleave factor as overridden by the user.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010044 static unsigned VectorizationInterleave;
Andrew Scullcdfcccc2018-10-05 20:58:37 +010045 /// True if force-vector-interleave was specified by the user.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010046 static bool isInterleaveForced();
47
Andrew Scullcdfcccc2018-10-05 20:58:37 +010048 /// \When performing memory disambiguation checks at runtime do not
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010049 /// make more than this number of comparisons.
50 static unsigned RuntimeMemoryCheckThreshold;
51};
52
Andrew Scullcdfcccc2018-10-05 20:58:37 +010053/// Checks memory dependences among accesses to the same underlying
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010054/// object to determine whether there vectorization is legal or not (and at
55/// which vectorization factor).
56///
57/// Note: This class will compute a conservative dependence for access to
58/// different underlying pointers. Clients, such as the loop vectorizer, will
59/// sometimes deal these potential dependencies by emitting runtime checks.
60///
61/// We use the ScalarEvolution framework to symbolically evalutate access
62/// functions pairs. Since we currently don't restructure the loop we can rely
63/// on the program order of memory accesses to determine their safety.
64/// At the moment we will only deem accesses as safe for:
65/// * A negative constant distance assuming program order.
66///
67/// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
68/// a[i] = tmp; y = a[i];
69///
70/// The latter case is safe because later checks guarantuee that there can't
71/// be a cycle through a phi node (that is, we check that "x" and "y" is not
72/// the same variable: a header phi can only be an induction or a reduction, a
73/// reduction can't have a memory sink, an induction can't have a memory
74/// source). This is important and must not be violated (or we have to
75/// resort to checking for cycles through memory).
76///
77/// * A positive constant distance assuming program order that is bigger
78/// than the biggest memory access.
79///
80/// tmp = a[i] OR b[i] = x
81/// a[i+2] = tmp y = b[i+2];
82///
83/// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
84///
85/// * Zero distances and all accesses have the same size.
86///
87class MemoryDepChecker {
88public:
89 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
90 typedef SmallVector<MemAccessInfo, 8> MemAccessInfoList;
Andrew Scullcdfcccc2018-10-05 20:58:37 +010091 /// Set of potential dependent memory accesses.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010092 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
93
Andrew Walbran16937d02019-10-22 13:54:20 +010094 /// Type to keep track of the status of the dependence check. The order of
95 /// the elements is important and has to be from most permissive to least
96 /// permissive.
97 enum class VectorizationSafetyStatus {
98 // Can vectorize safely without RT checks. All dependences are known to be
99 // safe.
100 Safe,
101 // Can possibly vectorize with RT checks to overcome unknown dependencies.
102 PossiblySafeWithRtChecks,
103 // Cannot vectorize due to known unsafe dependencies.
104 Unsafe,
105 };
106
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100107 /// Dependece between memory access instructions.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100108 struct Dependence {
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100109 /// The type of the dependence.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100110 enum DepType {
111 // No dependence.
112 NoDep,
113 // We couldn't determine the direction or the distance.
114 Unknown,
115 // Lexically forward.
116 //
117 // FIXME: If we only have loop-independent forward dependences (e.g. a
118 // read and write of A[i]), LAA will locally deem the dependence "safe"
119 // without querying the MemoryDepChecker. Therefore we can miss
120 // enumerating loop-independent forward dependences in
121 // getDependences. Note that as soon as there are different
122 // indices used to access the same array, the MemoryDepChecker *is*
123 // queried and the dependence list is complete.
124 Forward,
125 // Forward, but if vectorized, is likely to prevent store-to-load
126 // forwarding.
127 ForwardButPreventsForwarding,
128 // Lexically backward.
129 Backward,
130 // Backward, but the distance allows a vectorization factor of
131 // MaxSafeDepDistBytes.
132 BackwardVectorizable,
133 // Same, but may prevent store-to-load forwarding.
134 BackwardVectorizableButPreventsForwarding
135 };
136
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100137 /// String version of the types.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100138 static const char *DepName[];
139
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100140 /// Index of the source of the dependence in the InstMap vector.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100141 unsigned Source;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100142 /// Index of the destination of the dependence in the InstMap vector.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100143 unsigned Destination;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100144 /// The type of the dependence.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100145 DepType Type;
146
147 Dependence(unsigned Source, unsigned Destination, DepType Type)
148 : Source(Source), Destination(Destination), Type(Type) {}
149
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100150 /// Return the source instruction of the dependence.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100151 Instruction *getSource(const LoopAccessInfo &LAI) const;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100152 /// Return the destination instruction of the dependence.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100153 Instruction *getDestination(const LoopAccessInfo &LAI) const;
154
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100155 /// Dependence types that don't prevent vectorization.
Andrew Walbran16937d02019-10-22 13:54:20 +0100156 static VectorizationSafetyStatus isSafeForVectorization(DepType Type);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100157
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100158 /// Lexically forward dependence.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100159 bool isForward() const;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100160 /// Lexically backward dependence.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100161 bool isBackward() const;
162
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100163 /// May be a lexically backward dependence type (includes Unknown).
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100164 bool isPossiblyBackward() const;
165
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100166 /// Print the dependence. \p Instr is used to map the instruction
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100167 /// indices to instructions.
168 void print(raw_ostream &OS, unsigned Depth,
169 const SmallVectorImpl<Instruction *> &Instrs) const;
170 };
171
172 MemoryDepChecker(PredicatedScalarEvolution &PSE, const Loop *L)
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200173 : PSE(PSE), InnermostLoop(L), AccessIdx(0), MaxSafeDepDistBytes(0),
174 MaxSafeVectorWidthInBits(-1U),
Andrew Walbran16937d02019-10-22 13:54:20 +0100175 FoundNonConstantDistanceDependence(false),
176 Status(VectorizationSafetyStatus::Safe), RecordDependences(true) {}
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100177
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100178 /// Register the location (instructions are given increasing numbers)
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100179 /// of a write access.
180 void addAccess(StoreInst *SI) {
181 Value *Ptr = SI->getPointerOperand();
182 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
183 InstMap.push_back(SI);
184 ++AccessIdx;
185 }
186
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100187 /// Register the location (instructions are given increasing numbers)
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100188 /// of a write access.
189 void addAccess(LoadInst *LI) {
190 Value *Ptr = LI->getPointerOperand();
191 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
192 InstMap.push_back(LI);
193 ++AccessIdx;
194 }
195
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100196 /// Check whether the dependencies between the accesses are safe.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100197 ///
198 /// Only checks sets with elements in \p CheckDeps.
199 bool areDepsSafe(DepCandidates &AccessSets, MemAccessInfoList &CheckDeps,
200 const ValueToValueMap &Strides);
201
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100202 /// No memory dependence was encountered that would inhibit
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100203 /// vectorization.
Andrew Walbran16937d02019-10-22 13:54:20 +0100204 bool isSafeForVectorization() const {
205 return Status == VectorizationSafetyStatus::Safe;
206 }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100207
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200208 /// Return true if the number of elements that are safe to operate on
209 /// simultaneously is not bounded.
210 bool isSafeForAnyVectorWidth() const {
211 return MaxSafeVectorWidthInBits == UINT_MAX;
212 }
213
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100214 /// The maximum number of bytes of a vector register we can vectorize
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100215 /// the accesses safely with.
216 uint64_t getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
217
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100218 /// Return the number of elements that are safe to operate on
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100219 /// simultaneously, multiplied by the size of the element in bits.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200220 uint64_t getMaxSafeVectorWidthInBits() const {
221 return MaxSafeVectorWidthInBits;
222 }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100223
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100224 /// In same cases when the dependency check fails we can still
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100225 /// vectorize the loop with a dynamic array access check.
Andrew Walbran16937d02019-10-22 13:54:20 +0100226 bool shouldRetryWithRuntimeCheck() const {
227 return FoundNonConstantDistanceDependence &&
228 Status == VectorizationSafetyStatus::PossiblySafeWithRtChecks;
229 }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100230
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100231 /// Returns the memory dependences. If null is returned we exceeded
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100232 /// the MaxDependences threshold and this information is not
233 /// available.
234 const SmallVectorImpl<Dependence> *getDependences() const {
235 return RecordDependences ? &Dependences : nullptr;
236 }
237
238 void clearDependences() { Dependences.clear(); }
239
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100240 /// The vector of memory access instructions. The indices are used as
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100241 /// instruction identifiers in the Dependence class.
242 const SmallVectorImpl<Instruction *> &getMemoryInstructions() const {
243 return InstMap;
244 }
245
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100246 /// Generate a mapping between the memory instructions and their
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100247 /// indices according to program order.
248 DenseMap<Instruction *, unsigned> generateInstructionOrderMap() const {
249 DenseMap<Instruction *, unsigned> OrderMap;
250
251 for (unsigned I = 0; I < InstMap.size(); ++I)
252 OrderMap[InstMap[I]] = I;
253
254 return OrderMap;
255 }
256
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100257 /// Find the set of instructions that read or write via \p Ptr.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100258 SmallVector<Instruction *, 4> getInstructionsForAccess(Value *Ptr,
259 bool isWrite) const;
260
261private:
262 /// A wrapper around ScalarEvolution, used to add runtime SCEV checks, and
263 /// applies dynamic knowledge to simplify SCEV expressions and convert them
264 /// to a more usable form. We need this in case assumptions about SCEV
265 /// expressions need to be made in order to avoid unknown dependences. For
266 /// example we might assume a unit stride for a pointer in order to prove
267 /// that a memory access is strided and doesn't wrap.
268 PredicatedScalarEvolution &PSE;
269 const Loop *InnermostLoop;
270
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100271 /// Maps access locations (ptr, read/write) to program order.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100272 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
273
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100274 /// Memory access instructions in program order.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100275 SmallVector<Instruction *, 16> InstMap;
276
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100277 /// The program order index to be used for the next instruction.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100278 unsigned AccessIdx;
279
280 // We can access this many bytes in parallel safely.
281 uint64_t MaxSafeDepDistBytes;
282
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100283 /// Number of elements (from consecutive iterations) that are safe to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100284 /// operate on simultaneously, multiplied by the size of the element in bits.
285 /// The size of the element is taken from the memory access that is most
286 /// restrictive.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200287 uint64_t MaxSafeVectorWidthInBits;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100288
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100289 /// If we see a non-constant dependence distance we can still try to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100290 /// vectorize this loop with runtime checks.
Andrew Walbran16937d02019-10-22 13:54:20 +0100291 bool FoundNonConstantDistanceDependence;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100292
Andrew Walbran16937d02019-10-22 13:54:20 +0100293 /// Result of the dependence checks, indicating whether the checked
294 /// dependences are safe for vectorization, require RT checks or are known to
295 /// be unsafe.
296 VectorizationSafetyStatus Status;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100297
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100298 //// True if Dependences reflects the dependences in the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100299 //// loop. If false we exceeded MaxDependences and
300 //// Dependences is invalid.
301 bool RecordDependences;
302
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100303 /// Memory dependences collected during the analysis. Only valid if
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100304 /// RecordDependences is true.
305 SmallVector<Dependence, 8> Dependences;
306
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100307 /// Check whether there is a plausible dependence between the two
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100308 /// accesses.
309 ///
310 /// Access \p A must happen before \p B in program order. The two indices
311 /// identify the index into the program order map.
312 ///
313 /// This function checks whether there is a plausible dependence (or the
314 /// absence of such can't be proved) between the two accesses. If there is a
315 /// plausible dependence but the dependence distance is bigger than one
316 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
317 /// distance is smaller than any other distance encountered so far).
318 /// Otherwise, this function returns true signaling a possible dependence.
319 Dependence::DepType isDependent(const MemAccessInfo &A, unsigned AIdx,
320 const MemAccessInfo &B, unsigned BIdx,
321 const ValueToValueMap &Strides);
322
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100323 /// Check whether the data dependence could prevent store-load
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100324 /// forwarding.
325 ///
326 /// \return false if we shouldn't vectorize at all or avoid larger
327 /// vectorization factors by limiting MaxSafeDepDistBytes.
328 bool couldPreventStoreLoadForward(uint64_t Distance, uint64_t TypeByteSize);
Andrew Walbran16937d02019-10-22 13:54:20 +0100329
330 /// Updates the current safety status with \p S. We can go from Safe to
331 /// either PossiblySafeWithRtChecks or Unsafe and from
332 /// PossiblySafeWithRtChecks to Unsafe.
333 void mergeInStatus(VectorizationSafetyStatus S);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100334};
335
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200336class RuntimePointerChecking;
337/// A grouping of pointers. A single memcheck is required between
338/// two groups.
339struct RuntimeCheckingPtrGroup {
340 /// Create a new pointer checking group containing a single
341 /// pointer, with index \p Index in RtCheck.
342 RuntimeCheckingPtrGroup(unsigned Index, RuntimePointerChecking &RtCheck);
343
344 /// Tries to add the pointer recorded in RtCheck at index
345 /// \p Index to this pointer checking group. We can only add a pointer
346 /// to a checking group if we will still be able to get
347 /// the upper and lower bounds of the check. Returns true in case
348 /// of success, false otherwise.
349 bool addPointer(unsigned Index);
350
351 /// Constitutes the context of this pointer checking group. For each
352 /// pointer that is a member of this group we will retain the index
353 /// at which it appears in RtCheck.
354 RuntimePointerChecking &RtCheck;
355 /// The SCEV expression which represents the upper bound of all the
356 /// pointers in this group.
357 const SCEV *High;
358 /// The SCEV expression which represents the lower bound of all the
359 /// pointers in this group.
360 const SCEV *Low;
361 /// Indices of all the pointers that constitute this grouping.
362 SmallVector<unsigned, 2> Members;
363};
364
365/// A memcheck which made up of a pair of grouped pointers.
366typedef std::pair<const RuntimeCheckingPtrGroup *,
367 const RuntimeCheckingPtrGroup *>
368 RuntimePointerCheck;
369
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100370/// Holds information about the memory runtime legality checks to verify
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100371/// that a group of pointers do not overlap.
372class RuntimePointerChecking {
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200373 friend struct RuntimeCheckingPtrGroup;
374
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100375public:
376 struct PointerInfo {
377 /// Holds the pointer value that we need to check.
378 TrackingVH<Value> PointerValue;
379 /// Holds the smallest byte address accessed by the pointer throughout all
380 /// iterations of the loop.
381 const SCEV *Start;
382 /// Holds the largest byte address accessed by the pointer throughout all
383 /// iterations of the loop, plus 1.
384 const SCEV *End;
385 /// Holds the information if this pointer is used for writing to memory.
386 bool IsWritePtr;
387 /// Holds the id of the set of pointers that could be dependent because of a
388 /// shared underlying object.
389 unsigned DependencySetId;
390 /// Holds the id of the disjoint alias set to which this pointer belongs.
391 unsigned AliasSetId;
392 /// SCEV for the access.
393 const SCEV *Expr;
394
395 PointerInfo(Value *PointerValue, const SCEV *Start, const SCEV *End,
396 bool IsWritePtr, unsigned DependencySetId, unsigned AliasSetId,
397 const SCEV *Expr)
398 : PointerValue(PointerValue), Start(Start), End(End),
399 IsWritePtr(IsWritePtr), DependencySetId(DependencySetId),
400 AliasSetId(AliasSetId), Expr(Expr) {}
401 };
402
403 RuntimePointerChecking(ScalarEvolution *SE) : Need(false), SE(SE) {}
404
405 /// Reset the state of the pointer runtime information.
406 void reset() {
407 Need = false;
408 Pointers.clear();
409 Checks.clear();
410 }
411
412 /// Insert a pointer and calculate the start and end SCEVs.
413 /// We need \p PSE in order to compute the SCEV expression of the pointer
414 /// according to the assumptions that we've made during the analysis.
415 /// The method might also version the pointer stride according to \p Strides,
416 /// and add new predicates to \p PSE.
417 void insert(Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
418 unsigned ASId, const ValueToValueMap &Strides,
419 PredicatedScalarEvolution &PSE);
420
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100421 /// No run-time memory checking is necessary.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100422 bool empty() const { return Pointers.empty(); }
423
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100424 /// Generate the checks and store it. This also performs the grouping
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100425 /// of pointers to reduce the number of memchecks necessary.
426 void generateChecks(MemoryDepChecker::DepCandidates &DepCands,
427 bool UseDependencies);
428
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100429 /// Returns the checks that generateChecks created.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200430 const SmallVectorImpl<RuntimePointerCheck> &getChecks() const {
431 return Checks;
432 }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100433
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100434 /// Decide if we need to add a check between two groups of pointers,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100435 /// according to needsChecking.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200436 bool needsChecking(const RuntimeCheckingPtrGroup &M,
437 const RuntimeCheckingPtrGroup &N) const;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100438
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100439 /// Returns the number of run-time checks required according to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100440 /// needsChecking.
441 unsigned getNumberOfChecks() const { return Checks.size(); }
442
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100443 /// Print the list run-time memory checks necessary.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100444 void print(raw_ostream &OS, unsigned Depth = 0) const;
445
446 /// Print \p Checks.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200447 void printChecks(raw_ostream &OS,
448 const SmallVectorImpl<RuntimePointerCheck> &Checks,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100449 unsigned Depth = 0) const;
450
451 /// This flag indicates if we need to add the runtime check.
452 bool Need;
453
454 /// Information about the pointers that may require checking.
455 SmallVector<PointerInfo, 2> Pointers;
456
457 /// Holds a partitioning of pointers into "check groups".
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200458 SmallVector<RuntimeCheckingPtrGroup, 2> CheckingGroups;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100459
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100460 /// Check if pointers are in the same partition
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100461 ///
462 /// \p PtrToPartition contains the partition number for pointers (-1 if the
463 /// pointer belongs to multiple partitions).
464 static bool
465 arePointersInSamePartition(const SmallVectorImpl<int> &PtrToPartition,
466 unsigned PtrIdx1, unsigned PtrIdx2);
467
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100468 /// Decide whether we need to issue a run-time check for pointer at
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100469 /// index \p I and \p J to prove their independence.
470 bool needsChecking(unsigned I, unsigned J) const;
471
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100472 /// Return PointerInfo for pointer at index \p PtrIdx.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100473 const PointerInfo &getPointerInfo(unsigned PtrIdx) const {
474 return Pointers[PtrIdx];
475 }
476
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200477 ScalarEvolution *getSE() const { return SE; }
478
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100479private:
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100480 /// Groups pointers such that a single memcheck is required
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100481 /// between two different groups. This will clear the CheckingGroups vector
482 /// and re-compute it. We will only group dependecies if \p UseDependencies
483 /// is true, otherwise we will create a separate group for each pointer.
484 void groupChecks(MemoryDepChecker::DepCandidates &DepCands,
485 bool UseDependencies);
486
487 /// Generate the checks and return them.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200488 SmallVector<RuntimePointerCheck, 4> generateChecks() const;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100489
490 /// Holds a pointer to the ScalarEvolution analysis.
491 ScalarEvolution *SE;
492
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100493 /// Set of run-time checks required to establish independence of
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100494 /// otherwise may-aliasing pointers in the loop.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200495 SmallVector<RuntimePointerCheck, 4> Checks;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100496};
497
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100498/// Drive the analysis of memory accesses in the loop
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100499///
500/// This class is responsible for analyzing the memory accesses of a loop. It
501/// collects the accesses and then its main helper the AccessAnalysis class
502/// finds and categorizes the dependences in buildDependenceSets.
503///
504/// For memory dependences that can be analyzed at compile time, it determines
505/// whether the dependence is part of cycle inhibiting vectorization. This work
506/// is delegated to the MemoryDepChecker class.
507///
508/// For memory dependences that cannot be determined at compile time, it
509/// generates run-time checks to prove independence. This is done by
510/// AccessAnalysis::canCheckPtrAtRT and the checks are maintained by the
511/// RuntimePointerCheck class.
512///
513/// If pointers can wrap or can't be expressed as affine AddRec expressions by
514/// ScalarEvolution, we will generate run-time checks by emitting a
515/// SCEVUnionPredicate.
516///
517/// Checks for both memory dependences and the SCEV predicates contained in the
518/// PSE must be emitted in order for the results of this analysis to be valid.
519class LoopAccessInfo {
520public:
521 LoopAccessInfo(Loop *L, ScalarEvolution *SE, const TargetLibraryInfo *TLI,
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200522 AAResults *AA, DominatorTree *DT, LoopInfo *LI);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100523
524 /// Return true we can analyze the memory accesses in the loop and there are
525 /// no memory dependence cycles.
526 bool canVectorizeMemory() const { return CanVecMem; }
527
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100528 /// Return true if there is a convergent operation in the loop. There may
529 /// still be reported runtime pointer checks that would be required, but it is
530 /// not legal to insert them.
531 bool hasConvergentOp() const { return HasConvergentOp; }
532
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100533 const RuntimePointerChecking *getRuntimePointerChecking() const {
534 return PtrRtChecking.get();
535 }
536
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100537 /// Number of memchecks required to prove independence of otherwise
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100538 /// may-alias pointers.
539 unsigned getNumRuntimePointerChecks() const {
540 return PtrRtChecking->getNumberOfChecks();
541 }
542
543 /// Return true if the block BB needs to be predicated in order for the loop
544 /// to be vectorized.
545 static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
546 DominatorTree *DT);
547
548 /// Returns true if the value V is uniform within the loop.
549 bool isUniform(Value *V) const;
550
551 uint64_t getMaxSafeDepDistBytes() const { return MaxSafeDepDistBytes; }
552 unsigned getNumStores() const { return NumStores; }
553 unsigned getNumLoads() const { return NumLoads;}
554
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100555 /// The diagnostics report generated for the analysis. E.g. why we
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100556 /// couldn't analyze the loop.
557 const OptimizationRemarkAnalysis *getReport() const { return Report.get(); }
558
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100559 /// the Memory Dependence Checker which can determine the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100560 /// loop-independent and loop-carried dependences between memory accesses.
561 const MemoryDepChecker &getDepChecker() const { return *DepChecker; }
562
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100563 /// Return the list of instructions that use \p Ptr to read or write
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100564 /// memory.
565 SmallVector<Instruction *, 4> getInstructionsForAccess(Value *Ptr,
566 bool isWrite) const {
567 return DepChecker->getInstructionsForAccess(Ptr, isWrite);
568 }
569
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100570 /// If an access has a symbolic strides, this maps the pointer value to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100571 /// the stride symbol.
572 const ValueToValueMap &getSymbolicStrides() const { return SymbolicStrides; }
573
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100574 /// Pointer has a symbolic stride.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100575 bool hasStride(Value *V) const { return StrideSet.count(V); }
576
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100577 /// Print the information about the memory accesses in the loop.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100578 void print(raw_ostream &OS, unsigned Depth = 0) const;
579
Andrew Walbran16937d02019-10-22 13:54:20 +0100580 /// If the loop has memory dependence involving an invariant address, i.e. two
581 /// stores or a store and a load, then return true, else return false.
582 bool hasDependenceInvolvingLoopInvariantAddress() const {
583 return HasDependenceInvolvingLoopInvariantAddress;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100584 }
585
586 /// Used to add runtime SCEV checks. Simplifies SCEV expressions and converts
587 /// them to a more usable form. All SCEV expressions during the analysis
588 /// should be re-written (and therefore simplified) according to PSE.
589 /// A user of LoopAccessAnalysis will need to emit the runtime checks
590 /// associated with this predicate.
591 const PredicatedScalarEvolution &getPSE() const { return *PSE; }
592
593private:
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100594 /// Analyze the loop.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200595 void analyzeLoop(AAResults *AA, LoopInfo *LI,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100596 const TargetLibraryInfo *TLI, DominatorTree *DT);
597
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100598 /// Check if the structure of the loop allows it to be analyzed by this
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100599 /// pass.
600 bool canAnalyzeLoop();
601
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100602 /// Save the analysis remark.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100603 ///
604 /// LAA does not directly emits the remarks. Instead it stores it which the
605 /// client can retrieve and presents as its own analysis
606 /// (e.g. -Rpass-analysis=loop-vectorize).
607 OptimizationRemarkAnalysis &recordAnalysis(StringRef RemarkName,
608 Instruction *Instr = nullptr);
609
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100610 /// Collect memory access with loop invariant strides.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100611 ///
612 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
613 /// invariant.
614 void collectStridedAccess(Value *LoadOrStoreInst);
615
616 std::unique_ptr<PredicatedScalarEvolution> PSE;
617
618 /// We need to check that all of the pointers in this list are disjoint
619 /// at runtime. Using std::unique_ptr to make using move ctor simpler.
620 std::unique_ptr<RuntimePointerChecking> PtrRtChecking;
621
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100622 /// the Memory Dependence Checker which can determine the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100623 /// loop-independent and loop-carried dependences between memory accesses.
624 std::unique_ptr<MemoryDepChecker> DepChecker;
625
626 Loop *TheLoop;
627
628 unsigned NumLoads;
629 unsigned NumStores;
630
631 uint64_t MaxSafeDepDistBytes;
632
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100633 /// Cache the result of analyzeLoop.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100634 bool CanVecMem;
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100635 bool HasConvergentOp;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100636
Andrew Walbran16937d02019-10-22 13:54:20 +0100637 /// Indicator that there are non vectorizable stores to a uniform address.
638 bool HasDependenceInvolvingLoopInvariantAddress;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100639
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100640 /// The diagnostics report generated for the analysis. E.g. why we
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100641 /// couldn't analyze the loop.
642 std::unique_ptr<OptimizationRemarkAnalysis> Report;
643
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100644 /// If an access has a symbolic strides, this maps the pointer value to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100645 /// the stride symbol.
646 ValueToValueMap SymbolicStrides;
647
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100648 /// Set of symbolic strides values.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100649 SmallPtrSet<Value *, 8> StrideSet;
650};
651
652Value *stripIntegerCast(Value *V);
653
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100654/// Return the SCEV corresponding to a pointer with the symbolic stride
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100655/// replaced with constant one, assuming the SCEV predicate associated with
656/// \p PSE is true.
657///
658/// If necessary this method will version the stride of the pointer according
659/// to \p PtrToStride and therefore add further predicates to \p PSE.
660///
661/// If \p OrigPtr is not null, use it to look up the stride value instead of \p
662/// Ptr. \p PtrToStride provides the mapping between the pointer value and its
663/// stride as collected by LoopVectorizationLegality::collectStridedAccess.
664const SCEV *replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
665 const ValueToValueMap &PtrToStride,
666 Value *Ptr, Value *OrigPtr = nullptr);
667
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100668/// If the pointer has a constant stride return it in units of its
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100669/// element size. Otherwise return zero.
670///
671/// Ensure that it does not wrap in the address space, assuming the predicate
672/// associated with \p PSE is true.
673///
674/// If necessary this method will version the stride of the pointer according
675/// to \p PtrToStride and therefore add further predicates to \p PSE.
676/// The \p Assume parameter indicates if we are allowed to make additional
677/// run-time assumptions.
678int64_t getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr, const Loop *Lp,
679 const ValueToValueMap &StridesMap = ValueToValueMap(),
680 bool Assume = false, bool ShouldCheckWrap = true);
681
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100682/// Attempt to sort the pointers in \p VL and return the sorted indices
683/// in \p SortedIndices, if reordering is required.
684///
685/// Returns 'true' if sorting is legal, otherwise returns 'false'.
686///
687/// For example, for a given \p VL of memory accesses in program order, a[i+4],
688/// a[i+0], a[i+1] and a[i+7], this function will sort the \p VL and save the
689/// sorted indices in \p SortedIndices as a[i+0], a[i+1], a[i+4], a[i+7] and
690/// saves the mask for actual memory accesses in program order in
691/// \p SortedIndices as <1,2,0,3>
692bool sortPtrAccesses(ArrayRef<Value *> VL, const DataLayout &DL,
693 ScalarEvolution &SE,
694 SmallVectorImpl<unsigned> &SortedIndices);
695
696/// Returns true if the memory operations \p A and \p B are consecutive.
697/// This is a simple API that does not depend on the analysis pass.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100698bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
699 ScalarEvolution &SE, bool CheckType = true);
700
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100701/// This analysis provides dependence information for the memory accesses
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100702/// of a loop.
703///
704/// It runs the analysis for a loop on demand. This can be initiated by
705/// querying the loop access info via LAA::getInfo. getInfo return a
706/// LoopAccessInfo object. See this class for the specifics of what information
707/// is provided.
708class LoopAccessLegacyAnalysis : public FunctionPass {
709public:
710 static char ID;
711
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200712 LoopAccessLegacyAnalysis();
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100713
714 bool runOnFunction(Function &F) override;
715
716 void getAnalysisUsage(AnalysisUsage &AU) const override;
717
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100718 /// Query the result of the loop access information for the loop \p L.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100719 ///
720 /// If there is no cached result available run the analysis.
721 const LoopAccessInfo &getInfo(Loop *L);
722
723 void releaseMemory() override {
724 // Invalidate the cache when the pass is freed.
725 LoopAccessInfoMap.clear();
726 }
727
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100728 /// Print the result of the analysis when invoked with -analyze.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100729 void print(raw_ostream &OS, const Module *M = nullptr) const override;
730
731private:
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100732 /// The cache.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100733 DenseMap<Loop *, std::unique_ptr<LoopAccessInfo>> LoopAccessInfoMap;
734
735 // The used analysis passes.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200736 ScalarEvolution *SE = nullptr;
737 const TargetLibraryInfo *TLI = nullptr;
738 AAResults *AA = nullptr;
739 DominatorTree *DT = nullptr;
740 LoopInfo *LI = nullptr;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100741};
742
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100743/// This analysis provides dependence information for the memory
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100744/// accesses of a loop.
745///
746/// It runs the analysis for a loop on demand. This can be initiated by
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100747/// querying the loop access info via AM.getResult<LoopAccessAnalysis>.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100748/// getResult return a LoopAccessInfo object. See this class for the
749/// specifics of what information is provided.
750class LoopAccessAnalysis
751 : public AnalysisInfoMixin<LoopAccessAnalysis> {
752 friend AnalysisInfoMixin<LoopAccessAnalysis>;
753 static AnalysisKey Key;
754
755public:
756 typedef LoopAccessInfo Result;
757
758 Result run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR);
759};
760
761inline Instruction *MemoryDepChecker::Dependence::getSource(
762 const LoopAccessInfo &LAI) const {
763 return LAI.getDepChecker().getMemoryInstructions()[Source];
764}
765
766inline Instruction *MemoryDepChecker::Dependence::getDestination(
767 const LoopAccessInfo &LAI) const {
768 return LAI.getDepChecker().getMemoryInstructions()[Destination];
769}
770
771} // End llvm namespace
772
773#endif