2
0

LazyValueInfo.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  1. //===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the interface for lazy computation of value constraint
  11. // information.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Analysis/LazyValueInfo.h"
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/Analysis/AssumptionCache.h"
  18. #include "llvm/Analysis/ConstantFolding.h"
  19. #include "llvm/Analysis/TargetLibraryInfo.h"
  20. #include "llvm/Analysis/ValueTracking.h"
  21. #include "llvm/IR/CFG.h"
  22. #include "llvm/IR/ConstantRange.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/DataLayout.h"
  25. #include "llvm/IR/Dominators.h"
  26. #include "llvm/IR/Instructions.h"
  27. #include "llvm/IR/IntrinsicInst.h"
  28. #include "llvm/IR/PatternMatch.h"
  29. #include "llvm/IR/ValueHandle.h"
  30. #include "llvm/Support/Debug.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include <map>
  33. #include <stack>
  34. using namespace llvm;
  35. using namespace PatternMatch;
  36. #define DEBUG_TYPE "lazy-value-info"
  37. char LazyValueInfo::ID = 0;
  38. INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
  39. "Lazy Value Information Analysis", false, true)
  40. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  41. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  42. INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
  43. "Lazy Value Information Analysis", false, true)
  44. namespace llvm {
  45. FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
  46. }
  47. //===----------------------------------------------------------------------===//
  48. // LVILatticeVal
  49. //===----------------------------------------------------------------------===//
  50. /// This is the information tracked by LazyValueInfo for each value.
  51. ///
  52. /// FIXME: This is basically just for bringup, this can be made a lot more rich
  53. /// in the future.
  54. ///
  55. namespace {
  56. class LVILatticeVal {
  57. enum LatticeValueTy {
  58. /// This Value has no known value yet.
  59. undefined,
  60. /// This Value has a specific constant value.
  61. constant,
  62. /// This Value is known to not have the specified value.
  63. notconstant,
  64. /// The Value falls within this range.
  65. constantrange,
  66. /// This value is not known to be constant, and we know that it has a value.
  67. overdefined
  68. };
  69. /// Val: This stores the current lattice value along with the Constant* for
  70. /// the constant if this is a 'constant' or 'notconstant' value.
  71. LatticeValueTy Tag;
  72. Constant *Val;
  73. ConstantRange Range;
  74. public:
  75. LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
  76. static LVILatticeVal get(Constant *C) {
  77. LVILatticeVal Res;
  78. if (!isa<UndefValue>(C))
  79. Res.markConstant(C);
  80. return Res;
  81. }
  82. static LVILatticeVal getNot(Constant *C) {
  83. LVILatticeVal Res;
  84. if (!isa<UndefValue>(C))
  85. Res.markNotConstant(C);
  86. return Res;
  87. }
  88. static LVILatticeVal getRange(ConstantRange CR) {
  89. LVILatticeVal Res;
  90. Res.markConstantRange(CR);
  91. return Res;
  92. }
  93. bool isUndefined() const { return Tag == undefined; }
  94. bool isConstant() const { return Tag == constant; }
  95. bool isNotConstant() const { return Tag == notconstant; }
  96. bool isConstantRange() const { return Tag == constantrange; }
  97. bool isOverdefined() const { return Tag == overdefined; }
  98. Constant *getConstant() const {
  99. assert(isConstant() && "Cannot get the constant of a non-constant!");
  100. return Val;
  101. }
  102. Constant *getNotConstant() const {
  103. assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
  104. return Val;
  105. }
  106. ConstantRange getConstantRange() const {
  107. assert(isConstantRange() &&
  108. "Cannot get the constant-range of a non-constant-range!");
  109. return Range;
  110. }
  111. /// Return true if this is a change in status.
  112. bool markOverdefined() {
  113. if (isOverdefined())
  114. return false;
  115. Tag = overdefined;
  116. return true;
  117. }
  118. /// Return true if this is a change in status.
  119. bool markConstant(Constant *V) {
  120. assert(V && "Marking constant with NULL");
  121. if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
  122. return markConstantRange(ConstantRange(CI->getValue()));
  123. if (isa<UndefValue>(V))
  124. return false;
  125. assert((!isConstant() || getConstant() == V) &&
  126. "Marking constant with different value");
  127. assert(isUndefined());
  128. Tag = constant;
  129. Val = V;
  130. return true;
  131. }
  132. /// Return true if this is a change in status.
  133. bool markNotConstant(Constant *V) {
  134. assert(V && "Marking constant with NULL");
  135. if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
  136. return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
  137. if (isa<UndefValue>(V))
  138. return false;
  139. assert((!isConstant() || getConstant() != V) &&
  140. "Marking constant !constant with same value");
  141. assert((!isNotConstant() || getNotConstant() == V) &&
  142. "Marking !constant with different value");
  143. assert(isUndefined() || isConstant());
  144. Tag = notconstant;
  145. Val = V;
  146. return true;
  147. }
  148. /// Return true if this is a change in status.
  149. bool markConstantRange(const ConstantRange NewR) {
  150. if (isConstantRange()) {
  151. if (NewR.isEmptySet())
  152. return markOverdefined();
  153. bool changed = Range != NewR;
  154. Range = NewR;
  155. return changed;
  156. }
  157. assert(isUndefined());
  158. if (NewR.isEmptySet())
  159. return markOverdefined();
  160. Tag = constantrange;
  161. Range = NewR;
  162. return true;
  163. }
  164. /// Merge the specified lattice value into this one, updating this
  165. /// one and returning true if anything changed.
  166. bool mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
  167. if (RHS.isUndefined() || isOverdefined()) return false;
  168. if (RHS.isOverdefined()) return markOverdefined();
  169. if (isUndefined()) {
  170. Tag = RHS.Tag;
  171. Val = RHS.Val;
  172. Range = RHS.Range;
  173. return true;
  174. }
  175. if (isConstant()) {
  176. if (RHS.isConstant()) {
  177. if (Val == RHS.Val)
  178. return false;
  179. return markOverdefined();
  180. }
  181. if (RHS.isNotConstant()) {
  182. if (Val == RHS.Val)
  183. return markOverdefined();
  184. // Unless we can prove that the two Constants are different, we must
  185. // move to overdefined.
  186. if (ConstantInt *Res =
  187. dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
  188. CmpInst::ICMP_NE, getConstant(), RHS.getNotConstant(), DL)))
  189. if (Res->isOne())
  190. return markNotConstant(RHS.getNotConstant());
  191. return markOverdefined();
  192. }
  193. // RHS is a ConstantRange, LHS is a non-integer Constant.
  194. // FIXME: consider the case where RHS is a range [1, 0) and LHS is
  195. // a function. The correct result is to pick up RHS.
  196. return markOverdefined();
  197. }
  198. if (isNotConstant()) {
  199. if (RHS.isConstant()) {
  200. if (Val == RHS.Val)
  201. return markOverdefined();
  202. // Unless we can prove that the two Constants are different, we must
  203. // move to overdefined.
  204. if (ConstantInt *Res =
  205. dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
  206. CmpInst::ICMP_NE, getNotConstant(), RHS.getConstant(), DL)))
  207. if (Res->isOne())
  208. return false;
  209. return markOverdefined();
  210. }
  211. if (RHS.isNotConstant()) {
  212. if (Val == RHS.Val)
  213. return false;
  214. return markOverdefined();
  215. }
  216. return markOverdefined();
  217. }
  218. assert(isConstantRange() && "New LVILattice type?");
  219. if (!RHS.isConstantRange())
  220. return markOverdefined();
  221. ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
  222. if (NewR.isFullSet())
  223. return markOverdefined();
  224. return markConstantRange(NewR);
  225. }
  226. };
  227. } // end anonymous namespace.
  228. namespace llvm {
  229. raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
  230. LLVM_ATTRIBUTE_USED;
  231. raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
  232. if (Val.isUndefined())
  233. return OS << "undefined";
  234. if (Val.isOverdefined())
  235. return OS << "overdefined";
  236. if (Val.isNotConstant())
  237. return OS << "notconstant<" << *Val.getNotConstant() << '>';
  238. else if (Val.isConstantRange())
  239. return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
  240. << Val.getConstantRange().getUpper() << '>';
  241. return OS << "constant<" << *Val.getConstant() << '>';
  242. }
  243. }
  244. //===----------------------------------------------------------------------===//
  245. // LazyValueInfoCache Decl
  246. //===----------------------------------------------------------------------===//
  247. namespace {
  248. /// A callback value handle updates the cache when values are erased.
  249. class LazyValueInfoCache;
  250. struct LVIValueHandle : public CallbackVH {
  251. LazyValueInfoCache *Parent;
  252. LVIValueHandle(Value *V, LazyValueInfoCache *P)
  253. : CallbackVH(V), Parent(P) { }
  254. void deleted() override;
  255. void allUsesReplacedWith(Value *V) override {
  256. deleted();
  257. }
  258. };
  259. }
  260. namespace {
  261. /// This is the cache kept by LazyValueInfo which
  262. /// maintains information about queries across the clients' queries.
  263. class LazyValueInfoCache {
  264. /// This is all of the cached block information for exactly one Value*.
  265. /// The entries are sorted by the BasicBlock* of the
  266. /// entries, allowing us to do a lookup with a binary search.
  267. typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
  268. /// This is all of the cached information for all values,
  269. /// mapped from Value* to key information.
  270. std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
  271. /// This tracks, on a per-block basis, the set of values that are
  272. /// over-defined at the end of that block. This is required
  273. /// for cache updating.
  274. typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
  275. DenseSet<OverDefinedPairTy> OverDefinedCache;
  276. /// Keep track of all blocks that we have ever seen, so we
  277. /// don't spend time removing unused blocks from our caches.
  278. DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
  279. /// This stack holds the state of the value solver during a query.
  280. /// It basically emulates the callstack of the naive
  281. /// recursive value lookup process.
  282. std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
  283. /// Keeps track of which block-value pairs are in BlockValueStack.
  284. DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
  285. /// Push BV onto BlockValueStack unless it's already in there.
  286. /// Returns true on success.
  287. bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
  288. if (!BlockValueSet.insert(BV).second)
  289. return false; // It's already in the stack.
  290. BlockValueStack.push(BV);
  291. return true;
  292. }
  293. AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
  294. const DataLayout &DL; ///< A mandatory DataLayout
  295. DominatorTree *DT; ///< An optional DT pointer.
  296. friend struct LVIValueHandle;
  297. void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
  298. SeenBlocks.insert(BB);
  299. lookup(Val)[BB] = Result;
  300. if (Result.isOverdefined())
  301. OverDefinedCache.insert(std::make_pair(BB, Val));
  302. }
  303. LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
  304. bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
  305. LVILatticeVal &Result,
  306. Instruction *CxtI = nullptr);
  307. bool hasBlockValue(Value *Val, BasicBlock *BB);
  308. // These methods process one work item and may add more. A false value
  309. // returned means that the work item was not completely processed and must
  310. // be revisited after going through the new items.
  311. bool solveBlockValue(Value *Val, BasicBlock *BB);
  312. bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
  313. Value *Val, BasicBlock *BB);
  314. bool solveBlockValuePHINode(LVILatticeVal &BBLV,
  315. PHINode *PN, BasicBlock *BB);
  316. bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
  317. Instruction *BBI, BasicBlock *BB);
  318. void mergeAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
  319. Instruction *BBI);
  320. void solve();
  321. ValueCacheEntryTy &lookup(Value *V) {
  322. return ValueCache[LVIValueHandle(V, this)];
  323. }
  324. public:
  325. /// This is the query interface to determine the lattice
  326. /// value for the specified Value* at the end of the specified block.
  327. LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
  328. Instruction *CxtI = nullptr);
  329. /// This is the query interface to determine the lattice
  330. /// value for the specified Value* at the specified instruction (generally
  331. /// from an assume intrinsic).
  332. LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
  333. /// This is the query interface to determine the lattice
  334. /// value for the specified Value* that is true on the specified edge.
  335. LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
  336. Instruction *CxtI = nullptr);
  337. /// This is the update interface to inform the cache that an edge from
  338. /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
  339. void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
  340. /// This is part of the update interface to inform the cache
  341. /// that a block has been deleted.
  342. void eraseBlock(BasicBlock *BB);
  343. /// clear - Empty the cache.
  344. void clear() {
  345. SeenBlocks.clear();
  346. ValueCache.clear();
  347. OverDefinedCache.clear();
  348. }
  349. LazyValueInfoCache(AssumptionCache *AC, const DataLayout &DL,
  350. DominatorTree *DT = nullptr)
  351. : AC(AC), DL(DL), DT(DT) {}
  352. };
  353. } // end anonymous namespace
  354. void LVIValueHandle::deleted() {
  355. typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
  356. SmallVector<OverDefinedPairTy, 4> ToErase;
  357. for (const OverDefinedPairTy &P : Parent->OverDefinedCache)
  358. if (P.second == getValPtr())
  359. ToErase.push_back(P);
  360. for (const OverDefinedPairTy &P : ToErase)
  361. Parent->OverDefinedCache.erase(P);
  362. // This erasure deallocates *this, so it MUST happen after we're done
  363. // using any and all members of *this.
  364. Parent->ValueCache.erase(*this);
  365. }
  366. void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
  367. // Shortcut if we have never seen this block.
  368. DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
  369. if (I == SeenBlocks.end())
  370. return;
  371. SeenBlocks.erase(I);
  372. SmallVector<OverDefinedPairTy, 4> ToErase;
  373. for (const OverDefinedPairTy& P : OverDefinedCache)
  374. if (P.first == BB)
  375. ToErase.push_back(P);
  376. for (const OverDefinedPairTy &P : ToErase)
  377. OverDefinedCache.erase(P);
  378. for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
  379. I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
  380. I->second.erase(BB);
  381. }
  382. void LazyValueInfoCache::solve() {
  383. while (!BlockValueStack.empty()) {
  384. std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
  385. assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
  386. if (solveBlockValue(e.second, e.first)) {
  387. // The work item was completely processed.
  388. assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
  389. assert(lookup(e.second).count(e.first) && "Result should be in cache!");
  390. BlockValueStack.pop();
  391. BlockValueSet.erase(e);
  392. } else {
  393. // More work needs to be done before revisiting.
  394. assert(BlockValueStack.top() != e && "Stack should have been pushed!");
  395. }
  396. }
  397. }
  398. bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
  399. // If already a constant, there is nothing to compute.
  400. if (isa<Constant>(Val))
  401. return true;
  402. LVIValueHandle ValHandle(Val, this);
  403. std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I =
  404. ValueCache.find(ValHandle);
  405. if (I == ValueCache.end()) return false;
  406. return I->second.count(BB);
  407. }
  408. LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
  409. // If already a constant, there is nothing to compute.
  410. if (Constant *VC = dyn_cast<Constant>(Val))
  411. return LVILatticeVal::get(VC);
  412. SeenBlocks.insert(BB);
  413. return lookup(Val)[BB];
  414. }
  415. bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
  416. if (isa<Constant>(Val))
  417. return true;
  418. if (lookup(Val).count(BB)) {
  419. // If we have a cached value, use that.
  420. DEBUG(dbgs() << " reuse BB '" << BB->getName()
  421. << "' val=" << lookup(Val)[BB] << '\n');
  422. // Since we're reusing a cached value, we don't need to update the
  423. // OverDefinedCache. The cache will have been properly updated whenever the
  424. // cached value was inserted.
  425. return true;
  426. }
  427. // Hold off inserting this value into the Cache in case we have to return
  428. // false and come back later.
  429. LVILatticeVal Res;
  430. Instruction *BBI = dyn_cast<Instruction>(Val);
  431. if (!BBI || BBI->getParent() != BB) {
  432. if (!solveBlockValueNonLocal(Res, Val, BB))
  433. return false;
  434. insertResult(Val, BB, Res);
  435. return true;
  436. }
  437. if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
  438. if (!solveBlockValuePHINode(Res, PN, BB))
  439. return false;
  440. insertResult(Val, BB, Res);
  441. return true;
  442. }
  443. if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
  444. Res = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
  445. insertResult(Val, BB, Res);
  446. return true;
  447. }
  448. // We can only analyze the definitions of certain classes of instructions
  449. // (integral binops and casts at the moment), so bail if this isn't one.
  450. LVILatticeVal Result;
  451. if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
  452. !BBI->getType()->isIntegerTy()) {
  453. DEBUG(dbgs() << " compute BB '" << BB->getName()
  454. << "' - overdefined because inst def found.\n");
  455. Res.markOverdefined();
  456. insertResult(Val, BB, Res);
  457. return true;
  458. }
  459. // FIXME: We're currently limited to binops with a constant RHS. This should
  460. // be improved.
  461. BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
  462. if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
  463. DEBUG(dbgs() << " compute BB '" << BB->getName()
  464. << "' - overdefined because inst def found.\n");
  465. Res.markOverdefined();
  466. insertResult(Val, BB, Res);
  467. return true;
  468. }
  469. if (!solveBlockValueConstantRange(Res, BBI, BB))
  470. return false;
  471. insertResult(Val, BB, Res);
  472. return true;
  473. }
  474. static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
  475. if (LoadInst *L = dyn_cast<LoadInst>(I)) {
  476. return L->getPointerAddressSpace() == 0 &&
  477. GetUnderlyingObject(L->getPointerOperand(),
  478. L->getModule()->getDataLayout()) == Ptr;
  479. }
  480. if (StoreInst *S = dyn_cast<StoreInst>(I)) {
  481. return S->getPointerAddressSpace() == 0 &&
  482. GetUnderlyingObject(S->getPointerOperand(),
  483. S->getModule()->getDataLayout()) == Ptr;
  484. }
  485. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
  486. if (MI->isVolatile()) return false;
  487. // FIXME: check whether it has a valuerange that excludes zero?
  488. ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
  489. if (!Len || Len->isZero()) return false;
  490. if (MI->getDestAddressSpace() == 0)
  491. if (GetUnderlyingObject(MI->getRawDest(),
  492. MI->getModule()->getDataLayout()) == Ptr)
  493. return true;
  494. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
  495. if (MTI->getSourceAddressSpace() == 0)
  496. if (GetUnderlyingObject(MTI->getRawSource(),
  497. MTI->getModule()->getDataLayout()) == Ptr)
  498. return true;
  499. }
  500. return false;
  501. }
  502. bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
  503. Value *Val, BasicBlock *BB) {
  504. LVILatticeVal Result; // Start Undefined.
  505. // If this is a pointer, and there's a load from that pointer in this BB,
  506. // then we know that the pointer can't be NULL.
  507. bool NotNull = false;
  508. if (Val->getType()->isPointerTy()) {
  509. if (isKnownNonNull(Val)) {
  510. NotNull = true;
  511. } else {
  512. const DataLayout &DL = BB->getModule()->getDataLayout();
  513. Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
  514. // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
  515. // inside InstructionDereferencesPointer either.
  516. if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1)) {
  517. for (Instruction &I : *BB) {
  518. if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
  519. NotNull = true;
  520. break;
  521. }
  522. }
  523. }
  524. }
  525. }
  526. // If this is the entry block, we must be asking about an argument. The
  527. // value is overdefined.
  528. if (BB == &BB->getParent()->getEntryBlock()) {
  529. assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
  530. if (NotNull) {
  531. PointerType *PTy = cast<PointerType>(Val->getType());
  532. Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
  533. } else {
  534. Result.markOverdefined();
  535. }
  536. BBLV = Result;
  537. return true;
  538. }
  539. // Loop over all of our predecessors, merging what we know from them into
  540. // result.
  541. bool EdgesMissing = false;
  542. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  543. LVILatticeVal EdgeResult;
  544. EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
  545. if (EdgesMissing)
  546. continue;
  547. Result.mergeIn(EdgeResult, DL);
  548. // If we hit overdefined, exit early. The BlockVals entry is already set
  549. // to overdefined.
  550. if (Result.isOverdefined()) {
  551. DEBUG(dbgs() << " compute BB '" << BB->getName()
  552. << "' - overdefined because of pred.\n");
  553. // If we previously determined that this is a pointer that can't be null
  554. // then return that rather than giving up entirely.
  555. if (NotNull) {
  556. PointerType *PTy = cast<PointerType>(Val->getType());
  557. Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
  558. }
  559. BBLV = Result;
  560. return true;
  561. }
  562. }
  563. if (EdgesMissing)
  564. return false;
  565. // Return the merged value, which is more precise than 'overdefined'.
  566. assert(!Result.isOverdefined());
  567. BBLV = Result;
  568. return true;
  569. }
  570. bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
  571. PHINode *PN, BasicBlock *BB) {
  572. LVILatticeVal Result; // Start Undefined.
  573. // Loop over all of our predecessors, merging what we know from them into
  574. // result.
  575. bool EdgesMissing = false;
  576. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  577. BasicBlock *PhiBB = PN->getIncomingBlock(i);
  578. Value *PhiVal = PN->getIncomingValue(i);
  579. LVILatticeVal EdgeResult;
  580. // Note that we can provide PN as the context value to getEdgeValue, even
  581. // though the results will be cached, because PN is the value being used as
  582. // the cache key in the caller.
  583. EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
  584. if (EdgesMissing)
  585. continue;
  586. Result.mergeIn(EdgeResult, DL);
  587. // If we hit overdefined, exit early. The BlockVals entry is already set
  588. // to overdefined.
  589. if (Result.isOverdefined()) {
  590. DEBUG(dbgs() << " compute BB '" << BB->getName()
  591. << "' - overdefined because of pred.\n");
  592. BBLV = Result;
  593. return true;
  594. }
  595. }
  596. if (EdgesMissing)
  597. return false;
  598. // Return the merged value, which is more precise than 'overdefined'.
  599. assert(!Result.isOverdefined() && "Possible PHI in entry block?");
  600. BBLV = Result;
  601. return true;
  602. }
  603. static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
  604. LVILatticeVal &Result,
  605. bool isTrueDest = true);
  606. // If we can determine a constant range for the value Val in the context
  607. // provided by the instruction BBI, then merge it into BBLV. If we did find a
  608. // constant range, return true.
  609. void LazyValueInfoCache::mergeAssumeBlockValueConstantRange(Value *Val,
  610. LVILatticeVal &BBLV,
  611. Instruction *BBI) {
  612. BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
  613. if (!BBI)
  614. return;
  615. for (auto &AssumeVH : AC->assumptions()) {
  616. if (!AssumeVH)
  617. continue;
  618. auto *I = cast<CallInst>(AssumeVH);
  619. if (!isValidAssumeForContext(I, BBI, DT))
  620. continue;
  621. Value *C = I->getArgOperand(0);
  622. if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
  623. LVILatticeVal Result;
  624. if (getValueFromFromCondition(Val, ICI, Result)) {
  625. if (BBLV.isOverdefined())
  626. BBLV = Result;
  627. else
  628. BBLV.mergeIn(Result, DL);
  629. }
  630. }
  631. }
  632. }
  633. bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
  634. Instruction *BBI,
  635. BasicBlock *BB) {
  636. // Figure out the range of the LHS. If that fails, bail.
  637. if (!hasBlockValue(BBI->getOperand(0), BB)) {
  638. if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
  639. return false;
  640. BBLV.markOverdefined();
  641. return true;
  642. }
  643. LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
  644. mergeAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
  645. if (!LHSVal.isConstantRange()) {
  646. BBLV.markOverdefined();
  647. return true;
  648. }
  649. ConstantRange LHSRange = LHSVal.getConstantRange();
  650. ConstantRange RHSRange(1);
  651. IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
  652. if (isa<BinaryOperator>(BBI)) {
  653. if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
  654. RHSRange = ConstantRange(RHS->getValue());
  655. } else {
  656. BBLV.markOverdefined();
  657. return true;
  658. }
  659. }
  660. // NOTE: We're currently limited by the set of operations that ConstantRange
  661. // can evaluate symbolically. Enhancing that set will allows us to analyze
  662. // more definitions.
  663. LVILatticeVal Result;
  664. switch (BBI->getOpcode()) {
  665. case Instruction::Add:
  666. Result.markConstantRange(LHSRange.add(RHSRange));
  667. break;
  668. case Instruction::Sub:
  669. Result.markConstantRange(LHSRange.sub(RHSRange));
  670. break;
  671. case Instruction::Mul:
  672. Result.markConstantRange(LHSRange.multiply(RHSRange));
  673. break;
  674. case Instruction::UDiv:
  675. Result.markConstantRange(LHSRange.udiv(RHSRange));
  676. break;
  677. case Instruction::Shl:
  678. Result.markConstantRange(LHSRange.shl(RHSRange));
  679. break;
  680. case Instruction::LShr:
  681. Result.markConstantRange(LHSRange.lshr(RHSRange));
  682. break;
  683. case Instruction::Trunc:
  684. Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
  685. break;
  686. case Instruction::SExt:
  687. Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
  688. break;
  689. case Instruction::ZExt:
  690. Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
  691. break;
  692. case Instruction::BitCast:
  693. Result.markConstantRange(LHSRange);
  694. break;
  695. case Instruction::And:
  696. Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
  697. break;
  698. case Instruction::Or:
  699. Result.markConstantRange(LHSRange.binaryOr(RHSRange));
  700. break;
  701. // Unhandled instructions are overdefined.
  702. default:
  703. DEBUG(dbgs() << " compute BB '" << BB->getName()
  704. << "' - overdefined because inst def found.\n");
  705. Result.markOverdefined();
  706. break;
  707. }
  708. BBLV = Result;
  709. return true;
  710. }
  711. bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
  712. LVILatticeVal &Result, bool isTrueDest) {
  713. if (ICI && isa<Constant>(ICI->getOperand(1))) {
  714. if (ICI->isEquality() && ICI->getOperand(0) == Val) {
  715. // We know that V has the RHS constant if this is a true SETEQ or
  716. // false SETNE.
  717. if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
  718. Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
  719. else
  720. Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
  721. return true;
  722. }
  723. // Recognize the range checking idiom that InstCombine produces.
  724. // (X-C1) u< C2 --> [C1, C1+C2)
  725. ConstantInt *NegOffset = nullptr;
  726. if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
  727. match(ICI->getOperand(0), m_Add(m_Specific(Val),
  728. m_ConstantInt(NegOffset)));
  729. ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
  730. if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
  731. // Calculate the range of values that are allowed by the comparison
  732. ConstantRange CmpRange(CI->getValue());
  733. ConstantRange TrueValues =
  734. ConstantRange::makeAllowedICmpRegion(ICI->getPredicate(), CmpRange);
  735. if (NegOffset) // Apply the offset from above.
  736. TrueValues = TrueValues.subtract(NegOffset->getValue());
  737. // If we're interested in the false dest, invert the condition.
  738. if (!isTrueDest) TrueValues = TrueValues.inverse();
  739. Result = LVILatticeVal::getRange(TrueValues);
  740. return true;
  741. }
  742. }
  743. return false;
  744. }
  745. /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
  746. /// Val is not constrained on the edge.
  747. static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
  748. BasicBlock *BBTo, LVILatticeVal &Result) {
  749. // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
  750. // know that v != 0.
  751. if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
  752. // If this is a conditional branch and only one successor goes to BBTo, then
  753. // we may be able to infer something from the condition.
  754. if (BI->isConditional() &&
  755. BI->getSuccessor(0) != BI->getSuccessor(1)) {
  756. bool isTrueDest = BI->getSuccessor(0) == BBTo;
  757. assert(BI->getSuccessor(!isTrueDest) == BBTo &&
  758. "BBTo isn't a successor of BBFrom");
  759. // If V is the condition of the branch itself, then we know exactly what
  760. // it is.
  761. if (BI->getCondition() == Val) {
  762. Result = LVILatticeVal::get(ConstantInt::get(
  763. Type::getInt1Ty(Val->getContext()), isTrueDest));
  764. return true;
  765. }
  766. // If the condition of the branch is an equality comparison, we may be
  767. // able to infer the value.
  768. if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
  769. if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
  770. return true;
  771. }
  772. }
  773. // If the edge was formed by a switch on the value, then we may know exactly
  774. // what it is.
  775. if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
  776. if (SI->getCondition() != Val)
  777. return false;
  778. bool DefaultCase = SI->getDefaultDest() == BBTo;
  779. unsigned BitWidth = Val->getType()->getIntegerBitWidth();
  780. ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
  781. for (SwitchInst::CaseIt i : SI->cases()) {
  782. ConstantRange EdgeVal(i.getCaseValue()->getValue());
  783. if (DefaultCase) {
  784. // It is possible that the default destination is the destination of
  785. // some cases. There is no need to perform difference for those cases.
  786. if (i.getCaseSuccessor() != BBTo)
  787. EdgesVals = EdgesVals.difference(EdgeVal);
  788. } else if (i.getCaseSuccessor() == BBTo)
  789. EdgesVals = EdgesVals.unionWith(EdgeVal);
  790. }
  791. Result = LVILatticeVal::getRange(EdgesVals);
  792. return true;
  793. }
  794. return false;
  795. }
  796. /// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
  797. /// the basic block if the edge does not constrain Val.
  798. bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
  799. BasicBlock *BBTo, LVILatticeVal &Result,
  800. Instruction *CxtI) {
  801. // If already a constant, there is nothing to compute.
  802. if (Constant *VC = dyn_cast<Constant>(Val)) {
  803. Result = LVILatticeVal::get(VC);
  804. return true;
  805. }
  806. if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
  807. if (!Result.isConstantRange() ||
  808. Result.getConstantRange().getSingleElement())
  809. return true;
  810. // FIXME: this check should be moved to the beginning of the function when
  811. // LVI better supports recursive values. Even for the single value case, we
  812. // can intersect to detect dead code (an empty range).
  813. if (!hasBlockValue(Val, BBFrom)) {
  814. if (pushBlockValue(std::make_pair(BBFrom, Val)))
  815. return false;
  816. Result.markOverdefined();
  817. return true;
  818. }
  819. // Try to intersect ranges of the BB and the constraint on the edge.
  820. LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
  821. mergeAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
  822. // See note on the use of the CxtI with mergeAssumeBlockValueConstantRange,
  823. // and caching, below.
  824. mergeAssumeBlockValueConstantRange(Val, InBlock, CxtI);
  825. if (!InBlock.isConstantRange())
  826. return true;
  827. ConstantRange Range =
  828. Result.getConstantRange().intersectWith(InBlock.getConstantRange());
  829. Result = LVILatticeVal::getRange(Range);
  830. return true;
  831. }
  832. if (!hasBlockValue(Val, BBFrom)) {
  833. if (pushBlockValue(std::make_pair(BBFrom, Val)))
  834. return false;
  835. Result.markOverdefined();
  836. return true;
  837. }
  838. // If we couldn't compute the value on the edge, use the value from the BB.
  839. Result = getBlockValue(Val, BBFrom);
  840. mergeAssumeBlockValueConstantRange(Val, Result, BBFrom->getTerminator());
  841. // We can use the context instruction (generically the ultimate instruction
  842. // the calling pass is trying to simplify) here, even though the result of
  843. // this function is generally cached when called from the solve* functions
  844. // (and that cached result might be used with queries using a different
  845. // context instruction), because when this function is called from the solve*
  846. // functions, the context instruction is not provided. When called from
  847. // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
  848. // but then the result is not cached.
  849. mergeAssumeBlockValueConstantRange(Val, Result, CxtI);
  850. return true;
  851. }
  852. LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
  853. Instruction *CxtI) {
  854. DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
  855. << BB->getName() << "'\n");
  856. assert(BlockValueStack.empty() && BlockValueSet.empty());
  857. pushBlockValue(std::make_pair(BB, V));
  858. solve();
  859. LVILatticeVal Result = getBlockValue(V, BB);
  860. mergeAssumeBlockValueConstantRange(V, Result, CxtI);
  861. DEBUG(dbgs() << " Result = " << Result << "\n");
  862. return Result;
  863. }
  864. LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
  865. DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
  866. << CxtI->getName() << "'\n");
  867. LVILatticeVal Result;
  868. mergeAssumeBlockValueConstantRange(V, Result, CxtI);
  869. DEBUG(dbgs() << " Result = " << Result << "\n");
  870. return Result;
  871. }
  872. LVILatticeVal LazyValueInfoCache::
  873. getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
  874. Instruction *CxtI) {
  875. DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
  876. << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
  877. LVILatticeVal Result;
  878. if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
  879. solve();
  880. bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
  881. (void)WasFastQuery;
  882. assert(WasFastQuery && "More work to do after problem solved?");
  883. }
  884. DEBUG(dbgs() << " Result = " << Result << "\n");
  885. return Result;
  886. }
  887. void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
  888. BasicBlock *NewSucc) {
  889. // When an edge in the graph has been threaded, values that we could not
  890. // determine a value for before (i.e. were marked overdefined) may be possible
  891. // to solve now. We do NOT try to proactively update these values. Instead,
  892. // we clear their entries from the cache, and allow lazy updating to recompute
  893. // them when needed.
  894. // The updating process is fairly simple: we need to drop cached info
  895. // for all values that were marked overdefined in OldSucc, and for those same
  896. // values in any successor of OldSucc (except NewSucc) in which they were
  897. // also marked overdefined.
  898. std::vector<BasicBlock*> worklist;
  899. worklist.push_back(OldSucc);
  900. DenseSet<Value*> ClearSet;
  901. for (OverDefinedPairTy &P : OverDefinedCache)
  902. if (P.first == OldSucc)
  903. ClearSet.insert(P.second);
  904. // Use a worklist to perform a depth-first search of OldSucc's successors.
  905. // NOTE: We do not need a visited list since any blocks we have already
  906. // visited will have had their overdefined markers cleared already, and we
  907. // thus won't loop to their successors.
  908. while (!worklist.empty()) {
  909. BasicBlock *ToUpdate = worklist.back();
  910. worklist.pop_back();
  911. // Skip blocks only accessible through NewSucc.
  912. if (ToUpdate == NewSucc) continue;
  913. bool changed = false;
  914. for (Value *V : ClearSet) {
  915. // If a value was marked overdefined in OldSucc, and is here too...
  916. DenseSet<OverDefinedPairTy>::iterator OI =
  917. OverDefinedCache.find(std::make_pair(ToUpdate, V));
  918. if (OI == OverDefinedCache.end()) continue;
  919. // Remove it from the caches.
  920. ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(V, this)];
  921. ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
  922. assert(CI != Entry.end() && "Couldn't find entry to update?");
  923. Entry.erase(CI);
  924. OverDefinedCache.erase(OI);
  925. // If we removed anything, then we potentially need to update
  926. // blocks successors too.
  927. changed = true;
  928. }
  929. if (!changed) continue;
  930. worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
  931. }
  932. }
  933. //===----------------------------------------------------------------------===//
  934. // LazyValueInfo Impl
  935. //===----------------------------------------------------------------------===//
  936. /// This lazily constructs the LazyValueInfoCache.
  937. static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
  938. const DataLayout *DL,
  939. DominatorTree *DT = nullptr) {
  940. if (!PImpl) {
  941. assert(DL && "getCache() called with a null DataLayout");
  942. PImpl = new LazyValueInfoCache(AC, *DL, DT);
  943. }
  944. return *static_cast<LazyValueInfoCache*>(PImpl);
  945. }
  946. bool LazyValueInfo::runOnFunction(Function &F) {
  947. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  948. const DataLayout &DL = F.getParent()->getDataLayout();
  949. DominatorTreeWrapperPass *DTWP =
  950. getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  951. DT = DTWP ? &DTWP->getDomTree() : nullptr;
  952. TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  953. if (PImpl)
  954. getCache(PImpl, AC, &DL, DT).clear();
  955. // Fully lazy.
  956. return false;
  957. }
  958. void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
  959. AU.setPreservesAll();
  960. AU.addRequired<AssumptionCacheTracker>();
  961. AU.addRequired<TargetLibraryInfoWrapperPass>();
  962. }
  963. void LazyValueInfo::releaseMemory() {
  964. // If the cache was allocated, free it.
  965. if (PImpl) {
  966. delete &getCache(PImpl, AC, nullptr);
  967. PImpl = nullptr;
  968. }
  969. }
  970. Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
  971. Instruction *CxtI) {
  972. const DataLayout &DL = BB->getModule()->getDataLayout();
  973. LVILatticeVal Result =
  974. getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
  975. if (Result.isConstant())
  976. return Result.getConstant();
  977. if (Result.isConstantRange()) {
  978. ConstantRange CR = Result.getConstantRange();
  979. if (const APInt *SingleVal = CR.getSingleElement())
  980. return ConstantInt::get(V->getContext(), *SingleVal);
  981. }
  982. return nullptr;
  983. }
  984. /// Determine whether the specified value is known to be a
  985. /// constant on the specified edge. Return null if not.
  986. Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
  987. BasicBlock *ToBB,
  988. Instruction *CxtI) {
  989. const DataLayout &DL = FromBB->getModule()->getDataLayout();
  990. LVILatticeVal Result =
  991. getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
  992. if (Result.isConstant())
  993. return Result.getConstant();
  994. if (Result.isConstantRange()) {
  995. ConstantRange CR = Result.getConstantRange();
  996. if (const APInt *SingleVal = CR.getSingleElement())
  997. return ConstantInt::get(V->getContext(), *SingleVal);
  998. }
  999. return nullptr;
  1000. }
  1001. static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
  1002. LVILatticeVal &Result,
  1003. const DataLayout &DL,
  1004. TargetLibraryInfo *TLI) {
  1005. // If we know the value is a constant, evaluate the conditional.
  1006. Constant *Res = nullptr;
  1007. if (Result.isConstant()) {
  1008. Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
  1009. TLI);
  1010. if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
  1011. return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
  1012. return LazyValueInfo::Unknown;
  1013. }
  1014. if (Result.isConstantRange()) {
  1015. ConstantInt *CI = dyn_cast<ConstantInt>(C);
  1016. if (!CI) return LazyValueInfo::Unknown;
  1017. ConstantRange CR = Result.getConstantRange();
  1018. if (Pred == ICmpInst::ICMP_EQ) {
  1019. if (!CR.contains(CI->getValue()))
  1020. return LazyValueInfo::False;
  1021. if (CR.isSingleElement() && CR.contains(CI->getValue()))
  1022. return LazyValueInfo::True;
  1023. } else if (Pred == ICmpInst::ICMP_NE) {
  1024. if (!CR.contains(CI->getValue()))
  1025. return LazyValueInfo::True;
  1026. if (CR.isSingleElement() && CR.contains(CI->getValue()))
  1027. return LazyValueInfo::False;
  1028. }
  1029. // Handle more complex predicates.
  1030. ConstantRange TrueValues =
  1031. ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
  1032. if (TrueValues.contains(CR))
  1033. return LazyValueInfo::True;
  1034. if (TrueValues.inverse().contains(CR))
  1035. return LazyValueInfo::False;
  1036. return LazyValueInfo::Unknown;
  1037. }
  1038. if (Result.isNotConstant()) {
  1039. // If this is an equality comparison, we can try to fold it knowing that
  1040. // "V != C1".
  1041. if (Pred == ICmpInst::ICMP_EQ) {
  1042. // !C1 == C -> false iff C1 == C.
  1043. Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
  1044. Result.getNotConstant(), C, DL,
  1045. TLI);
  1046. if (Res->isNullValue())
  1047. return LazyValueInfo::False;
  1048. } else if (Pred == ICmpInst::ICMP_NE) {
  1049. // !C1 != C -> true iff C1 == C.
  1050. Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
  1051. Result.getNotConstant(), C, DL,
  1052. TLI);
  1053. if (Res->isNullValue())
  1054. return LazyValueInfo::True;
  1055. }
  1056. return LazyValueInfo::Unknown;
  1057. }
  1058. return LazyValueInfo::Unknown;
  1059. }
  1060. /// Determine whether the specified value comparison with a constant is known to
  1061. /// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
  1062. LazyValueInfo::Tristate
  1063. LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
  1064. BasicBlock *FromBB, BasicBlock *ToBB,
  1065. Instruction *CxtI) {
  1066. const DataLayout &DL = FromBB->getModule()->getDataLayout();
  1067. LVILatticeVal Result =
  1068. getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
  1069. return getPredicateResult(Pred, C, Result, DL, TLI);
  1070. }
  1071. LazyValueInfo::Tristate
  1072. LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
  1073. Instruction *CxtI) {
  1074. const DataLayout &DL = CxtI->getModule()->getDataLayout();
  1075. LVILatticeVal Result = getCache(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
  1076. Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
  1077. if (Ret != Unknown)
  1078. return Ret;
  1079. // TODO: Move this logic inside getValueAt so that it can be cached rather
  1080. // than re-queried on each call. This would also allow us to merge the
  1081. // underlying lattice values to get more information
  1082. if (CxtI) {
  1083. // For a comparison where the V is outside this block, it's possible
  1084. // that we've branched on it before. Look to see if the value is known
  1085. // on all incoming edges.
  1086. BasicBlock *BB = CxtI->getParent();
  1087. pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
  1088. if (PI != PE &&
  1089. (!isa<Instruction>(V) ||
  1090. cast<Instruction>(V)->getParent() != BB)) {
  1091. // For predecessor edge, determine if the comparison is true or false
  1092. // on that edge. If they're all true or all false, we can conclude
  1093. // the value of the comparison in this block.
  1094. Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
  1095. if (Baseline != Unknown) {
  1096. // Check that all remaining incoming values match the first one.
  1097. while (++PI != PE) {
  1098. Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
  1099. if (Ret != Baseline) break;
  1100. }
  1101. // If we terminated early, then one of the values didn't match.
  1102. if (PI == PE) {
  1103. return Baseline;
  1104. }
  1105. }
  1106. }
  1107. }
  1108. return Unknown;
  1109. }
  1110. void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
  1111. BasicBlock *NewSucc) {
  1112. if (PImpl) {
  1113. const DataLayout &DL = PredBB->getModule()->getDataLayout();
  1114. getCache(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
  1115. }
  1116. }
  1117. void LazyValueInfo::eraseBlock(BasicBlock *BB) {
  1118. if (PImpl) {
  1119. const DataLayout &DL = BB->getModule()->getDataLayout();
  1120. getCache(PImpl, AC, &DL, DT).eraseBlock(BB);
  1121. }
  1122. }