1 //===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===// 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 // This file defines the primary stateless implementation of the 11 // Alias Analysis interface that implements identities (two different 12 // globals cannot alias, etc), but does no stateful analysis. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/Analysis/Passes.h" 17 #include "llvm/ADT/SmallPtrSet.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/Analysis/AliasAnalysis.h" 20 #include "llvm/Analysis/AssumptionTracker.h" 21 #include "llvm/Analysis/CFG.h" 22 #include "llvm/Analysis/CaptureTracking.h" 23 #include "llvm/Analysis/InstructionSimplify.h" 24 #include "llvm/Analysis/LoopInfo.h" 25 #include "llvm/Analysis/MemoryBuiltins.h" 26 #include "llvm/Analysis/ValueTracking.h" 27 #include "llvm/IR/Constants.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/Dominators.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/GetElementPtrTypeIterator.h" 33 #include "llvm/IR/GlobalAlias.h" 34 #include "llvm/IR/GlobalVariable.h" 35 #include "llvm/IR/Instructions.h" 36 #include "llvm/IR/IntrinsicInst.h" 37 #include "llvm/IR/LLVMContext.h" 38 #include "llvm/IR/Operator.h" 39 #include "llvm/Pass.h" 40 #include "llvm/Support/ErrorHandling.h" 41 #include "llvm/Target/TargetLibraryInfo.h" 42 #include <algorithm> 43 using namespace llvm; 44 45 /// Cutoff after which to stop analysing a set of phi nodes potentially involved 46 /// in a cycle. Because we are analysing 'through' phi nodes we need to be 47 /// careful with value equivalence. We use reachability to make sure a value 48 /// cannot be involved in a cycle. 49 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20; 50 51 // The max limit of the search depth in DecomposeGEPExpression() and 52 // GetUnderlyingObject(), both functions need to use the same search 53 // depth otherwise the algorithm in aliasGEP will assert. 54 static const unsigned MaxLookupSearchDepth = 6; 55 56 //===----------------------------------------------------------------------===// 57 // Useful predicates 58 //===----------------------------------------------------------------------===// 59 60 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local 61 /// object that never escapes from the function. 62 static bool isNonEscapingLocalObject(const Value *V) { 63 // If this is a local allocation, check to see if it escapes. 64 if (isa<AllocaInst>(V) || isNoAliasCall(V)) 65 // Set StoreCaptures to True so that we can assume in our callers that the 66 // pointer is not the result of a load instruction. Currently 67 // PointerMayBeCaptured doesn't have any special analysis for the 68 // StoreCaptures=false case; if it did, our callers could be refined to be 69 // more precise. 70 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true); 71 72 // If this is an argument that corresponds to a byval or noalias argument, 73 // then it has not escaped before entering the function. Check if it escapes 74 // inside the function. 75 if (const Argument *A = dyn_cast<Argument>(V)) 76 if (A->hasByValAttr() || A->hasNoAliasAttr()) 77 // Note even if the argument is marked nocapture we still need to check 78 // for copies made inside the function. The nocapture attribute only 79 // specifies that there are no copies made that outlive the function. 80 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true); 81 82 return false; 83 } 84 85 /// isEscapeSource - Return true if the pointer is one which would have 86 /// been considered an escape by isNonEscapingLocalObject. 87 static bool isEscapeSource(const Value *V) { 88 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V)) 89 return true; 90 91 // The load case works because isNonEscapingLocalObject considers all 92 // stores to be escapes (it passes true for the StoreCaptures argument 93 // to PointerMayBeCaptured). 94 if (isa<LoadInst>(V)) 95 return true; 96 97 return false; 98 } 99 100 /// getObjectSize - Return the size of the object specified by V, or 101 /// UnknownSize if unknown. 102 static uint64_t getObjectSize(const Value *V, const DataLayout &DL, 103 const TargetLibraryInfo &TLI, 104 bool RoundToAlign = false) { 105 uint64_t Size; 106 if (getObjectSize(V, Size, &DL, &TLI, RoundToAlign)) 107 return Size; 108 return AliasAnalysis::UnknownSize; 109 } 110 111 /// isObjectSmallerThan - Return true if we can prove that the object specified 112 /// by V is smaller than Size. 113 static bool isObjectSmallerThan(const Value *V, uint64_t Size, 114 const DataLayout &DL, 115 const TargetLibraryInfo &TLI) { 116 // Note that the meanings of the "object" are slightly different in the 117 // following contexts: 118 // c1: llvm::getObjectSize() 119 // c2: llvm.objectsize() intrinsic 120 // c3: isObjectSmallerThan() 121 // c1 and c2 share the same meaning; however, the meaning of "object" in c3 122 // refers to the "entire object". 123 // 124 // Consider this example: 125 // char *p = (char*)malloc(100) 126 // char *q = p+80; 127 // 128 // In the context of c1 and c2, the "object" pointed by q refers to the 129 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20. 130 // 131 // However, in the context of c3, the "object" refers to the chunk of memory 132 // being allocated. So, the "object" has 100 bytes, and q points to the middle 133 // the "object". In case q is passed to isObjectSmallerThan() as the 1st 134 // parameter, before the llvm::getObjectSize() is called to get the size of 135 // entire object, we should: 136 // - either rewind the pointer q to the base-address of the object in 137 // question (in this case rewind to p), or 138 // - just give up. It is up to caller to make sure the pointer is pointing 139 // to the base address the object. 140 // 141 // We go for 2nd option for simplicity. 142 if (!isIdentifiedObject(V)) 143 return false; 144 145 // This function needs to use the aligned object size because we allow 146 // reads a bit past the end given sufficient alignment. 147 uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/true); 148 149 return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize < Size; 150 } 151 152 /// isObjectSize - Return true if we can prove that the object specified 153 /// by V has size Size. 154 static bool isObjectSize(const Value *V, uint64_t Size, 155 const DataLayout &DL, const TargetLibraryInfo &TLI) { 156 uint64_t ObjectSize = getObjectSize(V, DL, TLI); 157 return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize == Size; 158 } 159 160 //===----------------------------------------------------------------------===// 161 // GetElementPtr Instruction Decomposition and Analysis 162 //===----------------------------------------------------------------------===// 163 164 namespace { 165 enum ExtensionKind { 166 EK_NotExtended, 167 EK_SignExt, 168 EK_ZeroExt 169 }; 170 171 struct VariableGEPIndex { 172 const Value *V; 173 ExtensionKind Extension; 174 int64_t Scale; 175 176 bool operator==(const VariableGEPIndex &Other) const { 177 return V == Other.V && Extension == Other.Extension && 178 Scale == Other.Scale; 179 } 180 181 bool operator!=(const VariableGEPIndex &Other) const { 182 return !operator==(Other); 183 } 184 }; 185 } 186 187 188 /// GetLinearExpression - Analyze the specified value as a linear expression: 189 /// "A*V + B", where A and B are constant integers. Return the scale and offset 190 /// values as APInts and return V as a Value*, and return whether we looked 191 /// through any sign or zero extends. The incoming Value is known to have 192 /// IntegerType and it may already be sign or zero extended. 193 /// 194 /// Note that this looks through extends, so the high bits may not be 195 /// represented in the result. 196 static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset, 197 ExtensionKind &Extension, 198 const DataLayout &DL, unsigned Depth, 199 AssumptionTracker *AT, 200 DominatorTree *DT) { 201 assert(V->getType()->isIntegerTy() && "Not an integer value"); 202 203 // Limit our recursion depth. 204 if (Depth == 6) { 205 Scale = 1; 206 Offset = 0; 207 return V; 208 } 209 210 if (ConstantInt *Const = dyn_cast<ConstantInt>(V)) { 211 // if it's a constant, just convert it to an offset 212 // and remove the variable. 213 Offset += Const->getValue(); 214 assert(Scale == 0 && "Constant values don't have a scale"); 215 return V; 216 } 217 218 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) { 219 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) { 220 switch (BOp->getOpcode()) { 221 default: break; 222 case Instruction::Or: 223 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't 224 // analyze it. 225 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), &DL, 0, 226 AT, BOp, DT)) 227 break; 228 // FALL THROUGH. 229 case Instruction::Add: 230 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension, 231 DL, Depth+1, AT, DT); 232 Offset += RHSC->getValue(); 233 return V; 234 case Instruction::Mul: 235 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension, 236 DL, Depth+1, AT, DT); 237 Offset *= RHSC->getValue(); 238 Scale *= RHSC->getValue(); 239 return V; 240 case Instruction::Shl: 241 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension, 242 DL, Depth+1, AT, DT); 243 Offset <<= RHSC->getValue().getLimitedValue(); 244 Scale <<= RHSC->getValue().getLimitedValue(); 245 return V; 246 } 247 } 248 } 249 250 // Since GEP indices are sign extended anyway, we don't care about the high 251 // bits of a sign or zero extended value - just scales and offsets. The 252 // extensions have to be consistent though. 253 if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) || 254 (isa<ZExtInst>(V) && Extension != EK_SignExt)) { 255 Value *CastOp = cast<CastInst>(V)->getOperand(0); 256 unsigned OldWidth = Scale.getBitWidth(); 257 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits(); 258 Scale = Scale.trunc(SmallWidth); 259 Offset = Offset.trunc(SmallWidth); 260 Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt; 261 262 Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension, 263 DL, Depth+1, AT, DT); 264 Scale = Scale.zext(OldWidth); 265 266 // We have to sign-extend even if Extension == EK_ZeroExt as we can't 267 // decompose a sign extension (i.e. zext(x - 1) != zext(x) - zext(-1)). 268 Offset = Offset.sext(OldWidth); 269 270 return Result; 271 } 272 273 Scale = 1; 274 Offset = 0; 275 return V; 276 } 277 278 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it 279 /// into a base pointer with a constant offset and a number of scaled symbolic 280 /// offsets. 281 /// 282 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale in 283 /// the VarIndices vector) are Value*'s that are known to be scaled by the 284 /// specified amount, but which may have other unrepresented high bits. As such, 285 /// the gep cannot necessarily be reconstructed from its decomposed form. 286 /// 287 /// When DataLayout is around, this function is capable of analyzing everything 288 /// that GetUnderlyingObject can look through. To be able to do that 289 /// GetUnderlyingObject and DecomposeGEPExpression must use the same search 290 /// depth (MaxLookupSearchDepth). 291 /// When DataLayout not is around, it just looks through pointer casts. 292 /// 293 static const Value * 294 DecomposeGEPExpression(const Value *V, int64_t &BaseOffs, 295 SmallVectorImpl<VariableGEPIndex> &VarIndices, 296 bool &MaxLookupReached, const DataLayout *DL, 297 AssumptionTracker *AT, DominatorTree *DT) { 298 // Limit recursion depth to limit compile time in crazy cases. 299 unsigned MaxLookup = MaxLookupSearchDepth; 300 MaxLookupReached = false; 301 302 BaseOffs = 0; 303 do { 304 // See if this is a bitcast or GEP. 305 const Operator *Op = dyn_cast<Operator>(V); 306 if (!Op) { 307 // The only non-operator case we can handle are GlobalAliases. 308 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 309 if (!GA->mayBeOverridden()) { 310 V = GA->getAliasee(); 311 continue; 312 } 313 } 314 return V; 315 } 316 317 if (Op->getOpcode() == Instruction::BitCast || 318 Op->getOpcode() == Instruction::AddrSpaceCast) { 319 V = Op->getOperand(0); 320 continue; 321 } 322 323 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op); 324 if (!GEPOp) { 325 // If it's not a GEP, hand it off to SimplifyInstruction to see if it 326 // can come up with something. This matches what GetUnderlyingObject does. 327 if (const Instruction *I = dyn_cast<Instruction>(V)) 328 // TODO: Get a DominatorTree and AssumptionTracker and use them here 329 // (these are both now available in this function, but this should be 330 // updated when GetUnderlyingObject is updated). TLI should be 331 // provided also. 332 if (const Value *Simplified = 333 SimplifyInstruction(const_cast<Instruction *>(I), DL)) { 334 V = Simplified; 335 continue; 336 } 337 338 return V; 339 } 340 341 // Don't attempt to analyze GEPs over unsized objects. 342 if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized()) 343 return V; 344 345 // If we are lacking DataLayout information, we can't compute the offets of 346 // elements computed by GEPs. However, we can handle bitcast equivalent 347 // GEPs. 348 if (!DL) { 349 if (!GEPOp->hasAllZeroIndices()) 350 return V; 351 V = GEPOp->getOperand(0); 352 continue; 353 } 354 355 unsigned AS = GEPOp->getPointerAddressSpace(); 356 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices. 357 gep_type_iterator GTI = gep_type_begin(GEPOp); 358 for (User::const_op_iterator I = GEPOp->op_begin()+1, 359 E = GEPOp->op_end(); I != E; ++I) { 360 Value *Index = *I; 361 // Compute the (potentially symbolic) offset in bytes for this index. 362 if (StructType *STy = dyn_cast<StructType>(*GTI++)) { 363 // For a struct, add the member offset. 364 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue(); 365 if (FieldNo == 0) continue; 366 367 BaseOffs += DL->getStructLayout(STy)->getElementOffset(FieldNo); 368 continue; 369 } 370 371 // For an array/pointer, add the element offset, explicitly scaled. 372 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) { 373 if (CIdx->isZero()) continue; 374 BaseOffs += DL->getTypeAllocSize(*GTI)*CIdx->getSExtValue(); 375 continue; 376 } 377 378 uint64_t Scale = DL->getTypeAllocSize(*GTI); 379 ExtensionKind Extension = EK_NotExtended; 380 381 // If the integer type is smaller than the pointer size, it is implicitly 382 // sign extended to pointer size. 383 unsigned Width = Index->getType()->getIntegerBitWidth(); 384 if (DL->getPointerSizeInBits(AS) > Width) 385 Extension = EK_SignExt; 386 387 // Use GetLinearExpression to decompose the index into a C1*V+C2 form. 388 APInt IndexScale(Width, 0), IndexOffset(Width, 0); 389 Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension, 390 *DL, 0, AT, DT); 391 392 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale. 393 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale. 394 BaseOffs += IndexOffset.getSExtValue()*Scale; 395 Scale *= IndexScale.getSExtValue(); 396 397 // If we already had an occurrence of this index variable, merge this 398 // scale into it. For example, we want to handle: 399 // A[x][x] -> x*16 + x*4 -> x*20 400 // This also ensures that 'x' only appears in the index list once. 401 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) { 402 if (VarIndices[i].V == Index && 403 VarIndices[i].Extension == Extension) { 404 Scale += VarIndices[i].Scale; 405 VarIndices.erase(VarIndices.begin()+i); 406 break; 407 } 408 } 409 410 // Make sure that we have a scale that makes sense for this target's 411 // pointer size. 412 if (unsigned ShiftBits = 64 - DL->getPointerSizeInBits(AS)) { 413 Scale <<= ShiftBits; 414 Scale = (int64_t)Scale >> ShiftBits; 415 } 416 417 if (Scale) { 418 VariableGEPIndex Entry = {Index, Extension, 419 static_cast<int64_t>(Scale)}; 420 VarIndices.push_back(Entry); 421 } 422 } 423 424 // Analyze the base pointer next. 425 V = GEPOp->getOperand(0); 426 } while (--MaxLookup); 427 428 // If the chain of expressions is too deep, just return early. 429 MaxLookupReached = true; 430 return V; 431 } 432 433 //===----------------------------------------------------------------------===// 434 // BasicAliasAnalysis Pass 435 //===----------------------------------------------------------------------===// 436 437 #ifndef NDEBUG 438 static const Function *getParent(const Value *V) { 439 if (const Instruction *inst = dyn_cast<Instruction>(V)) 440 return inst->getParent()->getParent(); 441 442 if (const Argument *arg = dyn_cast<Argument>(V)) 443 return arg->getParent(); 444 445 return nullptr; 446 } 447 448 static bool notDifferentParent(const Value *O1, const Value *O2) { 449 450 const Function *F1 = getParent(O1); 451 const Function *F2 = getParent(O2); 452 453 return !F1 || !F2 || F1 == F2; 454 } 455 #endif 456 457 namespace { 458 /// BasicAliasAnalysis - This is the primary alias analysis implementation. 459 struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis { 460 static char ID; // Class identification, replacement for typeinfo 461 BasicAliasAnalysis() : ImmutablePass(ID) { 462 initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry()); 463 } 464 465 void initializePass() override { 466 InitializeAliasAnalysis(this); 467 } 468 469 void getAnalysisUsage(AnalysisUsage &AU) const override { 470 AU.addRequired<AliasAnalysis>(); 471 AU.addRequired<AssumptionTracker>(); 472 AU.addRequired<TargetLibraryInfo>(); 473 } 474 475 AliasResult alias(const Location &LocA, const Location &LocB) override { 476 assert(AliasCache.empty() && "AliasCache must be cleared after use!"); 477 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) && 478 "BasicAliasAnalysis doesn't support interprocedural queries."); 479 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags, 480 LocB.Ptr, LocB.Size, LocB.AATags); 481 // AliasCache rarely has more than 1 or 2 elements, always use 482 // shrink_and_clear so it quickly returns to the inline capacity of the 483 // SmallDenseMap if it ever grows larger. 484 // FIXME: This should really be shrink_to_inline_capacity_and_clear(). 485 AliasCache.shrink_and_clear(); 486 VisitedPhiBBs.clear(); 487 return Alias; 488 } 489 490 ModRefResult getModRefInfo(ImmutableCallSite CS, 491 const Location &Loc) override; 492 493 ModRefResult getModRefInfo(ImmutableCallSite CS1, 494 ImmutableCallSite CS2) override; 495 496 /// pointsToConstantMemory - Chase pointers until we find a (constant 497 /// global) or not. 498 bool pointsToConstantMemory(const Location &Loc, bool OrLocal) override; 499 500 /// Get the location associated with a pointer argument of a callsite. 501 Location getArgLocation(ImmutableCallSite CS, unsigned ArgIdx, 502 ModRefResult &Mask) override; 503 504 /// getModRefBehavior - Return the behavior when calling the given 505 /// call site. 506 ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override; 507 508 /// getModRefBehavior - Return the behavior when calling the given function. 509 /// For use when the call site is not known. 510 ModRefBehavior getModRefBehavior(const Function *F) override; 511 512 /// getAdjustedAnalysisPointer - This method is used when a pass implements 513 /// an analysis interface through multiple inheritance. If needed, it 514 /// should override this to adjust the this pointer as needed for the 515 /// specified pass info. 516 void *getAdjustedAnalysisPointer(const void *ID) override { 517 if (ID == &AliasAnalysis::ID) 518 return (AliasAnalysis*)this; 519 return this; 520 } 521 522 private: 523 // AliasCache - Track alias queries to guard against recursion. 524 typedef std::pair<Location, Location> LocPair; 525 typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy; 526 AliasCacheTy AliasCache; 527 528 /// \brief Track phi nodes we have visited. When interpret "Value" pointer 529 /// equality as value equality we need to make sure that the "Value" is not 530 /// part of a cycle. Otherwise, two uses could come from different 531 /// "iterations" of a cycle and see different values for the same "Value" 532 /// pointer. 533 /// The following example shows the problem: 534 /// %p = phi(%alloca1, %addr2) 535 /// %l = load %ptr 536 /// %addr1 = gep, %alloca2, 0, %l 537 /// %addr2 = gep %alloca2, 0, (%l + 1) 538 /// alias(%p, %addr1) -> MayAlias ! 539 /// store %l, ... 540 SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs; 541 542 // Visited - Track instructions visited by pointsToConstantMemory. 543 SmallPtrSet<const Value*, 16> Visited; 544 545 /// \brief Check whether two Values can be considered equivalent. 546 /// 547 /// In addition to pointer equivalence of \p V1 and \p V2 this checks 548 /// whether they can not be part of a cycle in the value graph by looking at 549 /// all visited phi nodes an making sure that the phis cannot reach the 550 /// value. We have to do this because we are looking through phi nodes (That 551 /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB). 552 bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2); 553 554 /// \brief Dest and Src are the variable indices from two decomposed 555 /// GetElementPtr instructions GEP1 and GEP2 which have common base 556 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic 557 /// difference between the two pointers. 558 void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest, 559 const SmallVectorImpl<VariableGEPIndex> &Src); 560 561 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP 562 // instruction against another. 563 AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size, 564 const AAMDNodes &V1AAInfo, 565 const Value *V2, uint64_t V2Size, 566 const AAMDNodes &V2AAInfo, 567 const Value *UnderlyingV1, const Value *UnderlyingV2); 568 569 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI 570 // instruction against another. 571 AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize, 572 const AAMDNodes &PNAAInfo, 573 const Value *V2, uint64_t V2Size, 574 const AAMDNodes &V2AAInfo); 575 576 /// aliasSelect - Disambiguate a Select instruction against another value. 577 AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize, 578 const AAMDNodes &SIAAInfo, 579 const Value *V2, uint64_t V2Size, 580 const AAMDNodes &V2AAInfo); 581 582 AliasResult aliasCheck(const Value *V1, uint64_t V1Size, 583 AAMDNodes V1AATag, 584 const Value *V2, uint64_t V2Size, 585 AAMDNodes V2AATag); 586 }; 587 } // End of anonymous namespace 588 589 // Register this pass... 590 char BasicAliasAnalysis::ID = 0; 591 INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa", 592 "Basic Alias Analysis (stateless AA impl)", 593 false, true, false) 594 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker) 595 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo) 596 INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa", 597 "Basic Alias Analysis (stateless AA impl)", 598 false, true, false) 599 600 601 ImmutablePass *llvm::createBasicAliasAnalysisPass() { 602 return new BasicAliasAnalysis(); 603 } 604 605 /// pointsToConstantMemory - Returns whether the given pointer value 606 /// points to memory that is local to the function, with global constants being 607 /// considered local to all functions. 608 bool 609 BasicAliasAnalysis::pointsToConstantMemory(const Location &Loc, bool OrLocal) { 610 assert(Visited.empty() && "Visited must be cleared after use!"); 611 612 unsigned MaxLookup = 8; 613 SmallVector<const Value *, 16> Worklist; 614 Worklist.push_back(Loc.Ptr); 615 do { 616 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), DL); 617 if (!Visited.insert(V).second) { 618 Visited.clear(); 619 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal); 620 } 621 622 // An alloca instruction defines local memory. 623 if (OrLocal && isa<AllocaInst>(V)) 624 continue; 625 626 // A global constant counts as local memory for our purposes. 627 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) { 628 // Note: this doesn't require GV to be "ODR" because it isn't legal for a 629 // global to be marked constant in some modules and non-constant in 630 // others. GV may even be a declaration, not a definition. 631 if (!GV->isConstant()) { 632 Visited.clear(); 633 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal); 634 } 635 continue; 636 } 637 638 // If both select values point to local memory, then so does the select. 639 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) { 640 Worklist.push_back(SI->getTrueValue()); 641 Worklist.push_back(SI->getFalseValue()); 642 continue; 643 } 644 645 // If all values incoming to a phi node point to local memory, then so does 646 // the phi. 647 if (const PHINode *PN = dyn_cast<PHINode>(V)) { 648 // Don't bother inspecting phi nodes with many operands. 649 if (PN->getNumIncomingValues() > MaxLookup) { 650 Visited.clear(); 651 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal); 652 } 653 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 654 Worklist.push_back(PN->getIncomingValue(i)); 655 continue; 656 } 657 658 // Otherwise be conservative. 659 Visited.clear(); 660 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal); 661 662 } while (!Worklist.empty() && --MaxLookup); 663 664 Visited.clear(); 665 return Worklist.empty(); 666 } 667 668 static bool isMemsetPattern16(const Function *MS, 669 const TargetLibraryInfo &TLI) { 670 if (TLI.has(LibFunc::memset_pattern16) && 671 MS->getName() == "memset_pattern16") { 672 FunctionType *MemsetType = MS->getFunctionType(); 673 if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 && 674 isa<PointerType>(MemsetType->getParamType(0)) && 675 isa<PointerType>(MemsetType->getParamType(1)) && 676 isa<IntegerType>(MemsetType->getParamType(2))) 677 return true; 678 } 679 680 return false; 681 } 682 683 /// getModRefBehavior - Return the behavior when calling the given call site. 684 AliasAnalysis::ModRefBehavior 685 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) { 686 if (CS.doesNotAccessMemory()) 687 // Can't do better than this. 688 return DoesNotAccessMemory; 689 690 ModRefBehavior Min = UnknownModRefBehavior; 691 692 // If the callsite knows it only reads memory, don't return worse 693 // than that. 694 if (CS.onlyReadsMemory()) 695 Min = OnlyReadsMemory; 696 697 // The AliasAnalysis base class has some smarts, lets use them. 698 return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min); 699 } 700 701 /// getModRefBehavior - Return the behavior when calling the given function. 702 /// For use when the call site is not known. 703 AliasAnalysis::ModRefBehavior 704 BasicAliasAnalysis::getModRefBehavior(const Function *F) { 705 // If the function declares it doesn't access memory, we can't do better. 706 if (F->doesNotAccessMemory()) 707 return DoesNotAccessMemory; 708 709 // For intrinsics, we can check the table. 710 if (unsigned iid = F->getIntrinsicID()) { 711 #define GET_INTRINSIC_MODREF_BEHAVIOR 712 #include "llvm/IR/Intrinsics.gen" 713 #undef GET_INTRINSIC_MODREF_BEHAVIOR 714 } 715 716 ModRefBehavior Min = UnknownModRefBehavior; 717 718 // If the function declares it only reads memory, go with that. 719 if (F->onlyReadsMemory()) 720 Min = OnlyReadsMemory; 721 722 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfo>(); 723 if (isMemsetPattern16(F, TLI)) 724 Min = OnlyAccessesArgumentPointees; 725 726 // Otherwise be conservative. 727 return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min); 728 } 729 730 AliasAnalysis::Location 731 BasicAliasAnalysis::getArgLocation(ImmutableCallSite CS, unsigned ArgIdx, 732 ModRefResult &Mask) { 733 Location Loc = AliasAnalysis::getArgLocation(CS, ArgIdx, Mask); 734 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfo>(); 735 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction()); 736 if (II != nullptr) 737 switch (II->getIntrinsicID()) { 738 default: break; 739 case Intrinsic::memset: 740 case Intrinsic::memcpy: 741 case Intrinsic::memmove: { 742 assert((ArgIdx == 0 || ArgIdx == 1) && 743 "Invalid argument index for memory intrinsic"); 744 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2))) 745 Loc.Size = LenCI->getZExtValue(); 746 assert(Loc.Ptr == II->getArgOperand(ArgIdx) && 747 "Memory intrinsic location pointer not argument?"); 748 Mask = ArgIdx ? Ref : Mod; 749 break; 750 } 751 case Intrinsic::lifetime_start: 752 case Intrinsic::lifetime_end: 753 case Intrinsic::invariant_start: { 754 assert(ArgIdx == 1 && "Invalid argument index"); 755 assert(Loc.Ptr == II->getArgOperand(ArgIdx) && 756 "Intrinsic location pointer not argument?"); 757 Loc.Size = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue(); 758 break; 759 } 760 case Intrinsic::invariant_end: { 761 assert(ArgIdx == 2 && "Invalid argument index"); 762 assert(Loc.Ptr == II->getArgOperand(ArgIdx) && 763 "Intrinsic location pointer not argument?"); 764 Loc.Size = cast<ConstantInt>(II->getArgOperand(1))->getZExtValue(); 765 break; 766 } 767 case Intrinsic::arm_neon_vld1: { 768 assert(ArgIdx == 0 && "Invalid argument index"); 769 assert(Loc.Ptr == II->getArgOperand(ArgIdx) && 770 "Intrinsic location pointer not argument?"); 771 // LLVM's vld1 and vst1 intrinsics currently only support a single 772 // vector register. 773 if (DL) 774 Loc.Size = DL->getTypeStoreSize(II->getType()); 775 break; 776 } 777 case Intrinsic::arm_neon_vst1: { 778 assert(ArgIdx == 0 && "Invalid argument index"); 779 assert(Loc.Ptr == II->getArgOperand(ArgIdx) && 780 "Intrinsic location pointer not argument?"); 781 if (DL) 782 Loc.Size = DL->getTypeStoreSize(II->getArgOperand(1)->getType()); 783 break; 784 } 785 } 786 787 // We can bound the aliasing properties of memset_pattern16 just as we can 788 // for memcpy/memset. This is particularly important because the 789 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16 790 // whenever possible. 791 else if (CS.getCalledFunction() && 792 isMemsetPattern16(CS.getCalledFunction(), TLI)) { 793 assert((ArgIdx == 0 || ArgIdx == 1) && 794 "Invalid argument index for memset_pattern16"); 795 if (ArgIdx == 1) 796 Loc.Size = 16; 797 else if (const ConstantInt *LenCI = 798 dyn_cast<ConstantInt>(CS.getArgument(2))) 799 Loc.Size = LenCI->getZExtValue(); 800 assert(Loc.Ptr == CS.getArgument(ArgIdx) && 801 "memset_pattern16 location pointer not argument?"); 802 Mask = ArgIdx ? Ref : Mod; 803 } 804 // FIXME: Handle memset_pattern4 and memset_pattern8 also. 805 806 return Loc; 807 } 808 809 static bool isAssumeIntrinsic(ImmutableCallSite CS) { 810 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction()); 811 if (II && II->getIntrinsicID() == Intrinsic::assume) 812 return true; 813 814 return false; 815 } 816 817 /// getModRefInfo - Check to see if the specified callsite can clobber the 818 /// specified memory object. Since we only look at local properties of this 819 /// function, we really can't say much about this query. We do, however, use 820 /// simple "address taken" analysis on local objects. 821 AliasAnalysis::ModRefResult 822 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS, 823 const Location &Loc) { 824 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) && 825 "AliasAnalysis query involving multiple functions!"); 826 827 const Value *Object = GetUnderlyingObject(Loc.Ptr, DL); 828 829 // If this is a tail call and Loc.Ptr points to a stack location, we know that 830 // the tail call cannot access or modify the local stack. 831 // We cannot exclude byval arguments here; these belong to the caller of 832 // the current function not to the current function, and a tail callee 833 // may reference them. 834 if (isa<AllocaInst>(Object)) 835 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) 836 if (CI->isTailCall()) 837 return NoModRef; 838 839 // If the pointer is to a locally allocated object that does not escape, 840 // then the call can not mod/ref the pointer unless the call takes the pointer 841 // as an argument, and itself doesn't capture it. 842 if (!isa<Constant>(Object) && CS.getInstruction() != Object && 843 isNonEscapingLocalObject(Object)) { 844 bool PassedAsArg = false; 845 unsigned ArgNo = 0; 846 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end(); 847 CI != CE; ++CI, ++ArgNo) { 848 // Only look at the no-capture or byval pointer arguments. If this 849 // pointer were passed to arguments that were neither of these, then it 850 // couldn't be no-capture. 851 if (!(*CI)->getType()->isPointerTy() || 852 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo))) 853 continue; 854 855 // If this is a no-capture pointer argument, see if we can tell that it 856 // is impossible to alias the pointer we're checking. If not, we have to 857 // assume that the call could touch the pointer, even though it doesn't 858 // escape. 859 if (!isNoAlias(Location(*CI), Location(Object))) { 860 PassedAsArg = true; 861 break; 862 } 863 } 864 865 if (!PassedAsArg) 866 return NoModRef; 867 } 868 869 // While the assume intrinsic is marked as arbitrarily writing so that 870 // proper control dependencies will be maintained, it never aliases any 871 // particular memory location. 872 if (isAssumeIntrinsic(CS)) 873 return NoModRef; 874 875 // The AliasAnalysis base class has some smarts, lets use them. 876 return AliasAnalysis::getModRefInfo(CS, Loc); 877 } 878 879 AliasAnalysis::ModRefResult 880 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS1, 881 ImmutableCallSite CS2) { 882 // While the assume intrinsic is marked as arbitrarily writing so that 883 // proper control dependencies will be maintained, it never aliases any 884 // particular memory location. 885 if (isAssumeIntrinsic(CS1) || isAssumeIntrinsic(CS2)) 886 return NoModRef; 887 888 // The AliasAnalysis base class has some smarts, lets use them. 889 return AliasAnalysis::getModRefInfo(CS1, CS2); 890 } 891 892 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction 893 /// against another pointer. We know that V1 is a GEP, but we don't know 894 /// anything about V2. UnderlyingV1 is GetUnderlyingObject(GEP1, DL), 895 /// UnderlyingV2 is the same for V2. 896 /// 897 AliasAnalysis::AliasResult 898 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size, 899 const AAMDNodes &V1AAInfo, 900 const Value *V2, uint64_t V2Size, 901 const AAMDNodes &V2AAInfo, 902 const Value *UnderlyingV1, 903 const Value *UnderlyingV2) { 904 int64_t GEP1BaseOffset; 905 bool GEP1MaxLookupReached; 906 SmallVector<VariableGEPIndex, 4> GEP1VariableIndices; 907 908 AssumptionTracker *AT = &getAnalysis<AssumptionTracker>(); 909 DominatorTreeWrapperPass *DTWP = 910 getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 911 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr; 912 913 // If we have two gep instructions with must-alias or not-alias'ing base 914 // pointers, figure out if the indexes to the GEP tell us anything about the 915 // derived pointer. 916 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) { 917 // Do the base pointers alias? 918 AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, AAMDNodes(), 919 UnderlyingV2, UnknownSize, AAMDNodes()); 920 921 // Check for geps of non-aliasing underlying pointers where the offsets are 922 // identical. 923 if ((BaseAlias == MayAlias) && V1Size == V2Size) { 924 // Do the base pointers alias assuming type and size. 925 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size, 926 V1AAInfo, UnderlyingV2, 927 V2Size, V2AAInfo); 928 if (PreciseBaseAlias == NoAlias) { 929 // See if the computed offset from the common pointer tells us about the 930 // relation of the resulting pointer. 931 int64_t GEP2BaseOffset; 932 bool GEP2MaxLookupReached; 933 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices; 934 const Value *GEP2BasePtr = 935 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, 936 GEP2MaxLookupReached, DL, AT, DT); 937 const Value *GEP1BasePtr = 938 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, 939 GEP1MaxLookupReached, DL, AT, DT); 940 // DecomposeGEPExpression and GetUnderlyingObject should return the 941 // same result except when DecomposeGEPExpression has no DataLayout. 942 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) { 943 assert(!DL && 944 "DecomposeGEPExpression and GetUnderlyingObject disagree!"); 945 return MayAlias; 946 } 947 // If the max search depth is reached the result is undefined 948 if (GEP2MaxLookupReached || GEP1MaxLookupReached) 949 return MayAlias; 950 951 // Same offsets. 952 if (GEP1BaseOffset == GEP2BaseOffset && 953 GEP1VariableIndices == GEP2VariableIndices) 954 return NoAlias; 955 GEP1VariableIndices.clear(); 956 } 957 } 958 959 // If we get a No or May, then return it immediately, no amount of analysis 960 // will improve this situation. 961 if (BaseAlias != MustAlias) return BaseAlias; 962 963 // Otherwise, we have a MustAlias. Since the base pointers alias each other 964 // exactly, see if the computed offset from the common pointer tells us 965 // about the relation of the resulting pointer. 966 const Value *GEP1BasePtr = 967 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, 968 GEP1MaxLookupReached, DL, AT, DT); 969 970 int64_t GEP2BaseOffset; 971 bool GEP2MaxLookupReached; 972 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices; 973 const Value *GEP2BasePtr = 974 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, 975 GEP2MaxLookupReached, DL, AT, DT); 976 977 // DecomposeGEPExpression and GetUnderlyingObject should return the 978 // same result except when DecomposeGEPExpression has no DataLayout. 979 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) { 980 assert(!DL && 981 "DecomposeGEPExpression and GetUnderlyingObject disagree!"); 982 return MayAlias; 983 } 984 // If the max search depth is reached the result is undefined 985 if (GEP2MaxLookupReached || GEP1MaxLookupReached) 986 return MayAlias; 987 988 // Subtract the GEP2 pointer from the GEP1 pointer to find out their 989 // symbolic difference. 990 GEP1BaseOffset -= GEP2BaseOffset; 991 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices); 992 993 } else { 994 // Check to see if these two pointers are related by the getelementptr 995 // instruction. If one pointer is a GEP with a non-zero index of the other 996 // pointer, we know they cannot alias. 997 998 // If both accesses are unknown size, we can't do anything useful here. 999 if (V1Size == UnknownSize && V2Size == UnknownSize) 1000 return MayAlias; 1001 1002 AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, AAMDNodes(), 1003 V2, V2Size, V2AAInfo); 1004 if (R != MustAlias) 1005 // If V2 may alias GEP base pointer, conservatively returns MayAlias. 1006 // If V2 is known not to alias GEP base pointer, then the two values 1007 // cannot alias per GEP semantics: "A pointer value formed from a 1008 // getelementptr instruction is associated with the addresses associated 1009 // with the first operand of the getelementptr". 1010 return R; 1011 1012 const Value *GEP1BasePtr = 1013 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, 1014 GEP1MaxLookupReached, DL, AT, DT); 1015 1016 // DecomposeGEPExpression and GetUnderlyingObject should return the 1017 // same result except when DecomposeGEPExpression has no DataLayout. 1018 if (GEP1BasePtr != UnderlyingV1) { 1019 assert(!DL && 1020 "DecomposeGEPExpression and GetUnderlyingObject disagree!"); 1021 return MayAlias; 1022 } 1023 // If the max search depth is reached the result is undefined 1024 if (GEP1MaxLookupReached) 1025 return MayAlias; 1026 } 1027 1028 // In the two GEP Case, if there is no difference in the offsets of the 1029 // computed pointers, the resultant pointers are a must alias. This 1030 // hapens when we have two lexically identical GEP's (for example). 1031 // 1032 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2 1033 // must aliases the GEP, the end result is a must alias also. 1034 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty()) 1035 return MustAlias; 1036 1037 // If there is a constant difference between the pointers, but the difference 1038 // is less than the size of the associated memory object, then we know 1039 // that the objects are partially overlapping. If the difference is 1040 // greater, we know they do not overlap. 1041 if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) { 1042 if (GEP1BaseOffset >= 0) { 1043 if (V2Size != UnknownSize) { 1044 if ((uint64_t)GEP1BaseOffset < V2Size) 1045 return PartialAlias; 1046 return NoAlias; 1047 } 1048 } else { 1049 // We have the situation where: 1050 // + + 1051 // | BaseOffset | 1052 // ---------------->| 1053 // |-->V1Size |-------> V2Size 1054 // GEP1 V2 1055 // We need to know that V2Size is not unknown, otherwise we might have 1056 // stripped a gep with negative index ('gep <ptr>, -1, ...). 1057 if (V1Size != UnknownSize && V2Size != UnknownSize) { 1058 if (-(uint64_t)GEP1BaseOffset < V1Size) 1059 return PartialAlias; 1060 return NoAlias; 1061 } 1062 } 1063 } 1064 1065 if (!GEP1VariableIndices.empty()) { 1066 uint64_t Modulo = 0; 1067 bool AllPositive = true; 1068 for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i) { 1069 1070 // Try to distinguish something like &A[i][1] against &A[42][0]. 1071 // Grab the least significant bit set in any of the scales. We 1072 // don't need std::abs here (even if the scale's negative) as we'll 1073 // be ^'ing Modulo with itself later. 1074 Modulo |= (uint64_t) GEP1VariableIndices[i].Scale; 1075 1076 if (AllPositive) { 1077 // If the Value could change between cycles, then any reasoning about 1078 // the Value this cycle may not hold in the next cycle. We'll just 1079 // give up if we can't determine conditions that hold for every cycle: 1080 const Value *V = GEP1VariableIndices[i].V; 1081 1082 bool SignKnownZero, SignKnownOne; 1083 ComputeSignBit( 1084 const_cast<Value *>(V), 1085 SignKnownZero, SignKnownOne, 1086 DL, 0, AT, nullptr, DT); 1087 1088 // Zero-extension widens the variable, and so forces the sign 1089 // bit to zero. 1090 bool IsZExt = GEP1VariableIndices[i].Extension == EK_ZeroExt; 1091 SignKnownZero |= IsZExt; 1092 SignKnownOne &= !IsZExt; 1093 1094 // If the variable begins with a zero then we know it's 1095 // positive, regardless of whether the value is signed or 1096 // unsigned. 1097 int64_t Scale = GEP1VariableIndices[i].Scale; 1098 AllPositive = 1099 (SignKnownZero && Scale >= 0) || 1100 (SignKnownOne && Scale < 0); 1101 } 1102 } 1103 1104 Modulo = Modulo ^ (Modulo & (Modulo - 1)); 1105 1106 // We can compute the difference between the two addresses 1107 // mod Modulo. Check whether that difference guarantees that the 1108 // two locations do not alias. 1109 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1); 1110 if (V1Size != UnknownSize && V2Size != UnknownSize && 1111 ModOffset >= V2Size && V1Size <= Modulo - ModOffset) 1112 return NoAlias; 1113 1114 // If we know all the variables are positive, then GEP1 >= GEP1BasePtr. 1115 // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers 1116 // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr. 1117 if (AllPositive && GEP1BaseOffset > 0 && V2Size <= (uint64_t) GEP1BaseOffset) 1118 return NoAlias; 1119 } 1120 1121 // Statically, we can see that the base objects are the same, but the 1122 // pointers have dynamic offsets which we can't resolve. And none of our 1123 // little tricks above worked. 1124 // 1125 // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the 1126 // practical effect of this is protecting TBAA in the case of dynamic 1127 // indices into arrays of unions or malloc'd memory. 1128 return PartialAlias; 1129 } 1130 1131 static AliasAnalysis::AliasResult 1132 MergeAliasResults(AliasAnalysis::AliasResult A, AliasAnalysis::AliasResult B) { 1133 // If the results agree, take it. 1134 if (A == B) 1135 return A; 1136 // A mix of PartialAlias and MustAlias is PartialAlias. 1137 if ((A == AliasAnalysis::PartialAlias && B == AliasAnalysis::MustAlias) || 1138 (B == AliasAnalysis::PartialAlias && A == AliasAnalysis::MustAlias)) 1139 return AliasAnalysis::PartialAlias; 1140 // Otherwise, we don't know anything. 1141 return AliasAnalysis::MayAlias; 1142 } 1143 1144 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select 1145 /// instruction against another. 1146 AliasAnalysis::AliasResult 1147 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize, 1148 const AAMDNodes &SIAAInfo, 1149 const Value *V2, uint64_t V2Size, 1150 const AAMDNodes &V2AAInfo) { 1151 // If the values are Selects with the same condition, we can do a more precise 1152 // check: just check for aliases between the values on corresponding arms. 1153 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) 1154 if (SI->getCondition() == SI2->getCondition()) { 1155 AliasResult Alias = 1156 aliasCheck(SI->getTrueValue(), SISize, SIAAInfo, 1157 SI2->getTrueValue(), V2Size, V2AAInfo); 1158 if (Alias == MayAlias) 1159 return MayAlias; 1160 AliasResult ThisAlias = 1161 aliasCheck(SI->getFalseValue(), SISize, SIAAInfo, 1162 SI2->getFalseValue(), V2Size, V2AAInfo); 1163 return MergeAliasResults(ThisAlias, Alias); 1164 } 1165 1166 // If both arms of the Select node NoAlias or MustAlias V2, then returns 1167 // NoAlias / MustAlias. Otherwise, returns MayAlias. 1168 AliasResult Alias = 1169 aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(), SISize, SIAAInfo); 1170 if (Alias == MayAlias) 1171 return MayAlias; 1172 1173 AliasResult ThisAlias = 1174 aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo); 1175 return MergeAliasResults(ThisAlias, Alias); 1176 } 1177 1178 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction 1179 // against another. 1180 AliasAnalysis::AliasResult 1181 BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize, 1182 const AAMDNodes &PNAAInfo, 1183 const Value *V2, uint64_t V2Size, 1184 const AAMDNodes &V2AAInfo) { 1185 // Track phi nodes we have visited. We use this information when we determine 1186 // value equivalence. 1187 VisitedPhiBBs.insert(PN->getParent()); 1188 1189 // If the values are PHIs in the same block, we can do a more precise 1190 // as well as efficient check: just check for aliases between the values 1191 // on corresponding edges. 1192 if (const PHINode *PN2 = dyn_cast<PHINode>(V2)) 1193 if (PN2->getParent() == PN->getParent()) { 1194 LocPair Locs(Location(PN, PNSize, PNAAInfo), 1195 Location(V2, V2Size, V2AAInfo)); 1196 if (PN > V2) 1197 std::swap(Locs.first, Locs.second); 1198 // Analyse the PHIs' inputs under the assumption that the PHIs are 1199 // NoAlias. 1200 // If the PHIs are May/MustAlias there must be (recursively) an input 1201 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or 1202 // there must be an operation on the PHIs within the PHIs' value cycle 1203 // that causes a MayAlias. 1204 // Pretend the phis do not alias. 1205 AliasResult Alias = NoAlias; 1206 assert(AliasCache.count(Locs) && 1207 "There must exist an entry for the phi node"); 1208 AliasResult OrigAliasResult = AliasCache[Locs]; 1209 AliasCache[Locs] = NoAlias; 1210 1211 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1212 AliasResult ThisAlias = 1213 aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo, 1214 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)), 1215 V2Size, V2AAInfo); 1216 Alias = MergeAliasResults(ThisAlias, Alias); 1217 if (Alias == MayAlias) 1218 break; 1219 } 1220 1221 // Reset if speculation failed. 1222 if (Alias != NoAlias) 1223 AliasCache[Locs] = OrigAliasResult; 1224 1225 return Alias; 1226 } 1227 1228 SmallPtrSet<Value*, 4> UniqueSrc; 1229 SmallVector<Value*, 4> V1Srcs; 1230 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1231 Value *PV1 = PN->getIncomingValue(i); 1232 if (isa<PHINode>(PV1)) 1233 // If any of the source itself is a PHI, return MayAlias conservatively 1234 // to avoid compile time explosion. The worst possible case is if both 1235 // sides are PHI nodes. In which case, this is O(m x n) time where 'm' 1236 // and 'n' are the number of PHI sources. 1237 return MayAlias; 1238 if (UniqueSrc.insert(PV1).second) 1239 V1Srcs.push_back(PV1); 1240 } 1241 1242 AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo, 1243 V1Srcs[0], PNSize, PNAAInfo); 1244 // Early exit if the check of the first PHI source against V2 is MayAlias. 1245 // Other results are not possible. 1246 if (Alias == MayAlias) 1247 return MayAlias; 1248 1249 // If all sources of the PHI node NoAlias or MustAlias V2, then returns 1250 // NoAlias / MustAlias. Otherwise, returns MayAlias. 1251 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) { 1252 Value *V = V1Srcs[i]; 1253 1254 AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo, 1255 V, PNSize, PNAAInfo); 1256 Alias = MergeAliasResults(ThisAlias, Alias); 1257 if (Alias == MayAlias) 1258 break; 1259 } 1260 1261 return Alias; 1262 } 1263 1264 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases, 1265 // such as array references. 1266 // 1267 AliasAnalysis::AliasResult 1268 BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size, 1269 AAMDNodes V1AAInfo, 1270 const Value *V2, uint64_t V2Size, 1271 AAMDNodes V2AAInfo) { 1272 // If either of the memory references is empty, it doesn't matter what the 1273 // pointer values are. 1274 if (V1Size == 0 || V2Size == 0) 1275 return NoAlias; 1276 1277 // Strip off any casts if they exist. 1278 V1 = V1->stripPointerCasts(); 1279 V2 = V2->stripPointerCasts(); 1280 1281 // Are we checking for alias of the same value? 1282 // Because we look 'through' phi nodes we could look at "Value" pointers from 1283 // different iterations. We must therefore make sure that this is not the 1284 // case. The function isValueEqualInPotentialCycles ensures that this cannot 1285 // happen by looking at the visited phi nodes and making sure they cannot 1286 // reach the value. 1287 if (isValueEqualInPotentialCycles(V1, V2)) 1288 return MustAlias; 1289 1290 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy()) 1291 return NoAlias; // Scalars cannot alias each other 1292 1293 // Figure out what objects these things are pointing to if we can. 1294 const Value *O1 = GetUnderlyingObject(V1, DL, MaxLookupSearchDepth); 1295 const Value *O2 = GetUnderlyingObject(V2, DL, MaxLookupSearchDepth); 1296 1297 // Null values in the default address space don't point to any object, so they 1298 // don't alias any other pointer. 1299 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1)) 1300 if (CPN->getType()->getAddressSpace() == 0) 1301 return NoAlias; 1302 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2)) 1303 if (CPN->getType()->getAddressSpace() == 0) 1304 return NoAlias; 1305 1306 if (O1 != O2) { 1307 // If V1/V2 point to two different objects we know that we have no alias. 1308 if (isIdentifiedObject(O1) && isIdentifiedObject(O2)) 1309 return NoAlias; 1310 1311 // Constant pointers can't alias with non-const isIdentifiedObject objects. 1312 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) || 1313 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1))) 1314 return NoAlias; 1315 1316 // Function arguments can't alias with things that are known to be 1317 // unambigously identified at the function level. 1318 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) || 1319 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1))) 1320 return NoAlias; 1321 1322 // Most objects can't alias null. 1323 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) || 1324 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2))) 1325 return NoAlias; 1326 1327 // If one pointer is the result of a call/invoke or load and the other is a 1328 // non-escaping local object within the same function, then we know the 1329 // object couldn't escape to a point where the call could return it. 1330 // 1331 // Note that if the pointers are in different functions, there are a 1332 // variety of complications. A call with a nocapture argument may still 1333 // temporary store the nocapture argument's value in a temporary memory 1334 // location if that memory location doesn't escape. Or it may pass a 1335 // nocapture value to other functions as long as they don't capture it. 1336 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2)) 1337 return NoAlias; 1338 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1)) 1339 return NoAlias; 1340 } 1341 1342 // If the size of one access is larger than the entire object on the other 1343 // side, then we know such behavior is undefined and can assume no alias. 1344 if (DL) 1345 if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *DL, *TLI)) || 1346 (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *DL, *TLI))) 1347 return NoAlias; 1348 1349 // Check the cache before climbing up use-def chains. This also terminates 1350 // otherwise infinitely recursive queries. 1351 LocPair Locs(Location(V1, V1Size, V1AAInfo), 1352 Location(V2, V2Size, V2AAInfo)); 1353 if (V1 > V2) 1354 std::swap(Locs.first, Locs.second); 1355 std::pair<AliasCacheTy::iterator, bool> Pair = 1356 AliasCache.insert(std::make_pair(Locs, MayAlias)); 1357 if (!Pair.second) 1358 return Pair.first->second; 1359 1360 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the 1361 // GEP can't simplify, we don't even look at the PHI cases. 1362 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) { 1363 std::swap(V1, V2); 1364 std::swap(V1Size, V2Size); 1365 std::swap(O1, O2); 1366 std::swap(V1AAInfo, V2AAInfo); 1367 } 1368 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) { 1369 AliasResult Result = aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2); 1370 if (Result != MayAlias) return AliasCache[Locs] = Result; 1371 } 1372 1373 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) { 1374 std::swap(V1, V2); 1375 std::swap(V1Size, V2Size); 1376 std::swap(V1AAInfo, V2AAInfo); 1377 } 1378 if (const PHINode *PN = dyn_cast<PHINode>(V1)) { 1379 AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo, 1380 V2, V2Size, V2AAInfo); 1381 if (Result != MayAlias) return AliasCache[Locs] = Result; 1382 } 1383 1384 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) { 1385 std::swap(V1, V2); 1386 std::swap(V1Size, V2Size); 1387 std::swap(V1AAInfo, V2AAInfo); 1388 } 1389 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) { 1390 AliasResult Result = aliasSelect(S1, V1Size, V1AAInfo, 1391 V2, V2Size, V2AAInfo); 1392 if (Result != MayAlias) return AliasCache[Locs] = Result; 1393 } 1394 1395 // If both pointers are pointing into the same object and one of them 1396 // accesses is accessing the entire object, then the accesses must 1397 // overlap in some way. 1398 if (DL && O1 == O2) 1399 if ((V1Size != UnknownSize && isObjectSize(O1, V1Size, *DL, *TLI)) || 1400 (V2Size != UnknownSize && isObjectSize(O2, V2Size, *DL, *TLI))) 1401 return AliasCache[Locs] = PartialAlias; 1402 1403 AliasResult Result = 1404 AliasAnalysis::alias(Location(V1, V1Size, V1AAInfo), 1405 Location(V2, V2Size, V2AAInfo)); 1406 return AliasCache[Locs] = Result; 1407 } 1408 1409 bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V, 1410 const Value *V2) { 1411 if (V != V2) 1412 return false; 1413 1414 const Instruction *Inst = dyn_cast<Instruction>(V); 1415 if (!Inst) 1416 return true; 1417 1418 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck) 1419 return false; 1420 1421 // Use dominance or loop info if available. 1422 DominatorTreeWrapperPass *DTWP = 1423 getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 1424 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr; 1425 LoopInfo *LI = getAnalysisIfAvailable<LoopInfo>(); 1426 1427 // Make sure that the visited phis cannot reach the Value. This ensures that 1428 // the Values cannot come from different iterations of a potential cycle the 1429 // phi nodes could be involved in. 1430 for (auto *P : VisitedPhiBBs) 1431 if (isPotentiallyReachable(P->begin(), Inst, DT, LI)) 1432 return false; 1433 1434 return true; 1435 } 1436 1437 /// GetIndexDifference - Dest and Src are the variable indices from two 1438 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base 1439 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic 1440 /// difference between the two pointers. 1441 void BasicAliasAnalysis::GetIndexDifference( 1442 SmallVectorImpl<VariableGEPIndex> &Dest, 1443 const SmallVectorImpl<VariableGEPIndex> &Src) { 1444 if (Src.empty()) 1445 return; 1446 1447 for (unsigned i = 0, e = Src.size(); i != e; ++i) { 1448 const Value *V = Src[i].V; 1449 ExtensionKind Extension = Src[i].Extension; 1450 int64_t Scale = Src[i].Scale; 1451 1452 // Find V in Dest. This is N^2, but pointer indices almost never have more 1453 // than a few variable indexes. 1454 for (unsigned j = 0, e = Dest.size(); j != e; ++j) { 1455 if (!isValueEqualInPotentialCycles(Dest[j].V, V) || 1456 Dest[j].Extension != Extension) 1457 continue; 1458 1459 // If we found it, subtract off Scale V's from the entry in Dest. If it 1460 // goes to zero, remove the entry. 1461 if (Dest[j].Scale != Scale) 1462 Dest[j].Scale -= Scale; 1463 else 1464 Dest.erase(Dest.begin() + j); 1465 Scale = 0; 1466 break; 1467 } 1468 1469 // If we didn't consume this entry, add it to the end of the Dest list. 1470 if (Scale) { 1471 VariableGEPIndex Entry = { V, Extension, -Scale }; 1472 Dest.push_back(Entry); 1473 } 1474 } 1475 } 1476