1 //===----------------------- AlignmentFromAssumptions.cpp -----------------===// 2 // Set Load/Store Alignments From Assumptions 3 // 4 // The LLVM Compiler Infrastructure 5 // 6 // This file is distributed under the University of Illinois Open Source 7 // License. See LICENSE.TXT for details. 8 // 9 //===----------------------------------------------------------------------===// 10 // 11 // This file implements a ScalarEvolution-based transformation to set 12 // the alignments of load, stores and memory intrinsics based on the truth 13 // expressions of assume intrinsics. The primary motivation is to handle 14 // complex alignment assumptions that apply to vector loads and stores that 15 // appear after vectorization and unrolling. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #define AA_NAME "alignment-from-assumptions" 20 #define DEBUG_TYPE AA_NAME 21 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h" 22 #include "llvm/Transforms/Scalar.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/Analysis/AliasAnalysis.h" 26 #include "llvm/Analysis/GlobalsModRef.h" 27 #include "llvm/Analysis/LoopInfo.h" 28 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/IR/Constant.h" 31 #include "llvm/IR/Dominators.h" 32 #include "llvm/IR/Instruction.h" 33 #include "llvm/IR/Intrinsics.h" 34 #include "llvm/IR/Module.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/raw_ostream.h" 37 using namespace llvm; 38 39 STATISTIC(NumLoadAlignChanged, 40 "Number of loads changed by alignment assumptions"); 41 STATISTIC(NumStoreAlignChanged, 42 "Number of stores changed by alignment assumptions"); 43 STATISTIC(NumMemIntAlignChanged, 44 "Number of memory intrinsics changed by alignment assumptions"); 45 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 53 bool runOnFunction(Function &F) override; 54 55 void getAnalysisUsage(AnalysisUsage &AU) const override { 56 AU.addRequired<ScalarEvolutionWrapperPass>(); 57 AU.addRequired<DominatorTreeWrapperPass>(); 58 59 AU.setPreservesCFG(); 60 AU.addPreserved<AAResultsWrapperPass>(); 61 AU.addPreserved<GlobalsAAWrapperPass>(); 62 AU.addPreserved<LoopInfoWrapperPass>(); 63 AU.addPreserved<DominatorTreeWrapperPass>(); 64 AU.addPreserved<ScalarEvolutionWrapperPass>(); 65 } 66 67 AlignmentFromAssumptionsPass Impl; 68 }; 69 } 70 71 char AlignmentFromAssumptions::ID = 0; 72 static const char aip_name[] = "Alignment from assumptions"; 73 INITIALIZE_PASS_BEGIN(AlignmentFromAssumptions, AA_NAME, 74 aip_name, false, false) 75 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 76 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 77 INITIALIZE_PASS_END(AlignmentFromAssumptions, AA_NAME, 78 aip_name, false, false) 79 80 FunctionPass *llvm::createAlignmentFromAssumptionsPass() { 81 return new AlignmentFromAssumptions(); 82 } 83 84 // Given an expression for the (constant) alignment, AlignSCEV, and an 85 // expression for the displacement between a pointer and the aligned address, 86 // DiffSCEV, compute the alignment of the displaced pointer if it can be reduced 87 // to a constant. Using SCEV to compute alignment handles the case where 88 // DiffSCEV is a recurrence with constant start such that the aligned offset 89 // is constant. e.g. {16,+,32} % 32 -> 16. 90 static unsigned getNewAlignmentDiff(const SCEV *DiffSCEV, 91 const SCEV *AlignSCEV, 92 ScalarEvolution *SE) { 93 // DiffUnits = Diff % int64_t(Alignment) 94 const SCEV *DiffAlignDiv = SE->getUDivExpr(DiffSCEV, AlignSCEV); 95 const SCEV *DiffAlign = SE->getMulExpr(DiffAlignDiv, AlignSCEV); 96 const SCEV *DiffUnitsSCEV = SE->getMinusSCEV(DiffAlign, DiffSCEV); 97 98 DEBUG(dbgs() << "\talignment relative to " << *AlignSCEV << " is " << 99 *DiffUnitsSCEV << " (diff: " << *DiffSCEV << ")\n"); 100 101 if (const SCEVConstant *ConstDUSCEV = 102 dyn_cast<SCEVConstant>(DiffUnitsSCEV)) { 103 int64_t DiffUnits = ConstDUSCEV->getValue()->getSExtValue(); 104 105 // If the displacement is an exact multiple of the alignment, then the 106 // displaced pointer has the same alignment as the aligned pointer, so 107 // return the alignment value. 108 if (!DiffUnits) 109 return (unsigned) 110 cast<SCEVConstant>(AlignSCEV)->getValue()->getSExtValue(); 111 112 // If the displacement is not an exact multiple, but the remainder is a 113 // constant, then return this remainder (but only if it is a power of 2). 114 uint64_t DiffUnitsAbs = std::abs(DiffUnits); 115 if (isPowerOf2_64(DiffUnitsAbs)) 116 return (unsigned) DiffUnitsAbs; 117 } 118 119 return 0; 120 } 121 122 // There is an address given by an offset OffSCEV from AASCEV which has an 123 // alignment AlignSCEV. Use that information, if possible, to compute a new 124 // alignment for Ptr. 125 static unsigned getNewAlignment(const SCEV *AASCEV, const SCEV *AlignSCEV, 126 const SCEV *OffSCEV, Value *Ptr, 127 ScalarEvolution *SE) { 128 const SCEV *PtrSCEV = SE->getSCEV(Ptr); 129 const SCEV *DiffSCEV = SE->getMinusSCEV(PtrSCEV, AASCEV); 130 131 // On 32-bit platforms, DiffSCEV might now have type i32 -- we've always 132 // sign-extended OffSCEV to i64, so make sure they agree again. 133 DiffSCEV = SE->getNoopOrSignExtend(DiffSCEV, OffSCEV->getType()); 134 135 // What we really want to know is the overall offset to the aligned 136 // address. This address is displaced by the provided offset. 137 DiffSCEV = SE->getMinusSCEV(DiffSCEV, OffSCEV); 138 139 DEBUG(dbgs() << "AFI: alignment of " << *Ptr << " relative to " << 140 *AlignSCEV << " and offset " << *OffSCEV << 141 " using diff " << *DiffSCEV << "\n"); 142 143 unsigned NewAlignment = getNewAlignmentDiff(DiffSCEV, AlignSCEV, SE); 144 DEBUG(dbgs() << "\tnew alignment: " << NewAlignment << "\n"); 145 146 if (NewAlignment) { 147 return NewAlignment; 148 } else if (const SCEVAddRecExpr *DiffARSCEV = 149 dyn_cast<SCEVAddRecExpr>(DiffSCEV)) { 150 // The relative offset to the alignment assumption did not yield a constant, 151 // but we should try harder: if we assume that a is 32-byte aligned, then in 152 // for (i = 0; i < 1024; i += 4) r += a[i]; not all of the loads from a are 153 // 32-byte aligned, but instead alternate between 32 and 16-byte alignment. 154 // As a result, the new alignment will not be a constant, but can still 155 // be improved over the default (of 4) to 16. 156 157 const SCEV *DiffStartSCEV = DiffARSCEV->getStart(); 158 const SCEV *DiffIncSCEV = DiffARSCEV->getStepRecurrence(*SE); 159 160 DEBUG(dbgs() << "\ttrying start/inc alignment using start " << 161 *DiffStartSCEV << " and inc " << *DiffIncSCEV << "\n"); 162 163 // Now compute the new alignment using the displacement to the value in the 164 // first iteration, and also the alignment using the per-iteration delta. 165 // If these are the same, then use that answer. Otherwise, use the smaller 166 // one, but only if it divides the larger one. 167 NewAlignment = getNewAlignmentDiff(DiffStartSCEV, AlignSCEV, SE); 168 unsigned NewIncAlignment = getNewAlignmentDiff(DiffIncSCEV, AlignSCEV, SE); 169 170 DEBUG(dbgs() << "\tnew start alignment: " << NewAlignment << "\n"); 171 DEBUG(dbgs() << "\tnew inc alignment: " << NewIncAlignment << "\n"); 172 173 if (!NewAlignment || !NewIncAlignment) { 174 return 0; 175 } else if (NewAlignment > NewIncAlignment) { 176 if (NewAlignment % NewIncAlignment == 0) { 177 DEBUG(dbgs() << "\tnew start/inc alignment: " << 178 NewIncAlignment << "\n"); 179 return NewIncAlignment; 180 } 181 } else if (NewIncAlignment > NewAlignment) { 182 if (NewIncAlignment % NewAlignment == 0) { 183 DEBUG(dbgs() << "\tnew start/inc alignment: " << 184 NewAlignment << "\n"); 185 return NewAlignment; 186 } 187 } else if (NewIncAlignment == NewAlignment) { 188 DEBUG(dbgs() << "\tnew start/inc alignment: " << 189 NewAlignment << "\n"); 190 return NewAlignment; 191 } 192 } 193 194 return 0; 195 } 196 197 bool AlignmentFromAssumptionsPass::extractAlignmentInfo(CallInst *I, 198 Value *&AAPtr, 199 const SCEV *&AlignSCEV, 200 const SCEV *&OffSCEV) { 201 // An alignment assume must be a statement about the least-significant 202 // bits of the pointer being zero, possibly with some offset. 203 ICmpInst *ICI = dyn_cast<ICmpInst>(I->getArgOperand(0)); 204 if (!ICI) 205 return false; 206 207 // This must be an expression of the form: x & m == 0. 208 if (ICI->getPredicate() != ICmpInst::ICMP_EQ) 209 return false; 210 211 // Swap things around so that the RHS is 0. 212 Value *CmpLHS = ICI->getOperand(0); 213 Value *CmpRHS = ICI->getOperand(1); 214 const SCEV *CmpLHSSCEV = SE->getSCEV(CmpLHS); 215 const SCEV *CmpRHSSCEV = SE->getSCEV(CmpRHS); 216 if (CmpLHSSCEV->isZero()) 217 std::swap(CmpLHS, CmpRHS); 218 else if (!CmpRHSSCEV->isZero()) 219 return false; 220 221 BinaryOperator *CmpBO = dyn_cast<BinaryOperator>(CmpLHS); 222 if (!CmpBO || CmpBO->getOpcode() != Instruction::And) 223 return false; 224 225 // Swap things around so that the right operand of the and is a constant 226 // (the mask); we cannot deal with variable masks. 227 Value *AndLHS = CmpBO->getOperand(0); 228 Value *AndRHS = CmpBO->getOperand(1); 229 const SCEV *AndLHSSCEV = SE->getSCEV(AndLHS); 230 const SCEV *AndRHSSCEV = SE->getSCEV(AndRHS); 231 if (isa<SCEVConstant>(AndLHSSCEV)) { 232 std::swap(AndLHS, AndRHS); 233 std::swap(AndLHSSCEV, AndRHSSCEV); 234 } 235 236 const SCEVConstant *MaskSCEV = dyn_cast<SCEVConstant>(AndRHSSCEV); 237 if (!MaskSCEV) 238 return false; 239 240 // The mask must have some trailing ones (otherwise the condition is 241 // trivial and tells us nothing about the alignment of the left operand). 242 unsigned TrailingOnes = MaskSCEV->getAPInt().countTrailingOnes(); 243 if (!TrailingOnes) 244 return false; 245 246 // Cap the alignment at the maximum with which LLVM can deal (and make sure 247 // we don't overflow the shift). 248 uint64_t Alignment; 249 TrailingOnes = std::min(TrailingOnes, 250 unsigned(sizeof(unsigned) * CHAR_BIT - 1)); 251 Alignment = std::min(1u << TrailingOnes, +Value::MaximumAlignment); 252 253 Type *Int64Ty = Type::getInt64Ty(I->getParent()->getParent()->getContext()); 254 AlignSCEV = SE->getConstant(Int64Ty, Alignment); 255 256 // The LHS might be a ptrtoint instruction, or it might be the pointer 257 // with an offset. 258 AAPtr = nullptr; 259 OffSCEV = nullptr; 260 if (PtrToIntInst *PToI = dyn_cast<PtrToIntInst>(AndLHS)) { 261 AAPtr = PToI->getPointerOperand(); 262 OffSCEV = SE->getZero(Int64Ty); 263 } else if (const SCEVAddExpr* AndLHSAddSCEV = 264 dyn_cast<SCEVAddExpr>(AndLHSSCEV)) { 265 // Try to find the ptrtoint; subtract it and the rest is the offset. 266 for (SCEVAddExpr::op_iterator J = AndLHSAddSCEV->op_begin(), 267 JE = AndLHSAddSCEV->op_end(); J != JE; ++J) 268 if (const SCEVUnknown *OpUnk = dyn_cast<SCEVUnknown>(*J)) 269 if (PtrToIntInst *PToI = dyn_cast<PtrToIntInst>(OpUnk->getValue())) { 270 AAPtr = PToI->getPointerOperand(); 271 OffSCEV = SE->getMinusSCEV(AndLHSAddSCEV, *J); 272 break; 273 } 274 } 275 276 if (!AAPtr) 277 return false; 278 279 // Sign extend the offset to 64 bits (so that it is like all of the other 280 // expressions). 281 unsigned OffSCEVBits = OffSCEV->getType()->getPrimitiveSizeInBits(); 282 if (OffSCEVBits < 64) 283 OffSCEV = SE->getSignExtendExpr(OffSCEV, Int64Ty); 284 else if (OffSCEVBits > 64) 285 return false; 286 287 AAPtr = AAPtr->stripPointerCasts(); 288 return true; 289 } 290 291 bool AlignmentFromAssumptionsPass::processAssumption(CallInst *ACall) { 292 Value *AAPtr; 293 const SCEV *AlignSCEV, *OffSCEV; 294 if (!extractAlignmentInfo(ACall, AAPtr, AlignSCEV, OffSCEV)) 295 return false; 296 297 // Skip ConstantPointerNull and UndefValue. Assumptions on these shouldn't 298 // affect other users. 299 if (isa<ConstantData>(AAPtr)) 300 return false; 301 302 const SCEV *AASCEV = SE->getSCEV(AAPtr); 303 304 // Apply the assumption to all other users of the specified pointer. 305 SmallPtrSet<Instruction *, 32> Visited; 306 SmallVector<Instruction*, 16> WorkList; 307 for (User *J : AAPtr->users()) { 308 if (J == ACall) 309 continue; 310 311 if (Instruction *K = dyn_cast<Instruction>(J)) 312 if (isValidAssumeForContext(ACall, K, DT)) 313 WorkList.push_back(K); 314 } 315 316 while (!WorkList.empty()) { 317 Instruction *J = WorkList.pop_back_val(); 318 319 if (LoadInst *LI = dyn_cast<LoadInst>(J)) { 320 unsigned NewAlignment = getNewAlignment(AASCEV, AlignSCEV, OffSCEV, 321 LI->getPointerOperand(), SE); 322 323 if (NewAlignment > LI->getAlignment()) { 324 LI->setAlignment(NewAlignment); 325 ++NumLoadAlignChanged; 326 } 327 } else if (StoreInst *SI = dyn_cast<StoreInst>(J)) { 328 unsigned NewAlignment = getNewAlignment(AASCEV, AlignSCEV, OffSCEV, 329 SI->getPointerOperand(), SE); 330 331 if (NewAlignment > SI->getAlignment()) { 332 SI->setAlignment(NewAlignment); 333 ++NumStoreAlignChanged; 334 } 335 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(J)) { 336 unsigned NewDestAlignment = getNewAlignment(AASCEV, AlignSCEV, OffSCEV, 337 MI->getDest(), SE); 338 339 // For memory transfers, we need a common alignment for both the 340 // source and destination. If we have a new alignment for this 341 // instruction, but only for one operand, save it. If we reach the 342 // other operand through another assumption later, then we may 343 // change the alignment at that point. 344 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { 345 unsigned NewSrcAlignment = getNewAlignment(AASCEV, AlignSCEV, OffSCEV, 346 MTI->getSource(), SE); 347 348 DenseMap<MemTransferInst *, unsigned>::iterator DI = 349 NewDestAlignments.find(MTI); 350 unsigned AltDestAlignment = (DI == NewDestAlignments.end()) ? 351 0 : DI->second; 352 353 DenseMap<MemTransferInst *, unsigned>::iterator SI = 354 NewSrcAlignments.find(MTI); 355 unsigned AltSrcAlignment = (SI == NewSrcAlignments.end()) ? 356 0 : SI->second; 357 358 DEBUG(dbgs() << "\tmem trans: " << NewDestAlignment << " " << 359 AltDestAlignment << " " << NewSrcAlignment << 360 " " << AltSrcAlignment << "\n"); 361 362 // Of these four alignments, pick the largest possible... 363 unsigned NewAlignment = 0; 364 if (NewDestAlignment <= std::max(NewSrcAlignment, AltSrcAlignment)) 365 NewAlignment = std::max(NewAlignment, NewDestAlignment); 366 if (AltDestAlignment <= std::max(NewSrcAlignment, AltSrcAlignment)) 367 NewAlignment = std::max(NewAlignment, AltDestAlignment); 368 if (NewSrcAlignment <= std::max(NewDestAlignment, AltDestAlignment)) 369 NewAlignment = std::max(NewAlignment, NewSrcAlignment); 370 if (AltSrcAlignment <= std::max(NewDestAlignment, AltDestAlignment)) 371 NewAlignment = std::max(NewAlignment, AltSrcAlignment); 372 373 if (NewAlignment > MI->getAlignment()) { 374 MI->setAlignment(ConstantInt::get(Type::getInt32Ty( 375 MI->getParent()->getContext()), NewAlignment)); 376 ++NumMemIntAlignChanged; 377 } 378 379 NewDestAlignments.insert(std::make_pair(MTI, NewDestAlignment)); 380 NewSrcAlignments.insert(std::make_pair(MTI, NewSrcAlignment)); 381 } else if (NewDestAlignment > MI->getAlignment()) { 382 assert((!isa<MemIntrinsic>(MI) || isa<MemSetInst>(MI)) && 383 "Unknown memory intrinsic"); 384 385 MI->setAlignment(ConstantInt::get(Type::getInt32Ty( 386 MI->getParent()->getContext()), NewDestAlignment)); 387 ++NumMemIntAlignChanged; 388 } 389 } 390 391 // Now that we've updated that use of the pointer, look for other uses of 392 // the pointer to update. 393 Visited.insert(J); 394 for (User *UJ : J->users()) { 395 Instruction *K = cast<Instruction>(UJ); 396 if (!Visited.count(K) && isValidAssumeForContext(ACall, K, DT)) 397 WorkList.push_back(K); 398 } 399 } 400 401 return true; 402 } 403 404 bool AlignmentFromAssumptions::runOnFunction(Function &F) { 405 if (skipFunction(F)) 406 return false; 407 408 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 409 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 410 411 return Impl.runImpl(F, SE, DT); 412 } 413 414 bool AlignmentFromAssumptionsPass::runImpl(Function &F, ScalarEvolution *SE_, 415 DominatorTree *DT_) { 416 SE = SE_; 417 DT = DT_; 418 419 NewDestAlignments.clear(); 420 NewSrcAlignments.clear(); 421 422 bool Changed = false; 423 424 for (auto &B : F) 425 for (auto &I : B) 426 if (auto *II = dyn_cast<IntrinsicInst>(&I)) 427 if (II->getIntrinsicID() == Intrinsic::assume) 428 Changed |= processAssumption(II); 429 430 return Changed; 431 } 432 433 PreservedAnalyses 434 AlignmentFromAssumptionsPass::run(Function &F, FunctionAnalysisManager &AM) { 435 436 ScalarEvolution &SE = AM.getResult<ScalarEvolutionAnalysis>(F); 437 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F); 438 bool Changed = runImpl(F, &SE, &DT); 439 440 // FIXME: We need to invalidate this to avoid PR28400. Is there a better 441 // solution? 442 AM.invalidate<ScalarEvolutionAnalysis>(F); 443 444 if (!Changed) 445 return PreservedAnalyses::all(); 446 PreservedAnalyses PA; 447 PA.preserve<AAManager>(); 448 PA.preserve<ScalarEvolutionAnalysis>(); 449 PA.preserve<GlobalsAA>(); 450 PA.preserve<LoopAnalysis>(); 451 PA.preserve<DominatorTreeAnalysis>(); 452 return PA; 453 } 454