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