BasicAliasAnalysis.cpp 71 KB

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