AliasAnalysis.h 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Analysis/AliasAnalysis.h - Alias Analysis Interface -*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the generic AliasAnalysis interface, which is used as the
  15. // common interface used by all clients of alias analysis information, and
  16. // implemented by all alias analysis implementations. Mod/Ref information is
  17. // also captured by this interface.
  18. //
  19. // Implementations of this interface must implement the various virtual methods,
  20. // which automatically provides functionality for the entire suite of client
  21. // APIs.
  22. //
  23. // This API identifies memory regions with the MemoryLocation class. The pointer
  24. // component specifies the base memory address of the region. The Size specifies
  25. // the maximum size (in address units) of the memory region, or
  26. // MemoryLocation::UnknownSize if the size is not known. The TBAA tag
  27. // identifies the "type" of the memory reference; see the
  28. // TypeBasedAliasAnalysis class for details.
  29. //
  30. // Some non-obvious details include:
  31. // - Pointers that point to two completely different objects in memory never
  32. // alias, regardless of the value of the Size component.
  33. // - NoAlias doesn't imply inequal pointers. The most obvious example of this
  34. // is two pointers to constant memory. Even if they are equal, constant
  35. // memory is never stored to, so there will never be any dependencies.
  36. // In this and other situations, the pointers may be both NoAlias and
  37. // MustAlias at the same time. The current API can only return one result,
  38. // though this is rarely a problem in practice.
  39. //
  40. //===----------------------------------------------------------------------===//
  41. #ifndef LLVM_ANALYSIS_ALIASANALYSIS_H
  42. #define LLVM_ANALYSIS_ALIASANALYSIS_H
  43. #include "llvm/ADT/DenseMap.h"
  44. #include "llvm/ADT/None.h"
  45. #include "llvm/ADT/Optional.h"
  46. #include "llvm/ADT/SmallVector.h"
  47. #include "llvm/Analysis/MemoryLocation.h"
  48. #include "llvm/IR/PassManager.h"
  49. #include "llvm/Pass.h"
  50. #include <cstdint>
  51. #include <functional>
  52. #include <memory>
  53. #include <vector>
  54. namespace llvm {
  55. class AnalysisUsage;
  56. class AtomicCmpXchgInst;
  57. class BasicAAResult;
  58. class BasicBlock;
  59. class CatchPadInst;
  60. class CatchReturnInst;
  61. class DominatorTree;
  62. class FenceInst;
  63. class Function;
  64. class LoopInfo;
  65. class PreservedAnalyses;
  66. class TargetLibraryInfo;
  67. class Value;
  68. /// The possible results of an alias query.
  69. ///
  70. /// These results are always computed between two MemoryLocation objects as
  71. /// a query to some alias analysis.
  72. ///
  73. /// Note that these are unscoped enumerations because we would like to support
  74. /// implicitly testing a result for the existence of any possible aliasing with
  75. /// a conversion to bool, but an "enum class" doesn't support this. The
  76. /// canonical names from the literature are suffixed and unique anyways, and so
  77. /// they serve as global constants in LLVM for these results.
  78. ///
  79. /// See docs/AliasAnalysis.html for more information on the specific meanings
  80. /// of these values.
  81. class AliasResult {
  82. private:
  83. static const int OffsetBits = 23;
  84. static const int AliasBits = 8;
  85. static_assert(AliasBits + 1 + OffsetBits <= 32,
  86. "AliasResult size is intended to be 4 bytes!");
  87. unsigned int Alias : AliasBits;
  88. unsigned int HasOffset : 1;
  89. signed int Offset : OffsetBits;
  90. public:
  91. enum Kind : uint8_t {
  92. /// The two locations do not alias at all.
  93. ///
  94. /// This value is arranged to convert to false, while all other values
  95. /// convert to true. This allows a boolean context to convert the result to
  96. /// a binary flag indicating whether there is the possibility of aliasing.
  97. NoAlias = 0,
  98. /// The two locations may or may not alias. This is the least precise
  99. /// result.
  100. MayAlias,
  101. /// The two locations alias, but only due to a partial overlap.
  102. PartialAlias,
  103. /// The two locations precisely alias each other.
  104. MustAlias,
  105. };
  106. static_assert(MustAlias < (1 << AliasBits),
  107. "Not enough bit field size for the enum!");
  108. explicit AliasResult() = delete;
  109. constexpr AliasResult(const Kind &Alias)
  110. : Alias(Alias), HasOffset(false), Offset(0) {}
  111. operator Kind() const { return static_cast<Kind>(Alias); }
  112. constexpr bool hasOffset() const { return HasOffset; }
  113. constexpr int32_t getOffset() const {
  114. assert(HasOffset && "No offset!");
  115. return Offset;
  116. }
  117. void setOffset(int32_t NewOffset) {
  118. if (isInt<OffsetBits>(NewOffset)) {
  119. HasOffset = true;
  120. Offset = NewOffset;
  121. }
  122. }
  123. /// Helper for processing AliasResult for swapped memory location pairs.
  124. void swap(bool DoSwap = true) {
  125. if (DoSwap && hasOffset())
  126. setOffset(-getOffset());
  127. }
  128. };
  129. static_assert(sizeof(AliasResult) == 4,
  130. "AliasResult size is intended to be 4 bytes!");
  131. /// << operator for AliasResult.
  132. raw_ostream &operator<<(raw_ostream &OS, AliasResult AR);
  133. /// Flags indicating whether a memory access modifies or references memory.
  134. ///
  135. /// This is no access at all, a modification, a reference, or both
  136. /// a modification and a reference. These are specifically structured such that
  137. /// they form a three bit matrix and bit-tests for 'mod' or 'ref' or 'must'
  138. /// work with any of the possible values.
  139. enum class ModRefInfo : uint8_t {
  140. /// Must is provided for completeness, but no routines will return only
  141. /// Must today. See definition of Must below.
  142. Must = 0,
  143. /// The access may reference the value stored in memory,
  144. /// a mustAlias relation was found, and no mayAlias or partialAlias found.
  145. MustRef = 1,
  146. /// The access may modify the value stored in memory,
  147. /// a mustAlias relation was found, and no mayAlias or partialAlias found.
  148. MustMod = 2,
  149. /// The access may reference, modify or both the value stored in memory,
  150. /// a mustAlias relation was found, and no mayAlias or partialAlias found.
  151. MustModRef = MustRef | MustMod,
  152. /// The access neither references nor modifies the value stored in memory.
  153. NoModRef = 4,
  154. /// The access may reference the value stored in memory.
  155. Ref = NoModRef | MustRef,
  156. /// The access may modify the value stored in memory.
  157. Mod = NoModRef | MustMod,
  158. /// The access may reference and may modify the value stored in memory.
  159. ModRef = Ref | Mod,
  160. /// About Must:
  161. /// Must is set in a best effort manner.
  162. /// We usually do not try our best to infer Must, instead it is merely
  163. /// another piece of "free" information that is presented when available.
  164. /// Must set means there was certainly a MustAlias found. For calls,
  165. /// where multiple arguments are checked (argmemonly), this translates to
  166. /// only MustAlias or NoAlias was found.
  167. /// Must is not set for RAR accesses, even if the two locations must
  168. /// alias. The reason is that two read accesses translate to an early return
  169. /// of NoModRef. An additional alias check to set Must may be
  170. /// expensive. Other cases may also not set Must(e.g. callCapturesBefore).
  171. /// We refer to Must being *set* when the most significant bit is *cleared*.
  172. /// Conversely we *clear* Must information by *setting* the Must bit to 1.
  173. };
  174. LLVM_NODISCARD inline bool isNoModRef(const ModRefInfo MRI) {
  175. return (static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustModRef)) ==
  176. static_cast<int>(ModRefInfo::Must);
  177. }
  178. LLVM_NODISCARD inline bool isModOrRefSet(const ModRefInfo MRI) {
  179. return static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustModRef);
  180. }
  181. LLVM_NODISCARD inline bool isModAndRefSet(const ModRefInfo MRI) {
  182. return (static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustModRef)) ==
  183. static_cast<int>(ModRefInfo::MustModRef);
  184. }
  185. LLVM_NODISCARD inline bool isModSet(const ModRefInfo MRI) {
  186. return static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustMod);
  187. }
  188. LLVM_NODISCARD inline bool isRefSet(const ModRefInfo MRI) {
  189. return static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustRef);
  190. }
  191. LLVM_NODISCARD inline bool isMustSet(const ModRefInfo MRI) {
  192. return !(static_cast<int>(MRI) & static_cast<int>(ModRefInfo::NoModRef));
  193. }
  194. LLVM_NODISCARD inline ModRefInfo setMod(const ModRefInfo MRI) {
  195. return ModRefInfo(static_cast<int>(MRI) |
  196. static_cast<int>(ModRefInfo::MustMod));
  197. }
  198. LLVM_NODISCARD inline ModRefInfo setRef(const ModRefInfo MRI) {
  199. return ModRefInfo(static_cast<int>(MRI) |
  200. static_cast<int>(ModRefInfo::MustRef));
  201. }
  202. LLVM_NODISCARD inline ModRefInfo setMust(const ModRefInfo MRI) {
  203. return ModRefInfo(static_cast<int>(MRI) &
  204. static_cast<int>(ModRefInfo::MustModRef));
  205. }
  206. LLVM_NODISCARD inline ModRefInfo setModAndRef(const ModRefInfo MRI) {
  207. return ModRefInfo(static_cast<int>(MRI) |
  208. static_cast<int>(ModRefInfo::MustModRef));
  209. }
  210. LLVM_NODISCARD inline ModRefInfo clearMod(const ModRefInfo MRI) {
  211. return ModRefInfo(static_cast<int>(MRI) & static_cast<int>(ModRefInfo::Ref));
  212. }
  213. LLVM_NODISCARD inline ModRefInfo clearRef(const ModRefInfo MRI) {
  214. return ModRefInfo(static_cast<int>(MRI) & static_cast<int>(ModRefInfo::Mod));
  215. }
  216. LLVM_NODISCARD inline ModRefInfo clearMust(const ModRefInfo MRI) {
  217. return ModRefInfo(static_cast<int>(MRI) |
  218. static_cast<int>(ModRefInfo::NoModRef));
  219. }
  220. LLVM_NODISCARD inline ModRefInfo unionModRef(const ModRefInfo MRI1,
  221. const ModRefInfo MRI2) {
  222. return ModRefInfo(static_cast<int>(MRI1) | static_cast<int>(MRI2));
  223. }
  224. LLVM_NODISCARD inline ModRefInfo intersectModRef(const ModRefInfo MRI1,
  225. const ModRefInfo MRI2) {
  226. return ModRefInfo(static_cast<int>(MRI1) & static_cast<int>(MRI2));
  227. }
  228. /// The locations at which a function might access memory.
  229. ///
  230. /// These are primarily used in conjunction with the \c AccessKind bits to
  231. /// describe both the nature of access and the locations of access for a
  232. /// function call.
  233. enum FunctionModRefLocation {
  234. /// Base case is no access to memory.
  235. FMRL_Nowhere = 0,
  236. /// Access to memory via argument pointers.
  237. FMRL_ArgumentPointees = 8,
  238. /// Memory that is inaccessible via LLVM IR.
  239. FMRL_InaccessibleMem = 16,
  240. /// Access to any memory.
  241. FMRL_Anywhere = 32 | FMRL_InaccessibleMem | FMRL_ArgumentPointees
  242. };
  243. /// Summary of how a function affects memory in the program.
  244. ///
  245. /// Loads from constant globals are not considered memory accesses for this
  246. /// interface. Also, functions may freely modify stack space local to their
  247. /// invocation without having to report it through these interfaces.
  248. enum FunctionModRefBehavior {
  249. /// This function does not perform any non-local loads or stores to memory.
  250. ///
  251. /// This property corresponds to the GCC 'const' attribute.
  252. /// This property corresponds to the LLVM IR 'readnone' attribute.
  253. /// This property corresponds to the IntrNoMem LLVM intrinsic flag.
  254. FMRB_DoesNotAccessMemory =
  255. FMRL_Nowhere | static_cast<int>(ModRefInfo::NoModRef),
  256. /// The only memory references in this function (if it has any) are
  257. /// non-volatile loads from objects pointed to by its pointer-typed
  258. /// arguments, with arbitrary offsets.
  259. ///
  260. /// This property corresponds to the combination of the IntrReadMem
  261. /// and IntrArgMemOnly LLVM intrinsic flags.
  262. FMRB_OnlyReadsArgumentPointees =
  263. FMRL_ArgumentPointees | static_cast<int>(ModRefInfo::Ref),
  264. /// The only memory references in this function (if it has any) are
  265. /// non-volatile stores from objects pointed to by its pointer-typed
  266. /// arguments, with arbitrary offsets.
  267. ///
  268. /// This property corresponds to the combination of the IntrWriteMem
  269. /// and IntrArgMemOnly LLVM intrinsic flags.
  270. FMRB_OnlyWritesArgumentPointees =
  271. FMRL_ArgumentPointees | static_cast<int>(ModRefInfo::Mod),
  272. /// The only memory references in this function (if it has any) are
  273. /// non-volatile loads and stores from objects pointed to by its
  274. /// pointer-typed arguments, with arbitrary offsets.
  275. ///
  276. /// This property corresponds to the IntrArgMemOnly LLVM intrinsic flag.
  277. FMRB_OnlyAccessesArgumentPointees =
  278. FMRL_ArgumentPointees | static_cast<int>(ModRefInfo::ModRef),
  279. /// The only memory references in this function (if it has any) are
  280. /// reads of memory that is otherwise inaccessible via LLVM IR.
  281. ///
  282. /// This property corresponds to the LLVM IR inaccessiblememonly attribute.
  283. FMRB_OnlyReadsInaccessibleMem =
  284. FMRL_InaccessibleMem | static_cast<int>(ModRefInfo::Ref),
  285. /// The only memory references in this function (if it has any) are
  286. /// writes to memory that is otherwise inaccessible via LLVM IR.
  287. ///
  288. /// This property corresponds to the LLVM IR inaccessiblememonly attribute.
  289. FMRB_OnlyWritesInaccessibleMem =
  290. FMRL_InaccessibleMem | static_cast<int>(ModRefInfo::Mod),
  291. /// The only memory references in this function (if it has any) are
  292. /// references of memory that is otherwise inaccessible via LLVM IR.
  293. ///
  294. /// This property corresponds to the LLVM IR inaccessiblememonly attribute.
  295. FMRB_OnlyAccessesInaccessibleMem =
  296. FMRL_InaccessibleMem | static_cast<int>(ModRefInfo::ModRef),
  297. /// The function may perform non-volatile loads from objects pointed
  298. /// to by its pointer-typed arguments, with arbitrary offsets, and
  299. /// it may also perform loads of memory that is otherwise
  300. /// inaccessible via LLVM IR.
  301. ///
  302. /// This property corresponds to the LLVM IR
  303. /// inaccessiblemem_or_argmemonly attribute.
  304. FMRB_OnlyReadsInaccessibleOrArgMem = FMRL_InaccessibleMem |
  305. FMRL_ArgumentPointees |
  306. static_cast<int>(ModRefInfo::Ref),
  307. /// The function may perform non-volatile stores to objects pointed
  308. /// to by its pointer-typed arguments, with arbitrary offsets, and
  309. /// it may also perform stores of memory that is otherwise
  310. /// inaccessible via LLVM IR.
  311. ///
  312. /// This property corresponds to the LLVM IR
  313. /// inaccessiblemem_or_argmemonly attribute.
  314. FMRB_OnlyWritesInaccessibleOrArgMem = FMRL_InaccessibleMem |
  315. FMRL_ArgumentPointees |
  316. static_cast<int>(ModRefInfo::Mod),
  317. /// The function may perform non-volatile loads and stores of objects
  318. /// pointed to by its pointer-typed arguments, with arbitrary offsets, and
  319. /// it may also perform loads and stores of memory that is otherwise
  320. /// inaccessible via LLVM IR.
  321. ///
  322. /// This property corresponds to the LLVM IR
  323. /// inaccessiblemem_or_argmemonly attribute.
  324. FMRB_OnlyAccessesInaccessibleOrArgMem = FMRL_InaccessibleMem |
  325. FMRL_ArgumentPointees |
  326. static_cast<int>(ModRefInfo::ModRef),
  327. /// This function does not perform any non-local stores or volatile loads,
  328. /// but may read from any memory location.
  329. ///
  330. /// This property corresponds to the GCC 'pure' attribute.
  331. /// This property corresponds to the LLVM IR 'readonly' attribute.
  332. /// This property corresponds to the IntrReadMem LLVM intrinsic flag.
  333. FMRB_OnlyReadsMemory = FMRL_Anywhere | static_cast<int>(ModRefInfo::Ref),
  334. // This function does not read from memory anywhere, but may write to any
  335. // memory location.
  336. //
  337. // This property corresponds to the LLVM IR 'writeonly' attribute.
  338. // This property corresponds to the IntrWriteMem LLVM intrinsic flag.
  339. FMRB_OnlyWritesMemory = FMRL_Anywhere | static_cast<int>(ModRefInfo::Mod),
  340. /// This indicates that the function could not be classified into one of the
  341. /// behaviors above.
  342. FMRB_UnknownModRefBehavior =
  343. FMRL_Anywhere | static_cast<int>(ModRefInfo::ModRef)
  344. };
  345. // Wrapper method strips bits significant only in FunctionModRefBehavior,
  346. // to obtain a valid ModRefInfo. The benefit of using the wrapper is that if
  347. // ModRefInfo enum changes, the wrapper can be updated to & with the new enum
  348. // entry with all bits set to 1.
  349. LLVM_NODISCARD inline ModRefInfo
  350. createModRefInfo(const FunctionModRefBehavior FMRB) {
  351. return ModRefInfo(FMRB & static_cast<int>(ModRefInfo::ModRef));
  352. }
  353. /// Virtual base class for providers of capture information.
  354. struct CaptureInfo {
  355. virtual ~CaptureInfo() = 0;
  356. virtual bool isNotCapturedBeforeOrAt(const Value *Object,
  357. const Instruction *I) = 0;
  358. };
  359. /// Context-free CaptureInfo provider, which computes and caches whether an
  360. /// object is captured in the function at all, but does not distinguish whether
  361. /// it was captured before or after the context instruction.
  362. class SimpleCaptureInfo final : public CaptureInfo {
  363. SmallDenseMap<const Value *, bool, 8> IsCapturedCache;
  364. public:
  365. bool isNotCapturedBeforeOrAt(const Value *Object,
  366. const Instruction *I) override;
  367. };
  368. /// Context-sensitive CaptureInfo provider, which computes and caches the
  369. /// earliest common dominator closure of all captures. It provides a good
  370. /// approximation to a precise "captures before" analysis.
  371. class EarliestEscapeInfo final : public CaptureInfo {
  372. DominatorTree &DT;
  373. const LoopInfo &LI;
  374. /// Map from identified local object to an instruction before which it does
  375. /// not escape, or nullptr if it never escapes. The "earliest" instruction
  376. /// may be a conservative approximation, e.g. the first instruction in the
  377. /// function is always a legal choice.
  378. DenseMap<const Value *, Instruction *> EarliestEscapes;
  379. /// Reverse map from instruction to the objects it is the earliest escape for.
  380. /// This is used for cache invalidation purposes.
  381. DenseMap<Instruction *, TinyPtrVector<const Value *>> Inst2Obj;
  382. public:
  383. EarliestEscapeInfo(DominatorTree &DT, const LoopInfo &LI) : DT(DT), LI(LI) {}
  384. bool isNotCapturedBeforeOrAt(const Value *Object,
  385. const Instruction *I) override;
  386. void removeInstruction(Instruction *I);
  387. };
  388. /// Reduced version of MemoryLocation that only stores a pointer and size.
  389. /// Used for caching AATags independent BasicAA results.
  390. struct AACacheLoc {
  391. const Value *Ptr;
  392. LocationSize Size;
  393. };
  394. template <> struct DenseMapInfo<AACacheLoc> {
  395. static inline AACacheLoc getEmptyKey() {
  396. return {DenseMapInfo<const Value *>::getEmptyKey(),
  397. DenseMapInfo<LocationSize>::getEmptyKey()};
  398. }
  399. static inline AACacheLoc getTombstoneKey() {
  400. return {DenseMapInfo<const Value *>::getTombstoneKey(),
  401. DenseMapInfo<LocationSize>::getTombstoneKey()};
  402. }
  403. static unsigned getHashValue(const AACacheLoc &Val) {
  404. return DenseMapInfo<const Value *>::getHashValue(Val.Ptr) ^
  405. DenseMapInfo<LocationSize>::getHashValue(Val.Size);
  406. }
  407. static bool isEqual(const AACacheLoc &LHS, const AACacheLoc &RHS) {
  408. return LHS.Ptr == RHS.Ptr && LHS.Size == RHS.Size;
  409. }
  410. };
  411. /// This class stores info we want to provide to or retain within an alias
  412. /// query. By default, the root query is stateless and starts with a freshly
  413. /// constructed info object. Specific alias analyses can use this query info to
  414. /// store per-query state that is important for recursive or nested queries to
  415. /// avoid recomputing. To enable preserving this state across multiple queries
  416. /// where safe (due to the IR not changing), use a `BatchAAResults` wrapper.
  417. /// The information stored in an `AAQueryInfo` is currently limitted to the
  418. /// caches used by BasicAA, but can further be extended to fit other AA needs.
  419. class AAQueryInfo {
  420. public:
  421. using LocPair = std::pair<AACacheLoc, AACacheLoc>;
  422. struct CacheEntry {
  423. AliasResult Result;
  424. /// Number of times a NoAlias assumption has been used.
  425. /// 0 for assumptions that have not been used, -1 for definitive results.
  426. int NumAssumptionUses;
  427. /// Whether this is a definitive (non-assumption) result.
  428. bool isDefinitive() const { return NumAssumptionUses < 0; }
  429. };
  430. using AliasCacheT = SmallDenseMap<LocPair, CacheEntry, 8>;
  431. AliasCacheT AliasCache;
  432. CaptureInfo *CI;
  433. /// Query depth used to distinguish recursive queries.
  434. unsigned Depth = 0;
  435. /// How many active NoAlias assumption uses there are.
  436. int NumAssumptionUses = 0;
  437. /// Location pairs for which an assumption based result is currently stored.
  438. /// Used to remove all potentially incorrect results from the cache if an
  439. /// assumption is disproven.
  440. SmallVector<AAQueryInfo::LocPair, 4> AssumptionBasedResults;
  441. AAQueryInfo(CaptureInfo *CI) : CI(CI) {}
  442. /// Create a new AAQueryInfo based on this one, but with the cache cleared.
  443. /// This is used for recursive queries across phis, where cache results may
  444. /// not be valid.
  445. AAQueryInfo withEmptyCache() {
  446. AAQueryInfo NewAAQI(CI);
  447. NewAAQI.Depth = Depth;
  448. return NewAAQI;
  449. }
  450. };
  451. /// AAQueryInfo that uses SimpleCaptureInfo.
  452. class SimpleAAQueryInfo : public AAQueryInfo {
  453. SimpleCaptureInfo CI;
  454. public:
  455. SimpleAAQueryInfo() : AAQueryInfo(&CI) {}
  456. };
  457. class BatchAAResults;
  458. class AAResults {
  459. public:
  460. // Make these results default constructable and movable. We have to spell
  461. // these out because MSVC won't synthesize them.
  462. AAResults(const TargetLibraryInfo &TLI) : TLI(TLI) {}
  463. AAResults(AAResults &&Arg);
  464. ~AAResults();
  465. /// Register a specific AA result.
  466. template <typename AAResultT> void addAAResult(AAResultT &AAResult) {
  467. // FIXME: We should use a much lighter weight system than the usual
  468. // polymorphic pattern because we don't own AAResult. It should
  469. // ideally involve two pointers and no separate allocation.
  470. AAs.emplace_back(new Model<AAResultT>(AAResult, *this));
  471. }
  472. /// Register a function analysis ID that the results aggregation depends on.
  473. ///
  474. /// This is used in the new pass manager to implement the invalidation logic
  475. /// where we must invalidate the results aggregation if any of our component
  476. /// analyses become invalid.
  477. void addAADependencyID(AnalysisKey *ID) { AADeps.push_back(ID); }
  478. /// Handle invalidation events in the new pass manager.
  479. ///
  480. /// The aggregation is invalidated if any of the underlying analyses is
  481. /// invalidated.
  482. bool invalidate(Function &F, const PreservedAnalyses &PA,
  483. FunctionAnalysisManager::Invalidator &Inv);
  484. //===--------------------------------------------------------------------===//
  485. /// \name Alias Queries
  486. /// @{
  487. /// The main low level interface to the alias analysis implementation.
  488. /// Returns an AliasResult indicating whether the two pointers are aliased to
  489. /// each other. This is the interface that must be implemented by specific
  490. /// alias analysis implementations.
  491. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
  492. /// A convenience wrapper around the primary \c alias interface.
  493. AliasResult alias(const Value *V1, LocationSize V1Size, const Value *V2,
  494. LocationSize V2Size) {
  495. return alias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size));
  496. }
  497. /// A convenience wrapper around the primary \c alias interface.
  498. AliasResult alias(const Value *V1, const Value *V2) {
  499. return alias(MemoryLocation::getBeforeOrAfter(V1),
  500. MemoryLocation::getBeforeOrAfter(V2));
  501. }
  502. /// A trivial helper function to check to see if the specified pointers are
  503. /// no-alias.
  504. bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
  505. return alias(LocA, LocB) == AliasResult::NoAlias;
  506. }
  507. /// A convenience wrapper around the \c isNoAlias helper interface.
  508. bool isNoAlias(const Value *V1, LocationSize V1Size, const Value *V2,
  509. LocationSize V2Size) {
  510. return isNoAlias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size));
  511. }
  512. /// A convenience wrapper around the \c isNoAlias helper interface.
  513. bool isNoAlias(const Value *V1, const Value *V2) {
  514. return isNoAlias(MemoryLocation::getBeforeOrAfter(V1),
  515. MemoryLocation::getBeforeOrAfter(V2));
  516. }
  517. /// A trivial helper function to check to see if the specified pointers are
  518. /// must-alias.
  519. bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
  520. return alias(LocA, LocB) == AliasResult::MustAlias;
  521. }
  522. /// A convenience wrapper around the \c isMustAlias helper interface.
  523. bool isMustAlias(const Value *V1, const Value *V2) {
  524. return alias(V1, LocationSize::precise(1), V2, LocationSize::precise(1)) ==
  525. AliasResult::MustAlias;
  526. }
  527. /// Checks whether the given location points to constant memory, or if
  528. /// \p OrLocal is true whether it points to a local alloca.
  529. bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false);
  530. /// A convenience wrapper around the primary \c pointsToConstantMemory
  531. /// interface.
  532. bool pointsToConstantMemory(const Value *P, bool OrLocal = false) {
  533. return pointsToConstantMemory(MemoryLocation::getBeforeOrAfter(P), OrLocal);
  534. }
  535. /// @}
  536. //===--------------------------------------------------------------------===//
  537. /// \name Simple mod/ref information
  538. /// @{
  539. /// Get the ModRef info associated with a pointer argument of a call. The
  540. /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
  541. /// that these bits do not necessarily account for the overall behavior of
  542. /// the function, but rather only provide additional per-argument
  543. /// information. This never sets ModRefInfo::Must.
  544. ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx);
  545. /// Return the behavior of the given call site.
  546. FunctionModRefBehavior getModRefBehavior(const CallBase *Call);
  547. /// Return the behavior when calling the given function.
  548. FunctionModRefBehavior getModRefBehavior(const Function *F);
  549. /// Checks if the specified call is known to never read or write memory.
  550. ///
  551. /// Note that if the call only reads from known-constant memory, it is also
  552. /// legal to return true. Also, calls that unwind the stack are legal for
  553. /// this predicate.
  554. ///
  555. /// Many optimizations (such as CSE and LICM) can be performed on such calls
  556. /// without worrying about aliasing properties, and many calls have this
  557. /// property (e.g. calls to 'sin' and 'cos').
  558. ///
  559. /// This property corresponds to the GCC 'const' attribute.
  560. bool doesNotAccessMemory(const CallBase *Call) {
  561. return getModRefBehavior(Call) == FMRB_DoesNotAccessMemory;
  562. }
  563. /// Checks if the specified function is known to never read or write memory.
  564. ///
  565. /// Note that if the function only reads from known-constant memory, it is
  566. /// also legal to return true. Also, function that unwind the stack are legal
  567. /// for this predicate.
  568. ///
  569. /// Many optimizations (such as CSE and LICM) can be performed on such calls
  570. /// to such functions without worrying about aliasing properties, and many
  571. /// functions have this property (e.g. 'sin' and 'cos').
  572. ///
  573. /// This property corresponds to the GCC 'const' attribute.
  574. bool doesNotAccessMemory(const Function *F) {
  575. return getModRefBehavior(F) == FMRB_DoesNotAccessMemory;
  576. }
  577. /// Checks if the specified call is known to only read from non-volatile
  578. /// memory (or not access memory at all).
  579. ///
  580. /// Calls that unwind the stack are legal for this predicate.
  581. ///
  582. /// This property allows many common optimizations to be performed in the
  583. /// absence of interfering store instructions, such as CSE of strlen calls.
  584. ///
  585. /// This property corresponds to the GCC 'pure' attribute.
  586. bool onlyReadsMemory(const CallBase *Call) {
  587. return onlyReadsMemory(getModRefBehavior(Call));
  588. }
  589. /// Checks if the specified function is known to only read from non-volatile
  590. /// memory (or not access memory at all).
  591. ///
  592. /// Functions that unwind the stack are legal for this predicate.
  593. ///
  594. /// This property allows many common optimizations to be performed in the
  595. /// absence of interfering store instructions, such as CSE of strlen calls.
  596. ///
  597. /// This property corresponds to the GCC 'pure' attribute.
  598. bool onlyReadsMemory(const Function *F) {
  599. return onlyReadsMemory(getModRefBehavior(F));
  600. }
  601. /// Checks if functions with the specified behavior are known to only read
  602. /// from non-volatile memory (or not access memory at all).
  603. static bool onlyReadsMemory(FunctionModRefBehavior MRB) {
  604. return !isModSet(createModRefInfo(MRB));
  605. }
  606. /// Checks if functions with the specified behavior are known to only write
  607. /// memory (or not access memory at all).
  608. static bool onlyWritesMemory(FunctionModRefBehavior MRB) {
  609. return !isRefSet(createModRefInfo(MRB));
  610. }
  611. /// Checks if functions with the specified behavior are known to read and
  612. /// write at most from objects pointed to by their pointer-typed arguments
  613. /// (with arbitrary offsets).
  614. static bool onlyAccessesArgPointees(FunctionModRefBehavior MRB) {
  615. return !((unsigned)MRB & FMRL_Anywhere & ~FMRL_ArgumentPointees);
  616. }
  617. /// Checks if functions with the specified behavior are known to potentially
  618. /// read or write from objects pointed to be their pointer-typed arguments
  619. /// (with arbitrary offsets).
  620. static bool doesAccessArgPointees(FunctionModRefBehavior MRB) {
  621. return isModOrRefSet(createModRefInfo(MRB)) &&
  622. ((unsigned)MRB & FMRL_ArgumentPointees);
  623. }
  624. /// Checks if functions with the specified behavior are known to read and
  625. /// write at most from memory that is inaccessible from LLVM IR.
  626. static bool onlyAccessesInaccessibleMem(FunctionModRefBehavior MRB) {
  627. return !((unsigned)MRB & FMRL_Anywhere & ~FMRL_InaccessibleMem);
  628. }
  629. /// Checks if functions with the specified behavior are known to potentially
  630. /// read or write from memory that is inaccessible from LLVM IR.
  631. static bool doesAccessInaccessibleMem(FunctionModRefBehavior MRB) {
  632. return isModOrRefSet(createModRefInfo(MRB)) &&
  633. ((unsigned)MRB & FMRL_InaccessibleMem);
  634. }
  635. /// Checks if functions with the specified behavior are known to read and
  636. /// write at most from memory that is inaccessible from LLVM IR or objects
  637. /// pointed to by their pointer-typed arguments (with arbitrary offsets).
  638. static bool onlyAccessesInaccessibleOrArgMem(FunctionModRefBehavior MRB) {
  639. return !((unsigned)MRB & FMRL_Anywhere &
  640. ~(FMRL_InaccessibleMem | FMRL_ArgumentPointees));
  641. }
  642. /// getModRefInfo (for call sites) - Return information about whether
  643. /// a particular call site modifies or reads the specified memory location.
  644. ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc);
  645. /// getModRefInfo (for call sites) - A convenience wrapper.
  646. ModRefInfo getModRefInfo(const CallBase *Call, const Value *P,
  647. LocationSize Size) {
  648. return getModRefInfo(Call, MemoryLocation(P, Size));
  649. }
  650. /// getModRefInfo (for loads) - Return information about whether
  651. /// a particular load modifies or reads the specified memory location.
  652. ModRefInfo getModRefInfo(const LoadInst *L, const MemoryLocation &Loc);
  653. /// getModRefInfo (for loads) - A convenience wrapper.
  654. ModRefInfo getModRefInfo(const LoadInst *L, const Value *P,
  655. LocationSize Size) {
  656. return getModRefInfo(L, MemoryLocation(P, Size));
  657. }
  658. /// getModRefInfo (for stores) - Return information about whether
  659. /// a particular store modifies or reads the specified memory location.
  660. ModRefInfo getModRefInfo(const StoreInst *S, const MemoryLocation &Loc);
  661. /// getModRefInfo (for stores) - A convenience wrapper.
  662. ModRefInfo getModRefInfo(const StoreInst *S, const Value *P,
  663. LocationSize Size) {
  664. return getModRefInfo(S, MemoryLocation(P, Size));
  665. }
  666. /// getModRefInfo (for fences) - Return information about whether
  667. /// a particular store modifies or reads the specified memory location.
  668. ModRefInfo getModRefInfo(const FenceInst *S, const MemoryLocation &Loc);
  669. /// getModRefInfo (for fences) - A convenience wrapper.
  670. ModRefInfo getModRefInfo(const FenceInst *S, const Value *P,
  671. LocationSize Size) {
  672. return getModRefInfo(S, MemoryLocation(P, Size));
  673. }
  674. /// getModRefInfo (for cmpxchges) - Return information about whether
  675. /// a particular cmpxchg modifies or reads the specified memory location.
  676. ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX,
  677. const MemoryLocation &Loc);
  678. /// getModRefInfo (for cmpxchges) - A convenience wrapper.
  679. ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX, const Value *P,
  680. LocationSize Size) {
  681. return getModRefInfo(CX, MemoryLocation(P, Size));
  682. }
  683. /// getModRefInfo (for atomicrmws) - Return information about whether
  684. /// a particular atomicrmw modifies or reads the specified memory location.
  685. ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const MemoryLocation &Loc);
  686. /// getModRefInfo (for atomicrmws) - A convenience wrapper.
  687. ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const Value *P,
  688. LocationSize Size) {
  689. return getModRefInfo(RMW, MemoryLocation(P, Size));
  690. }
  691. /// getModRefInfo (for va_args) - Return information about whether
  692. /// a particular va_arg modifies or reads the specified memory location.
  693. ModRefInfo getModRefInfo(const VAArgInst *I, const MemoryLocation &Loc);
  694. /// getModRefInfo (for va_args) - A convenience wrapper.
  695. ModRefInfo getModRefInfo(const VAArgInst *I, const Value *P,
  696. LocationSize Size) {
  697. return getModRefInfo(I, MemoryLocation(P, Size));
  698. }
  699. /// getModRefInfo (for catchpads) - Return information about whether
  700. /// a particular catchpad modifies or reads the specified memory location.
  701. ModRefInfo getModRefInfo(const CatchPadInst *I, const MemoryLocation &Loc);
  702. /// getModRefInfo (for catchpads) - A convenience wrapper.
  703. ModRefInfo getModRefInfo(const CatchPadInst *I, const Value *P,
  704. LocationSize Size) {
  705. return getModRefInfo(I, MemoryLocation(P, Size));
  706. }
  707. /// getModRefInfo (for catchrets) - Return information about whether
  708. /// a particular catchret modifies or reads the specified memory location.
  709. ModRefInfo getModRefInfo(const CatchReturnInst *I, const MemoryLocation &Loc);
  710. /// getModRefInfo (for catchrets) - A convenience wrapper.
  711. ModRefInfo getModRefInfo(const CatchReturnInst *I, const Value *P,
  712. LocationSize Size) {
  713. return getModRefInfo(I, MemoryLocation(P, Size));
  714. }
  715. /// Check whether or not an instruction may read or write the optionally
  716. /// specified memory location.
  717. ///
  718. ///
  719. /// An instruction that doesn't read or write memory may be trivially LICM'd
  720. /// for example.
  721. ///
  722. /// For function calls, this delegates to the alias-analysis specific
  723. /// call-site mod-ref behavior queries. Otherwise it delegates to the specific
  724. /// helpers above.
  725. ModRefInfo getModRefInfo(const Instruction *I,
  726. const Optional<MemoryLocation> &OptLoc) {
  727. SimpleAAQueryInfo AAQIP;
  728. return getModRefInfo(I, OptLoc, AAQIP);
  729. }
  730. /// A convenience wrapper for constructing the memory location.
  731. ModRefInfo getModRefInfo(const Instruction *I, const Value *P,
  732. LocationSize Size) {
  733. return getModRefInfo(I, MemoryLocation(P, Size));
  734. }
  735. /// Return information about whether a call and an instruction may refer to
  736. /// the same memory locations.
  737. ModRefInfo getModRefInfo(Instruction *I, const CallBase *Call);
  738. /// Return information about whether two call sites may refer to the same set
  739. /// of memory locations. See the AA documentation for details:
  740. /// http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
  741. ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2);
  742. /// Return information about whether a particular call site modifies
  743. /// or reads the specified memory location \p MemLoc before instruction \p I
  744. /// in a BasicBlock.
  745. /// Early exits in callCapturesBefore may lead to ModRefInfo::Must not being
  746. /// set.
  747. ModRefInfo callCapturesBefore(const Instruction *I,
  748. const MemoryLocation &MemLoc,
  749. DominatorTree *DT) {
  750. SimpleAAQueryInfo AAQIP;
  751. return callCapturesBefore(I, MemLoc, DT, AAQIP);
  752. }
  753. /// A convenience wrapper to synthesize a memory location.
  754. ModRefInfo callCapturesBefore(const Instruction *I, const Value *P,
  755. LocationSize Size, DominatorTree *DT) {
  756. return callCapturesBefore(I, MemoryLocation(P, Size), DT);
  757. }
  758. /// @}
  759. //===--------------------------------------------------------------------===//
  760. /// \name Higher level methods for querying mod/ref information.
  761. /// @{
  762. /// Check if it is possible for execution of the specified basic block to
  763. /// modify the location Loc.
  764. bool canBasicBlockModify(const BasicBlock &BB, const MemoryLocation &Loc);
  765. /// A convenience wrapper synthesizing a memory location.
  766. bool canBasicBlockModify(const BasicBlock &BB, const Value *P,
  767. LocationSize Size) {
  768. return canBasicBlockModify(BB, MemoryLocation(P, Size));
  769. }
  770. /// Check if it is possible for the execution of the specified instructions
  771. /// to mod\ref (according to the mode) the location Loc.
  772. ///
  773. /// The instructions to consider are all of the instructions in the range of
  774. /// [I1,I2] INCLUSIVE. I1 and I2 must be in the same basic block.
  775. bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2,
  776. const MemoryLocation &Loc,
  777. const ModRefInfo Mode);
  778. /// A convenience wrapper synthesizing a memory location.
  779. bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2,
  780. const Value *Ptr, LocationSize Size,
  781. const ModRefInfo Mode) {
  782. return canInstructionRangeModRef(I1, I2, MemoryLocation(Ptr, Size), Mode);
  783. }
  784. private:
  785. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
  786. AAQueryInfo &AAQI);
  787. bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
  788. bool OrLocal = false);
  789. ModRefInfo getModRefInfo(Instruction *I, const CallBase *Call2,
  790. AAQueryInfo &AAQIP);
  791. ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
  792. AAQueryInfo &AAQI);
  793. ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
  794. AAQueryInfo &AAQI);
  795. ModRefInfo getModRefInfo(const VAArgInst *V, const MemoryLocation &Loc,
  796. AAQueryInfo &AAQI);
  797. ModRefInfo getModRefInfo(const LoadInst *L, const MemoryLocation &Loc,
  798. AAQueryInfo &AAQI);
  799. ModRefInfo getModRefInfo(const StoreInst *S, const MemoryLocation &Loc,
  800. AAQueryInfo &AAQI);
  801. ModRefInfo getModRefInfo(const FenceInst *S, const MemoryLocation &Loc,
  802. AAQueryInfo &AAQI);
  803. ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX,
  804. const MemoryLocation &Loc, AAQueryInfo &AAQI);
  805. ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const MemoryLocation &Loc,
  806. AAQueryInfo &AAQI);
  807. ModRefInfo getModRefInfo(const CatchPadInst *I, const MemoryLocation &Loc,
  808. AAQueryInfo &AAQI);
  809. ModRefInfo getModRefInfo(const CatchReturnInst *I, const MemoryLocation &Loc,
  810. AAQueryInfo &AAQI);
  811. ModRefInfo getModRefInfo(const Instruction *I,
  812. const Optional<MemoryLocation> &OptLoc,
  813. AAQueryInfo &AAQIP);
  814. ModRefInfo callCapturesBefore(const Instruction *I,
  815. const MemoryLocation &MemLoc, DominatorTree *DT,
  816. AAQueryInfo &AAQIP);
  817. class Concept;
  818. template <typename T> class Model;
  819. template <typename T> friend class AAResultBase;
  820. const TargetLibraryInfo &TLI;
  821. std::vector<std::unique_ptr<Concept>> AAs;
  822. std::vector<AnalysisKey *> AADeps;
  823. friend class BatchAAResults;
  824. };
  825. /// This class is a wrapper over an AAResults, and it is intended to be used
  826. /// only when there are no IR changes inbetween queries. BatchAAResults is
  827. /// reusing the same `AAQueryInfo` to preserve the state across queries,
  828. /// esentially making AA work in "batch mode". The internal state cannot be
  829. /// cleared, so to go "out-of-batch-mode", the user must either use AAResults,
  830. /// or create a new BatchAAResults.
  831. class BatchAAResults {
  832. AAResults &AA;
  833. AAQueryInfo AAQI;
  834. SimpleCaptureInfo SimpleCI;
  835. public:
  836. BatchAAResults(AAResults &AAR) : AA(AAR), AAQI(&SimpleCI) {}
  837. BatchAAResults(AAResults &AAR, CaptureInfo *CI) : AA(AAR), AAQI(CI) {}
  838. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
  839. return AA.alias(LocA, LocB, AAQI);
  840. }
  841. bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false) {
  842. return AA.pointsToConstantMemory(Loc, AAQI, OrLocal);
  843. }
  844. ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc) {
  845. return AA.getModRefInfo(Call, Loc, AAQI);
  846. }
  847. ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2) {
  848. return AA.getModRefInfo(Call1, Call2, AAQI);
  849. }
  850. ModRefInfo getModRefInfo(const Instruction *I,
  851. const Optional<MemoryLocation> &OptLoc) {
  852. return AA.getModRefInfo(I, OptLoc, AAQI);
  853. }
  854. ModRefInfo getModRefInfo(Instruction *I, const CallBase *Call2) {
  855. return AA.getModRefInfo(I, Call2, AAQI);
  856. }
  857. ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
  858. return AA.getArgModRefInfo(Call, ArgIdx);
  859. }
  860. FunctionModRefBehavior getModRefBehavior(const CallBase *Call) {
  861. return AA.getModRefBehavior(Call);
  862. }
  863. bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
  864. return alias(LocA, LocB) == AliasResult::MustAlias;
  865. }
  866. bool isMustAlias(const Value *V1, const Value *V2) {
  867. return alias(MemoryLocation(V1, LocationSize::precise(1)),
  868. MemoryLocation(V2, LocationSize::precise(1))) ==
  869. AliasResult::MustAlias;
  870. }
  871. ModRefInfo callCapturesBefore(const Instruction *I,
  872. const MemoryLocation &MemLoc,
  873. DominatorTree *DT) {
  874. return AA.callCapturesBefore(I, MemLoc, DT, AAQI);
  875. }
  876. };
  877. /// Temporary typedef for legacy code that uses a generic \c AliasAnalysis
  878. /// pointer or reference.
  879. using AliasAnalysis = AAResults;
  880. /// A private abstract base class describing the concept of an individual alias
  881. /// analysis implementation.
  882. ///
  883. /// This interface is implemented by any \c Model instantiation. It is also the
  884. /// interface which a type used to instantiate the model must provide.
  885. ///
  886. /// All of these methods model methods by the same name in the \c
  887. /// AAResults class. Only differences and specifics to how the
  888. /// implementations are called are documented here.
  889. class AAResults::Concept {
  890. public:
  891. virtual ~Concept() = 0;
  892. /// An update API used internally by the AAResults to provide
  893. /// a handle back to the top level aggregation.
  894. virtual void setAAResults(AAResults *NewAAR) = 0;
  895. //===--------------------------------------------------------------------===//
  896. /// \name Alias Queries
  897. /// @{
  898. /// The main low level interface to the alias analysis implementation.
  899. /// Returns an AliasResult indicating whether the two pointers are aliased to
  900. /// each other. This is the interface that must be implemented by specific
  901. /// alias analysis implementations.
  902. virtual AliasResult alias(const MemoryLocation &LocA,
  903. const MemoryLocation &LocB, AAQueryInfo &AAQI) = 0;
  904. /// Checks whether the given location points to constant memory, or if
  905. /// \p OrLocal is true whether it points to a local alloca.
  906. virtual bool pointsToConstantMemory(const MemoryLocation &Loc,
  907. AAQueryInfo &AAQI, bool OrLocal) = 0;
  908. /// @}
  909. //===--------------------------------------------------------------------===//
  910. /// \name Simple mod/ref information
  911. /// @{
  912. /// Get the ModRef info associated with a pointer argument of a callsite. The
  913. /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
  914. /// that these bits do not necessarily account for the overall behavior of
  915. /// the function, but rather only provide additional per-argument
  916. /// information.
  917. virtual ModRefInfo getArgModRefInfo(const CallBase *Call,
  918. unsigned ArgIdx) = 0;
  919. /// Return the behavior of the given call site.
  920. virtual FunctionModRefBehavior getModRefBehavior(const CallBase *Call) = 0;
  921. /// Return the behavior when calling the given function.
  922. virtual FunctionModRefBehavior getModRefBehavior(const Function *F) = 0;
  923. /// getModRefInfo (for call sites) - Return information about whether
  924. /// a particular call site modifies or reads the specified memory location.
  925. virtual ModRefInfo getModRefInfo(const CallBase *Call,
  926. const MemoryLocation &Loc,
  927. AAQueryInfo &AAQI) = 0;
  928. /// Return information about whether two call sites may refer to the same set
  929. /// of memory locations. See the AA documentation for details:
  930. /// http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
  931. virtual ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
  932. AAQueryInfo &AAQI) = 0;
  933. /// @}
  934. };
  935. /// A private class template which derives from \c Concept and wraps some other
  936. /// type.
  937. ///
  938. /// This models the concept by directly forwarding each interface point to the
  939. /// wrapped type which must implement a compatible interface. This provides
  940. /// a type erased binding.
  941. template <typename AAResultT> class AAResults::Model final : public Concept {
  942. AAResultT &Result;
  943. public:
  944. explicit Model(AAResultT &Result, AAResults &AAR) : Result(Result) {
  945. Result.setAAResults(&AAR);
  946. }
  947. ~Model() override = default;
  948. void setAAResults(AAResults *NewAAR) override { Result.setAAResults(NewAAR); }
  949. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
  950. AAQueryInfo &AAQI) override {
  951. return Result.alias(LocA, LocB, AAQI);
  952. }
  953. bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
  954. bool OrLocal) override {
  955. return Result.pointsToConstantMemory(Loc, AAQI, OrLocal);
  956. }
  957. ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) override {
  958. return Result.getArgModRefInfo(Call, ArgIdx);
  959. }
  960. FunctionModRefBehavior getModRefBehavior(const CallBase *Call) override {
  961. return Result.getModRefBehavior(Call);
  962. }
  963. FunctionModRefBehavior getModRefBehavior(const Function *F) override {
  964. return Result.getModRefBehavior(F);
  965. }
  966. ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
  967. AAQueryInfo &AAQI) override {
  968. return Result.getModRefInfo(Call, Loc, AAQI);
  969. }
  970. ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
  971. AAQueryInfo &AAQI) override {
  972. return Result.getModRefInfo(Call1, Call2, AAQI);
  973. }
  974. };
  975. /// A CRTP-driven "mixin" base class to help implement the function alias
  976. /// analysis results concept.
  977. ///
  978. /// Because of the nature of many alias analysis implementations, they often
  979. /// only implement a subset of the interface. This base class will attempt to
  980. /// implement the remaining portions of the interface in terms of simpler forms
  981. /// of the interface where possible, and otherwise provide conservatively
  982. /// correct fallback implementations.
  983. ///
  984. /// Implementors of an alias analysis should derive from this CRTP, and then
  985. /// override specific methods that they wish to customize. There is no need to
  986. /// use virtual anywhere, the CRTP base class does static dispatch to the
  987. /// derived type passed into it.
  988. template <typename DerivedT> class AAResultBase {
  989. // Expose some parts of the interface only to the AAResults::Model
  990. // for wrapping. Specifically, this allows the model to call our
  991. // setAAResults method without exposing it as a fully public API.
  992. friend class AAResults::Model<DerivedT>;
  993. /// A pointer to the AAResults object that this AAResult is
  994. /// aggregated within. May be null if not aggregated.
  995. AAResults *AAR = nullptr;
  996. /// Helper to dispatch calls back through the derived type.
  997. DerivedT &derived() { return static_cast<DerivedT &>(*this); }
  998. /// A setter for the AAResults pointer, which is used to satisfy the
  999. /// AAResults::Model contract.
  1000. void setAAResults(AAResults *NewAAR) { AAR = NewAAR; }
  1001. protected:
  1002. /// This proxy class models a common pattern where we delegate to either the
  1003. /// top-level \c AAResults aggregation if one is registered, or to the
  1004. /// current result if none are registered.
  1005. class AAResultsProxy {
  1006. AAResults *AAR;
  1007. DerivedT &CurrentResult;
  1008. public:
  1009. AAResultsProxy(AAResults *AAR, DerivedT &CurrentResult)
  1010. : AAR(AAR), CurrentResult(CurrentResult) {}
  1011. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
  1012. AAQueryInfo &AAQI) {
  1013. return AAR ? AAR->alias(LocA, LocB, AAQI)
  1014. : CurrentResult.alias(LocA, LocB, AAQI);
  1015. }
  1016. bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
  1017. bool OrLocal) {
  1018. return AAR ? AAR->pointsToConstantMemory(Loc, AAQI, OrLocal)
  1019. : CurrentResult.pointsToConstantMemory(Loc, AAQI, OrLocal);
  1020. }
  1021. ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
  1022. return AAR ? AAR->getArgModRefInfo(Call, ArgIdx)
  1023. : CurrentResult.getArgModRefInfo(Call, ArgIdx);
  1024. }
  1025. FunctionModRefBehavior getModRefBehavior(const CallBase *Call) {
  1026. return AAR ? AAR->getModRefBehavior(Call)
  1027. : CurrentResult.getModRefBehavior(Call);
  1028. }
  1029. FunctionModRefBehavior getModRefBehavior(const Function *F) {
  1030. return AAR ? AAR->getModRefBehavior(F) : CurrentResult.getModRefBehavior(F);
  1031. }
  1032. ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
  1033. AAQueryInfo &AAQI) {
  1034. return AAR ? AAR->getModRefInfo(Call, Loc, AAQI)
  1035. : CurrentResult.getModRefInfo(Call, Loc, AAQI);
  1036. }
  1037. ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
  1038. AAQueryInfo &AAQI) {
  1039. return AAR ? AAR->getModRefInfo(Call1, Call2, AAQI)
  1040. : CurrentResult.getModRefInfo(Call1, Call2, AAQI);
  1041. }
  1042. };
  1043. explicit AAResultBase() = default;
  1044. // Provide all the copy and move constructors so that derived types aren't
  1045. // constrained.
  1046. AAResultBase(const AAResultBase &Arg) {}
  1047. AAResultBase(AAResultBase &&Arg) {}
  1048. /// Get a proxy for the best AA result set to query at this time.
  1049. ///
  1050. /// When this result is part of a larger aggregation, this will proxy to that
  1051. /// aggregation. When this result is used in isolation, it will just delegate
  1052. /// back to the derived class's implementation.
  1053. ///
  1054. /// Note that callers of this need to take considerable care to not cause
  1055. /// performance problems when they use this routine, in the case of a large
  1056. /// number of alias analyses being aggregated, it can be expensive to walk
  1057. /// back across the chain.
  1058. AAResultsProxy getBestAAResults() { return AAResultsProxy(AAR, derived()); }
  1059. public:
  1060. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
  1061. AAQueryInfo &AAQI) {
  1062. return AliasResult::MayAlias;
  1063. }
  1064. bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
  1065. bool OrLocal) {
  1066. return false;
  1067. }
  1068. ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
  1069. return ModRefInfo::ModRef;
  1070. }
  1071. FunctionModRefBehavior getModRefBehavior(const CallBase *Call) {
  1072. return FMRB_UnknownModRefBehavior;
  1073. }
  1074. FunctionModRefBehavior getModRefBehavior(const Function *F) {
  1075. return FMRB_UnknownModRefBehavior;
  1076. }
  1077. ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
  1078. AAQueryInfo &AAQI) {
  1079. return ModRefInfo::ModRef;
  1080. }
  1081. ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
  1082. AAQueryInfo &AAQI) {
  1083. return ModRefInfo::ModRef;
  1084. }
  1085. };
  1086. /// Return true if this pointer is returned by a noalias function.
  1087. bool isNoAliasCall(const Value *V);
  1088. /// Return true if this pointer refers to a distinct and identifiable object.
  1089. /// This returns true for:
  1090. /// Global Variables and Functions (but not Global Aliases)
  1091. /// Allocas
  1092. /// ByVal and NoAlias Arguments
  1093. /// NoAlias returns (e.g. calls to malloc)
  1094. ///
  1095. bool isIdentifiedObject(const Value *V);
  1096. /// Return true if V is umabigously identified at the function-level.
  1097. /// Different IdentifiedFunctionLocals can't alias.
  1098. /// Further, an IdentifiedFunctionLocal can not alias with any function
  1099. /// arguments other than itself, which is not necessarily true for
  1100. /// IdentifiedObjects.
  1101. bool isIdentifiedFunctionLocal(const Value *V);
  1102. /// Return true if Object memory is not visible after an unwind, in the sense
  1103. /// that program semantics cannot depend on Object containing any particular
  1104. /// value on unwind. If the RequiresNoCaptureBeforeUnwind out parameter is set
  1105. /// to true, then the memory is only not visible if the object has not been
  1106. /// captured prior to the unwind. Otherwise it is not visible even if captured.
  1107. bool isNotVisibleOnUnwind(const Value *Object,
  1108. bool &RequiresNoCaptureBeforeUnwind);
  1109. /// A manager for alias analyses.
  1110. ///
  1111. /// This class can have analyses registered with it and when run, it will run
  1112. /// all of them and aggregate their results into single AA results interface
  1113. /// that dispatches across all of the alias analysis results available.
  1114. ///
  1115. /// Note that the order in which analyses are registered is very significant.
  1116. /// That is the order in which the results will be aggregated and queried.
  1117. ///
  1118. /// This manager effectively wraps the AnalysisManager for registering alias
  1119. /// analyses. When you register your alias analysis with this manager, it will
  1120. /// ensure the analysis itself is registered with its AnalysisManager.
  1121. ///
  1122. /// The result of this analysis is only invalidated if one of the particular
  1123. /// aggregated AA results end up being invalidated. This removes the need to
  1124. /// explicitly preserve the results of `AAManager`. Note that analyses should no
  1125. /// longer be registered once the `AAManager` is run.
  1126. class AAManager : public AnalysisInfoMixin<AAManager> {
  1127. public:
  1128. using Result = AAResults;
  1129. /// Register a specific AA result.
  1130. template <typename AnalysisT> void registerFunctionAnalysis() {
  1131. ResultGetters.push_back(&getFunctionAAResultImpl<AnalysisT>);
  1132. }
  1133. /// Register a specific AA result.
  1134. template <typename AnalysisT> void registerModuleAnalysis() {
  1135. ResultGetters.push_back(&getModuleAAResultImpl<AnalysisT>);
  1136. }
  1137. Result run(Function &F, FunctionAnalysisManager &AM);
  1138. private:
  1139. friend AnalysisInfoMixin<AAManager>;
  1140. static AnalysisKey Key;
  1141. SmallVector<void (*)(Function &F, FunctionAnalysisManager &AM,
  1142. AAResults &AAResults),
  1143. 4> ResultGetters;
  1144. template <typename AnalysisT>
  1145. static void getFunctionAAResultImpl(Function &F,
  1146. FunctionAnalysisManager &AM,
  1147. AAResults &AAResults) {
  1148. AAResults.addAAResult(AM.template getResult<AnalysisT>(F));
  1149. AAResults.addAADependencyID(AnalysisT::ID());
  1150. }
  1151. template <typename AnalysisT>
  1152. static void getModuleAAResultImpl(Function &F, FunctionAnalysisManager &AM,
  1153. AAResults &AAResults) {
  1154. auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
  1155. if (auto *R =
  1156. MAMProxy.template getCachedResult<AnalysisT>(*F.getParent())) {
  1157. AAResults.addAAResult(*R);
  1158. MAMProxy
  1159. .template registerOuterAnalysisInvalidation<AnalysisT, AAManager>();
  1160. }
  1161. }
  1162. };
  1163. /// A wrapper pass to provide the legacy pass manager access to a suitably
  1164. /// prepared AAResults object.
  1165. class AAResultsWrapperPass : public FunctionPass {
  1166. std::unique_ptr<AAResults> AAR;
  1167. public:
  1168. static char ID;
  1169. AAResultsWrapperPass();
  1170. AAResults &getAAResults() { return *AAR; }
  1171. const AAResults &getAAResults() const { return *AAR; }
  1172. bool runOnFunction(Function &F) override;
  1173. void getAnalysisUsage(AnalysisUsage &AU) const override;
  1174. };
  1175. /// A wrapper pass for external alias analyses. This just squirrels away the
  1176. /// callback used to run any analyses and register their results.
  1177. struct ExternalAAWrapperPass : ImmutablePass {
  1178. using CallbackT = std::function<void(Pass &, Function &, AAResults &)>;
  1179. CallbackT CB;
  1180. static char ID;
  1181. ExternalAAWrapperPass();
  1182. explicit ExternalAAWrapperPass(CallbackT CB);
  1183. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1184. AU.setPreservesAll();
  1185. }
  1186. };
  1187. FunctionPass *createAAResultsWrapperPass();
  1188. /// A wrapper pass around a callback which can be used to populate the
  1189. /// AAResults in the AAResultsWrapperPass from an external AA.
  1190. ///
  1191. /// The callback provided here will be used each time we prepare an AAResults
  1192. /// object, and will receive a reference to the function wrapper pass, the
  1193. /// function, and the AAResults object to populate. This should be used when
  1194. /// setting up a custom pass pipeline to inject a hook into the AA results.
  1195. ImmutablePass *createExternalAAWrapperPass(
  1196. std::function<void(Pass &, Function &, AAResults &)> Callback);
  1197. /// A helper for the legacy pass manager to create a \c AAResults
  1198. /// object populated to the best of our ability for a particular function when
  1199. /// inside of a \c ModulePass or a \c CallGraphSCCPass.
  1200. ///
  1201. /// If a \c ModulePass or a \c CallGraphSCCPass calls \p
  1202. /// createLegacyPMAAResults, it also needs to call \p addUsedAAAnalyses in \p
  1203. /// getAnalysisUsage.
  1204. AAResults createLegacyPMAAResults(Pass &P, Function &F, BasicAAResult &BAR);
  1205. /// A helper for the legacy pass manager to populate \p AU to add uses to make
  1206. /// sure the analyses required by \p createLegacyPMAAResults are available.
  1207. void getAAResultsAnalysisUsage(AnalysisUsage &AU);
  1208. } // end namespace llvm
  1209. #endif // LLVM_ANALYSIS_ALIASANALYSIS_H
  1210. #ifdef __GNUC__
  1211. #pragma GCC diagnostic pop
  1212. #endif