CFLAliasAnalysis.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. //===- CFLAliasAnalysis.cpp - CFL-Based Alias Analysis Implementation ------==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements a CFL-based context-insensitive alias analysis
  11. // algorithm. It does not depend on types. The algorithm is a mixture of the one
  12. // described in "Demand-driven alias analysis for C" by Xin Zheng and Radu
  13. // Rugina, and "Fast algorithms for Dyck-CFL-reachability with applications to
  14. // Alias Analysis" by Zhang Q, Lyu M R, Yuan H, and Su Z. -- to summarize the
  15. // papers, we build a graph of the uses of a variable, where each node is a
  16. // memory location, and each edge is an action that happened on that memory
  17. // location. The "actions" can be one of Dereference, Reference, Assign, or
  18. // Assign.
  19. //
  20. // Two variables are considered as aliasing iff you can reach one value's node
  21. // from the other value's node and the language formed by concatenating all of
  22. // the edge labels (actions) conforms to a context-free grammar.
  23. //
  24. // Because this algorithm requires a graph search on each query, we execute the
  25. // algorithm outlined in "Fast algorithms..." (mentioned above)
  26. // in order to transform the graph into sets of variables that may alias in
  27. // ~nlogn time (n = number of variables.), which makes queries take constant
  28. // time.
  29. //===----------------------------------------------------------------------===//
  30. #include "StratifiedSets.h"
  31. #include "llvm/ADT/BitVector.h"
  32. #include "llvm/ADT/DenseMap.h"
  33. #include "llvm/ADT/None.h"
  34. #include "llvm/ADT/Optional.h"
  35. #include "llvm/Analysis/AliasAnalysis.h"
  36. #include "llvm/Analysis/Passes.h"
  37. #include "llvm/IR/Constants.h"
  38. #include "llvm/IR/Function.h"
  39. #include "llvm/IR/InstVisitor.h"
  40. #include "llvm/IR/Instructions.h"
  41. #include "llvm/IR/ValueHandle.h"
  42. #include "llvm/Pass.h"
  43. #include "llvm/Support/Allocator.h"
  44. #include "llvm/Support/Compiler.h"
  45. #include "llvm/Support/ErrorHandling.h"
  46. #include <algorithm>
  47. #include <cassert>
  48. #include <forward_list>
  49. #include <tuple>
  50. using namespace llvm;
  51. // Try to go from a Value* to a Function*. Never returns nullptr.
  52. static Optional<Function *> parentFunctionOfValue(Value *);
  53. // Returns possible functions called by the Inst* into the given
  54. // SmallVectorImpl. Returns true if targets found, false otherwise.
  55. // This is templated because InvokeInst/CallInst give us the same
  56. // set of functions that we care about, and I don't like repeating
  57. // myself.
  58. template <typename Inst>
  59. static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
  60. // Some instructions need to have their users tracked. Instructions like
  61. // `add` require you to get the users of the Instruction* itself, other
  62. // instructions like `store` require you to get the users of the first
  63. // operand. This function gets the "proper" value to track for each
  64. // type of instruction we support.
  65. static Optional<Value *> getTargetValue(Instruction *);
  66. // There are certain instructions (i.e. FenceInst, etc.) that we ignore.
  67. // This notes that we should ignore those.
  68. static bool hasUsefulEdges(Instruction *);
  69. const StratifiedIndex StratifiedLink::SetSentinel =
  70. std::numeric_limits<StratifiedIndex>::max();
  71. namespace {
  72. // StratifiedInfo Attribute things.
  73. typedef unsigned StratifiedAttr;
  74. LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
  75. LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
  76. LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
  77. LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 2;
  78. LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
  79. LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
  80. LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
  81. LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
  82. // \brief StratifiedSets call for knowledge of "direction", so this is how we
  83. // represent that locally.
  84. enum class Level { Same, Above, Below };
  85. // \brief Edges can be one of four "weights" -- each weight must have an inverse
  86. // weight (Assign has Assign; Reference has Dereference).
  87. enum class EdgeType {
  88. // The weight assigned when assigning from or to a value. For example, in:
  89. // %b = getelementptr %a, 0
  90. // ...The relationships are %b assign %a, and %a assign %b. This used to be
  91. // two edges, but having a distinction bought us nothing.
  92. Assign,
  93. // The edge used when we have an edge going from some handle to a Value.
  94. // Examples of this include:
  95. // %b = load %a (%b Dereference %a)
  96. // %b = extractelement %a, 0 (%a Dereference %b)
  97. Dereference,
  98. // The edge used when our edge goes from a value to a handle that may have
  99. // contained it at some point. Examples:
  100. // %b = load %a (%a Reference %b)
  101. // %b = extractelement %a, 0 (%b Reference %a)
  102. Reference
  103. };
  104. // \brief Encodes the notion of a "use"
  105. struct Edge {
  106. // \brief Which value the edge is coming from
  107. Value *From;
  108. // \brief Which value the edge is pointing to
  109. Value *To;
  110. // \brief Edge weight
  111. EdgeType Weight;
  112. // \brief Whether we aliased any external values along the way that may be
  113. // invisible to the analysis (i.e. landingpad for exceptions, calls for
  114. // interprocedural analysis, etc.)
  115. StratifiedAttrs AdditionalAttrs;
  116. Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
  117. : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
  118. };
  119. // \brief Information we have about a function and would like to keep around
  120. struct FunctionInfo {
  121. StratifiedSets<Value *> Sets;
  122. // Lots of functions have < 4 returns. Adjust as necessary.
  123. SmallVector<Value *, 4> ReturnedValues;
  124. FunctionInfo(StratifiedSets<Value *> &&S,
  125. SmallVector<Value *, 4> &&RV)
  126. : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
  127. };
  128. struct CFLAliasAnalysis;
  129. struct FunctionHandle : public CallbackVH {
  130. FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
  131. : CallbackVH(Fn), CFLAA(CFLAA) {
  132. assert(Fn != nullptr);
  133. assert(CFLAA != nullptr);
  134. }
  135. virtual ~FunctionHandle() {}
  136. void deleted() override { removeSelfFromCache(); }
  137. void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
  138. private:
  139. CFLAliasAnalysis *CFLAA;
  140. void removeSelfFromCache();
  141. };
  142. struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
  143. private:
  144. /// \brief Cached mapping of Functions to their StratifiedSets.
  145. /// If a function's sets are currently being built, it is marked
  146. /// in the cache as an Optional without a value. This way, if we
  147. /// have any kind of recursion, it is discernable from a function
  148. /// that simply has empty sets.
  149. DenseMap<Function *, Optional<FunctionInfo>> Cache;
  150. std::forward_list<FunctionHandle> Handles;
  151. public:
  152. static char ID;
  153. CFLAliasAnalysis() : ImmutablePass(ID) {
  154. initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
  155. }
  156. virtual ~CFLAliasAnalysis() {}
  157. void getAnalysisUsage(AnalysisUsage &AU) const override {
  158. AliasAnalysis::getAnalysisUsage(AU);
  159. }
  160. void *getAdjustedAnalysisPointer(const void *ID) override {
  161. if (ID == &AliasAnalysis::ID)
  162. return (AliasAnalysis *)this;
  163. return this;
  164. }
  165. /// \brief Inserts the given Function into the cache.
  166. void scan(Function *Fn);
  167. void evict(Function *Fn) { Cache.erase(Fn); }
  168. /// \brief Ensures that the given function is available in the cache.
  169. /// Returns the appropriate entry from the cache.
  170. const Optional<FunctionInfo> &ensureCached(Function *Fn) {
  171. auto Iter = Cache.find(Fn);
  172. if (Iter == Cache.end()) {
  173. scan(Fn);
  174. Iter = Cache.find(Fn);
  175. assert(Iter != Cache.end());
  176. assert(Iter->second.hasValue());
  177. }
  178. return Iter->second;
  179. }
  180. AliasResult query(const Location &LocA, const Location &LocB);
  181. AliasResult alias(const Location &LocA, const Location &LocB) override {
  182. if (LocA.Ptr == LocB.Ptr) {
  183. if (LocA.Size == LocB.Size) {
  184. return MustAlias;
  185. } else {
  186. return PartialAlias;
  187. }
  188. }
  189. // Comparisons between global variables and other constants should be
  190. // handled by BasicAA.
  191. if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
  192. return MayAlias;
  193. }
  194. return query(LocA, LocB);
  195. }
  196. void initializePass() override { InitializeAliasAnalysis(this); }
  197. };
  198. void FunctionHandle::removeSelfFromCache() {
  199. assert(CFLAA != nullptr);
  200. auto *Val = getValPtr();
  201. CFLAA->evict(cast<Function>(Val));
  202. setValPtr(nullptr);
  203. }
  204. // \brief Gets the edges our graph should have, based on an Instruction*
  205. class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
  206. CFLAliasAnalysis &AA;
  207. SmallVectorImpl<Edge> &Output;
  208. public:
  209. GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
  210. : AA(AA), Output(Output) {}
  211. void visitInstruction(Instruction &) {
  212. llvm_unreachable("Unsupported instruction encountered");
  213. }
  214. void visitCastInst(CastInst &Inst) {
  215. Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign,
  216. AttrNone));
  217. }
  218. void visitBinaryOperator(BinaryOperator &Inst) {
  219. auto *Op1 = Inst.getOperand(0);
  220. auto *Op2 = Inst.getOperand(1);
  221. Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
  222. Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
  223. }
  224. void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
  225. auto *Ptr = Inst.getPointerOperand();
  226. auto *Val = Inst.getNewValOperand();
  227. Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
  228. }
  229. void visitAtomicRMWInst(AtomicRMWInst &Inst) {
  230. auto *Ptr = Inst.getPointerOperand();
  231. auto *Val = Inst.getValOperand();
  232. Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
  233. }
  234. void visitPHINode(PHINode &Inst) {
  235. for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
  236. Value *Val = Inst.getIncomingValue(I);
  237. Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
  238. }
  239. }
  240. void visitGetElementPtrInst(GetElementPtrInst &Inst) {
  241. auto *Op = Inst.getPointerOperand();
  242. Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
  243. for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
  244. Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
  245. }
  246. void visitSelectInst(SelectInst &Inst) {
  247. auto *Condition = Inst.getCondition();
  248. Output.push_back(Edge(&Inst, Condition, EdgeType::Assign, AttrNone));
  249. auto *TrueVal = Inst.getTrueValue();
  250. Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
  251. auto *FalseVal = Inst.getFalseValue();
  252. Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
  253. }
  254. void visitAllocaInst(AllocaInst &) {}
  255. void visitLoadInst(LoadInst &Inst) {
  256. auto *Ptr = Inst.getPointerOperand();
  257. auto *Val = &Inst;
  258. Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
  259. }
  260. void visitStoreInst(StoreInst &Inst) {
  261. auto *Ptr = Inst.getPointerOperand();
  262. auto *Val = Inst.getValueOperand();
  263. Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
  264. }
  265. void visitVAArgInst(VAArgInst &Inst) {
  266. // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
  267. // two things:
  268. // 1. Loads a value from *((T*)*Ptr).
  269. // 2. Increments (stores to) *Ptr by some target-specific amount.
  270. // For now, we'll handle this like a landingpad instruction (by placing the
  271. // result in its own group, and having that group alias externals).
  272. auto *Val = &Inst;
  273. Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
  274. }
  275. static bool isFunctionExternal(Function *Fn) {
  276. return Fn->isDeclaration() || !Fn->hasLocalLinkage();
  277. }
  278. // Gets whether the sets at Index1 above, below, or equal to the sets at
  279. // Index2. Returns None if they are not in the same set chain.
  280. static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
  281. StratifiedIndex Index1,
  282. StratifiedIndex Index2) {
  283. if (Index1 == Index2)
  284. return Level::Same;
  285. const auto *Current = &Sets.getLink(Index1);
  286. while (Current->hasBelow()) {
  287. if (Current->Below == Index2)
  288. return Level::Below;
  289. Current = &Sets.getLink(Current->Below);
  290. }
  291. Current = &Sets.getLink(Index1);
  292. while (Current->hasAbove()) {
  293. if (Current->Above == Index2)
  294. return Level::Above;
  295. Current = &Sets.getLink(Current->Above);
  296. }
  297. return NoneType();
  298. }
  299. bool
  300. tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
  301. Value *FuncValue,
  302. const iterator_range<User::op_iterator> &Args) {
  303. const unsigned ExpectedMaxArgs = 8;
  304. const unsigned MaxSupportedArgs = 50;
  305. assert(Fns.size() > 0);
  306. // I put this here to give us an upper bound on time taken by IPA. Is it
  307. // really (realistically) needed? Keep in mind that we do have an n^2 algo.
  308. if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs)
  309. return false;
  310. // Exit early if we'll fail anyway
  311. for (auto *Fn : Fns) {
  312. if (isFunctionExternal(Fn) || Fn->isVarArg())
  313. return false;
  314. auto &MaybeInfo = AA.ensureCached(Fn);
  315. if (!MaybeInfo.hasValue())
  316. return false;
  317. }
  318. SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
  319. SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
  320. for (auto *Fn : Fns) {
  321. auto &Info = *AA.ensureCached(Fn);
  322. auto &Sets = Info.Sets;
  323. auto &RetVals = Info.ReturnedValues;
  324. Parameters.clear();
  325. for (auto &Param : Fn->args()) {
  326. auto MaybeInfo = Sets.find(&Param);
  327. // Did a new parameter somehow get added to the function/slip by?
  328. if (!MaybeInfo.hasValue())
  329. return false;
  330. Parameters.push_back(*MaybeInfo);
  331. }
  332. // Adding an edge from argument -> return value for each parameter that
  333. // may alias the return value
  334. for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
  335. auto &ParamInfo = Parameters[I];
  336. auto &ArgVal = Arguments[I];
  337. bool AddEdge = false;
  338. StratifiedAttrs Externals;
  339. for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
  340. auto MaybeInfo = Sets.find(RetVals[X]);
  341. if (!MaybeInfo.hasValue())
  342. return false;
  343. auto &RetInfo = *MaybeInfo;
  344. auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
  345. auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
  346. auto MaybeRelation =
  347. getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
  348. if (MaybeRelation.hasValue()) {
  349. AddEdge = true;
  350. Externals |= RetAttrs | ParamAttrs;
  351. }
  352. }
  353. if (AddEdge)
  354. Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
  355. StratifiedAttrs().flip()));
  356. }
  357. if (Parameters.size() != Arguments.size())
  358. return false;
  359. // Adding edges between arguments for arguments that may end up aliasing
  360. // each other. This is necessary for functions such as
  361. // void foo(int** a, int** b) { *a = *b; }
  362. // (Technically, the proper sets for this would be those below
  363. // Arguments[I] and Arguments[X], but our algorithm will produce
  364. // extremely similar, and equally correct, results either way)
  365. for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
  366. auto &MainVal = Arguments[I];
  367. auto &MainInfo = Parameters[I];
  368. auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
  369. for (unsigned X = I + 1; X != E; ++X) {
  370. auto &SubInfo = Parameters[X];
  371. auto &SubVal = Arguments[X];
  372. auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
  373. auto MaybeRelation =
  374. getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
  375. if (!MaybeRelation.hasValue())
  376. continue;
  377. auto NewAttrs = SubAttrs | MainAttrs;
  378. Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
  379. }
  380. }
  381. }
  382. return true;
  383. }
  384. template <typename InstT> void visitCallLikeInst(InstT &Inst) {
  385. SmallVector<Function *, 4> Targets;
  386. if (getPossibleTargets(&Inst, Targets)) {
  387. if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
  388. return;
  389. // Cleanup from interprocedural analysis
  390. Output.clear();
  391. }
  392. for (Value *V : Inst.arg_operands())
  393. Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
  394. }
  395. void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
  396. void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
  397. // Because vectors/aggregates are immutable and unaddressable,
  398. // there's nothing we can do to coax a value out of them, other
  399. // than calling Extract{Element,Value}. We can effectively treat
  400. // them as pointers to arbitrary memory locations we can store in
  401. // and load from.
  402. void visitExtractElementInst(ExtractElementInst &Inst) {
  403. auto *Ptr = Inst.getVectorOperand();
  404. auto *Val = &Inst;
  405. Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
  406. }
  407. void visitInsertElementInst(InsertElementInst &Inst) {
  408. auto *Vec = Inst.getOperand(0);
  409. auto *Val = Inst.getOperand(1);
  410. Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
  411. Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
  412. }
  413. void visitLandingPadInst(LandingPadInst &Inst) {
  414. // Exceptions come from "nowhere", from our analysis' perspective.
  415. // So we place the instruction its own group, noting that said group may
  416. // alias externals
  417. Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
  418. }
  419. void visitInsertValueInst(InsertValueInst &Inst) {
  420. auto *Agg = Inst.getOperand(0);
  421. auto *Val = Inst.getOperand(1);
  422. Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
  423. Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
  424. }
  425. void visitExtractValueInst(ExtractValueInst &Inst) {
  426. auto *Ptr = Inst.getAggregateOperand();
  427. Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
  428. }
  429. void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
  430. auto *From1 = Inst.getOperand(0);
  431. auto *From2 = Inst.getOperand(1);
  432. Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
  433. Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
  434. }
  435. };
  436. // For a given instruction, we need to know which Value* to get the
  437. // users of in order to build our graph. In some cases (i.e. add),
  438. // we simply need the Instruction*. In other cases (i.e. store),
  439. // finding the users of the Instruction* is useless; we need to find
  440. // the users of the first operand. This handles determining which
  441. // value to follow for us.
  442. //
  443. // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
  444. // something to GetEdgesVisitor, add it here -- remove something from
  445. // GetEdgesVisitor, remove it here.
  446. class GetTargetValueVisitor
  447. : public InstVisitor<GetTargetValueVisitor, Value *> {
  448. public:
  449. Value *visitInstruction(Instruction &Inst) { return &Inst; }
  450. Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
  451. Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
  452. return Inst.getPointerOperand();
  453. }
  454. Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
  455. return Inst.getPointerOperand();
  456. }
  457. Value *visitInsertElementInst(InsertElementInst &Inst) {
  458. return Inst.getOperand(0);
  459. }
  460. Value *visitInsertValueInst(InsertValueInst &Inst) {
  461. return Inst.getAggregateOperand();
  462. }
  463. };
  464. // Set building requires a weighted bidirectional graph.
  465. template <typename EdgeTypeT> class WeightedBidirectionalGraph {
  466. public:
  467. typedef std::size_t Node;
  468. private:
  469. const static Node StartNode = Node(0);
  470. struct Edge {
  471. EdgeTypeT Weight;
  472. Node Other;
  473. Edge(const EdgeTypeT &W, const Node &N)
  474. : Weight(W), Other(N) {}
  475. bool operator==(const Edge &E) const {
  476. return Weight == E.Weight && Other == E.Other;
  477. }
  478. bool operator!=(const Edge &E) const { return !operator==(E); }
  479. };
  480. struct NodeImpl {
  481. std::vector<Edge> Edges;
  482. };
  483. std::vector<NodeImpl> NodeImpls;
  484. bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
  485. const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
  486. NodeImpl &getNode(Node N) { return NodeImpls[N]; }
  487. public:
  488. // ----- Various Edge iterators for the graph ----- //
  489. // \brief Iterator for edges. Because this graph is bidirected, we don't
  490. // allow modificaiton of the edges using this iterator. Additionally, the
  491. // iterator becomes invalid if you add edges to or from the node you're
  492. // getting the edges of.
  493. struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
  494. std::tuple<EdgeTypeT, Node *>> {
  495. EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
  496. : Current(Iter) {}
  497. EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
  498. EdgeIterator &operator++() {
  499. ++Current;
  500. return *this;
  501. }
  502. EdgeIterator operator++(int) {
  503. EdgeIterator Copy(Current);
  504. operator++();
  505. return Copy;
  506. }
  507. std::tuple<EdgeTypeT, Node> &operator*() {
  508. Store = std::make_tuple(Current->Weight, Current->Other);
  509. return Store;
  510. }
  511. bool operator==(const EdgeIterator &Other) const {
  512. return Current == Other.Current;
  513. }
  514. bool operator!=(const EdgeIterator &Other) const {
  515. return !operator==(Other);
  516. }
  517. private:
  518. typename std::vector<Edge>::const_iterator Current;
  519. std::tuple<EdgeTypeT, Node> Store;
  520. };
  521. // Wrapper for EdgeIterator with begin()/end() calls.
  522. struct EdgeIterable {
  523. EdgeIterable(const std::vector<Edge> &Edges)
  524. : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
  525. EdgeIterator begin() { return EdgeIterator(BeginIter); }
  526. EdgeIterator end() { return EdgeIterator(EndIter); }
  527. private:
  528. typename std::vector<Edge>::const_iterator BeginIter;
  529. typename std::vector<Edge>::const_iterator EndIter;
  530. };
  531. // ----- Actual graph-related things ----- //
  532. WeightedBidirectionalGraph() {}
  533. WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
  534. : NodeImpls(std::move(Other.NodeImpls)) {}
  535. WeightedBidirectionalGraph<EdgeTypeT> &
  536. operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
  537. NodeImpls = std::move(Other.NodeImpls);
  538. return *this;
  539. }
  540. Node addNode() {
  541. auto Index = NodeImpls.size();
  542. auto NewNode = Node(Index);
  543. NodeImpls.push_back(NodeImpl());
  544. return NewNode;
  545. }
  546. void addEdge(Node From, Node To, const EdgeTypeT &Weight,
  547. const EdgeTypeT &ReverseWeight) {
  548. assert(inbounds(From));
  549. assert(inbounds(To));
  550. auto &FromNode = getNode(From);
  551. auto &ToNode = getNode(To);
  552. FromNode.Edges.push_back(Edge(Weight, To));
  553. ToNode.Edges.push_back(Edge(ReverseWeight, From));
  554. }
  555. EdgeIterable edgesFor(const Node &N) const {
  556. const auto &Node = getNode(N);
  557. return EdgeIterable(Node.Edges);
  558. }
  559. bool empty() const { return NodeImpls.empty(); }
  560. std::size_t size() const { return NodeImpls.size(); }
  561. // \brief Gets an arbitrary node in the graph as a starting point for
  562. // traversal.
  563. Node getEntryNode() {
  564. assert(inbounds(StartNode));
  565. return StartNode;
  566. }
  567. };
  568. typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
  569. typedef DenseMap<Value *, GraphT::Node> NodeMapT;
  570. }
  571. // -- Setting up/registering CFLAA pass -- //
  572. char CFLAliasAnalysis::ID = 0;
  573. INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
  574. "CFL-Based AA implementation", false, true, false)
  575. ImmutablePass *llvm::createCFLAliasAnalysisPass() {
  576. return new CFLAliasAnalysis();
  577. }
  578. //===----------------------------------------------------------------------===//
  579. // Function declarations that require types defined in the namespace above
  580. //===----------------------------------------------------------------------===//
  581. // Given an argument number, returns the appropriate Attr index to set.
  582. static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
  583. // Given a Value, potentially return which AttrIndex it maps to.
  584. static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
  585. // Gets the inverse of a given EdgeType.
  586. static EdgeType flipWeight(EdgeType);
  587. // Gets edges of the given Instruction*, writing them to the SmallVector*.
  588. static void argsToEdges(CFLAliasAnalysis &, Instruction *,
  589. SmallVectorImpl<Edge> &);
  590. // Gets the "Level" that one should travel in StratifiedSets
  591. // given an EdgeType.
  592. static Level directionOfEdgeType(EdgeType);
  593. // Builds the graph needed for constructing the StratifiedSets for the
  594. // given function
  595. static void buildGraphFrom(CFLAliasAnalysis &, Function *,
  596. SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
  597. // Builds the graph + StratifiedSets for a function.
  598. static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
  599. static Optional<Function *> parentFunctionOfValue(Value *Val) {
  600. if (auto *Inst = dyn_cast<Instruction>(Val)) {
  601. auto *Bb = Inst->getParent();
  602. return Bb->getParent();
  603. }
  604. if (auto *Arg = dyn_cast<Argument>(Val))
  605. return Arg->getParent();
  606. return NoneType();
  607. }
  608. template <typename Inst>
  609. static bool getPossibleTargets(Inst *Call,
  610. SmallVectorImpl<Function *> &Output) {
  611. if (auto *Fn = Call->getCalledFunction()) {
  612. Output.push_back(Fn);
  613. return true;
  614. }
  615. // TODO: If the call is indirect, we might be able to enumerate all potential
  616. // targets of the call and return them, rather than just failing.
  617. return false;
  618. }
  619. static Optional<Value *> getTargetValue(Instruction *Inst) {
  620. GetTargetValueVisitor V;
  621. return V.visit(Inst);
  622. }
  623. static bool hasUsefulEdges(Instruction *Inst) {
  624. bool IsNonInvokeTerminator =
  625. isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
  626. return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
  627. }
  628. static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
  629. if (isa<GlobalValue>(Val))
  630. return AttrGlobalIndex;
  631. if (auto *Arg = dyn_cast<Argument>(Val))
  632. if (!Arg->hasNoAliasAttr())
  633. return argNumberToAttrIndex(Arg->getArgNo());
  634. return NoneType();
  635. }
  636. static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
  637. if (ArgNum > AttrMaxNumArgs)
  638. return AttrAllIndex;
  639. return ArgNum + AttrFirstArgIndex;
  640. }
  641. static EdgeType flipWeight(EdgeType Initial) {
  642. switch (Initial) {
  643. case EdgeType::Assign:
  644. return EdgeType::Assign;
  645. case EdgeType::Dereference:
  646. return EdgeType::Reference;
  647. case EdgeType::Reference:
  648. return EdgeType::Dereference;
  649. }
  650. llvm_unreachable("Incomplete coverage of EdgeType enum");
  651. }
  652. static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
  653. SmallVectorImpl<Edge> &Output) {
  654. GetEdgesVisitor v(Analysis, Output);
  655. v.visit(Inst);
  656. }
  657. static Level directionOfEdgeType(EdgeType Weight) {
  658. switch (Weight) {
  659. case EdgeType::Reference:
  660. return Level::Above;
  661. case EdgeType::Dereference:
  662. return Level::Below;
  663. case EdgeType::Assign:
  664. return Level::Same;
  665. }
  666. llvm_unreachable("Incomplete switch coverage");
  667. }
  668. // Aside: We may remove graph construction entirely, because it doesn't really
  669. // buy us much that we don't already have. I'd like to add interprocedural
  670. // analysis prior to this however, in case that somehow requires the graph
  671. // produced by this for efficient execution
  672. static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
  673. SmallVectorImpl<Value *> &ReturnedValues,
  674. NodeMapT &Map, GraphT &Graph) {
  675. const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
  676. auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
  677. auto &Iter = Pair.first;
  678. if (Pair.second) {
  679. auto NewNode = Graph.addNode();
  680. Iter->second = NewNode;
  681. }
  682. return Iter->second;
  683. };
  684. SmallVector<Edge, 8> Edges;
  685. for (auto &Bb : Fn->getBasicBlockList()) {
  686. for (auto &Inst : Bb.getInstList()) {
  687. // We don't want the edges of most "return" instructions, but we *do* want
  688. // to know what can be returned.
  689. if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
  690. ReturnedValues.push_back(Ret);
  691. if (!hasUsefulEdges(&Inst))
  692. continue;
  693. Edges.clear();
  694. argsToEdges(Analysis, &Inst, Edges);
  695. // In the case of an unused alloca (or similar), edges may be empty. Note
  696. // that it exists so we can potentially answer NoAlias.
  697. if (Edges.empty()) {
  698. auto MaybeVal = getTargetValue(&Inst);
  699. assert(MaybeVal.hasValue());
  700. auto *Target = *MaybeVal;
  701. findOrInsertNode(Target);
  702. continue;
  703. }
  704. for (const Edge &E : Edges) {
  705. auto To = findOrInsertNode(E.To);
  706. auto From = findOrInsertNode(E.From);
  707. auto FlippedWeight = flipWeight(E.Weight);
  708. auto Attrs = E.AdditionalAttrs;
  709. Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
  710. std::make_pair(FlippedWeight, Attrs));
  711. }
  712. }
  713. }
  714. }
  715. static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
  716. NodeMapT Map;
  717. GraphT Graph;
  718. SmallVector<Value *, 4> ReturnedValues;
  719. buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
  720. DenseMap<GraphT::Node, Value *> NodeValueMap;
  721. NodeValueMap.resize(Map.size());
  722. for (const auto &Pair : Map)
  723. NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
  724. const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
  725. auto ValIter = NodeValueMap.find(Node);
  726. assert(ValIter != NodeValueMap.end());
  727. return ValIter->second;
  728. };
  729. StratifiedSetsBuilder<Value *> Builder;
  730. SmallVector<GraphT::Node, 16> Worklist;
  731. for (auto &Pair : Map) {
  732. Worklist.clear();
  733. auto *Value = Pair.first;
  734. Builder.add(Value);
  735. auto InitialNode = Pair.second;
  736. Worklist.push_back(InitialNode);
  737. while (!Worklist.empty()) {
  738. auto Node = Worklist.pop_back_val();
  739. auto *CurValue = findValueOrDie(Node);
  740. if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
  741. continue;
  742. for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
  743. auto Weight = std::get<0>(EdgeTuple);
  744. auto Label = Weight.first;
  745. auto &OtherNode = std::get<1>(EdgeTuple);
  746. auto *OtherValue = findValueOrDie(OtherNode);
  747. if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
  748. continue;
  749. bool Added;
  750. switch (directionOfEdgeType(Label)) {
  751. case Level::Above:
  752. Added = Builder.addAbove(CurValue, OtherValue);
  753. break;
  754. case Level::Below:
  755. Added = Builder.addBelow(CurValue, OtherValue);
  756. break;
  757. case Level::Same:
  758. Added = Builder.addWith(CurValue, OtherValue);
  759. break;
  760. }
  761. if (Added) {
  762. auto Aliasing = Weight.second;
  763. if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
  764. Aliasing.set(*MaybeCurIndex);
  765. if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
  766. Aliasing.set(*MaybeOtherIndex);
  767. Builder.noteAttributes(CurValue, Aliasing);
  768. Builder.noteAttributes(OtherValue, Aliasing);
  769. Worklist.push_back(OtherNode);
  770. }
  771. }
  772. }
  773. }
  774. // There are times when we end up with parameters not in our graph (i.e. if
  775. // it's only used as the condition of a branch). Other bits of code depend on
  776. // things that were present during construction being present in the graph.
  777. // So, we add all present arguments here.
  778. for (auto &Arg : Fn->args()) {
  779. Builder.add(&Arg);
  780. }
  781. return FunctionInfo(Builder.build(), std::move(ReturnedValues));
  782. }
  783. void CFLAliasAnalysis::scan(Function *Fn) {
  784. auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
  785. (void)InsertPair;
  786. assert(InsertPair.second &&
  787. "Trying to scan a function that has already been cached");
  788. FunctionInfo Info(buildSetsFrom(*this, Fn));
  789. Cache[Fn] = std::move(Info);
  790. Handles.push_front(FunctionHandle(Fn, this));
  791. }
  792. AliasAnalysis::AliasResult
  793. CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
  794. const AliasAnalysis::Location &LocB) {
  795. auto *ValA = const_cast<Value *>(LocA.Ptr);
  796. auto *ValB = const_cast<Value *>(LocB.Ptr);
  797. Function *Fn = nullptr;
  798. auto MaybeFnA = parentFunctionOfValue(ValA);
  799. auto MaybeFnB = parentFunctionOfValue(ValB);
  800. if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
  801. llvm_unreachable("Don't know how to extract the parent function "
  802. "from values A or B");
  803. }
  804. if (MaybeFnA.hasValue()) {
  805. Fn = *MaybeFnA;
  806. assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
  807. "Interprocedural queries not supported");
  808. } else {
  809. Fn = *MaybeFnB;
  810. }
  811. assert(Fn != nullptr);
  812. auto &MaybeInfo = ensureCached(Fn);
  813. assert(MaybeInfo.hasValue());
  814. auto &Sets = MaybeInfo->Sets;
  815. auto MaybeA = Sets.find(ValA);
  816. if (!MaybeA.hasValue())
  817. return AliasAnalysis::MayAlias;
  818. auto MaybeB = Sets.find(ValB);
  819. if (!MaybeB.hasValue())
  820. return AliasAnalysis::MayAlias;
  821. auto SetA = *MaybeA;
  822. auto SetB = *MaybeB;
  823. if (SetA.Index == SetB.Index)
  824. return AliasAnalysis::PartialAlias;
  825. auto AttrsA = Sets.getLink(SetA.Index).Attrs;
  826. auto AttrsB = Sets.getLink(SetB.Index).Attrs;
  827. // Stratified set attributes are used as markets to signify whether a member
  828. // of a StratifiedSet (or a member of a set above the current set) has
  829. // interacted with either arguments or globals. "Interacted with" meaning
  830. // its value may be different depending on the value of an argument or
  831. // global. The thought behind this is that, because arguments and globals
  832. // may alias each other, if AttrsA and AttrsB have touched args/globals,
  833. // we must conservatively say that they alias. However, if at least one of
  834. // the sets has no values that could legally be altered by changing the value
  835. // of an argument or global, then we don't have to be as conservative.
  836. if (AttrsA.any() && AttrsB.any())
  837. return AliasAnalysis::MayAlias;
  838. return AliasAnalysis::NoAlias;
  839. }