AlignmentFromAssumptions.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. //===----------------------- AlignmentFromAssumptions.cpp -----------------===//
  2. // Set Load/Store Alignments From Assumptions
  3. //
  4. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  5. // See https://llvm.org/LICENSE.txt for license information.
  6. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements a ScalarEvolution-based transformation to set
  11. // the alignments of load, stores and memory intrinsics based on the truth
  12. // expressions of assume intrinsics. The primary motivation is to handle
  13. // complex alignment assumptions that apply to vector loads and stores that
  14. // appear after vectorization and unrolling.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/IR/Instructions.h"
  18. #include "llvm/InitializePasses.h"
  19. #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/Analysis/AliasAnalysis.h"
  23. #include "llvm/Analysis/AssumptionCache.h"
  24. #include "llvm/Analysis/GlobalsModRef.h"
  25. #include "llvm/Analysis/LoopInfo.h"
  26. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  27. #include "llvm/Analysis/ValueTracking.h"
  28. #include "llvm/IR/Constant.h"
  29. #include "llvm/IR/Dominators.h"
  30. #include "llvm/IR/Instruction.h"
  31. #include "llvm/IR/IntrinsicInst.h"
  32. #include "llvm/IR/Intrinsics.h"
  33. #include "llvm/IR/Module.h"
  34. #include "llvm/Support/Debug.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include "llvm/Transforms/Scalar.h"
  37. #define AA_NAME "alignment-from-assumptions"
  38. #define DEBUG_TYPE AA_NAME
  39. using namespace llvm;
  40. STATISTIC(NumLoadAlignChanged,
  41. "Number of loads changed by alignment assumptions");
  42. STATISTIC(NumStoreAlignChanged,
  43. "Number of stores changed by alignment assumptions");
  44. STATISTIC(NumMemIntAlignChanged,
  45. "Number of memory intrinsics changed by alignment assumptions");
  46. namespace {
  47. struct AlignmentFromAssumptions : public FunctionPass {
  48. static char ID; // Pass identification, replacement for typeid
  49. AlignmentFromAssumptions() : FunctionPass(ID) {
  50. initializeAlignmentFromAssumptionsPass(*PassRegistry::getPassRegistry());
  51. }
  52. bool runOnFunction(Function &F) override;
  53. void getAnalysisUsage(AnalysisUsage &AU) const override {
  54. AU.addRequired<AssumptionCacheTracker>();
  55. AU.addRequired<ScalarEvolutionWrapperPass>();
  56. AU.addRequired<DominatorTreeWrapperPass>();
  57. AU.setPreservesCFG();
  58. AU.addPreserved<AAResultsWrapperPass>();
  59. AU.addPreserved<GlobalsAAWrapperPass>();
  60. AU.addPreserved<LoopInfoWrapperPass>();
  61. AU.addPreserved<DominatorTreeWrapperPass>();
  62. AU.addPreserved<ScalarEvolutionWrapperPass>();
  63. }
  64. AlignmentFromAssumptionsPass Impl;
  65. };
  66. }
  67. char AlignmentFromAssumptions::ID = 0;
  68. static const char aip_name[] = "Alignment from assumptions";
  69. INITIALIZE_PASS_BEGIN(AlignmentFromAssumptions, AA_NAME,
  70. aip_name, false, false)
  71. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  72. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  73. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  74. INITIALIZE_PASS_END(AlignmentFromAssumptions, AA_NAME,
  75. aip_name, false, false)
  76. FunctionPass *llvm::createAlignmentFromAssumptionsPass() {
  77. return new AlignmentFromAssumptions();
  78. }
  79. // Given an expression for the (constant) alignment, AlignSCEV, and an
  80. // expression for the displacement between a pointer and the aligned address,
  81. // DiffSCEV, compute the alignment of the displaced pointer if it can be reduced
  82. // to a constant. Using SCEV to compute alignment handles the case where
  83. // DiffSCEV is a recurrence with constant start such that the aligned offset
  84. // is constant. e.g. {16,+,32} % 32 -> 16.
  85. static MaybeAlign getNewAlignmentDiff(const SCEV *DiffSCEV,
  86. const SCEV *AlignSCEV,
  87. ScalarEvolution *SE) {
  88. // DiffUnits = Diff % int64_t(Alignment)
  89. const SCEV *DiffUnitsSCEV = SE->getURemExpr(DiffSCEV, AlignSCEV);
  90. LLVM_DEBUG(dbgs() << "\talignment relative to " << *AlignSCEV << " is "
  91. << *DiffUnitsSCEV << " (diff: " << *DiffSCEV << ")\n");
  92. if (const SCEVConstant *ConstDUSCEV =
  93. dyn_cast<SCEVConstant>(DiffUnitsSCEV)) {
  94. int64_t DiffUnits = ConstDUSCEV->getValue()->getSExtValue();
  95. // If the displacement is an exact multiple of the alignment, then the
  96. // displaced pointer has the same alignment as the aligned pointer, so
  97. // return the alignment value.
  98. if (!DiffUnits)
  99. return cast<SCEVConstant>(AlignSCEV)->getValue()->getAlignValue();
  100. // If the displacement is not an exact multiple, but the remainder is a
  101. // constant, then return this remainder (but only if it is a power of 2).
  102. uint64_t DiffUnitsAbs = std::abs(DiffUnits);
  103. if (isPowerOf2_64(DiffUnitsAbs))
  104. return Align(DiffUnitsAbs);
  105. }
  106. return None;
  107. }
  108. // There is an address given by an offset OffSCEV from AASCEV which has an
  109. // alignment AlignSCEV. Use that information, if possible, to compute a new
  110. // alignment for Ptr.
  111. static Align getNewAlignment(const SCEV *AASCEV, const SCEV *AlignSCEV,
  112. const SCEV *OffSCEV, Value *Ptr,
  113. ScalarEvolution *SE) {
  114. const SCEV *PtrSCEV = SE->getSCEV(Ptr);
  115. // On a platform with 32-bit allocas, but 64-bit flat/global pointer sizes
  116. // (*cough* AMDGPU), the effective SCEV type of AASCEV and PtrSCEV
  117. // may disagree. Trunc/extend so they agree.
  118. PtrSCEV = SE->getTruncateOrZeroExtend(
  119. PtrSCEV, SE->getEffectiveSCEVType(AASCEV->getType()));
  120. const SCEV *DiffSCEV = SE->getMinusSCEV(PtrSCEV, AASCEV);
  121. if (isa<SCEVCouldNotCompute>(DiffSCEV))
  122. return Align(1);
  123. // On 32-bit platforms, DiffSCEV might now have type i32 -- we've always
  124. // sign-extended OffSCEV to i64, so make sure they agree again.
  125. DiffSCEV = SE->getNoopOrSignExtend(DiffSCEV, OffSCEV->getType());
  126. // What we really want to know is the overall offset to the aligned
  127. // address. This address is displaced by the provided offset.
  128. DiffSCEV = SE->getAddExpr(DiffSCEV, OffSCEV);
  129. LLVM_DEBUG(dbgs() << "AFI: alignment of " << *Ptr << " relative to "
  130. << *AlignSCEV << " and offset " << *OffSCEV
  131. << " using diff " << *DiffSCEV << "\n");
  132. if (MaybeAlign NewAlignment = getNewAlignmentDiff(DiffSCEV, AlignSCEV, SE)) {
  133. LLVM_DEBUG(dbgs() << "\tnew alignment: " << DebugStr(NewAlignment) << "\n");
  134. return *NewAlignment;
  135. }
  136. if (const SCEVAddRecExpr *DiffARSCEV = dyn_cast<SCEVAddRecExpr>(DiffSCEV)) {
  137. // The relative offset to the alignment assumption did not yield a constant,
  138. // but we should try harder: if we assume that a is 32-byte aligned, then in
  139. // for (i = 0; i < 1024; i += 4) r += a[i]; not all of the loads from a are
  140. // 32-byte aligned, but instead alternate between 32 and 16-byte alignment.
  141. // As a result, the new alignment will not be a constant, but can still
  142. // be improved over the default (of 4) to 16.
  143. const SCEV *DiffStartSCEV = DiffARSCEV->getStart();
  144. const SCEV *DiffIncSCEV = DiffARSCEV->getStepRecurrence(*SE);
  145. LLVM_DEBUG(dbgs() << "\ttrying start/inc alignment using start "
  146. << *DiffStartSCEV << " and inc " << *DiffIncSCEV << "\n");
  147. // Now compute the new alignment using the displacement to the value in the
  148. // first iteration, and also the alignment using the per-iteration delta.
  149. // If these are the same, then use that answer. Otherwise, use the smaller
  150. // one, but only if it divides the larger one.
  151. MaybeAlign NewAlignment = getNewAlignmentDiff(DiffStartSCEV, AlignSCEV, SE);
  152. MaybeAlign NewIncAlignment =
  153. getNewAlignmentDiff(DiffIncSCEV, AlignSCEV, SE);
  154. LLVM_DEBUG(dbgs() << "\tnew start alignment: " << DebugStr(NewAlignment)
  155. << "\n");
  156. LLVM_DEBUG(dbgs() << "\tnew inc alignment: " << DebugStr(NewIncAlignment)
  157. << "\n");
  158. if (!NewAlignment || !NewIncAlignment)
  159. return Align(1);
  160. const Align NewAlign = *NewAlignment;
  161. const Align NewIncAlign = *NewIncAlignment;
  162. if (NewAlign > NewIncAlign) {
  163. LLVM_DEBUG(dbgs() << "\tnew start/inc alignment: "
  164. << DebugStr(NewIncAlign) << "\n");
  165. return NewIncAlign;
  166. }
  167. if (NewIncAlign > NewAlign) {
  168. LLVM_DEBUG(dbgs() << "\tnew start/inc alignment: " << DebugStr(NewAlign)
  169. << "\n");
  170. return NewAlign;
  171. }
  172. assert(NewIncAlign == NewAlign);
  173. LLVM_DEBUG(dbgs() << "\tnew start/inc alignment: " << DebugStr(NewAlign)
  174. << "\n");
  175. return NewAlign;
  176. }
  177. return Align(1);
  178. }
  179. bool AlignmentFromAssumptionsPass::extractAlignmentInfo(CallInst *I,
  180. unsigned Idx,
  181. Value *&AAPtr,
  182. const SCEV *&AlignSCEV,
  183. const SCEV *&OffSCEV) {
  184. Type *Int64Ty = Type::getInt64Ty(I->getContext());
  185. OperandBundleUse AlignOB = I->getOperandBundleAt(Idx);
  186. if (AlignOB.getTagName() != "align")
  187. return false;
  188. assert(AlignOB.Inputs.size() >= 2);
  189. AAPtr = AlignOB.Inputs[0].get();
  190. // TODO: Consider accumulating the offset to the base.
  191. AAPtr = AAPtr->stripPointerCastsSameRepresentation();
  192. AlignSCEV = SE->getSCEV(AlignOB.Inputs[1].get());
  193. AlignSCEV = SE->getTruncateOrZeroExtend(AlignSCEV, Int64Ty);
  194. if (!isa<SCEVConstant>(AlignSCEV))
  195. // Added to suppress a crash because consumer doesn't expect non-constant
  196. // alignments in the assume bundle. TODO: Consider generalizing caller.
  197. return false;
  198. if (AlignOB.Inputs.size() == 3)
  199. OffSCEV = SE->getSCEV(AlignOB.Inputs[2].get());
  200. else
  201. OffSCEV = SE->getZero(Int64Ty);
  202. OffSCEV = SE->getTruncateOrZeroExtend(OffSCEV, Int64Ty);
  203. return true;
  204. }
  205. bool AlignmentFromAssumptionsPass::processAssumption(CallInst *ACall,
  206. unsigned Idx) {
  207. Value *AAPtr;
  208. const SCEV *AlignSCEV, *OffSCEV;
  209. if (!extractAlignmentInfo(ACall, Idx, AAPtr, AlignSCEV, OffSCEV))
  210. return false;
  211. // Skip ConstantPointerNull and UndefValue. Assumptions on these shouldn't
  212. // affect other users.
  213. if (isa<ConstantData>(AAPtr))
  214. return false;
  215. const SCEV *AASCEV = SE->getSCEV(AAPtr);
  216. // Apply the assumption to all other users of the specified pointer.
  217. SmallPtrSet<Instruction *, 32> Visited;
  218. SmallVector<Instruction*, 16> WorkList;
  219. for (User *J : AAPtr->users()) {
  220. if (J == ACall)
  221. continue;
  222. if (Instruction *K = dyn_cast<Instruction>(J))
  223. WorkList.push_back(K);
  224. }
  225. while (!WorkList.empty()) {
  226. Instruction *J = WorkList.pop_back_val();
  227. if (LoadInst *LI = dyn_cast<LoadInst>(J)) {
  228. if (!isValidAssumeForContext(ACall, J, DT))
  229. continue;
  230. Align NewAlignment = getNewAlignment(AASCEV, AlignSCEV, OffSCEV,
  231. LI->getPointerOperand(), SE);
  232. if (NewAlignment > LI->getAlign()) {
  233. LI->setAlignment(NewAlignment);
  234. ++NumLoadAlignChanged;
  235. }
  236. } else if (StoreInst *SI = dyn_cast<StoreInst>(J)) {
  237. if (!isValidAssumeForContext(ACall, J, DT))
  238. continue;
  239. Align NewAlignment = getNewAlignment(AASCEV, AlignSCEV, OffSCEV,
  240. SI->getPointerOperand(), SE);
  241. if (NewAlignment > SI->getAlign()) {
  242. SI->setAlignment(NewAlignment);
  243. ++NumStoreAlignChanged;
  244. }
  245. } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(J)) {
  246. if (!isValidAssumeForContext(ACall, J, DT))
  247. continue;
  248. Align NewDestAlignment =
  249. getNewAlignment(AASCEV, AlignSCEV, OffSCEV, MI->getDest(), SE);
  250. LLVM_DEBUG(dbgs() << "\tmem inst: " << DebugStr(NewDestAlignment)
  251. << "\n";);
  252. if (NewDestAlignment > *MI->getDestAlign()) {
  253. MI->setDestAlignment(NewDestAlignment);
  254. ++NumMemIntAlignChanged;
  255. }
  256. // For memory transfers, there is also a source alignment that
  257. // can be set.
  258. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
  259. Align NewSrcAlignment =
  260. getNewAlignment(AASCEV, AlignSCEV, OffSCEV, MTI->getSource(), SE);
  261. LLVM_DEBUG(dbgs() << "\tmem trans: " << DebugStr(NewSrcAlignment)
  262. << "\n";);
  263. if (NewSrcAlignment > *MTI->getSourceAlign()) {
  264. MTI->setSourceAlignment(NewSrcAlignment);
  265. ++NumMemIntAlignChanged;
  266. }
  267. }
  268. }
  269. // Now that we've updated that use of the pointer, look for other uses of
  270. // the pointer to update.
  271. Visited.insert(J);
  272. for (User *UJ : J->users()) {
  273. Instruction *K = cast<Instruction>(UJ);
  274. if (!Visited.count(K))
  275. WorkList.push_back(K);
  276. }
  277. }
  278. return true;
  279. }
  280. bool AlignmentFromAssumptions::runOnFunction(Function &F) {
  281. if (skipFunction(F))
  282. return false;
  283. auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  284. ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  285. DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  286. return Impl.runImpl(F, AC, SE, DT);
  287. }
  288. bool AlignmentFromAssumptionsPass::runImpl(Function &F, AssumptionCache &AC,
  289. ScalarEvolution *SE_,
  290. DominatorTree *DT_) {
  291. SE = SE_;
  292. DT = DT_;
  293. bool Changed = false;
  294. for (auto &AssumeVH : AC.assumptions())
  295. if (AssumeVH) {
  296. CallInst *Call = cast<CallInst>(AssumeVH);
  297. for (unsigned Idx = 0; Idx < Call->getNumOperandBundles(); Idx++)
  298. Changed |= processAssumption(Call, Idx);
  299. }
  300. return Changed;
  301. }
  302. PreservedAnalyses
  303. AlignmentFromAssumptionsPass::run(Function &F, FunctionAnalysisManager &AM) {
  304. AssumptionCache &AC = AM.getResult<AssumptionAnalysis>(F);
  305. ScalarEvolution &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
  306. DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
  307. if (!runImpl(F, AC, &SE, &DT))
  308. return PreservedAnalyses::all();
  309. PreservedAnalyses PA;
  310. PA.preserveSet<CFGAnalyses>();
  311. PA.preserve<ScalarEvolutionAnalysis>();
  312. return PA;
  313. }