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