LoopAccessAnalysis.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774
  1. //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // The implementation for the loop memory dependence that was originally
  11. // developed for the loop vectorizer.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Analysis/LoopAccessAnalysis.h"
  15. #include "llvm/Analysis/LoopInfo.h"
  16. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  17. #include "llvm/Analysis/TargetLibraryInfo.h"
  18. #include "llvm/Analysis/ValueTracking.h"
  19. #include "llvm/IR/DiagnosticInfo.h"
  20. #include "llvm/IR/Dominators.h"
  21. #include "llvm/IR/IRBuilder.h"
  22. #include "llvm/Support/Debug.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. #include "llvm/Analysis/VectorUtils.h"
  25. using namespace llvm;
  26. #define DEBUG_TYPE "loop-accesses"
  27. static cl::opt<unsigned, true>
  28. VectorizationFactor("force-vector-width", cl::Hidden,
  29. cl::desc("Sets the SIMD width. Zero is autoselect."),
  30. cl::location(VectorizerParams::VectorizationFactor));
  31. unsigned VectorizerParams::VectorizationFactor;
  32. static cl::opt<unsigned, true>
  33. VectorizationInterleave("force-vector-interleave", cl::Hidden,
  34. cl::desc("Sets the vectorization interleave count. "
  35. "Zero is autoselect."),
  36. cl::location(
  37. VectorizerParams::VectorizationInterleave));
  38. unsigned VectorizerParams::VectorizationInterleave;
  39. static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
  40. "runtime-memory-check-threshold", cl::Hidden,
  41. cl::desc("When performing memory disambiguation checks at runtime do not "
  42. "generate more than this number of comparisons (default = 8)."),
  43. cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
  44. unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
  45. /// \brief The maximum iterations used to merge memory checks
  46. static cl::opt<unsigned> MemoryCheckMergeThreshold(
  47. "memory-check-merge-threshold", cl::Hidden,
  48. cl::desc("Maximum number of comparisons done when trying to merge "
  49. "runtime memory checks. (default = 100)"),
  50. cl::init(100));
  51. /// Maximum SIMD width.
  52. const unsigned VectorizerParams::MaxVectorWidth = 64;
  53. /// \brief We collect interesting dependences up to this threshold.
  54. static cl::opt<unsigned> MaxInterestingDependence(
  55. "max-interesting-dependences", cl::Hidden,
  56. cl::desc("Maximum number of interesting dependences collected by "
  57. "loop-access analysis (default = 100)"),
  58. cl::init(100));
  59. bool VectorizerParams::isInterleaveForced() {
  60. return ::VectorizationInterleave.getNumOccurrences() > 0;
  61. }
  62. void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
  63. const Function *TheFunction,
  64. const Loop *TheLoop,
  65. const char *PassName) {
  66. DebugLoc DL = TheLoop->getStartLoc();
  67. if (const Instruction *I = Message.getInstr())
  68. DL = I->getDebugLoc();
  69. emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
  70. *TheFunction, DL, Message.str());
  71. }
  72. Value *llvm::stripIntegerCast(Value *V) {
  73. if (CastInst *CI = dyn_cast<CastInst>(V))
  74. if (CI->getOperand(0)->getType()->isIntegerTy())
  75. return CI->getOperand(0);
  76. return V;
  77. }
  78. const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
  79. const ValueToValueMap &PtrToStride,
  80. Value *Ptr, Value *OrigPtr) {
  81. const SCEV *OrigSCEV = SE->getSCEV(Ptr);
  82. // If there is an entry in the map return the SCEV of the pointer with the
  83. // symbolic stride replaced by one.
  84. ValueToValueMap::const_iterator SI =
  85. PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
  86. if (SI != PtrToStride.end()) {
  87. Value *StrideVal = SI->second;
  88. // Strip casts.
  89. StrideVal = stripIntegerCast(StrideVal);
  90. // Replace symbolic stride by one.
  91. Value *One = ConstantInt::get(StrideVal->getType(), 1);
  92. ValueToValueMap RewriteMap;
  93. RewriteMap[StrideVal] = One;
  94. const SCEV *ByOne =
  95. SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
  96. DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
  97. << "\n");
  98. return ByOne;
  99. }
  100. // Otherwise, just return the SCEV of the original pointer.
  101. return SE->getSCEV(Ptr);
  102. }
  103. void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
  104. unsigned DepSetId, unsigned ASId,
  105. const ValueToValueMap &Strides) {
  106. // Get the stride replaced scev.
  107. const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
  108. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
  109. assert(AR && "Invalid addrec expression");
  110. const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
  111. const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
  112. Pointers.emplace_back(Ptr, AR->getStart(), ScEnd, WritePtr, DepSetId, ASId,
  113. Sc);
  114. }
  115. bool RuntimePointerChecking::needsChecking(
  116. const CheckingPtrGroup &M, const CheckingPtrGroup &N,
  117. const SmallVectorImpl<int> *PtrPartition) const {
  118. for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
  119. for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
  120. if (needsChecking(M.Members[I], N.Members[J], PtrPartition))
  121. return true;
  122. return false;
  123. }
  124. /// Compare \p I and \p J and return the minimum.
  125. /// Return nullptr in case we couldn't find an answer.
  126. static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
  127. ScalarEvolution *SE) {
  128. const SCEV *Diff = SE->getMinusSCEV(J, I);
  129. const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
  130. if (!C)
  131. return nullptr;
  132. if (C->getValue()->isNegative())
  133. return J;
  134. return I;
  135. }
  136. bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
  137. const SCEV *Start = RtCheck.Pointers[Index].Start;
  138. const SCEV *End = RtCheck.Pointers[Index].End;
  139. // Compare the starts and ends with the known minimum and maximum
  140. // of this set. We need to know how we compare against the min/max
  141. // of the set in order to be able to emit memchecks.
  142. const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
  143. if (!Min0)
  144. return false;
  145. const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
  146. if (!Min1)
  147. return false;
  148. // Update the low bound expression if we've found a new min value.
  149. if (Min0 == Start)
  150. Low = Start;
  151. // Update the high bound expression if we've found a new max value.
  152. if (Min1 != End)
  153. High = End;
  154. Members.push_back(Index);
  155. return true;
  156. }
  157. void RuntimePointerChecking::groupChecks(
  158. MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
  159. // We build the groups from dependency candidates equivalence classes
  160. // because:
  161. // - We know that pointers in the same equivalence class share
  162. // the same underlying object and therefore there is a chance
  163. // that we can compare pointers
  164. // - We wouldn't be able to merge two pointers for which we need
  165. // to emit a memcheck. The classes in DepCands are already
  166. // conveniently built such that no two pointers in the same
  167. // class need checking against each other.
  168. // We use the following (greedy) algorithm to construct the groups
  169. // For every pointer in the equivalence class:
  170. // For each existing group:
  171. // - if the difference between this pointer and the min/max bounds
  172. // of the group is a constant, then make the pointer part of the
  173. // group and update the min/max bounds of that group as required.
  174. CheckingGroups.clear();
  175. // If we don't have the dependency partitions, construct a new
  176. // checking pointer group for each pointer.
  177. if (!UseDependencies) {
  178. for (unsigned I = 0; I < Pointers.size(); ++I)
  179. CheckingGroups.push_back(CheckingPtrGroup(I, *this));
  180. return;
  181. }
  182. unsigned TotalComparisons = 0;
  183. DenseMap<Value *, unsigned> PositionMap;
  184. for (unsigned Index = 0; Index < Pointers.size(); ++Index)
  185. PositionMap[Pointers[Index].PointerValue] = Index;
  186. // We need to keep track of what pointers we've already seen so we
  187. // don't process them twice.
  188. SmallSet<unsigned, 2> Seen;
  189. // Go through all equivalence classes, get the the "pointer check groups"
  190. // and add them to the overall solution. We use the order in which accesses
  191. // appear in 'Pointers' to enforce determinism.
  192. for (unsigned I = 0; I < Pointers.size(); ++I) {
  193. // We've seen this pointer before, and therefore already processed
  194. // its equivalence class.
  195. if (Seen.count(I))
  196. continue;
  197. MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
  198. Pointers[I].IsWritePtr);
  199. SmallVector<CheckingPtrGroup, 2> Groups;
  200. auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
  201. // Because DepCands is constructed by visiting accesses in the order in
  202. // which they appear in alias sets (which is deterministic) and the
  203. // iteration order within an equivalence class member is only dependent on
  204. // the order in which unions and insertions are performed on the
  205. // equivalence class, the iteration order is deterministic.
  206. for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
  207. MI != ME; ++MI) {
  208. unsigned Pointer = PositionMap[MI->getPointer()];
  209. bool Merged = false;
  210. // Mark this pointer as seen.
  211. Seen.insert(Pointer);
  212. // Go through all the existing sets and see if we can find one
  213. // which can include this pointer.
  214. for (CheckingPtrGroup &Group : Groups) {
  215. // Don't perform more than a certain amount of comparisons.
  216. // This should limit the cost of grouping the pointers to something
  217. // reasonable. If we do end up hitting this threshold, the algorithm
  218. // will create separate groups for all remaining pointers.
  219. if (TotalComparisons > MemoryCheckMergeThreshold)
  220. break;
  221. TotalComparisons++;
  222. if (Group.addPointer(Pointer)) {
  223. Merged = true;
  224. break;
  225. }
  226. }
  227. if (!Merged)
  228. // We couldn't add this pointer to any existing set or the threshold
  229. // for the number of comparisons has been reached. Create a new group
  230. // to hold the current pointer.
  231. Groups.push_back(CheckingPtrGroup(Pointer, *this));
  232. }
  233. // We've computed the grouped checks for this partition.
  234. // Save the results and continue with the next one.
  235. std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
  236. }
  237. }
  238. bool RuntimePointerChecking::needsChecking(
  239. unsigned I, unsigned J, const SmallVectorImpl<int> *PtrPartition) const {
  240. const PointerInfo &PointerI = Pointers[I];
  241. const PointerInfo &PointerJ = Pointers[J];
  242. // No need to check if two readonly pointers intersect.
  243. if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
  244. return false;
  245. // Only need to check pointers between two different dependency sets.
  246. if (PointerI.DependencySetId == PointerJ.DependencySetId)
  247. return false;
  248. // Only need to check pointers in the same alias set.
  249. if (PointerI.AliasSetId != PointerJ.AliasSetId)
  250. return false;
  251. // If PtrPartition is set omit checks between pointers of the same partition.
  252. // Partition number -1 means that the pointer is used in multiple partitions.
  253. // In this case we can't omit the check.
  254. if (PtrPartition && (*PtrPartition)[I] != -1 &&
  255. (*PtrPartition)[I] == (*PtrPartition)[J])
  256. return false;
  257. return true;
  258. }
  259. void RuntimePointerChecking::print(
  260. raw_ostream &OS, unsigned Depth,
  261. const SmallVectorImpl<int> *PtrPartition) const {
  262. OS.indent(Depth) << "Run-time memory checks:\n";
  263. unsigned N = 0;
  264. for (unsigned I = 0; I < CheckingGroups.size(); ++I)
  265. for (unsigned J = I + 1; J < CheckingGroups.size(); ++J)
  266. if (needsChecking(CheckingGroups[I], CheckingGroups[J], PtrPartition)) {
  267. OS.indent(Depth) << "Check " << N++ << ":\n";
  268. OS.indent(Depth + 2) << "Comparing group " << I << ":\n";
  269. for (unsigned K = 0; K < CheckingGroups[I].Members.size(); ++K) {
  270. OS.indent(Depth + 2)
  271. << *Pointers[CheckingGroups[I].Members[K]].PointerValue << "\n";
  272. if (PtrPartition)
  273. OS << " (Partition: "
  274. << (*PtrPartition)[CheckingGroups[I].Members[K]] << ")"
  275. << "\n";
  276. }
  277. OS.indent(Depth + 2) << "Against group " << J << ":\n";
  278. for (unsigned K = 0; K < CheckingGroups[J].Members.size(); ++K) {
  279. OS.indent(Depth + 2)
  280. << *Pointers[CheckingGroups[J].Members[K]].PointerValue << "\n";
  281. if (PtrPartition)
  282. OS << " (Partition: "
  283. << (*PtrPartition)[CheckingGroups[J].Members[K]] << ")"
  284. << "\n";
  285. }
  286. }
  287. OS.indent(Depth) << "Grouped accesses:\n";
  288. for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
  289. OS.indent(Depth + 2) << "Group " << I << ":\n";
  290. OS.indent(Depth + 4) << "(Low: " << *CheckingGroups[I].Low
  291. << " High: " << *CheckingGroups[I].High << ")\n";
  292. for (unsigned J = 0; J < CheckingGroups[I].Members.size(); ++J) {
  293. OS.indent(Depth + 6) << "Member: "
  294. << *Pointers[CheckingGroups[I].Members[J]].Expr
  295. << "\n";
  296. }
  297. }
  298. }
  299. unsigned RuntimePointerChecking::getNumberOfChecks(
  300. const SmallVectorImpl<int> *PtrPartition) const {
  301. unsigned NumPartitions = CheckingGroups.size();
  302. unsigned CheckCount = 0;
  303. for (unsigned I = 0; I < NumPartitions; ++I)
  304. for (unsigned J = I + 1; J < NumPartitions; ++J)
  305. if (needsChecking(CheckingGroups[I], CheckingGroups[J], PtrPartition))
  306. CheckCount++;
  307. return CheckCount;
  308. }
  309. bool RuntimePointerChecking::needsAnyChecking(
  310. const SmallVectorImpl<int> *PtrPartition) const {
  311. unsigned NumPointers = Pointers.size();
  312. for (unsigned I = 0; I < NumPointers; ++I)
  313. for (unsigned J = I + 1; J < NumPointers; ++J)
  314. if (needsChecking(I, J, PtrPartition))
  315. return true;
  316. return false;
  317. }
  318. namespace {
  319. /// \brief Analyses memory accesses in a loop.
  320. ///
  321. /// Checks whether run time pointer checks are needed and builds sets for data
  322. /// dependence checking.
  323. class AccessAnalysis {
  324. public:
  325. /// \brief Read or write access location.
  326. typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
  327. typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
  328. AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
  329. MemoryDepChecker::DepCandidates &DA)
  330. : DL(Dl), AST(*AA), LI(LI), DepCands(DA),
  331. IsRTCheckAnalysisNeeded(false) {}
  332. /// \brief Register a load and whether it is only read from.
  333. void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
  334. Value *Ptr = const_cast<Value*>(Loc.Ptr);
  335. AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
  336. Accesses.insert(MemAccessInfo(Ptr, false));
  337. if (IsReadOnly)
  338. ReadOnlyPtr.insert(Ptr);
  339. }
  340. /// \brief Register a store.
  341. void addStore(MemoryLocation &Loc) {
  342. Value *Ptr = const_cast<Value*>(Loc.Ptr);
  343. AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
  344. Accesses.insert(MemAccessInfo(Ptr, true));
  345. }
  346. /// \brief Check whether we can check the pointers at runtime for
  347. /// non-intersection.
  348. ///
  349. /// Returns true if we need no check or if we do and we can generate them
  350. /// (i.e. the pointers have computable bounds).
  351. bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
  352. Loop *TheLoop, const ValueToValueMap &Strides,
  353. bool ShouldCheckStride = false);
  354. /// \brief Goes over all memory accesses, checks whether a RT check is needed
  355. /// and builds sets of dependent accesses.
  356. void buildDependenceSets() {
  357. processMemAccesses();
  358. }
  359. /// \brief Initial processing of memory accesses determined that we need to
  360. /// perform dependency checking.
  361. ///
  362. /// Note that this can later be cleared if we retry memcheck analysis without
  363. /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
  364. bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
  365. /// We decided that no dependence analysis would be used. Reset the state.
  366. void resetDepChecks(MemoryDepChecker &DepChecker) {
  367. CheckDeps.clear();
  368. DepChecker.clearInterestingDependences();
  369. }
  370. MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
  371. private:
  372. typedef SetVector<MemAccessInfo> PtrAccessSet;
  373. /// \brief Go over all memory access and check whether runtime pointer checks
  374. /// are needed and build sets of dependency check candidates.
  375. void processMemAccesses();
  376. /// Set of all accesses.
  377. PtrAccessSet Accesses;
  378. const DataLayout &DL;
  379. /// Set of accesses that need a further dependence check.
  380. MemAccessInfoSet CheckDeps;
  381. /// Set of pointers that are read only.
  382. SmallPtrSet<Value*, 16> ReadOnlyPtr;
  383. /// An alias set tracker to partition the access set by underlying object and
  384. //intrinsic property (such as TBAA metadata).
  385. AliasSetTracker AST;
  386. LoopInfo *LI;
  387. /// Sets of potentially dependent accesses - members of one set share an
  388. /// underlying pointer. The set "CheckDeps" identfies which sets really need a
  389. /// dependence check.
  390. MemoryDepChecker::DepCandidates &DepCands;
  391. /// \brief Initial processing of memory accesses determined that we may need
  392. /// to add memchecks. Perform the analysis to determine the necessary checks.
  393. ///
  394. /// Note that, this is different from isDependencyCheckNeeded. When we retry
  395. /// memcheck analysis without dependency checking
  396. /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
  397. /// while this remains set if we have potentially dependent accesses.
  398. bool IsRTCheckAnalysisNeeded;
  399. };
  400. } // end anonymous namespace
  401. /// \brief Check whether a pointer can participate in a runtime bounds check.
  402. static bool hasComputableBounds(ScalarEvolution *SE,
  403. const ValueToValueMap &Strides, Value *Ptr) {
  404. const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
  405. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
  406. if (!AR)
  407. return false;
  408. return AR->isAffine();
  409. }
  410. bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
  411. ScalarEvolution *SE, Loop *TheLoop,
  412. const ValueToValueMap &StridesMap,
  413. bool ShouldCheckStride) {
  414. // Find pointers with computable bounds. We are going to use this information
  415. // to place a runtime bound check.
  416. bool CanDoRT = true;
  417. bool NeedRTCheck = false;
  418. if (!IsRTCheckAnalysisNeeded) return true;
  419. bool IsDepCheckNeeded = isDependencyCheckNeeded();
  420. // We assign a consecutive id to access from different alias sets.
  421. // Accesses between different groups doesn't need to be checked.
  422. unsigned ASId = 1;
  423. for (auto &AS : AST) {
  424. int NumReadPtrChecks = 0;
  425. int NumWritePtrChecks = 0;
  426. // We assign consecutive id to access from different dependence sets.
  427. // Accesses within the same set don't need a runtime check.
  428. unsigned RunningDepId = 1;
  429. DenseMap<Value *, unsigned> DepSetId;
  430. for (auto A : AS) {
  431. Value *Ptr = A.getValue();
  432. bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
  433. MemAccessInfo Access(Ptr, IsWrite);
  434. if (IsWrite)
  435. ++NumWritePtrChecks;
  436. else
  437. ++NumReadPtrChecks;
  438. if (hasComputableBounds(SE, StridesMap, Ptr) &&
  439. // When we run after a failing dependency check we have to make sure
  440. // we don't have wrapping pointers.
  441. (!ShouldCheckStride ||
  442. isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
  443. // The id of the dependence set.
  444. unsigned DepId;
  445. if (IsDepCheckNeeded) {
  446. Value *Leader = DepCands.getLeaderValue(Access).getPointer();
  447. unsigned &LeaderId = DepSetId[Leader];
  448. if (!LeaderId)
  449. LeaderId = RunningDepId++;
  450. DepId = LeaderId;
  451. } else
  452. // Each access has its own dependence set.
  453. DepId = RunningDepId++;
  454. RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
  455. DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
  456. } else {
  457. DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
  458. CanDoRT = false;
  459. }
  460. }
  461. // If we have at least two writes or one write and a read then we need to
  462. // check them. But there is no need to checks if there is only one
  463. // dependence set for this alias set.
  464. //
  465. // Note that this function computes CanDoRT and NeedRTCheck independently.
  466. // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
  467. // for which we couldn't find the bounds but we don't actually need to emit
  468. // any checks so it does not matter.
  469. if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
  470. NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
  471. NumWritePtrChecks >= 1));
  472. ++ASId;
  473. }
  474. // If the pointers that we would use for the bounds comparison have different
  475. // address spaces, assume the values aren't directly comparable, so we can't
  476. // use them for the runtime check. We also have to assume they could
  477. // overlap. In the future there should be metadata for whether address spaces
  478. // are disjoint.
  479. unsigned NumPointers = RtCheck.Pointers.size();
  480. for (unsigned i = 0; i < NumPointers; ++i) {
  481. for (unsigned j = i + 1; j < NumPointers; ++j) {
  482. // Only need to check pointers between two different dependency sets.
  483. if (RtCheck.Pointers[i].DependencySetId ==
  484. RtCheck.Pointers[j].DependencySetId)
  485. continue;
  486. // Only need to check pointers in the same alias set.
  487. if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
  488. continue;
  489. Value *PtrI = RtCheck.Pointers[i].PointerValue;
  490. Value *PtrJ = RtCheck.Pointers[j].PointerValue;
  491. unsigned ASi = PtrI->getType()->getPointerAddressSpace();
  492. unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
  493. if (ASi != ASj) {
  494. DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
  495. " different address spaces\n");
  496. return false;
  497. }
  498. }
  499. }
  500. if (NeedRTCheck && CanDoRT)
  501. RtCheck.groupChecks(DepCands, IsDepCheckNeeded);
  502. DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks(nullptr)
  503. << " pointer comparisons.\n");
  504. RtCheck.Need = NeedRTCheck;
  505. bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
  506. if (!CanDoRTIfNeeded)
  507. RtCheck.reset();
  508. return CanDoRTIfNeeded;
  509. }
  510. void AccessAnalysis::processMemAccesses() {
  511. // We process the set twice: first we process read-write pointers, last we
  512. // process read-only pointers. This allows us to skip dependence tests for
  513. // read-only pointers.
  514. DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
  515. DEBUG(dbgs() << " AST: "; AST.dump());
  516. DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
  517. DEBUG({
  518. for (auto A : Accesses)
  519. dbgs() << "\t" << *A.getPointer() << " (" <<
  520. (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
  521. "read-only" : "read")) << ")\n";
  522. });
  523. // The AliasSetTracker has nicely partitioned our pointers by metadata
  524. // compatibility and potential for underlying-object overlap. As a result, we
  525. // only need to check for potential pointer dependencies within each alias
  526. // set.
  527. for (auto &AS : AST) {
  528. // Note that both the alias-set tracker and the alias sets themselves used
  529. // linked lists internally and so the iteration order here is deterministic
  530. // (matching the original instruction order within each set).
  531. bool SetHasWrite = false;
  532. // Map of pointers to last access encountered.
  533. typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
  534. UnderlyingObjToAccessMap ObjToLastAccess;
  535. // Set of access to check after all writes have been processed.
  536. PtrAccessSet DeferredAccesses;
  537. // Iterate over each alias set twice, once to process read/write pointers,
  538. // and then to process read-only pointers.
  539. for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
  540. bool UseDeferred = SetIteration > 0;
  541. PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
  542. for (auto AV : AS) {
  543. Value *Ptr = AV.getValue();
  544. // For a single memory access in AliasSetTracker, Accesses may contain
  545. // both read and write, and they both need to be handled for CheckDeps.
  546. for (auto AC : S) {
  547. if (AC.getPointer() != Ptr)
  548. continue;
  549. bool IsWrite = AC.getInt();
  550. // If we're using the deferred access set, then it contains only
  551. // reads.
  552. bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
  553. if (UseDeferred && !IsReadOnlyPtr)
  554. continue;
  555. // Otherwise, the pointer must be in the PtrAccessSet, either as a
  556. // read or a write.
  557. assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
  558. S.count(MemAccessInfo(Ptr, false))) &&
  559. "Alias-set pointer not in the access set?");
  560. MemAccessInfo Access(Ptr, IsWrite);
  561. DepCands.insert(Access);
  562. // Memorize read-only pointers for later processing and skip them in
  563. // the first round (they need to be checked after we have seen all
  564. // write pointers). Note: we also mark pointer that are not
  565. // consecutive as "read-only" pointers (so that we check
  566. // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
  567. if (!UseDeferred && IsReadOnlyPtr) {
  568. DeferredAccesses.insert(Access);
  569. continue;
  570. }
  571. // If this is a write - check other reads and writes for conflicts. If
  572. // this is a read only check other writes for conflicts (but only if
  573. // there is no other write to the ptr - this is an optimization to
  574. // catch "a[i] = a[i] + " without having to do a dependence check).
  575. if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
  576. CheckDeps.insert(Access);
  577. IsRTCheckAnalysisNeeded = true;
  578. }
  579. if (IsWrite)
  580. SetHasWrite = true;
  581. // Create sets of pointers connected by a shared alias set and
  582. // underlying object.
  583. typedef SmallVector<Value *, 16> ValueVector;
  584. ValueVector TempObjects;
  585. GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
  586. DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
  587. for (Value *UnderlyingObj : TempObjects) {
  588. UnderlyingObjToAccessMap::iterator Prev =
  589. ObjToLastAccess.find(UnderlyingObj);
  590. if (Prev != ObjToLastAccess.end())
  591. DepCands.unionSets(Access, Prev->second);
  592. ObjToLastAccess[UnderlyingObj] = Access;
  593. DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
  594. }
  595. }
  596. }
  597. }
  598. }
  599. }
  600. static bool isInBoundsGep(Value *Ptr) {
  601. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
  602. return GEP->isInBounds();
  603. return false;
  604. }
  605. /// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
  606. /// i.e. monotonically increasing/decreasing.
  607. static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
  608. ScalarEvolution *SE, const Loop *L) {
  609. // FIXME: This should probably only return true for NUW.
  610. if (AR->getNoWrapFlags(SCEV::NoWrapMask))
  611. return true;
  612. // Scalar evolution does not propagate the non-wrapping flags to values that
  613. // are derived from a non-wrapping induction variable because non-wrapping
  614. // could be flow-sensitive.
  615. //
  616. // Look through the potentially overflowing instruction to try to prove
  617. // non-wrapping for the *specific* value of Ptr.
  618. // The arithmetic implied by an inbounds GEP can't overflow.
  619. auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  620. if (!GEP || !GEP->isInBounds())
  621. return false;
  622. // Make sure there is only one non-const index and analyze that.
  623. Value *NonConstIndex = nullptr;
  624. for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
  625. if (!isa<ConstantInt>(*Index)) {
  626. if (NonConstIndex)
  627. return false;
  628. NonConstIndex = *Index;
  629. }
  630. if (!NonConstIndex)
  631. // The recurrence is on the pointer, ignore for now.
  632. return false;
  633. // The index in GEP is signed. It is non-wrapping if it's derived from a NSW
  634. // AddRec using a NSW operation.
  635. if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
  636. if (OBO->hasNoSignedWrap() &&
  637. // Assume constant for other the operand so that the AddRec can be
  638. // easily found.
  639. isa<ConstantInt>(OBO->getOperand(1))) {
  640. auto *OpScev = SE->getSCEV(OBO->getOperand(0));
  641. if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
  642. return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
  643. }
  644. return false;
  645. }
  646. /// \brief Check whether the access through \p Ptr has a constant stride.
  647. int llvm::isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
  648. const ValueToValueMap &StridesMap) {
  649. const Type *Ty = Ptr->getType();
  650. assert(Ty->isPointerTy() && "Unexpected non-ptr");
  651. // Make sure that the pointer does not point to aggregate types.
  652. const PointerType *PtrTy = cast<PointerType>(Ty);
  653. if (PtrTy->getElementType()->isAggregateType()) {
  654. DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
  655. << *Ptr << "\n");
  656. return 0;
  657. }
  658. const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
  659. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
  660. if (!AR) {
  661. DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
  662. << *Ptr << " SCEV: " << *PtrScev << "\n");
  663. return 0;
  664. }
  665. // The accesss function must stride over the innermost loop.
  666. if (Lp != AR->getLoop()) {
  667. DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
  668. *Ptr << " SCEV: " << *PtrScev << "\n");
  669. }
  670. // The address calculation must not wrap. Otherwise, a dependence could be
  671. // inverted.
  672. // An inbounds getelementptr that is a AddRec with a unit stride
  673. // cannot wrap per definition. The unit stride requirement is checked later.
  674. // An getelementptr without an inbounds attribute and unit stride would have
  675. // to access the pointer value "0" which is undefined behavior in address
  676. // space 0, therefore we can also vectorize this case.
  677. bool IsInBoundsGEP = isInBoundsGep(Ptr);
  678. bool IsNoWrapAddRec = isNoWrapAddRec(Ptr, AR, SE, Lp);
  679. bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
  680. if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
  681. DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
  682. << *Ptr << " SCEV: " << *PtrScev << "\n");
  683. return 0;
  684. }
  685. // Check the step is constant.
  686. const SCEV *Step = AR->getStepRecurrence(*SE);
  687. // Calculate the pointer stride and check if it is constant.
  688. const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
  689. if (!C) {
  690. DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
  691. " SCEV: " << *PtrScev << "\n");
  692. return 0;
  693. }
  694. auto &DL = Lp->getHeader()->getModule()->getDataLayout();
  695. int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
  696. const APInt &APStepVal = C->getValue()->getValue();
  697. // Huge step value - give up.
  698. if (APStepVal.getBitWidth() > 64)
  699. return 0;
  700. int64_t StepVal = APStepVal.getSExtValue();
  701. // Strided access.
  702. int64_t Stride = StepVal / Size;
  703. int64_t Rem = StepVal % Size;
  704. if (Rem)
  705. return 0;
  706. // If the SCEV could wrap but we have an inbounds gep with a unit stride we
  707. // know we can't "wrap around the address space". In case of address space
  708. // zero we know that this won't happen without triggering undefined behavior.
  709. if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
  710. Stride != 1 && Stride != -1)
  711. return 0;
  712. return Stride;
  713. }
  714. bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
  715. switch (Type) {
  716. case NoDep:
  717. case Forward:
  718. case BackwardVectorizable:
  719. return true;
  720. case Unknown:
  721. case ForwardButPreventsForwarding:
  722. case Backward:
  723. case BackwardVectorizableButPreventsForwarding:
  724. return false;
  725. }
  726. llvm_unreachable("unexpected DepType!");
  727. }
  728. bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
  729. switch (Type) {
  730. case NoDep:
  731. case Forward:
  732. return false;
  733. case BackwardVectorizable:
  734. case Unknown:
  735. case ForwardButPreventsForwarding:
  736. case Backward:
  737. case BackwardVectorizableButPreventsForwarding:
  738. return true;
  739. }
  740. llvm_unreachable("unexpected DepType!");
  741. }
  742. bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
  743. switch (Type) {
  744. case NoDep:
  745. case Forward:
  746. case ForwardButPreventsForwarding:
  747. return false;
  748. case Unknown:
  749. case BackwardVectorizable:
  750. case Backward:
  751. case BackwardVectorizableButPreventsForwarding:
  752. return true;
  753. }
  754. llvm_unreachable("unexpected DepType!");
  755. }
  756. bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
  757. unsigned TypeByteSize) {
  758. // If loads occur at a distance that is not a multiple of a feasible vector
  759. // factor store-load forwarding does not take place.
  760. // Positive dependences might cause troubles because vectorizing them might
  761. // prevent store-load forwarding making vectorized code run a lot slower.
  762. // a[i] = a[i-3] ^ a[i-8];
  763. // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
  764. // hence on your typical architecture store-load forwarding does not take
  765. // place. Vectorizing in such cases does not make sense.
  766. // Store-load forwarding distance.
  767. const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
  768. // Maximum vector factor.
  769. unsigned MaxVFWithoutSLForwardIssues =
  770. VectorizerParams::MaxVectorWidth * TypeByteSize;
  771. if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
  772. MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
  773. for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
  774. vf *= 2) {
  775. if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
  776. MaxVFWithoutSLForwardIssues = (vf >>=1);
  777. break;
  778. }
  779. }
  780. if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
  781. DEBUG(dbgs() << "LAA: Distance " << Distance <<
  782. " that could cause a store-load forwarding conflict\n");
  783. return true;
  784. }
  785. if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
  786. MaxVFWithoutSLForwardIssues !=
  787. VectorizerParams::MaxVectorWidth * TypeByteSize)
  788. MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
  789. return false;
  790. }
  791. /// \brief Check the dependence for two accesses with the same stride \p Stride.
  792. /// \p Distance is the positive distance and \p TypeByteSize is type size in
  793. /// bytes.
  794. ///
  795. /// \returns true if they are independent.
  796. static bool areStridedAccessesIndependent(unsigned Distance, unsigned Stride,
  797. unsigned TypeByteSize) {
  798. assert(Stride > 1 && "The stride must be greater than 1");
  799. assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
  800. assert(Distance > 0 && "The distance must be non-zero");
  801. // Skip if the distance is not multiple of type byte size.
  802. if (Distance % TypeByteSize)
  803. return false;
  804. unsigned ScaledDist = Distance / TypeByteSize;
  805. // No dependence if the scaled distance is not multiple of the stride.
  806. // E.g.
  807. // for (i = 0; i < 1024 ; i += 4)
  808. // A[i+2] = A[i] + 1;
  809. //
  810. // Two accesses in memory (scaled distance is 2, stride is 4):
  811. // | A[0] | | | | A[4] | | | |
  812. // | | | A[2] | | | | A[6] | |
  813. //
  814. // E.g.
  815. // for (i = 0; i < 1024 ; i += 3)
  816. // A[i+4] = A[i] + 1;
  817. //
  818. // Two accesses in memory (scaled distance is 4, stride is 3):
  819. // | A[0] | | | A[3] | | | A[6] | | |
  820. // | | | | | A[4] | | | A[7] | |
  821. return ScaledDist % Stride;
  822. }
  823. MemoryDepChecker::Dependence::DepType
  824. MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
  825. const MemAccessInfo &B, unsigned BIdx,
  826. const ValueToValueMap &Strides) {
  827. assert (AIdx < BIdx && "Must pass arguments in program order");
  828. Value *APtr = A.getPointer();
  829. Value *BPtr = B.getPointer();
  830. bool AIsWrite = A.getInt();
  831. bool BIsWrite = B.getInt();
  832. // Two reads are independent.
  833. if (!AIsWrite && !BIsWrite)
  834. return Dependence::NoDep;
  835. // We cannot check pointers in different address spaces.
  836. if (APtr->getType()->getPointerAddressSpace() !=
  837. BPtr->getType()->getPointerAddressSpace())
  838. return Dependence::Unknown;
  839. const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
  840. const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
  841. int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
  842. int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
  843. const SCEV *Src = AScev;
  844. const SCEV *Sink = BScev;
  845. // If the induction step is negative we have to invert source and sink of the
  846. // dependence.
  847. if (StrideAPtr < 0) {
  848. //Src = BScev;
  849. //Sink = AScev;
  850. std::swap(APtr, BPtr);
  851. std::swap(Src, Sink);
  852. std::swap(AIsWrite, BIsWrite);
  853. std::swap(AIdx, BIdx);
  854. std::swap(StrideAPtr, StrideBPtr);
  855. }
  856. const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
  857. DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
  858. << "(Induction step: " << StrideAPtr << ")\n");
  859. DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
  860. << *InstMap[BIdx] << ": " << *Dist << "\n");
  861. // Need accesses with constant stride. We don't want to vectorize
  862. // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
  863. // the address space.
  864. if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
  865. DEBUG(dbgs() << "Pointer access with non-constant stride\n");
  866. return Dependence::Unknown;
  867. }
  868. const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
  869. if (!C) {
  870. DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
  871. ShouldRetryWithRuntimeCheck = true;
  872. return Dependence::Unknown;
  873. }
  874. Type *ATy = APtr->getType()->getPointerElementType();
  875. Type *BTy = BPtr->getType()->getPointerElementType();
  876. auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
  877. unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
  878. // Negative distances are not plausible dependencies.
  879. const APInt &Val = C->getValue()->getValue();
  880. if (Val.isNegative()) {
  881. bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
  882. if (IsTrueDataDependence &&
  883. (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
  884. ATy != BTy))
  885. return Dependence::ForwardButPreventsForwarding;
  886. DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
  887. return Dependence::Forward;
  888. }
  889. // Write to the same location with the same size.
  890. // Could be improved to assert type sizes are the same (i32 == float, etc).
  891. if (Val == 0) {
  892. if (ATy == BTy)
  893. return Dependence::NoDep;
  894. DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
  895. return Dependence::Unknown;
  896. }
  897. assert(Val.isStrictlyPositive() && "Expect a positive value");
  898. if (ATy != BTy) {
  899. DEBUG(dbgs() <<
  900. "LAA: ReadWrite-Write positive dependency with different types\n");
  901. return Dependence::Unknown;
  902. }
  903. unsigned Distance = (unsigned) Val.getZExtValue();
  904. unsigned Stride = std::abs(StrideAPtr);
  905. if (Stride > 1 &&
  906. areStridedAccessesIndependent(Distance, Stride, TypeByteSize)) {
  907. DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
  908. return Dependence::NoDep;
  909. }
  910. // Bail out early if passed-in parameters make vectorization not feasible.
  911. unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
  912. VectorizerParams::VectorizationFactor : 1);
  913. unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
  914. VectorizerParams::VectorizationInterleave : 1);
  915. // The minimum number of iterations for a vectorized/unrolled version.
  916. unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
  917. // It's not vectorizable if the distance is smaller than the minimum distance
  918. // needed for a vectroized/unrolled version. Vectorizing one iteration in
  919. // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
  920. // TypeByteSize (No need to plus the last gap distance).
  921. //
  922. // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
  923. // foo(int *A) {
  924. // int *B = (int *)((char *)A + 14);
  925. // for (i = 0 ; i < 1024 ; i += 2)
  926. // B[i] = A[i] + 1;
  927. // }
  928. //
  929. // Two accesses in memory (stride is 2):
  930. // | A[0] | | A[2] | | A[4] | | A[6] | |
  931. // | B[0] | | B[2] | | B[4] |
  932. //
  933. // Distance needs for vectorizing iterations except the last iteration:
  934. // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
  935. // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
  936. //
  937. // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
  938. // 12, which is less than distance.
  939. //
  940. // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
  941. // the minimum distance needed is 28, which is greater than distance. It is
  942. // not safe to do vectorization.
  943. unsigned MinDistanceNeeded =
  944. TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
  945. if (MinDistanceNeeded > Distance) {
  946. DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
  947. << '\n');
  948. return Dependence::Backward;
  949. }
  950. // Unsafe if the minimum distance needed is greater than max safe distance.
  951. if (MinDistanceNeeded > MaxSafeDepDistBytes) {
  952. DEBUG(dbgs() << "LAA: Failure because it needs at least "
  953. << MinDistanceNeeded << " size in bytes");
  954. return Dependence::Backward;
  955. }
  956. // Positive distance bigger than max vectorization factor.
  957. // FIXME: Should use max factor instead of max distance in bytes, which could
  958. // not handle different types.
  959. // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
  960. // void foo (int *A, char *B) {
  961. // for (unsigned i = 0; i < 1024; i++) {
  962. // A[i+2] = A[i] + 1;
  963. // B[i+2] = B[i] + 1;
  964. // }
  965. // }
  966. //
  967. // This case is currently unsafe according to the max safe distance. If we
  968. // analyze the two accesses on array B, the max safe dependence distance
  969. // is 2. Then we analyze the accesses on array A, the minimum distance needed
  970. // is 8, which is less than 2 and forbidden vectorization, But actually
  971. // both A and B could be vectorized by 2 iterations.
  972. MaxSafeDepDistBytes =
  973. Distance < MaxSafeDepDistBytes ? Distance : MaxSafeDepDistBytes;
  974. bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
  975. if (IsTrueDataDependence &&
  976. couldPreventStoreLoadForward(Distance, TypeByteSize))
  977. return Dependence::BackwardVectorizableButPreventsForwarding;
  978. DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
  979. << " with max VF = "
  980. << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
  981. return Dependence::BackwardVectorizable;
  982. }
  983. bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
  984. MemAccessInfoSet &CheckDeps,
  985. const ValueToValueMap &Strides) {
  986. MaxSafeDepDistBytes = -1U;
  987. while (!CheckDeps.empty()) {
  988. MemAccessInfo CurAccess = *CheckDeps.begin();
  989. // Get the relevant memory access set.
  990. EquivalenceClasses<MemAccessInfo>::iterator I =
  991. AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
  992. // Check accesses within this set.
  993. EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
  994. AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
  995. // Check every access pair.
  996. while (AI != AE) {
  997. CheckDeps.erase(*AI);
  998. EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
  999. while (OI != AE) {
  1000. // Check every accessing instruction pair in program order.
  1001. for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
  1002. I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
  1003. for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
  1004. I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
  1005. auto A = std::make_pair(&*AI, *I1);
  1006. auto B = std::make_pair(&*OI, *I2);
  1007. assert(*I1 != *I2);
  1008. if (*I1 > *I2)
  1009. std::swap(A, B);
  1010. Dependence::DepType Type =
  1011. isDependent(*A.first, A.second, *B.first, B.second, Strides);
  1012. SafeForVectorization &= Dependence::isSafeForVectorization(Type);
  1013. // Gather dependences unless we accumulated MaxInterestingDependence
  1014. // dependences. In that case return as soon as we find the first
  1015. // unsafe dependence. This puts a limit on this quadratic
  1016. // algorithm.
  1017. if (RecordInterestingDependences) {
  1018. if (Dependence::isInterestingDependence(Type))
  1019. InterestingDependences.push_back(
  1020. Dependence(A.second, B.second, Type));
  1021. if (InterestingDependences.size() >= MaxInterestingDependence) {
  1022. RecordInterestingDependences = false;
  1023. InterestingDependences.clear();
  1024. DEBUG(dbgs() << "Too many dependences, stopped recording\n");
  1025. }
  1026. }
  1027. if (!RecordInterestingDependences && !SafeForVectorization)
  1028. return false;
  1029. }
  1030. ++OI;
  1031. }
  1032. AI++;
  1033. }
  1034. }
  1035. DEBUG(dbgs() << "Total Interesting Dependences: "
  1036. << InterestingDependences.size() << "\n");
  1037. return SafeForVectorization;
  1038. }
  1039. SmallVector<Instruction *, 4>
  1040. MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
  1041. MemAccessInfo Access(Ptr, isWrite);
  1042. auto &IndexVector = Accesses.find(Access)->second;
  1043. SmallVector<Instruction *, 4> Insts;
  1044. std::transform(IndexVector.begin(), IndexVector.end(),
  1045. std::back_inserter(Insts),
  1046. [&](unsigned Idx) { return this->InstMap[Idx]; });
  1047. return Insts;
  1048. }
  1049. const char *MemoryDepChecker::Dependence::DepName[] = {
  1050. "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
  1051. "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
  1052. void MemoryDepChecker::Dependence::print(
  1053. raw_ostream &OS, unsigned Depth,
  1054. const SmallVectorImpl<Instruction *> &Instrs) const {
  1055. OS.indent(Depth) << DepName[Type] << ":\n";
  1056. OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
  1057. OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
  1058. }
  1059. bool LoopAccessInfo::canAnalyzeLoop() {
  1060. // We need to have a loop header.
  1061. DEBUG(dbgs() << "LAA: Found a loop: " <<
  1062. TheLoop->getHeader()->getName() << '\n');
  1063. // We can only analyze innermost loops.
  1064. if (!TheLoop->empty()) {
  1065. DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
  1066. emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
  1067. return false;
  1068. }
  1069. // We must have a single backedge.
  1070. if (TheLoop->getNumBackEdges() != 1) {
  1071. DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
  1072. emitAnalysis(
  1073. LoopAccessReport() <<
  1074. "loop control flow is not understood by analyzer");
  1075. return false;
  1076. }
  1077. // We must have a single exiting block.
  1078. if (!TheLoop->getExitingBlock()) {
  1079. DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
  1080. emitAnalysis(
  1081. LoopAccessReport() <<
  1082. "loop control flow is not understood by analyzer");
  1083. return false;
  1084. }
  1085. // We only handle bottom-tested loops, i.e. loop in which the condition is
  1086. // checked at the end of each iteration. With that we can assume that all
  1087. // instructions in the loop are executed the same number of times.
  1088. if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
  1089. DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
  1090. emitAnalysis(
  1091. LoopAccessReport() <<
  1092. "loop control flow is not understood by analyzer");
  1093. return false;
  1094. }
  1095. // ScalarEvolution needs to be able to find the exit count.
  1096. const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
  1097. if (ExitCount == SE->getCouldNotCompute()) {
  1098. emitAnalysis(LoopAccessReport() <<
  1099. "could not determine number of loop iterations");
  1100. DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
  1101. return false;
  1102. }
  1103. return true;
  1104. }
  1105. void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
  1106. typedef SmallVector<Value*, 16> ValueVector;
  1107. typedef SmallPtrSet<Value*, 16> ValueSet;
  1108. // Holds the Load and Store *instructions*.
  1109. ValueVector Loads;
  1110. ValueVector Stores;
  1111. // Holds all the different accesses in the loop.
  1112. unsigned NumReads = 0;
  1113. unsigned NumReadWrites = 0;
  1114. PtrRtChecking.Pointers.clear();
  1115. PtrRtChecking.Need = false;
  1116. const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
  1117. // For each block.
  1118. for (Loop::block_iterator bb = TheLoop->block_begin(),
  1119. be = TheLoop->block_end(); bb != be; ++bb) {
  1120. // Scan the BB and collect legal loads and stores.
  1121. for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
  1122. ++it) {
  1123. // If this is a load, save it. If this instruction can read from memory
  1124. // but is not a load, then we quit. Notice that we don't handle function
  1125. // calls that read or write.
  1126. if (it->mayReadFromMemory()) {
  1127. // Many math library functions read the rounding mode. We will only
  1128. // vectorize a loop if it contains known function calls that don't set
  1129. // the flag. Therefore, it is safe to ignore this read from memory.
  1130. CallInst *Call = dyn_cast<CallInst>(it);
  1131. if (Call && getIntrinsicIDForCall(Call, TLI))
  1132. continue;
  1133. // If the function has an explicit vectorized counterpart, we can safely
  1134. // assume that it can be vectorized.
  1135. if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
  1136. TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
  1137. continue;
  1138. LoadInst *Ld = dyn_cast<LoadInst>(it);
  1139. if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
  1140. emitAnalysis(LoopAccessReport(Ld)
  1141. << "read with atomic ordering or volatile read");
  1142. DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
  1143. CanVecMem = false;
  1144. return;
  1145. }
  1146. NumLoads++;
  1147. Loads.push_back(Ld);
  1148. DepChecker.addAccess(Ld);
  1149. continue;
  1150. }
  1151. // Save 'store' instructions. Abort if other instructions write to memory.
  1152. if (it->mayWriteToMemory()) {
  1153. StoreInst *St = dyn_cast<StoreInst>(it);
  1154. if (!St) {
  1155. emitAnalysis(LoopAccessReport(it) <<
  1156. "instruction cannot be vectorized");
  1157. CanVecMem = false;
  1158. return;
  1159. }
  1160. if (!St->isSimple() && !IsAnnotatedParallel) {
  1161. emitAnalysis(LoopAccessReport(St)
  1162. << "write with atomic ordering or volatile write");
  1163. DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
  1164. CanVecMem = false;
  1165. return;
  1166. }
  1167. NumStores++;
  1168. Stores.push_back(St);
  1169. DepChecker.addAccess(St);
  1170. }
  1171. } // Next instr.
  1172. } // Next block.
  1173. // Now we have two lists that hold the loads and the stores.
  1174. // Next, we find the pointers that they use.
  1175. // Check if we see any stores. If there are no stores, then we don't
  1176. // care if the pointers are *restrict*.
  1177. if (!Stores.size()) {
  1178. DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
  1179. CanVecMem = true;
  1180. return;
  1181. }
  1182. MemoryDepChecker::DepCandidates DependentAccesses;
  1183. AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
  1184. AA, LI, DependentAccesses);
  1185. // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
  1186. // multiple times on the same object. If the ptr is accessed twice, once
  1187. // for read and once for write, it will only appear once (on the write
  1188. // list). This is okay, since we are going to check for conflicts between
  1189. // writes and between reads and writes, but not between reads and reads.
  1190. ValueSet Seen;
  1191. ValueVector::iterator I, IE;
  1192. for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
  1193. StoreInst *ST = cast<StoreInst>(*I);
  1194. Value* Ptr = ST->getPointerOperand();
  1195. // Check for store to loop invariant address.
  1196. StoreToLoopInvariantAddress |= isUniform(Ptr);
  1197. // If we did *not* see this pointer before, insert it to the read-write
  1198. // list. At this phase it is only a 'write' list.
  1199. if (Seen.insert(Ptr).second) {
  1200. ++NumReadWrites;
  1201. MemoryLocation Loc = MemoryLocation::get(ST);
  1202. // The TBAA metadata could have a control dependency on the predication
  1203. // condition, so we cannot rely on it when determining whether or not we
  1204. // need runtime pointer checks.
  1205. if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
  1206. Loc.AATags.TBAA = nullptr;
  1207. Accesses.addStore(Loc);
  1208. }
  1209. }
  1210. if (IsAnnotatedParallel) {
  1211. DEBUG(dbgs()
  1212. << "LAA: A loop annotated parallel, ignore memory dependency "
  1213. << "checks.\n");
  1214. CanVecMem = true;
  1215. return;
  1216. }
  1217. for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
  1218. LoadInst *LD = cast<LoadInst>(*I);
  1219. Value* Ptr = LD->getPointerOperand();
  1220. // If we did *not* see this pointer before, insert it to the
  1221. // read list. If we *did* see it before, then it is already in
  1222. // the read-write list. This allows us to vectorize expressions
  1223. // such as A[i] += x; Because the address of A[i] is a read-write
  1224. // pointer. This only works if the index of A[i] is consecutive.
  1225. // If the address of i is unknown (for example A[B[i]]) then we may
  1226. // read a few words, modify, and write a few words, and some of the
  1227. // words may be written to the same address.
  1228. bool IsReadOnlyPtr = false;
  1229. if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
  1230. ++NumReads;
  1231. IsReadOnlyPtr = true;
  1232. }
  1233. MemoryLocation Loc = MemoryLocation::get(LD);
  1234. // The TBAA metadata could have a control dependency on the predication
  1235. // condition, so we cannot rely on it when determining whether or not we
  1236. // need runtime pointer checks.
  1237. if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
  1238. Loc.AATags.TBAA = nullptr;
  1239. Accesses.addLoad(Loc, IsReadOnlyPtr);
  1240. }
  1241. // If we write (or read-write) to a single destination and there are no
  1242. // other reads in this loop then is it safe to vectorize.
  1243. if (NumReadWrites == 1 && NumReads == 0) {
  1244. DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
  1245. CanVecMem = true;
  1246. return;
  1247. }
  1248. // Build dependence sets and check whether we need a runtime pointer bounds
  1249. // check.
  1250. Accesses.buildDependenceSets();
  1251. // Find pointers with computable bounds. We are going to use this information
  1252. // to place a runtime bound check.
  1253. bool CanDoRTIfNeeded =
  1254. Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides);
  1255. if (!CanDoRTIfNeeded) {
  1256. emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
  1257. DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
  1258. << "the array bounds.\n");
  1259. CanVecMem = false;
  1260. return;
  1261. }
  1262. DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
  1263. CanVecMem = true;
  1264. if (Accesses.isDependencyCheckNeeded()) {
  1265. DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
  1266. CanVecMem = DepChecker.areDepsSafe(
  1267. DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
  1268. MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
  1269. if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
  1270. DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
  1271. // Clear the dependency checks. We assume they are not needed.
  1272. Accesses.resetDepChecks(DepChecker);
  1273. PtrRtChecking.reset();
  1274. PtrRtChecking.Need = true;
  1275. CanDoRTIfNeeded =
  1276. Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides, true);
  1277. // Check that we found the bounds for the pointer.
  1278. if (!CanDoRTIfNeeded) {
  1279. emitAnalysis(LoopAccessReport()
  1280. << "cannot check memory dependencies at runtime");
  1281. DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
  1282. CanVecMem = false;
  1283. return;
  1284. }
  1285. CanVecMem = true;
  1286. }
  1287. }
  1288. if (CanVecMem)
  1289. DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
  1290. << (PtrRtChecking.Need ? "" : " don't")
  1291. << " need runtime memory checks.\n");
  1292. else {
  1293. emitAnalysis(LoopAccessReport() <<
  1294. "unsafe dependent memory operations in loop");
  1295. DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
  1296. }
  1297. }
  1298. bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
  1299. DominatorTree *DT) {
  1300. assert(TheLoop->contains(BB) && "Unknown block used");
  1301. // Blocks that do not dominate the latch need predication.
  1302. BasicBlock* Latch = TheLoop->getLoopLatch();
  1303. return !DT->dominates(BB, Latch);
  1304. }
  1305. void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
  1306. assert(!Report && "Multiple reports generated");
  1307. Report = Message;
  1308. }
  1309. bool LoopAccessInfo::isUniform(Value *V) const {
  1310. return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
  1311. }
  1312. // FIXME: this function is currently a duplicate of the one in
  1313. // LoopVectorize.cpp.
  1314. static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
  1315. Instruction *Loc) {
  1316. if (FirstInst)
  1317. return FirstInst;
  1318. if (Instruction *I = dyn_cast<Instruction>(V))
  1319. return I->getParent() == Loc->getParent() ? I : nullptr;
  1320. return nullptr;
  1321. }
  1322. std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck(
  1323. Instruction *Loc, const SmallVectorImpl<int> *PtrPartition) const {
  1324. if (!PtrRtChecking.Need)
  1325. return std::make_pair(nullptr, nullptr);
  1326. SmallVector<TrackingVH<Value>, 2> Starts;
  1327. SmallVector<TrackingVH<Value>, 2> Ends;
  1328. LLVMContext &Ctx = Loc->getContext();
  1329. SCEVExpander Exp(*SE, DL, "induction");
  1330. Instruction *FirstInst = nullptr;
  1331. for (unsigned i = 0; i < PtrRtChecking.CheckingGroups.size(); ++i) {
  1332. const RuntimePointerChecking::CheckingPtrGroup &CG =
  1333. PtrRtChecking.CheckingGroups[i];
  1334. Value *Ptr = PtrRtChecking.Pointers[CG.Members[0]].PointerValue;
  1335. const SCEV *Sc = SE->getSCEV(Ptr);
  1336. if (SE->isLoopInvariant(Sc, TheLoop)) {
  1337. DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
  1338. << "\n");
  1339. Starts.push_back(Ptr);
  1340. Ends.push_back(Ptr);
  1341. } else {
  1342. unsigned AS = Ptr->getType()->getPointerAddressSpace();
  1343. // Use this type for pointer arithmetic.
  1344. Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
  1345. Value *Start = nullptr, *End = nullptr;
  1346. DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
  1347. Start = Exp.expandCodeFor(CG.Low, PtrArithTy, Loc);
  1348. End = Exp.expandCodeFor(CG.High, PtrArithTy, Loc);
  1349. DEBUG(dbgs() << "Start: " << *CG.Low << " End: " << *CG.High << "\n");
  1350. Starts.push_back(Start);
  1351. Ends.push_back(End);
  1352. }
  1353. }
  1354. IRBuilder<> ChkBuilder(Loc);
  1355. // Our instructions might fold to a constant.
  1356. Value *MemoryRuntimeCheck = nullptr;
  1357. for (unsigned i = 0; i < PtrRtChecking.CheckingGroups.size(); ++i) {
  1358. for (unsigned j = i + 1; j < PtrRtChecking.CheckingGroups.size(); ++j) {
  1359. const RuntimePointerChecking::CheckingPtrGroup &CGI =
  1360. PtrRtChecking.CheckingGroups[i];
  1361. const RuntimePointerChecking::CheckingPtrGroup &CGJ =
  1362. PtrRtChecking.CheckingGroups[j];
  1363. if (!PtrRtChecking.needsChecking(CGI, CGJ, PtrPartition))
  1364. continue;
  1365. unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
  1366. unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
  1367. assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
  1368. (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
  1369. "Trying to bounds check pointers with different address spaces");
  1370. Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
  1371. Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
  1372. Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
  1373. Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
  1374. Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
  1375. Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
  1376. Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
  1377. FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
  1378. Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
  1379. FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
  1380. Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
  1381. FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
  1382. if (MemoryRuntimeCheck) {
  1383. IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
  1384. "conflict.rdx");
  1385. FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
  1386. }
  1387. MemoryRuntimeCheck = IsConflict;
  1388. }
  1389. }
  1390. if (!MemoryRuntimeCheck)
  1391. return std::make_pair(nullptr, nullptr);
  1392. // We have to do this trickery because the IRBuilder might fold the check to a
  1393. // constant expression in which case there is no Instruction anchored in a
  1394. // the block.
  1395. Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
  1396. ConstantInt::getTrue(Ctx));
  1397. ChkBuilder.Insert(Check, "memcheck.conflict");
  1398. FirstInst = getFirstInst(FirstInst, Check, Loc);
  1399. return std::make_pair(FirstInst, Check);
  1400. }
  1401. LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
  1402. const DataLayout &DL,
  1403. const TargetLibraryInfo *TLI, AliasAnalysis *AA,
  1404. DominatorTree *DT, LoopInfo *LI,
  1405. const ValueToValueMap &Strides)
  1406. : PtrRtChecking(SE), DepChecker(SE, L), TheLoop(L), SE(SE), DL(DL),
  1407. TLI(TLI), AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
  1408. MaxSafeDepDistBytes(-1U), CanVecMem(false),
  1409. StoreToLoopInvariantAddress(false) {
  1410. if (canAnalyzeLoop())
  1411. analyzeLoop(Strides);
  1412. }
  1413. void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
  1414. if (CanVecMem) {
  1415. if (PtrRtChecking.Need)
  1416. OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
  1417. else
  1418. OS.indent(Depth) << "Memory dependences are safe\n";
  1419. }
  1420. if (Report)
  1421. OS.indent(Depth) << "Report: " << Report->str() << "\n";
  1422. if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
  1423. OS.indent(Depth) << "Interesting Dependences:\n";
  1424. for (auto &Dep : *InterestingDependences) {
  1425. Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
  1426. OS << "\n";
  1427. }
  1428. } else
  1429. OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
  1430. // List the pair of accesses need run-time checks to prove independence.
  1431. PtrRtChecking.print(OS, Depth);
  1432. OS << "\n";
  1433. OS.indent(Depth) << "Store to invariant address was "
  1434. << (StoreToLoopInvariantAddress ? "" : "not ")
  1435. << "found in loop.\n";
  1436. }
  1437. const LoopAccessInfo &
  1438. LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
  1439. auto &LAI = LoopAccessInfoMap[L];
  1440. #ifndef NDEBUG
  1441. assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
  1442. "Symbolic strides changed for loop");
  1443. #endif
  1444. if (!LAI) {
  1445. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  1446. LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI,
  1447. Strides);
  1448. #ifndef NDEBUG
  1449. LAI->NumSymbolicStrides = Strides.size();
  1450. #endif
  1451. }
  1452. return *LAI.get();
  1453. }
  1454. void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
  1455. LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
  1456. ValueToValueMap NoSymbolicStrides;
  1457. for (Loop *TopLevelLoop : *LI)
  1458. for (Loop *L : depth_first(TopLevelLoop)) {
  1459. OS.indent(2) << L->getHeader()->getName() << ":\n";
  1460. auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
  1461. LAI.print(OS, 4);
  1462. }
  1463. }
  1464. bool LoopAccessAnalysis::runOnFunction(Function &F) {
  1465. SE = &getAnalysis<ScalarEvolution>();
  1466. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  1467. TLI = TLIP ? &TLIP->getTLI() : nullptr;
  1468. AA = &getAnalysis<AliasAnalysis>();
  1469. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1470. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  1471. return false;
  1472. }
  1473. void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  1474. AU.addRequired<ScalarEvolution>();
  1475. AU.addRequired<AliasAnalysis>();
  1476. AU.addRequired<DominatorTreeWrapperPass>();
  1477. AU.addRequired<LoopInfoWrapperPass>();
  1478. AU.setPreservesAll();
  1479. }
  1480. char LoopAccessAnalysis::ID = 0;
  1481. static const char laa_name[] = "Loop Access Analysis";
  1482. #define LAA_NAME "loop-accesses"
  1483. INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
  1484. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  1485. INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
  1486. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  1487. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  1488. INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
  1489. namespace llvm {
  1490. Pass *createLAAPass() {
  1491. return new LoopAccessAnalysis();
  1492. }
  1493. }