1 //===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the primary stateless implementation of the 10 // Alias Analysis interface that implements identities (two different 11 // globals cannot alias, etc), but does no stateful analysis. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Analysis/BasicAliasAnalysis.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ScopeExit.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/Analysis/AliasAnalysis.h" 22 #include "llvm/Analysis/AssumptionCache.h" 23 #include "llvm/Analysis/CFG.h" 24 #include "llvm/Analysis/CaptureTracking.h" 25 #include "llvm/Analysis/InstructionSimplify.h" 26 #include "llvm/Analysis/MemoryBuiltins.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/PhiValues.h" 29 #include "llvm/Analysis/TargetLibraryInfo.h" 30 #include "llvm/Analysis/ValueTracking.h" 31 #include "llvm/IR/Argument.h" 32 #include "llvm/IR/Attributes.h" 33 #include "llvm/IR/Constant.h" 34 #include "llvm/IR/ConstantRange.h" 35 #include "llvm/IR/Constants.h" 36 #include "llvm/IR/DataLayout.h" 37 #include "llvm/IR/DerivedTypes.h" 38 #include "llvm/IR/Dominators.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GetElementPtrTypeIterator.h" 41 #include "llvm/IR/GlobalAlias.h" 42 #include "llvm/IR/GlobalVariable.h" 43 #include "llvm/IR/InstrTypes.h" 44 #include "llvm/IR/Instruction.h" 45 #include "llvm/IR/Instructions.h" 46 #include "llvm/IR/IntrinsicInst.h" 47 #include "llvm/IR/Intrinsics.h" 48 #include "llvm/IR/Metadata.h" 49 #include "llvm/IR/Operator.h" 50 #include "llvm/IR/Type.h" 51 #include "llvm/IR/User.h" 52 #include "llvm/IR/Value.h" 53 #include "llvm/InitializePasses.h" 54 #include "llvm/Pass.h" 55 #include "llvm/Support/Casting.h" 56 #include "llvm/Support/CommandLine.h" 57 #include "llvm/Support/Compiler.h" 58 #include "llvm/Support/KnownBits.h" 59 #include <cassert> 60 #include <cstdint> 61 #include <cstdlib> 62 #include <utility> 63 64 #define DEBUG_TYPE "basicaa" 65 66 using namespace llvm; 67 68 /// Enable analysis of recursive PHI nodes. 69 static cl::opt<bool> EnableRecPhiAnalysis("basic-aa-recphi", cl::Hidden, 70 cl::init(true)); 71 72 /// SearchLimitReached / SearchTimes shows how often the limit of 73 /// to decompose GEPs is reached. It will affect the precision 74 /// of basic alias analysis. 75 STATISTIC(SearchLimitReached, "Number of times the limit to " 76 "decompose GEPs is reached"); 77 STATISTIC(SearchTimes, "Number of times a GEP is decomposed"); 78 79 /// Cutoff after which to stop analysing a set of phi nodes potentially involved 80 /// in a cycle. Because we are analysing 'through' phi nodes, we need to be 81 /// careful with value equivalence. We use reachability to make sure a value 82 /// cannot be involved in a cycle. 83 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20; 84 85 // The max limit of the search depth in DecomposeGEPExpression() and 86 // getUnderlyingObject(). 87 static const unsigned MaxLookupSearchDepth = 6; 88 89 bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA, 90 FunctionAnalysisManager::Invalidator &Inv) { 91 // We don't care if this analysis itself is preserved, it has no state. But 92 // we need to check that the analyses it depends on have been. Note that we 93 // may be created without handles to some analyses and in that case don't 94 // depend on them. 95 if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) || 96 (DT && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)) || 97 (PV && Inv.invalidate<PhiValuesAnalysis>(Fn, PA))) 98 return true; 99 100 // Otherwise this analysis result remains valid. 101 return false; 102 } 103 104 //===----------------------------------------------------------------------===// 105 // Useful predicates 106 //===----------------------------------------------------------------------===// 107 108 /// Returns true if the pointer is one which would have been considered an 109 /// escape by isNonEscapingLocalObject. 110 static bool isEscapeSource(const Value *V) { 111 if (isa<CallBase>(V)) 112 return true; 113 114 // The load case works because isNonEscapingLocalObject considers all 115 // stores to be escapes (it passes true for the StoreCaptures argument 116 // to PointerMayBeCaptured). 117 if (isa<LoadInst>(V)) 118 return true; 119 120 // The inttoptr case works because isNonEscapingLocalObject considers all 121 // means of converting or equating a pointer to an int (ptrtoint, ptr store 122 // which could be followed by an integer load, ptr<->int compare) as 123 // escaping, and objects located at well-known addresses via platform-specific 124 // means cannot be considered non-escaping local objects. 125 if (isa<IntToPtrInst>(V)) 126 return true; 127 128 return false; 129 } 130 131 /// Returns the size of the object specified by V or UnknownSize if unknown. 132 static uint64_t getObjectSize(const Value *V, const DataLayout &DL, 133 const TargetLibraryInfo &TLI, 134 bool NullIsValidLoc, 135 bool RoundToAlign = false) { 136 uint64_t Size; 137 ObjectSizeOpts Opts; 138 Opts.RoundToAlign = RoundToAlign; 139 Opts.NullIsUnknownSize = NullIsValidLoc; 140 if (getObjectSize(V, Size, DL, &TLI, Opts)) 141 return Size; 142 return MemoryLocation::UnknownSize; 143 } 144 145 /// Returns true if we can prove that the object specified by V is smaller than 146 /// Size. 147 static bool isObjectSmallerThan(const Value *V, uint64_t Size, 148 const DataLayout &DL, 149 const TargetLibraryInfo &TLI, 150 bool NullIsValidLoc) { 151 // Note that the meanings of the "object" are slightly different in the 152 // following contexts: 153 // c1: llvm::getObjectSize() 154 // c2: llvm.objectsize() intrinsic 155 // c3: isObjectSmallerThan() 156 // c1 and c2 share the same meaning; however, the meaning of "object" in c3 157 // refers to the "entire object". 158 // 159 // Consider this example: 160 // char *p = (char*)malloc(100) 161 // char *q = p+80; 162 // 163 // In the context of c1 and c2, the "object" pointed by q refers to the 164 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20. 165 // 166 // However, in the context of c3, the "object" refers to the chunk of memory 167 // being allocated. So, the "object" has 100 bytes, and q points to the middle 168 // the "object". In case q is passed to isObjectSmallerThan() as the 1st 169 // parameter, before the llvm::getObjectSize() is called to get the size of 170 // entire object, we should: 171 // - either rewind the pointer q to the base-address of the object in 172 // question (in this case rewind to p), or 173 // - just give up. It is up to caller to make sure the pointer is pointing 174 // to the base address the object. 175 // 176 // We go for 2nd option for simplicity. 177 if (!isIdentifiedObject(V)) 178 return false; 179 180 // This function needs to use the aligned object size because we allow 181 // reads a bit past the end given sufficient alignment. 182 uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc, 183 /*RoundToAlign*/ true); 184 185 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size; 186 } 187 188 /// Return the minimal extent from \p V to the end of the underlying object, 189 /// assuming the result is used in an aliasing query. E.g., we do use the query 190 /// location size and the fact that null pointers cannot alias here. 191 static uint64_t getMinimalExtentFrom(const Value &V, 192 const LocationSize &LocSize, 193 const DataLayout &DL, 194 bool NullIsValidLoc) { 195 // If we have dereferenceability information we know a lower bound for the 196 // extent as accesses for a lower offset would be valid. We need to exclude 197 // the "or null" part if null is a valid pointer. We can ignore frees, as an 198 // access after free would be undefined behavior. 199 bool CanBeNull, CanBeFreed; 200 uint64_t DerefBytes = 201 V.getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed); 202 DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes; 203 // If queried with a precise location size, we assume that location size to be 204 // accessed, thus valid. 205 if (LocSize.isPrecise()) 206 DerefBytes = std::max(DerefBytes, LocSize.getValue()); 207 return DerefBytes; 208 } 209 210 /// Returns true if we can prove that the object specified by V has size Size. 211 static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL, 212 const TargetLibraryInfo &TLI, bool NullIsValidLoc) { 213 uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc); 214 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size; 215 } 216 217 //===----------------------------------------------------------------------===// 218 // CaptureInfo implementations 219 //===----------------------------------------------------------------------===// 220 221 CaptureInfo::~CaptureInfo() = default; 222 223 bool SimpleCaptureInfo::isNotCapturedBeforeOrAt(const Value *Object, 224 const Instruction *I) { 225 return isNonEscapingLocalObject(Object, &IsCapturedCache); 226 } 227 228 bool EarliestEscapeInfo::isNotCapturedBeforeOrAt(const Value *Object, 229 const Instruction *I) { 230 if (!isIdentifiedFunctionLocal(Object)) 231 return false; 232 233 auto Iter = EarliestEscapes.insert({Object, nullptr}); 234 if (Iter.second) { 235 Instruction *EarliestCapture = FindEarliestCapture( 236 Object, *const_cast<Function *>(I->getFunction()), 237 /*ReturnCaptures=*/false, /*StoreCaptures=*/true, DT); 238 if (EarliestCapture) { 239 auto Ins = Inst2Obj.insert({EarliestCapture, {}}); 240 Ins.first->second.push_back(Object); 241 } 242 Iter.first->second = EarliestCapture; 243 } 244 245 // No capturing instruction. 246 if (!Iter.first->second) 247 return true; 248 249 return I != Iter.first->second && 250 !isPotentiallyReachable(Iter.first->second, I, nullptr, &DT, &LI); 251 } 252 253 void EarliestEscapeInfo::removeInstruction(Instruction *I) { 254 auto Iter = Inst2Obj.find(I); 255 if (Iter != Inst2Obj.end()) { 256 for (const Value *Obj : Iter->second) 257 EarliestEscapes.erase(Obj); 258 Inst2Obj.erase(I); 259 } 260 } 261 262 //===----------------------------------------------------------------------===// 263 // GetElementPtr Instruction Decomposition and Analysis 264 //===----------------------------------------------------------------------===// 265 266 namespace { 267 /// Represents zext(sext(V)). 268 struct CastedValue { 269 const Value *V; 270 unsigned ZExtBits = 0; 271 unsigned SExtBits = 0; 272 273 explicit CastedValue(const Value *V) : V(V) {} 274 explicit CastedValue(const Value *V, unsigned ZExtBits, unsigned SExtBits) 275 : V(V), ZExtBits(ZExtBits), SExtBits(SExtBits) {} 276 277 unsigned getBitWidth() const { 278 return V->getType()->getPrimitiveSizeInBits() + ZExtBits + SExtBits; 279 } 280 281 CastedValue withValue(const Value *NewV) const { 282 return CastedValue(NewV, ZExtBits, SExtBits); 283 } 284 285 /// Replace V with zext(NewV) 286 CastedValue withZExtOfValue(const Value *NewV) const { 287 unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() - 288 NewV->getType()->getPrimitiveSizeInBits(); 289 // zext(sext(zext(NewV))) == zext(zext(zext(NewV))) 290 return CastedValue(NewV, ZExtBits + SExtBits + ExtendBy, 0); 291 } 292 293 /// Replace V with sext(NewV) 294 CastedValue withSExtOfValue(const Value *NewV) const { 295 unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() - 296 NewV->getType()->getPrimitiveSizeInBits(); 297 // zext(sext(sext(NewV))) 298 return CastedValue(NewV, ZExtBits, SExtBits + ExtendBy); 299 } 300 301 APInt evaluateWith(APInt N) const { 302 assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() && 303 "Incompatible bit width"); 304 if (SExtBits) N = N.sext(N.getBitWidth() + SExtBits); 305 if (ZExtBits) N = N.zext(N.getBitWidth() + ZExtBits); 306 return N; 307 } 308 309 KnownBits evaluateWith(KnownBits N) const { 310 assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() && 311 "Incompatible bit width"); 312 if (SExtBits) N = N.sext(N.getBitWidth() + SExtBits); 313 if (ZExtBits) N = N.zext(N.getBitWidth() + ZExtBits); 314 return N; 315 } 316 317 ConstantRange evaluateWith(ConstantRange N) const { 318 assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() && 319 "Incompatible bit width"); 320 if (SExtBits) N = N.signExtend(N.getBitWidth() + SExtBits); 321 if (ZExtBits) N = N.zeroExtend(N.getBitWidth() + ZExtBits); 322 return N; 323 } 324 325 bool canDistributeOver(bool NUW, bool NSW) const { 326 // zext(x op<nuw> y) == zext(x) op<nuw> zext(y) 327 // sext(x op<nsw> y) == sext(x) op<nsw> sext(y) 328 return (!ZExtBits || NUW) && (!SExtBits || NSW); 329 } 330 331 bool hasSameCastsAs(const CastedValue &Other) const { 332 return ZExtBits == Other.ZExtBits && SExtBits == Other.SExtBits; 333 } 334 }; 335 336 /// Represents zext(sext(V)) * Scale + Offset. 337 struct LinearExpression { 338 CastedValue Val; 339 APInt Scale; 340 APInt Offset; 341 342 /// True if all operations in this expression are NSW. 343 bool IsNSW; 344 345 LinearExpression(const CastedValue &Val, const APInt &Scale, 346 const APInt &Offset, bool IsNSW) 347 : Val(Val), Scale(Scale), Offset(Offset), IsNSW(IsNSW) {} 348 349 LinearExpression(const CastedValue &Val) : Val(Val), IsNSW(true) { 350 unsigned BitWidth = Val.getBitWidth(); 351 Scale = APInt(BitWidth, 1); 352 Offset = APInt(BitWidth, 0); 353 } 354 }; 355 } 356 357 /// Analyzes the specified value as a linear expression: "A*V + B", where A and 358 /// B are constant integers. 359 static LinearExpression GetLinearExpression( 360 const CastedValue &Val, const DataLayout &DL, unsigned Depth, 361 AssumptionCache *AC, DominatorTree *DT) { 362 // Limit our recursion depth. 363 if (Depth == 6) 364 return Val; 365 366 if (const ConstantInt *Const = dyn_cast<ConstantInt>(Val.V)) 367 return LinearExpression(Val, APInt(Val.getBitWidth(), 0), 368 Val.evaluateWith(Const->getValue()), true); 369 370 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val.V)) { 371 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) { 372 APInt RHS = Val.evaluateWith(RHSC->getValue()); 373 // The only non-OBO case we deal with is or, and only limited to the 374 // case where it is both nuw and nsw. 375 bool NUW = true, NSW = true; 376 if (isa<OverflowingBinaryOperator>(BOp)) { 377 NUW &= BOp->hasNoUnsignedWrap(); 378 NSW &= BOp->hasNoSignedWrap(); 379 } 380 if (!Val.canDistributeOver(NUW, NSW)) 381 return Val; 382 383 LinearExpression E(Val); 384 switch (BOp->getOpcode()) { 385 default: 386 // We don't understand this instruction, so we can't decompose it any 387 // further. 388 return Val; 389 case Instruction::Or: 390 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't 391 // analyze it. 392 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC, 393 BOp, DT)) 394 return Val; 395 396 LLVM_FALLTHROUGH; 397 case Instruction::Add: { 398 E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 399 Depth + 1, AC, DT); 400 E.Offset += RHS; 401 E.IsNSW &= NSW; 402 break; 403 } 404 case Instruction::Sub: { 405 E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 406 Depth + 1, AC, DT); 407 E.Offset -= RHS; 408 E.IsNSW &= NSW; 409 break; 410 } 411 case Instruction::Mul: { 412 E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 413 Depth + 1, AC, DT); 414 E.Offset *= RHS; 415 E.Scale *= RHS; 416 E.IsNSW &= NSW; 417 break; 418 } 419 case Instruction::Shl: 420 // We're trying to linearize an expression of the kind: 421 // shl i8 -128, 36 422 // where the shift count exceeds the bitwidth of the type. 423 // We can't decompose this further (the expression would return 424 // a poison value). 425 if (RHS.getLimitedValue() > Val.getBitWidth()) 426 return Val; 427 428 E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 429 Depth + 1, AC, DT); 430 E.Offset <<= RHS.getLimitedValue(); 431 E.Scale <<= RHS.getLimitedValue(); 432 E.IsNSW &= NSW; 433 break; 434 } 435 return E; 436 } 437 } 438 439 if (isa<ZExtInst>(Val.V)) 440 return GetLinearExpression( 441 Val.withZExtOfValue(cast<CastInst>(Val.V)->getOperand(0)), 442 DL, Depth + 1, AC, DT); 443 444 if (isa<SExtInst>(Val.V)) 445 return GetLinearExpression( 446 Val.withSExtOfValue(cast<CastInst>(Val.V)->getOperand(0)), 447 DL, Depth + 1, AC, DT); 448 449 return Val; 450 } 451 452 /// To ensure a pointer offset fits in an integer of size PointerSize 453 /// (in bits) when that size is smaller than the maximum pointer size. This is 454 /// an issue, for example, in particular for 32b pointers with negative indices 455 /// that rely on two's complement wrap-arounds for precise alias information 456 /// where the maximum pointer size is 64b. 457 static APInt adjustToPointerSize(const APInt &Offset, unsigned PointerSize) { 458 assert(PointerSize <= Offset.getBitWidth() && "Invalid PointerSize!"); 459 unsigned ShiftBits = Offset.getBitWidth() - PointerSize; 460 return (Offset << ShiftBits).ashr(ShiftBits); 461 } 462 463 namespace { 464 // A linear transformation of a Value; this class represents 465 // ZExt(SExt(V, SExtBits), ZExtBits) * Scale. 466 struct VariableGEPIndex { 467 CastedValue Val; 468 APInt Scale; 469 470 // Context instruction to use when querying information about this index. 471 const Instruction *CxtI; 472 473 /// True if all operations in this expression are NSW. 474 bool IsNSW; 475 476 void dump() const { 477 print(dbgs()); 478 dbgs() << "\n"; 479 } 480 void print(raw_ostream &OS) const { 481 OS << "(V=" << Val.V->getName() 482 << ", zextbits=" << Val.ZExtBits 483 << ", sextbits=" << Val.SExtBits 484 << ", scale=" << Scale << ")"; 485 } 486 }; 487 } 488 489 // Represents the internal structure of a GEP, decomposed into a base pointer, 490 // constant offsets, and variable scaled indices. 491 struct BasicAAResult::DecomposedGEP { 492 // Base pointer of the GEP 493 const Value *Base; 494 // Total constant offset from base. 495 APInt Offset; 496 // Scaled variable (non-constant) indices. 497 SmallVector<VariableGEPIndex, 4> VarIndices; 498 // Are all operations inbounds GEPs or non-indexing operations? 499 // (None iff expression doesn't involve any geps) 500 Optional<bool> InBounds; 501 502 void dump() const { 503 print(dbgs()); 504 dbgs() << "\n"; 505 } 506 void print(raw_ostream &OS) const { 507 OS << "(DecomposedGEP Base=" << Base->getName() 508 << ", Offset=" << Offset 509 << ", VarIndices=["; 510 for (size_t i = 0; i < VarIndices.size(); i++) { 511 if (i != 0) 512 OS << ", "; 513 VarIndices[i].print(OS); 514 } 515 OS << "])"; 516 } 517 }; 518 519 520 /// If V is a symbolic pointer expression, decompose it into a base pointer 521 /// with a constant offset and a number of scaled symbolic offsets. 522 /// 523 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale 524 /// in the VarIndices vector) are Value*'s that are known to be scaled by the 525 /// specified amount, but which may have other unrepresented high bits. As 526 /// such, the gep cannot necessarily be reconstructed from its decomposed form. 527 BasicAAResult::DecomposedGEP 528 BasicAAResult::DecomposeGEPExpression(const Value *V, const DataLayout &DL, 529 AssumptionCache *AC, DominatorTree *DT) { 530 // Limit recursion depth to limit compile time in crazy cases. 531 unsigned MaxLookup = MaxLookupSearchDepth; 532 SearchTimes++; 533 const Instruction *CxtI = dyn_cast<Instruction>(V); 534 535 unsigned MaxPointerSize = DL.getMaxPointerSizeInBits(); 536 DecomposedGEP Decomposed; 537 Decomposed.Offset = APInt(MaxPointerSize, 0); 538 do { 539 // See if this is a bitcast or GEP. 540 const Operator *Op = dyn_cast<Operator>(V); 541 if (!Op) { 542 // The only non-operator case we can handle are GlobalAliases. 543 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 544 if (!GA->isInterposable()) { 545 V = GA->getAliasee(); 546 continue; 547 } 548 } 549 Decomposed.Base = V; 550 return Decomposed; 551 } 552 553 if (Op->getOpcode() == Instruction::BitCast || 554 Op->getOpcode() == Instruction::AddrSpaceCast) { 555 V = Op->getOperand(0); 556 continue; 557 } 558 559 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op); 560 if (!GEPOp) { 561 if (const auto *PHI = dyn_cast<PHINode>(V)) { 562 // Look through single-arg phi nodes created by LCSSA. 563 if (PHI->getNumIncomingValues() == 1) { 564 V = PHI->getIncomingValue(0); 565 continue; 566 } 567 } else if (const auto *Call = dyn_cast<CallBase>(V)) { 568 // CaptureTracking can know about special capturing properties of some 569 // intrinsics like launder.invariant.group, that can't be expressed with 570 // the attributes, but have properties like returning aliasing pointer. 571 // Because some analysis may assume that nocaptured pointer is not 572 // returned from some special intrinsic (because function would have to 573 // be marked with returns attribute), it is crucial to use this function 574 // because it should be in sync with CaptureTracking. Not using it may 575 // cause weird miscompilations where 2 aliasing pointers are assumed to 576 // noalias. 577 if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) { 578 V = RP; 579 continue; 580 } 581 } 582 583 Decomposed.Base = V; 584 return Decomposed; 585 } 586 587 // Track whether we've seen at least one in bounds gep, and if so, whether 588 // all geps parsed were in bounds. 589 if (Decomposed.InBounds == None) 590 Decomposed.InBounds = GEPOp->isInBounds(); 591 else if (!GEPOp->isInBounds()) 592 Decomposed.InBounds = false; 593 594 assert(GEPOp->getSourceElementType()->isSized() && "GEP must be sized"); 595 596 // Don't attempt to analyze GEPs if index scale is not a compile-time 597 // constant. 598 if (isa<ScalableVectorType>(GEPOp->getSourceElementType())) { 599 Decomposed.Base = V; 600 return Decomposed; 601 } 602 603 unsigned AS = GEPOp->getPointerAddressSpace(); 604 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices. 605 gep_type_iterator GTI = gep_type_begin(GEPOp); 606 unsigned PointerSize = DL.getPointerSizeInBits(AS); 607 // Assume all GEP operands are constants until proven otherwise. 608 bool GepHasConstantOffset = true; 609 for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end(); 610 I != E; ++I, ++GTI) { 611 const Value *Index = *I; 612 // Compute the (potentially symbolic) offset in bytes for this index. 613 if (StructType *STy = GTI.getStructTypeOrNull()) { 614 // For a struct, add the member offset. 615 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue(); 616 if (FieldNo == 0) 617 continue; 618 619 Decomposed.Offset += DL.getStructLayout(STy)->getElementOffset(FieldNo); 620 continue; 621 } 622 623 // For an array/pointer, add the element offset, explicitly scaled. 624 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) { 625 if (CIdx->isZero()) 626 continue; 627 Decomposed.Offset += 628 DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize() * 629 CIdx->getValue().sextOrTrunc(MaxPointerSize); 630 continue; 631 } 632 633 GepHasConstantOffset = false; 634 635 APInt Scale(MaxPointerSize, 636 DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize()); 637 // If the integer type is smaller than the pointer size, it is implicitly 638 // sign extended to pointer size. 639 unsigned Width = Index->getType()->getIntegerBitWidth(); 640 unsigned SExtBits = PointerSize > Width ? PointerSize - Width : 0; 641 LinearExpression LE = GetLinearExpression( 642 CastedValue(Index, 0, SExtBits), DL, 0, AC, DT); 643 644 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale. 645 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale. 646 647 // It can be the case that, even through C1*V+C2 does not overflow for 648 // relevant values of V, (C2*Scale) can overflow. In that case, we cannot 649 // decompose the expression in this way. 650 // 651 // FIXME: C1*Scale and the other operations in the decomposed 652 // (C1*Scale)*V+C2*Scale can also overflow. We should check for this 653 // possibility. 654 bool Overflow; 655 APInt ScaledOffset = LE.Offset.sextOrTrunc(MaxPointerSize) 656 .smul_ov(Scale, Overflow); 657 if (Overflow) { 658 LE = LinearExpression(CastedValue(Index, 0, SExtBits)); 659 } else { 660 Decomposed.Offset += ScaledOffset; 661 Scale *= LE.Scale.sextOrTrunc(MaxPointerSize); 662 } 663 664 // If we already had an occurrence of this index variable, merge this 665 // scale into it. For example, we want to handle: 666 // A[x][x] -> x*16 + x*4 -> x*20 667 // This also ensures that 'x' only appears in the index list once. 668 for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) { 669 if (Decomposed.VarIndices[i].Val.V == LE.Val.V && 670 Decomposed.VarIndices[i].Val.hasSameCastsAs(LE.Val)) { 671 Scale += Decomposed.VarIndices[i].Scale; 672 Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i); 673 break; 674 } 675 } 676 677 // Make sure that we have a scale that makes sense for this target's 678 // pointer size. 679 Scale = adjustToPointerSize(Scale, PointerSize); 680 681 if (!!Scale) { 682 VariableGEPIndex Entry = {LE.Val, Scale, CxtI, LE.IsNSW}; 683 Decomposed.VarIndices.push_back(Entry); 684 } 685 } 686 687 // Take care of wrap-arounds 688 if (GepHasConstantOffset) 689 Decomposed.Offset = adjustToPointerSize(Decomposed.Offset, PointerSize); 690 691 // Analyze the base pointer next. 692 V = GEPOp->getOperand(0); 693 } while (--MaxLookup); 694 695 // If the chain of expressions is too deep, just return early. 696 Decomposed.Base = V; 697 SearchLimitReached++; 698 return Decomposed; 699 } 700 701 /// Returns whether the given pointer value points to memory that is local to 702 /// the function, with global constants being considered local to all 703 /// functions. 704 bool BasicAAResult::pointsToConstantMemory(const MemoryLocation &Loc, 705 AAQueryInfo &AAQI, bool OrLocal) { 706 assert(Visited.empty() && "Visited must be cleared after use!"); 707 708 unsigned MaxLookup = 8; 709 SmallVector<const Value *, 16> Worklist; 710 Worklist.push_back(Loc.Ptr); 711 do { 712 const Value *V = getUnderlyingObject(Worklist.pop_back_val()); 713 if (!Visited.insert(V).second) { 714 Visited.clear(); 715 return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal); 716 } 717 718 // An alloca instruction defines local memory. 719 if (OrLocal && isa<AllocaInst>(V)) 720 continue; 721 722 // A global constant counts as local memory for our purposes. 723 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) { 724 // Note: this doesn't require GV to be "ODR" because it isn't legal for a 725 // global to be marked constant in some modules and non-constant in 726 // others. GV may even be a declaration, not a definition. 727 if (!GV->isConstant()) { 728 Visited.clear(); 729 return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal); 730 } 731 continue; 732 } 733 734 // If both select values point to local memory, then so does the select. 735 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) { 736 Worklist.push_back(SI->getTrueValue()); 737 Worklist.push_back(SI->getFalseValue()); 738 continue; 739 } 740 741 // If all values incoming to a phi node point to local memory, then so does 742 // the phi. 743 if (const PHINode *PN = dyn_cast<PHINode>(V)) { 744 // Don't bother inspecting phi nodes with many operands. 745 if (PN->getNumIncomingValues() > MaxLookup) { 746 Visited.clear(); 747 return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal); 748 } 749 append_range(Worklist, PN->incoming_values()); 750 continue; 751 } 752 753 // Otherwise be conservative. 754 Visited.clear(); 755 return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal); 756 } while (!Worklist.empty() && --MaxLookup); 757 758 Visited.clear(); 759 return Worklist.empty(); 760 } 761 762 static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) { 763 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call); 764 return II && II->getIntrinsicID() == IID; 765 } 766 767 /// Returns the behavior when calling the given call site. 768 FunctionModRefBehavior BasicAAResult::getModRefBehavior(const CallBase *Call) { 769 if (Call->doesNotAccessMemory()) 770 // Can't do better than this. 771 return FMRB_DoesNotAccessMemory; 772 773 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior; 774 775 // If the callsite knows it only reads memory, don't return worse 776 // than that. 777 if (Call->onlyReadsMemory()) 778 Min = FMRB_OnlyReadsMemory; 779 else if (Call->doesNotReadMemory()) 780 Min = FMRB_OnlyWritesMemory; 781 782 if (Call->onlyAccessesArgMemory()) 783 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees); 784 else if (Call->onlyAccessesInaccessibleMemory()) 785 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem); 786 else if (Call->onlyAccessesInaccessibleMemOrArgMem()) 787 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem); 788 789 // If the call has operand bundles then aliasing attributes from the function 790 // it calls do not directly apply to the call. This can be made more precise 791 // in the future. 792 if (!Call->hasOperandBundles()) 793 if (const Function *F = Call->getCalledFunction()) 794 Min = 795 FunctionModRefBehavior(Min & getBestAAResults().getModRefBehavior(F)); 796 797 return Min; 798 } 799 800 /// Returns the behavior when calling the given function. For use when the call 801 /// site is not known. 802 FunctionModRefBehavior BasicAAResult::getModRefBehavior(const Function *F) { 803 // If the function declares it doesn't access memory, we can't do better. 804 if (F->doesNotAccessMemory()) 805 return FMRB_DoesNotAccessMemory; 806 807 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior; 808 809 // If the function declares it only reads memory, go with that. 810 if (F->onlyReadsMemory()) 811 Min = FMRB_OnlyReadsMemory; 812 else if (F->doesNotReadMemory()) 813 Min = FMRB_OnlyWritesMemory; 814 815 if (F->onlyAccessesArgMemory()) 816 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees); 817 else if (F->onlyAccessesInaccessibleMemory()) 818 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem); 819 else if (F->onlyAccessesInaccessibleMemOrArgMem()) 820 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem); 821 822 return Min; 823 } 824 825 /// Returns true if this is a writeonly (i.e Mod only) parameter. 826 static bool isWriteOnlyParam(const CallBase *Call, unsigned ArgIdx, 827 const TargetLibraryInfo &TLI) { 828 if (Call->paramHasAttr(ArgIdx, Attribute::WriteOnly)) 829 return true; 830 831 // We can bound the aliasing properties of memset_pattern16 just as we can 832 // for memcpy/memset. This is particularly important because the 833 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16 834 // whenever possible. 835 // FIXME Consider handling this in InferFunctionAttr.cpp together with other 836 // attributes. 837 LibFunc F; 838 if (Call->getCalledFunction() && 839 TLI.getLibFunc(*Call->getCalledFunction(), F) && 840 F == LibFunc_memset_pattern16 && TLI.has(F)) 841 if (ArgIdx == 0) 842 return true; 843 844 // TODO: memset_pattern4, memset_pattern8 845 // TODO: _chk variants 846 // TODO: strcmp, strcpy 847 848 return false; 849 } 850 851 ModRefInfo BasicAAResult::getArgModRefInfo(const CallBase *Call, 852 unsigned ArgIdx) { 853 // Checking for known builtin intrinsics and target library functions. 854 if (isWriteOnlyParam(Call, ArgIdx, TLI)) 855 return ModRefInfo::Mod; 856 857 if (Call->paramHasAttr(ArgIdx, Attribute::ReadOnly)) 858 return ModRefInfo::Ref; 859 860 if (Call->paramHasAttr(ArgIdx, Attribute::ReadNone)) 861 return ModRefInfo::NoModRef; 862 863 return AAResultBase::getArgModRefInfo(Call, ArgIdx); 864 } 865 866 #ifndef NDEBUG 867 static const Function *getParent(const Value *V) { 868 if (const Instruction *inst = dyn_cast<Instruction>(V)) { 869 if (!inst->getParent()) 870 return nullptr; 871 return inst->getParent()->getParent(); 872 } 873 874 if (const Argument *arg = dyn_cast<Argument>(V)) 875 return arg->getParent(); 876 877 return nullptr; 878 } 879 880 static bool notDifferentParent(const Value *O1, const Value *O2) { 881 882 const Function *F1 = getParent(O1); 883 const Function *F2 = getParent(O2); 884 885 return !F1 || !F2 || F1 == F2; 886 } 887 #endif 888 889 AliasResult BasicAAResult::alias(const MemoryLocation &LocA, 890 const MemoryLocation &LocB, 891 AAQueryInfo &AAQI) { 892 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) && 893 "BasicAliasAnalysis doesn't support interprocedural queries."); 894 return aliasCheck(LocA.Ptr, LocA.Size, LocB.Ptr, LocB.Size, AAQI); 895 } 896 897 /// Checks to see if the specified callsite can clobber the specified memory 898 /// object. 899 /// 900 /// Since we only look at local properties of this function, we really can't 901 /// say much about this query. We do, however, use simple "address taken" 902 /// analysis on local objects. 903 ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call, 904 const MemoryLocation &Loc, 905 AAQueryInfo &AAQI) { 906 assert(notDifferentParent(Call, Loc.Ptr) && 907 "AliasAnalysis query involving multiple functions!"); 908 909 const Value *Object = getUnderlyingObject(Loc.Ptr); 910 911 // Calls marked 'tail' cannot read or write allocas from the current frame 912 // because the current frame might be destroyed by the time they run. However, 913 // a tail call may use an alloca with byval. Calling with byval copies the 914 // contents of the alloca into argument registers or stack slots, so there is 915 // no lifetime issue. 916 if (isa<AllocaInst>(Object)) 917 if (const CallInst *CI = dyn_cast<CallInst>(Call)) 918 if (CI->isTailCall() && 919 !CI->getAttributes().hasAttrSomewhere(Attribute::ByVal)) 920 return ModRefInfo::NoModRef; 921 922 // Stack restore is able to modify unescaped dynamic allocas. Assume it may 923 // modify them even though the alloca is not escaped. 924 if (auto *AI = dyn_cast<AllocaInst>(Object)) 925 if (!AI->isStaticAlloca() && isIntrinsicCall(Call, Intrinsic::stackrestore)) 926 return ModRefInfo::Mod; 927 928 // If the pointer is to a locally allocated object that does not escape, 929 // then the call can not mod/ref the pointer unless the call takes the pointer 930 // as an argument, and itself doesn't capture it. 931 if (!isa<Constant>(Object) && Call != Object && 932 AAQI.CI->isNotCapturedBeforeOrAt(Object, Call)) { 933 934 // Optimistically assume that call doesn't touch Object and check this 935 // assumption in the following loop. 936 ModRefInfo Result = ModRefInfo::NoModRef; 937 bool IsMustAlias = true; 938 939 unsigned OperandNo = 0; 940 for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end(); 941 CI != CE; ++CI, ++OperandNo) { 942 // Only look at the no-capture or byval pointer arguments. If this 943 // pointer were passed to arguments that were neither of these, then it 944 // couldn't be no-capture. 945 if (!(*CI)->getType()->isPointerTy() || 946 (!Call->doesNotCapture(OperandNo) && OperandNo < Call->arg_size() && 947 !Call->isByValArgument(OperandNo))) 948 continue; 949 950 // Call doesn't access memory through this operand, so we don't care 951 // if it aliases with Object. 952 if (Call->doesNotAccessMemory(OperandNo)) 953 continue; 954 955 // If this is a no-capture pointer argument, see if we can tell that it 956 // is impossible to alias the pointer we're checking. 957 AliasResult AR = getBestAAResults().alias( 958 MemoryLocation::getBeforeOrAfter(*CI), 959 MemoryLocation::getBeforeOrAfter(Object), AAQI); 960 if (AR != AliasResult::MustAlias) 961 IsMustAlias = false; 962 // Operand doesn't alias 'Object', continue looking for other aliases 963 if (AR == AliasResult::NoAlias) 964 continue; 965 // Operand aliases 'Object', but call doesn't modify it. Strengthen 966 // initial assumption and keep looking in case if there are more aliases. 967 if (Call->onlyReadsMemory(OperandNo)) { 968 Result = setRef(Result); 969 continue; 970 } 971 // Operand aliases 'Object' but call only writes into it. 972 if (Call->doesNotReadMemory(OperandNo)) { 973 Result = setMod(Result); 974 continue; 975 } 976 // This operand aliases 'Object' and call reads and writes into it. 977 // Setting ModRef will not yield an early return below, MustAlias is not 978 // used further. 979 Result = ModRefInfo::ModRef; 980 break; 981 } 982 983 // No operand aliases, reset Must bit. Add below if at least one aliases 984 // and all aliases found are MustAlias. 985 if (isNoModRef(Result)) 986 IsMustAlias = false; 987 988 // Early return if we improved mod ref information 989 if (!isModAndRefSet(Result)) { 990 if (isNoModRef(Result)) 991 return ModRefInfo::NoModRef; 992 return IsMustAlias ? setMust(Result) : clearMust(Result); 993 } 994 } 995 996 // If the call is malloc/calloc like, we can assume that it doesn't 997 // modify any IR visible value. This is only valid because we assume these 998 // routines do not read values visible in the IR. TODO: Consider special 999 // casing realloc and strdup routines which access only their arguments as 1000 // well. Or alternatively, replace all of this with inaccessiblememonly once 1001 // that's implemented fully. 1002 if (isMallocOrCallocLikeFn(Call, &TLI)) { 1003 // Be conservative if the accessed pointer may alias the allocation - 1004 // fallback to the generic handling below. 1005 if (getBestAAResults().alias(MemoryLocation::getBeforeOrAfter(Call), Loc, 1006 AAQI) == AliasResult::NoAlias) 1007 return ModRefInfo::NoModRef; 1008 } 1009 1010 // The semantics of memcpy intrinsics either exactly overlap or do not 1011 // overlap, i.e., source and destination of any given memcpy are either 1012 // no-alias or must-alias. 1013 if (auto *Inst = dyn_cast<AnyMemCpyInst>(Call)) { 1014 AliasResult SrcAA = 1015 getBestAAResults().alias(MemoryLocation::getForSource(Inst), Loc, AAQI); 1016 AliasResult DestAA = 1017 getBestAAResults().alias(MemoryLocation::getForDest(Inst), Loc, AAQI); 1018 // It's also possible for Loc to alias both src and dest, or neither. 1019 ModRefInfo rv = ModRefInfo::NoModRef; 1020 if (SrcAA != AliasResult::NoAlias) 1021 rv = setRef(rv); 1022 if (DestAA != AliasResult::NoAlias) 1023 rv = setMod(rv); 1024 return rv; 1025 } 1026 1027 // Guard intrinsics are marked as arbitrarily writing so that proper control 1028 // dependencies are maintained but they never mods any particular memory 1029 // location. 1030 // 1031 // *Unlike* assumes, guard intrinsics are modeled as reading memory since the 1032 // heap state at the point the guard is issued needs to be consistent in case 1033 // the guard invokes the "deopt" continuation. 1034 if (isIntrinsicCall(Call, Intrinsic::experimental_guard)) 1035 return ModRefInfo::Ref; 1036 // The same applies to deoptimize which is essentially a guard(false). 1037 if (isIntrinsicCall(Call, Intrinsic::experimental_deoptimize)) 1038 return ModRefInfo::Ref; 1039 1040 // Like assumes, invariant.start intrinsics were also marked as arbitrarily 1041 // writing so that proper control dependencies are maintained but they never 1042 // mod any particular memory location visible to the IR. 1043 // *Unlike* assumes (which are now modeled as NoModRef), invariant.start 1044 // intrinsic is now modeled as reading memory. This prevents hoisting the 1045 // invariant.start intrinsic over stores. Consider: 1046 // *ptr = 40; 1047 // *ptr = 50; 1048 // invariant_start(ptr) 1049 // int val = *ptr; 1050 // print(val); 1051 // 1052 // This cannot be transformed to: 1053 // 1054 // *ptr = 40; 1055 // invariant_start(ptr) 1056 // *ptr = 50; 1057 // int val = *ptr; 1058 // print(val); 1059 // 1060 // The transformation will cause the second store to be ignored (based on 1061 // rules of invariant.start) and print 40, while the first program always 1062 // prints 50. 1063 if (isIntrinsicCall(Call, Intrinsic::invariant_start)) 1064 return ModRefInfo::Ref; 1065 1066 // The AAResultBase base class has some smarts, lets use them. 1067 return AAResultBase::getModRefInfo(Call, Loc, AAQI); 1068 } 1069 1070 ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1, 1071 const CallBase *Call2, 1072 AAQueryInfo &AAQI) { 1073 // Guard intrinsics are marked as arbitrarily writing so that proper control 1074 // dependencies are maintained but they never mods any particular memory 1075 // location. 1076 // 1077 // *Unlike* assumes, guard intrinsics are modeled as reading memory since the 1078 // heap state at the point the guard is issued needs to be consistent in case 1079 // the guard invokes the "deopt" continuation. 1080 1081 // NB! This function is *not* commutative, so we special case two 1082 // possibilities for guard intrinsics. 1083 1084 if (isIntrinsicCall(Call1, Intrinsic::experimental_guard)) 1085 return isModSet(createModRefInfo(getModRefBehavior(Call2))) 1086 ? ModRefInfo::Ref 1087 : ModRefInfo::NoModRef; 1088 1089 if (isIntrinsicCall(Call2, Intrinsic::experimental_guard)) 1090 return isModSet(createModRefInfo(getModRefBehavior(Call1))) 1091 ? ModRefInfo::Mod 1092 : ModRefInfo::NoModRef; 1093 1094 // The AAResultBase base class has some smarts, lets use them. 1095 return AAResultBase::getModRefInfo(Call1, Call2, AAQI); 1096 } 1097 1098 /// Return true if we know V to the base address of the corresponding memory 1099 /// object. This implies that any address less than V must be out of bounds 1100 /// for the underlying object. Note that just being isIdentifiedObject() is 1101 /// not enough - For example, a negative offset from a noalias argument or call 1102 /// can be inbounds w.r.t the actual underlying object. 1103 static bool isBaseOfObject(const Value *V) { 1104 // TODO: We can handle other cases here 1105 // 1) For GC languages, arguments to functions are often required to be 1106 // base pointers. 1107 // 2) Result of allocation routines are often base pointers. Leverage TLI. 1108 return (isa<AllocaInst>(V) || isa<GlobalVariable>(V)); 1109 } 1110 1111 /// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against 1112 /// another pointer. 1113 /// 1114 /// We know that V1 is a GEP, but we don't know anything about V2. 1115 /// UnderlyingV1 is getUnderlyingObject(GEP1), UnderlyingV2 is the same for 1116 /// V2. 1117 AliasResult BasicAAResult::aliasGEP( 1118 const GEPOperator *GEP1, LocationSize V1Size, 1119 const Value *V2, LocationSize V2Size, 1120 const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) { 1121 if (!V1Size.hasValue() && !V2Size.hasValue()) { 1122 // TODO: This limitation exists for compile-time reasons. Relax it if we 1123 // can avoid exponential pathological cases. 1124 if (!isa<GEPOperator>(V2)) 1125 return AliasResult::MayAlias; 1126 1127 // If both accesses have unknown size, we can only check whether the base 1128 // objects don't alias. 1129 AliasResult BaseAlias = getBestAAResults().alias( 1130 MemoryLocation::getBeforeOrAfter(UnderlyingV1), 1131 MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI); 1132 return BaseAlias == AliasResult::NoAlias ? AliasResult::NoAlias 1133 : AliasResult::MayAlias; 1134 } 1135 1136 DecomposedGEP DecompGEP1 = DecomposeGEPExpression(GEP1, DL, &AC, DT); 1137 DecomposedGEP DecompGEP2 = DecomposeGEPExpression(V2, DL, &AC, DT); 1138 1139 // Bail if we were not able to decompose anything. 1140 if (DecompGEP1.Base == GEP1 && DecompGEP2.Base == V2) 1141 return AliasResult::MayAlias; 1142 1143 // Subtract the GEP2 pointer from the GEP1 pointer to find out their 1144 // symbolic difference. 1145 subtractDecomposedGEPs(DecompGEP1, DecompGEP2); 1146 1147 // If an inbounds GEP would have to start from an out of bounds address 1148 // for the two to alias, then we can assume noalias. 1149 if (*DecompGEP1.InBounds && DecompGEP1.VarIndices.empty() && 1150 V2Size.hasValue() && DecompGEP1.Offset.sge(V2Size.getValue()) && 1151 isBaseOfObject(DecompGEP2.Base)) 1152 return AliasResult::NoAlias; 1153 1154 if (isa<GEPOperator>(V2)) { 1155 // Symmetric case to above. 1156 if (*DecompGEP2.InBounds && DecompGEP1.VarIndices.empty() && 1157 V1Size.hasValue() && DecompGEP1.Offset.sle(-V1Size.getValue()) && 1158 isBaseOfObject(DecompGEP1.Base)) 1159 return AliasResult::NoAlias; 1160 } 1161 1162 // For GEPs with identical offsets, we can preserve the size and AAInfo 1163 // when performing the alias check on the underlying objects. 1164 if (DecompGEP1.Offset == 0 && DecompGEP1.VarIndices.empty()) 1165 return getBestAAResults().alias(MemoryLocation(DecompGEP1.Base, V1Size), 1166 MemoryLocation(DecompGEP2.Base, V2Size), 1167 AAQI); 1168 1169 // Do the base pointers alias? 1170 AliasResult BaseAlias = getBestAAResults().alias( 1171 MemoryLocation::getBeforeOrAfter(DecompGEP1.Base), 1172 MemoryLocation::getBeforeOrAfter(DecompGEP2.Base), AAQI); 1173 1174 // If we get a No or May, then return it immediately, no amount of analysis 1175 // will improve this situation. 1176 if (BaseAlias != AliasResult::MustAlias) { 1177 assert(BaseAlias == AliasResult::NoAlias || 1178 BaseAlias == AliasResult::MayAlias); 1179 return BaseAlias; 1180 } 1181 1182 // If there is a constant difference between the pointers, but the difference 1183 // is less than the size of the associated memory object, then we know 1184 // that the objects are partially overlapping. If the difference is 1185 // greater, we know they do not overlap. 1186 if (DecompGEP1.Offset != 0 && DecompGEP1.VarIndices.empty()) { 1187 APInt &Off = DecompGEP1.Offset; 1188 1189 // Initialize for Off >= 0 (V2 <= GEP1) case. 1190 const Value *LeftPtr = V2; 1191 const Value *RightPtr = GEP1; 1192 LocationSize VLeftSize = V2Size; 1193 LocationSize VRightSize = V1Size; 1194 const bool Swapped = Off.isNegative(); 1195 1196 if (Swapped) { 1197 // Swap if we have the situation where: 1198 // + + 1199 // | BaseOffset | 1200 // ---------------->| 1201 // |-->V1Size |-------> V2Size 1202 // GEP1 V2 1203 std::swap(LeftPtr, RightPtr); 1204 std::swap(VLeftSize, VRightSize); 1205 Off = -Off; 1206 } 1207 1208 if (VLeftSize.hasValue()) { 1209 const uint64_t LSize = VLeftSize.getValue(); 1210 if (Off.ult(LSize)) { 1211 // Conservatively drop processing if a phi was visited and/or offset is 1212 // too big. 1213 AliasResult AR = AliasResult::PartialAlias; 1214 if (VRightSize.hasValue() && Off.ule(INT32_MAX) && 1215 (Off + VRightSize.getValue()).ule(LSize)) { 1216 // Memory referenced by right pointer is nested. Save the offset in 1217 // cache. Note that originally offset estimated as GEP1-V2, but 1218 // AliasResult contains the shift that represents GEP1+Offset=V2. 1219 AR.setOffset(-Off.getSExtValue()); 1220 AR.swap(Swapped); 1221 } 1222 return AR; 1223 } 1224 return AliasResult::NoAlias; 1225 } 1226 } 1227 1228 if (!DecompGEP1.VarIndices.empty()) { 1229 APInt GCD; 1230 bool AllNonNegative = DecompGEP1.Offset.isNonNegative(); 1231 bool AllNonPositive = DecompGEP1.Offset.isNonPositive(); 1232 for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) { 1233 const VariableGEPIndex &Index = DecompGEP1.VarIndices[i]; 1234 const APInt &Scale = Index.Scale; 1235 APInt ScaleForGCD = Scale; 1236 if (!Index.IsNSW) 1237 ScaleForGCD = APInt::getOneBitSet(Scale.getBitWidth(), 1238 Scale.countTrailingZeros()); 1239 1240 if (i == 0) 1241 GCD = ScaleForGCD.abs(); 1242 else 1243 GCD = APIntOps::GreatestCommonDivisor(GCD, ScaleForGCD.abs()); 1244 1245 if (AllNonNegative || AllNonPositive) { 1246 KnownBits Known = Index.Val.evaluateWith( 1247 computeKnownBits(Index.Val.V, DL, 0, &AC, Index.CxtI, DT)); 1248 // TODO: Account for implicit trunc. 1249 bool SignKnownZero = Known.isNonNegative(); 1250 bool SignKnownOne = Known.isNegative(); 1251 AllNonNegative &= (SignKnownZero && Scale.isNonNegative()) || 1252 (SignKnownOne && Scale.isNonPositive()); 1253 AllNonPositive &= (SignKnownZero && Scale.isNonPositive()) || 1254 (SignKnownOne && Scale.isNonNegative()); 1255 } 1256 } 1257 1258 // We now have accesses at two offsets from the same base: 1259 // 1. (...)*GCD + DecompGEP1.Offset with size V1Size 1260 // 2. 0 with size V2Size 1261 // Using arithmetic modulo GCD, the accesses are at 1262 // [ModOffset..ModOffset+V1Size) and [0..V2Size). If the first access fits 1263 // into the range [V2Size..GCD), then we know they cannot overlap. 1264 APInt ModOffset = DecompGEP1.Offset.srem(GCD); 1265 if (ModOffset.isNegative()) 1266 ModOffset += GCD; // We want mod, not rem. 1267 if (V1Size.hasValue() && V2Size.hasValue() && 1268 ModOffset.uge(V2Size.getValue()) && 1269 (GCD - ModOffset).uge(V1Size.getValue())) 1270 return AliasResult::NoAlias; 1271 1272 // If we know all the variables are non-negative, then the total offset is 1273 // also non-negative and >= DecompGEP1.Offset. We have the following layout: 1274 // [0, V2Size) ... [TotalOffset, TotalOffer+V1Size] 1275 // If DecompGEP1.Offset >= V2Size, the accesses don't alias. 1276 if (AllNonNegative && V2Size.hasValue() && 1277 DecompGEP1.Offset.uge(V2Size.getValue())) 1278 return AliasResult::NoAlias; 1279 // Similarly, if the variables are non-positive, then the total offset is 1280 // also non-positive and <= DecompGEP1.Offset. We have the following layout: 1281 // [TotalOffset, TotalOffset+V1Size) ... [0, V2Size) 1282 // If -DecompGEP1.Offset >= V1Size, the accesses don't alias. 1283 if (AllNonPositive && V1Size.hasValue() && 1284 (-DecompGEP1.Offset).uge(V1Size.getValue())) 1285 return AliasResult::NoAlias; 1286 1287 if (V1Size.hasValue() && V2Size.hasValue()) { 1288 // Try to determine the range of values for VarIndex. 1289 // VarIndexRange is such that: 1290 // (VarIndex <= -MinAbsVarIndex || MinAbsVarIndex <= VarIndex) && 1291 // VarIndexRange.contains(VarIndex) 1292 Optional<APInt> MinAbsVarIndex; 1293 Optional<ConstantRange> VarIndexRange; 1294 if (DecompGEP1.VarIndices.size() == 1) { 1295 // VarIndex = Scale*V. 1296 const VariableGEPIndex &Var = DecompGEP1.VarIndices[0]; 1297 if (isKnownNonZero(Var.Val.V, DL, 0, &AC, Var.CxtI, DT)) { 1298 // If V != 0 then abs(VarIndex) >= abs(Scale). 1299 MinAbsVarIndex = Var.Scale.abs(); 1300 } 1301 ConstantRange R = Var.Val.evaluateWith( 1302 computeConstantRange(Var.Val.V, true, &AC, Var.CxtI)); 1303 if (!R.isFullSet() && !R.isEmptySet()) 1304 VarIndexRange = R.sextOrTrunc(Var.Scale.getBitWidth()) 1305 .smul_fast(ConstantRange(Var.Scale)); 1306 } else if (DecompGEP1.VarIndices.size() == 2) { 1307 // VarIndex = Scale*V0 + (-Scale)*V1. 1308 // If V0 != V1 then abs(VarIndex) >= abs(Scale). 1309 // Check that VisitedPhiBBs is empty, to avoid reasoning about 1310 // inequality of values across loop iterations. 1311 const VariableGEPIndex &Var0 = DecompGEP1.VarIndices[0]; 1312 const VariableGEPIndex &Var1 = DecompGEP1.VarIndices[1]; 1313 if (Var0.Scale == -Var1.Scale && 1314 Var0.Val.hasSameCastsAs(Var1.Val) && VisitedPhiBBs.empty() && 1315 isKnownNonEqual(Var0.Val.V, Var1.Val.V, DL, &AC, /* CxtI */ nullptr, 1316 DT)) 1317 MinAbsVarIndex = Var0.Scale.abs(); 1318 } 1319 1320 if (MinAbsVarIndex) { 1321 // The constant offset will have added at least +/-MinAbsVarIndex to it. 1322 APInt OffsetLo = DecompGEP1.Offset - *MinAbsVarIndex; 1323 APInt OffsetHi = DecompGEP1.Offset + *MinAbsVarIndex; 1324 // We know that Offset <= OffsetLo || Offset >= OffsetHi 1325 if (OffsetLo.isNegative() && (-OffsetLo).uge(V1Size.getValue()) && 1326 OffsetHi.isNonNegative() && OffsetHi.uge(V2Size.getValue())) 1327 return AliasResult::NoAlias; 1328 } 1329 1330 if (VarIndexRange) { 1331 ConstantRange OffsetRange = 1332 VarIndexRange->add(ConstantRange(DecompGEP1.Offset)); 1333 1334 // We know that Offset >= MinOffset. 1335 // (MinOffset >= V2Size) => (Offset >= V2Size) => NoAlias. 1336 if (OffsetRange.getSignedMin().sge(V2Size.getValue())) 1337 return AliasResult::NoAlias; 1338 1339 // We know that Offset <= MaxOffset. 1340 // (MaxOffset <= -V1Size) => (Offset <= -V1Size) => NoAlias. 1341 if (OffsetRange.getSignedMax().sle(-V1Size.getValue())) 1342 return AliasResult::NoAlias; 1343 } 1344 } 1345 1346 if (constantOffsetHeuristic(DecompGEP1, V1Size, V2Size, &AC, DT)) 1347 return AliasResult::NoAlias; 1348 } 1349 1350 // Statically, we can see that the base objects are the same, but the 1351 // pointers have dynamic offsets which we can't resolve. And none of our 1352 // little tricks above worked. 1353 return AliasResult::MayAlias; 1354 } 1355 1356 static AliasResult MergeAliasResults(AliasResult A, AliasResult B) { 1357 // If the results agree, take it. 1358 if (A == B) 1359 return A; 1360 // A mix of PartialAlias and MustAlias is PartialAlias. 1361 if ((A == AliasResult::PartialAlias && B == AliasResult::MustAlias) || 1362 (B == AliasResult::PartialAlias && A == AliasResult::MustAlias)) 1363 return AliasResult::PartialAlias; 1364 // Otherwise, we don't know anything. 1365 return AliasResult::MayAlias; 1366 } 1367 1368 /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction 1369 /// against another. 1370 AliasResult 1371 BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize, 1372 const Value *V2, LocationSize V2Size, 1373 AAQueryInfo &AAQI) { 1374 // If the values are Selects with the same condition, we can do a more precise 1375 // check: just check for aliases between the values on corresponding arms. 1376 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) 1377 if (SI->getCondition() == SI2->getCondition()) { 1378 AliasResult Alias = getBestAAResults().alias( 1379 MemoryLocation(SI->getTrueValue(), SISize), 1380 MemoryLocation(SI2->getTrueValue(), V2Size), AAQI); 1381 if (Alias == AliasResult::MayAlias) 1382 return AliasResult::MayAlias; 1383 AliasResult ThisAlias = getBestAAResults().alias( 1384 MemoryLocation(SI->getFalseValue(), SISize), 1385 MemoryLocation(SI2->getFalseValue(), V2Size), AAQI); 1386 return MergeAliasResults(ThisAlias, Alias); 1387 } 1388 1389 // If both arms of the Select node NoAlias or MustAlias V2, then returns 1390 // NoAlias / MustAlias. Otherwise, returns MayAlias. 1391 AliasResult Alias = getBestAAResults().alias( 1392 MemoryLocation(V2, V2Size), 1393 MemoryLocation(SI->getTrueValue(), SISize), AAQI); 1394 if (Alias == AliasResult::MayAlias) 1395 return AliasResult::MayAlias; 1396 1397 AliasResult ThisAlias = getBestAAResults().alias( 1398 MemoryLocation(V2, V2Size), 1399 MemoryLocation(SI->getFalseValue(), SISize), AAQI); 1400 return MergeAliasResults(ThisAlias, Alias); 1401 } 1402 1403 /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against 1404 /// another. 1405 AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize, 1406 const Value *V2, LocationSize V2Size, 1407 AAQueryInfo &AAQI) { 1408 if (!PN->getNumIncomingValues()) 1409 return AliasResult::NoAlias; 1410 // If the values are PHIs in the same block, we can do a more precise 1411 // as well as efficient check: just check for aliases between the values 1412 // on corresponding edges. 1413 if (const PHINode *PN2 = dyn_cast<PHINode>(V2)) 1414 if (PN2->getParent() == PN->getParent()) { 1415 Optional<AliasResult> Alias; 1416 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1417 AliasResult ThisAlias = getBestAAResults().alias( 1418 MemoryLocation(PN->getIncomingValue(i), PNSize), 1419 MemoryLocation( 1420 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)), V2Size), 1421 AAQI); 1422 if (Alias) 1423 *Alias = MergeAliasResults(*Alias, ThisAlias); 1424 else 1425 Alias = ThisAlias; 1426 if (*Alias == AliasResult::MayAlias) 1427 break; 1428 } 1429 return *Alias; 1430 } 1431 1432 SmallVector<Value *, 4> V1Srcs; 1433 // If a phi operand recurses back to the phi, we can still determine NoAlias 1434 // if we don't alias the underlying objects of the other phi operands, as we 1435 // know that the recursive phi needs to be based on them in some way. 1436 bool isRecursive = false; 1437 auto CheckForRecPhi = [&](Value *PV) { 1438 if (!EnableRecPhiAnalysis) 1439 return false; 1440 if (getUnderlyingObject(PV) == PN) { 1441 isRecursive = true; 1442 return true; 1443 } 1444 return false; 1445 }; 1446 1447 if (PV) { 1448 // If we have PhiValues then use it to get the underlying phi values. 1449 const PhiValues::ValueSet &PhiValueSet = PV->getValuesForPhi(PN); 1450 // If we have more phi values than the search depth then return MayAlias 1451 // conservatively to avoid compile time explosion. The worst possible case 1452 // is if both sides are PHI nodes. In which case, this is O(m x n) time 1453 // where 'm' and 'n' are the number of PHI sources. 1454 if (PhiValueSet.size() > MaxLookupSearchDepth) 1455 return AliasResult::MayAlias; 1456 // Add the values to V1Srcs 1457 for (Value *PV1 : PhiValueSet) { 1458 if (CheckForRecPhi(PV1)) 1459 continue; 1460 V1Srcs.push_back(PV1); 1461 } 1462 } else { 1463 // If we don't have PhiInfo then just look at the operands of the phi itself 1464 // FIXME: Remove this once we can guarantee that we have PhiInfo always 1465 SmallPtrSet<Value *, 4> UniqueSrc; 1466 Value *OnePhi = nullptr; 1467 for (Value *PV1 : PN->incoming_values()) { 1468 if (isa<PHINode>(PV1)) { 1469 if (OnePhi && OnePhi != PV1) { 1470 // To control potential compile time explosion, we choose to be 1471 // conserviate when we have more than one Phi input. It is important 1472 // that we handle the single phi case as that lets us handle LCSSA 1473 // phi nodes and (combined with the recursive phi handling) simple 1474 // pointer induction variable patterns. 1475 return AliasResult::MayAlias; 1476 } 1477 OnePhi = PV1; 1478 } 1479 1480 if (CheckForRecPhi(PV1)) 1481 continue; 1482 1483 if (UniqueSrc.insert(PV1).second) 1484 V1Srcs.push_back(PV1); 1485 } 1486 1487 if (OnePhi && UniqueSrc.size() > 1) 1488 // Out of an abundance of caution, allow only the trivial lcssa and 1489 // recursive phi cases. 1490 return AliasResult::MayAlias; 1491 } 1492 1493 // If V1Srcs is empty then that means that the phi has no underlying non-phi 1494 // value. This should only be possible in blocks unreachable from the entry 1495 // block, but return MayAlias just in case. 1496 if (V1Srcs.empty()) 1497 return AliasResult::MayAlias; 1498 1499 // If this PHI node is recursive, indicate that the pointer may be moved 1500 // across iterations. We can only prove NoAlias if different underlying 1501 // objects are involved. 1502 if (isRecursive) 1503 PNSize = LocationSize::beforeOrAfterPointer(); 1504 1505 // In the recursive alias queries below, we may compare values from two 1506 // different loop iterations. Keep track of visited phi blocks, which will 1507 // be used when determining value equivalence. 1508 bool BlockInserted = VisitedPhiBBs.insert(PN->getParent()).second; 1509 auto _ = make_scope_exit([&]() { 1510 if (BlockInserted) 1511 VisitedPhiBBs.erase(PN->getParent()); 1512 }); 1513 1514 // If we inserted a block into VisitedPhiBBs, alias analysis results that 1515 // have been cached earlier may no longer be valid. Perform recursive queries 1516 // with a new AAQueryInfo. 1517 AAQueryInfo NewAAQI = AAQI.withEmptyCache(); 1518 AAQueryInfo *UseAAQI = BlockInserted ? &NewAAQI : &AAQI; 1519 1520 AliasResult Alias = getBestAAResults().alias( 1521 MemoryLocation(V2, V2Size), 1522 MemoryLocation(V1Srcs[0], PNSize), *UseAAQI); 1523 1524 // Early exit if the check of the first PHI source against V2 is MayAlias. 1525 // Other results are not possible. 1526 if (Alias == AliasResult::MayAlias) 1527 return AliasResult::MayAlias; 1528 // With recursive phis we cannot guarantee that MustAlias/PartialAlias will 1529 // remain valid to all elements and needs to conservatively return MayAlias. 1530 if (isRecursive && Alias != AliasResult::NoAlias) 1531 return AliasResult::MayAlias; 1532 1533 // If all sources of the PHI node NoAlias or MustAlias V2, then returns 1534 // NoAlias / MustAlias. Otherwise, returns MayAlias. 1535 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) { 1536 Value *V = V1Srcs[i]; 1537 1538 AliasResult ThisAlias = getBestAAResults().alias( 1539 MemoryLocation(V2, V2Size), MemoryLocation(V, PNSize), *UseAAQI); 1540 Alias = MergeAliasResults(ThisAlias, Alias); 1541 if (Alias == AliasResult::MayAlias) 1542 break; 1543 } 1544 1545 return Alias; 1546 } 1547 1548 /// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as 1549 /// array references. 1550 AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size, 1551 const Value *V2, LocationSize V2Size, 1552 AAQueryInfo &AAQI) { 1553 // If either of the memory references is empty, it doesn't matter what the 1554 // pointer values are. 1555 if (V1Size.isZero() || V2Size.isZero()) 1556 return AliasResult::NoAlias; 1557 1558 // Strip off any casts if they exist. 1559 V1 = V1->stripPointerCastsForAliasAnalysis(); 1560 V2 = V2->stripPointerCastsForAliasAnalysis(); 1561 1562 // If V1 or V2 is undef, the result is NoAlias because we can always pick a 1563 // value for undef that aliases nothing in the program. 1564 if (isa<UndefValue>(V1) || isa<UndefValue>(V2)) 1565 return AliasResult::NoAlias; 1566 1567 // Are we checking for alias of the same value? 1568 // Because we look 'through' phi nodes, we could look at "Value" pointers from 1569 // different iterations. We must therefore make sure that this is not the 1570 // case. The function isValueEqualInPotentialCycles ensures that this cannot 1571 // happen by looking at the visited phi nodes and making sure they cannot 1572 // reach the value. 1573 if (isValueEqualInPotentialCycles(V1, V2)) 1574 return AliasResult::MustAlias; 1575 1576 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy()) 1577 return AliasResult::NoAlias; // Scalars cannot alias each other 1578 1579 // Figure out what objects these things are pointing to if we can. 1580 const Value *O1 = getUnderlyingObject(V1, MaxLookupSearchDepth); 1581 const Value *O2 = getUnderlyingObject(V2, MaxLookupSearchDepth); 1582 1583 // Null values in the default address space don't point to any object, so they 1584 // don't alias any other pointer. 1585 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1)) 1586 if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace())) 1587 return AliasResult::NoAlias; 1588 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2)) 1589 if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace())) 1590 return AliasResult::NoAlias; 1591 1592 if (O1 != O2) { 1593 // If V1/V2 point to two different objects, we know that we have no alias. 1594 if (isIdentifiedObject(O1) && isIdentifiedObject(O2)) 1595 return AliasResult::NoAlias; 1596 1597 // Constant pointers can't alias with non-const isIdentifiedObject objects. 1598 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) || 1599 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1))) 1600 return AliasResult::NoAlias; 1601 1602 // Function arguments can't alias with things that are known to be 1603 // unambigously identified at the function level. 1604 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) || 1605 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1))) 1606 return AliasResult::NoAlias; 1607 1608 // If one pointer is the result of a call/invoke or load and the other is a 1609 // non-escaping local object within the same function, then we know the 1610 // object couldn't escape to a point where the call could return it. 1611 // 1612 // Note that if the pointers are in different functions, there are a 1613 // variety of complications. A call with a nocapture argument may still 1614 // temporary store the nocapture argument's value in a temporary memory 1615 // location if that memory location doesn't escape. Or it may pass a 1616 // nocapture value to other functions as long as they don't capture it. 1617 if (isEscapeSource(O1) && 1618 AAQI.CI->isNotCapturedBeforeOrAt(O2, cast<Instruction>(O1))) 1619 return AliasResult::NoAlias; 1620 if (isEscapeSource(O2) && 1621 AAQI.CI->isNotCapturedBeforeOrAt(O1, cast<Instruction>(O2))) 1622 return AliasResult::NoAlias; 1623 } 1624 1625 // If the size of one access is larger than the entire object on the other 1626 // side, then we know such behavior is undefined and can assume no alias. 1627 bool NullIsValidLocation = NullPointerIsDefined(&F); 1628 if ((isObjectSmallerThan( 1629 O2, getMinimalExtentFrom(*V1, V1Size, DL, NullIsValidLocation), DL, 1630 TLI, NullIsValidLocation)) || 1631 (isObjectSmallerThan( 1632 O1, getMinimalExtentFrom(*V2, V2Size, DL, NullIsValidLocation), DL, 1633 TLI, NullIsValidLocation))) 1634 return AliasResult::NoAlias; 1635 1636 // If one the accesses may be before the accessed pointer, canonicalize this 1637 // by using unknown after-pointer sizes for both accesses. This is 1638 // equivalent, because regardless of which pointer is lower, one of them 1639 // will always came after the other, as long as the underlying objects aren't 1640 // disjoint. We do this so that the rest of BasicAA does not have to deal 1641 // with accesses before the base pointer, and to improve cache utilization by 1642 // merging equivalent states. 1643 if (V1Size.mayBeBeforePointer() || V2Size.mayBeBeforePointer()) { 1644 V1Size = LocationSize::afterPointer(); 1645 V2Size = LocationSize::afterPointer(); 1646 } 1647 1648 // FIXME: If this depth limit is hit, then we may cache sub-optimal results 1649 // for recursive queries. For this reason, this limit is chosen to be large 1650 // enough to be very rarely hit, while still being small enough to avoid 1651 // stack overflows. 1652 if (AAQI.Depth >= 512) 1653 return AliasResult::MayAlias; 1654 1655 // Check the cache before climbing up use-def chains. This also terminates 1656 // otherwise infinitely recursive queries. 1657 AAQueryInfo::LocPair Locs({V1, V1Size}, {V2, V2Size}); 1658 const bool Swapped = V1 > V2; 1659 if (Swapped) 1660 std::swap(Locs.first, Locs.second); 1661 const auto &Pair = AAQI.AliasCache.try_emplace( 1662 Locs, AAQueryInfo::CacheEntry{AliasResult::NoAlias, 0}); 1663 if (!Pair.second) { 1664 auto &Entry = Pair.first->second; 1665 if (!Entry.isDefinitive()) { 1666 // Remember that we used an assumption. 1667 ++Entry.NumAssumptionUses; 1668 ++AAQI.NumAssumptionUses; 1669 } 1670 // Cache contains sorted {V1,V2} pairs but we should return original order. 1671 auto Result = Entry.Result; 1672 Result.swap(Swapped); 1673 return Result; 1674 } 1675 1676 int OrigNumAssumptionUses = AAQI.NumAssumptionUses; 1677 unsigned OrigNumAssumptionBasedResults = AAQI.AssumptionBasedResults.size(); 1678 AliasResult Result = 1679 aliasCheckRecursive(V1, V1Size, V2, V2Size, AAQI, O1, O2); 1680 1681 auto It = AAQI.AliasCache.find(Locs); 1682 assert(It != AAQI.AliasCache.end() && "Must be in cache"); 1683 auto &Entry = It->second; 1684 1685 // Check whether a NoAlias assumption has been used, but disproven. 1686 bool AssumptionDisproven = 1687 Entry.NumAssumptionUses > 0 && Result != AliasResult::NoAlias; 1688 if (AssumptionDisproven) 1689 Result = AliasResult::MayAlias; 1690 1691 // This is a definitive result now, when considered as a root query. 1692 AAQI.NumAssumptionUses -= Entry.NumAssumptionUses; 1693 Entry.Result = Result; 1694 // Cache contains sorted {V1,V2} pairs. 1695 Entry.Result.swap(Swapped); 1696 Entry.NumAssumptionUses = -1; 1697 1698 // If the assumption has been disproven, remove any results that may have 1699 // been based on this assumption. Do this after the Entry updates above to 1700 // avoid iterator invalidation. 1701 if (AssumptionDisproven) 1702 while (AAQI.AssumptionBasedResults.size() > OrigNumAssumptionBasedResults) 1703 AAQI.AliasCache.erase(AAQI.AssumptionBasedResults.pop_back_val()); 1704 1705 // The result may still be based on assumptions higher up in the chain. 1706 // Remember it, so it can be purged from the cache later. 1707 if (OrigNumAssumptionUses != AAQI.NumAssumptionUses && 1708 Result != AliasResult::MayAlias) 1709 AAQI.AssumptionBasedResults.push_back(Locs); 1710 return Result; 1711 } 1712 1713 AliasResult BasicAAResult::aliasCheckRecursive( 1714 const Value *V1, LocationSize V1Size, 1715 const Value *V2, LocationSize V2Size, 1716 AAQueryInfo &AAQI, const Value *O1, const Value *O2) { 1717 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) { 1718 AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, O1, O2, AAQI); 1719 if (Result != AliasResult::MayAlias) 1720 return Result; 1721 } else if (const GEPOperator *GV2 = dyn_cast<GEPOperator>(V2)) { 1722 AliasResult Result = aliasGEP(GV2, V2Size, V1, V1Size, O2, O1, AAQI); 1723 if (Result != AliasResult::MayAlias) 1724 return Result; 1725 } 1726 1727 if (const PHINode *PN = dyn_cast<PHINode>(V1)) { 1728 AliasResult Result = aliasPHI(PN, V1Size, V2, V2Size, AAQI); 1729 if (Result != AliasResult::MayAlias) 1730 return Result; 1731 } else if (const PHINode *PN = dyn_cast<PHINode>(V2)) { 1732 AliasResult Result = aliasPHI(PN, V2Size, V1, V1Size, AAQI); 1733 if (Result != AliasResult::MayAlias) 1734 return Result; 1735 } 1736 1737 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) { 1738 AliasResult Result = aliasSelect(S1, V1Size, V2, V2Size, AAQI); 1739 if (Result != AliasResult::MayAlias) 1740 return Result; 1741 } else if (const SelectInst *S2 = dyn_cast<SelectInst>(V2)) { 1742 AliasResult Result = aliasSelect(S2, V2Size, V1, V1Size, AAQI); 1743 if (Result != AliasResult::MayAlias) 1744 return Result; 1745 } 1746 1747 // If both pointers are pointing into the same object and one of them 1748 // accesses the entire object, then the accesses must overlap in some way. 1749 if (O1 == O2) { 1750 bool NullIsValidLocation = NullPointerIsDefined(&F); 1751 if (V1Size.isPrecise() && V2Size.isPrecise() && 1752 (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) || 1753 isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation))) 1754 return AliasResult::PartialAlias; 1755 } 1756 1757 return AliasResult::MayAlias; 1758 } 1759 1760 /// Check whether two Values can be considered equivalent. 1761 /// 1762 /// In addition to pointer equivalence of \p V1 and \p V2 this checks whether 1763 /// they can not be part of a cycle in the value graph by looking at all 1764 /// visited phi nodes an making sure that the phis cannot reach the value. We 1765 /// have to do this because we are looking through phi nodes (That is we say 1766 /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB). 1767 bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V, 1768 const Value *V2) { 1769 if (V != V2) 1770 return false; 1771 1772 const Instruction *Inst = dyn_cast<Instruction>(V); 1773 if (!Inst) 1774 return true; 1775 1776 if (VisitedPhiBBs.empty()) 1777 return true; 1778 1779 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck) 1780 return false; 1781 1782 // Make sure that the visited phis cannot reach the Value. This ensures that 1783 // the Values cannot come from different iterations of a potential cycle the 1784 // phi nodes could be involved in. 1785 for (auto *P : VisitedPhiBBs) 1786 if (isPotentiallyReachable(&P->front(), Inst, nullptr, DT)) 1787 return false; 1788 1789 return true; 1790 } 1791 1792 /// Computes the symbolic difference between two de-composed GEPs. 1793 void BasicAAResult::subtractDecomposedGEPs(DecomposedGEP &DestGEP, 1794 const DecomposedGEP &SrcGEP) { 1795 DestGEP.Offset -= SrcGEP.Offset; 1796 for (const VariableGEPIndex &Src : SrcGEP.VarIndices) { 1797 // Find V in Dest. This is N^2, but pointer indices almost never have more 1798 // than a few variable indexes. 1799 bool Found = false; 1800 for (auto I : enumerate(DestGEP.VarIndices)) { 1801 VariableGEPIndex &Dest = I.value(); 1802 if (!isValueEqualInPotentialCycles(Dest.Val.V, Src.Val.V) || 1803 !Dest.Val.hasSameCastsAs(Src.Val)) 1804 continue; 1805 1806 // If we found it, subtract off Scale V's from the entry in Dest. If it 1807 // goes to zero, remove the entry. 1808 if (Dest.Scale != Src.Scale) { 1809 Dest.Scale -= Src.Scale; 1810 Dest.IsNSW = false; 1811 } else { 1812 DestGEP.VarIndices.erase(DestGEP.VarIndices.begin() + I.index()); 1813 } 1814 Found = true; 1815 break; 1816 } 1817 1818 // If we didn't consume this entry, add it to the end of the Dest list. 1819 if (!Found) { 1820 VariableGEPIndex Entry = {Src.Val, -Src.Scale, Src.CxtI, Src.IsNSW}; 1821 DestGEP.VarIndices.push_back(Entry); 1822 } 1823 } 1824 } 1825 1826 bool BasicAAResult::constantOffsetHeuristic( 1827 const DecomposedGEP &GEP, LocationSize MaybeV1Size, 1828 LocationSize MaybeV2Size, AssumptionCache *AC, DominatorTree *DT) { 1829 if (GEP.VarIndices.size() != 2 || !MaybeV1Size.hasValue() || 1830 !MaybeV2Size.hasValue()) 1831 return false; 1832 1833 const uint64_t V1Size = MaybeV1Size.getValue(); 1834 const uint64_t V2Size = MaybeV2Size.getValue(); 1835 1836 const VariableGEPIndex &Var0 = GEP.VarIndices[0], &Var1 = GEP.VarIndices[1]; 1837 1838 if (!Var0.Val.hasSameCastsAs(Var1.Val) || Var0.Scale != -Var1.Scale || 1839 Var0.Val.V->getType() != Var1.Val.V->getType()) 1840 return false; 1841 1842 // We'll strip off the Extensions of Var0 and Var1 and do another round 1843 // of GetLinearExpression decomposition. In the example above, if Var0 1844 // is zext(%x + 1) we should get V1 == %x and V1Offset == 1. 1845 1846 LinearExpression E0 = 1847 GetLinearExpression(CastedValue(Var0.Val.V), DL, 0, AC, DT); 1848 LinearExpression E1 = 1849 GetLinearExpression(CastedValue(Var1.Val.V), DL, 0, AC, DT); 1850 if (E0.Scale != E1.Scale || !E0.Val.hasSameCastsAs(E1.Val) || 1851 !isValueEqualInPotentialCycles(E0.Val.V, E1.Val.V)) 1852 return false; 1853 1854 // We have a hit - Var0 and Var1 only differ by a constant offset! 1855 1856 // If we've been sext'ed then zext'd the maximum difference between Var0 and 1857 // Var1 is possible to calculate, but we're just interested in the absolute 1858 // minimum difference between the two. The minimum distance may occur due to 1859 // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so 1860 // the minimum distance between %i and %i + 5 is 3. 1861 APInt MinDiff = E0.Offset - E1.Offset, Wrapped = -MinDiff; 1862 MinDiff = APIntOps::umin(MinDiff, Wrapped); 1863 APInt MinDiffBytes = 1864 MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs(); 1865 1866 // We can't definitely say whether GEP1 is before or after V2 due to wrapping 1867 // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other 1868 // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and 1869 // V2Size can fit in the MinDiffBytes gap. 1870 return MinDiffBytes.uge(V1Size + GEP.Offset.abs()) && 1871 MinDiffBytes.uge(V2Size + GEP.Offset.abs()); 1872 } 1873 1874 //===----------------------------------------------------------------------===// 1875 // BasicAliasAnalysis Pass 1876 //===----------------------------------------------------------------------===// 1877 1878 AnalysisKey BasicAA::Key; 1879 1880 BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) { 1881 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1882 auto &AC = AM.getResult<AssumptionAnalysis>(F); 1883 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 1884 auto *PV = AM.getCachedResult<PhiValuesAnalysis>(F); 1885 return BasicAAResult(F.getParent()->getDataLayout(), F, TLI, AC, DT, PV); 1886 } 1887 1888 BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) { 1889 initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry()); 1890 } 1891 1892 char BasicAAWrapperPass::ID = 0; 1893 1894 void BasicAAWrapperPass::anchor() {} 1895 1896 INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basic-aa", 1897 "Basic Alias Analysis (stateless AA impl)", true, true) 1898 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1899 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1900 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1901 INITIALIZE_PASS_DEPENDENCY(PhiValuesWrapperPass) 1902 INITIALIZE_PASS_END(BasicAAWrapperPass, "basic-aa", 1903 "Basic Alias Analysis (stateless AA impl)", true, true) 1904 1905 FunctionPass *llvm::createBasicAAWrapperPass() { 1906 return new BasicAAWrapperPass(); 1907 } 1908 1909 bool BasicAAWrapperPass::runOnFunction(Function &F) { 1910 auto &ACT = getAnalysis<AssumptionCacheTracker>(); 1911 auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>(); 1912 auto &DTWP = getAnalysis<DominatorTreeWrapperPass>(); 1913 auto *PVWP = getAnalysisIfAvailable<PhiValuesWrapperPass>(); 1914 1915 Result.reset(new BasicAAResult(F.getParent()->getDataLayout(), F, 1916 TLIWP.getTLI(F), ACT.getAssumptionCache(F), 1917 &DTWP.getDomTree(), 1918 PVWP ? &PVWP->getResult() : nullptr)); 1919 1920 return false; 1921 } 1922 1923 void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 1924 AU.setPreservesAll(); 1925 AU.addRequiredTransitive<AssumptionCacheTracker>(); 1926 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 1927 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 1928 AU.addUsedIfAvailable<PhiValuesWrapperPass>(); 1929 } 1930 1931 BasicAAResult llvm::createLegacyPMBasicAAResult(Pass &P, Function &F) { 1932 return BasicAAResult( 1933 F.getParent()->getDataLayout(), F, 1934 P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 1935 P.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F)); 1936 } 1937