2
0

DxilValueCache.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. //===---------- DxilValueCache.cpp - Dxil Constant Value Cache ------------===//
  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. // Utility to compute and cache constant values for instructions.
  11. //
  12. #include "llvm/Pass.h"
  13. #include "dxc/DXIL/DxilConstants.h"
  14. #include "llvm/Analysis/DxilSimplify.h"
  15. #include "llvm/IR/Module.h"
  16. #include "llvm/IR/GlobalVariable.h"
  17. #include "llvm/IR/Constants.h"
  18. #include "llvm/IR/Instructions.h"
  19. #include "llvm/IR/Operator.h"
  20. #include "llvm/IR/CFG.h"
  21. #include "llvm/Support/Debug.h"
  22. #include "llvm/IR/Dominators.h"
  23. #include "llvm/Transforms/Scalar.h"
  24. #include "llvm/Analysis/InstructionSimplify.h"
  25. #include "llvm/Analysis/ConstantFolding.h"
  26. #include "llvm/ADT/Statistic.h"
  27. #include "llvm/Analysis/DxilValueCache.h"
  28. #include <unordered_set>
  29. #define DEBUG_TYPE "dxil-value-cache"
  30. using namespace llvm;
  31. static
  32. bool IsConstantTrue(const Value *V) {
  33. if (const ConstantInt *C = dyn_cast<ConstantInt>(V))
  34. return C->getLimitedValue() != 0;
  35. return false;
  36. }
  37. static
  38. bool IsConstantFalse(const Value *V) {
  39. if (const ConstantInt *C = dyn_cast<ConstantInt>(V))
  40. return C->getLimitedValue() == 0;
  41. return false;
  42. }
  43. static
  44. bool IsEntryBlock(const BasicBlock *BB) {
  45. return BB == &BB->getParent()->getEntryBlock();
  46. }
  47. void DxilValueCache::MarkAlwaysReachable(BasicBlock *BB) {
  48. ValueMap.Set(BB, ConstantInt::get(Type::getInt1Ty(BB->getContext()), 1));
  49. }
  50. void DxilValueCache::MarkUnreachable(BasicBlock *BB) {
  51. ValueMap.Set(BB, ConstantInt::get(Type::getInt1Ty(BB->getContext()), 0));
  52. }
  53. bool DxilValueCache::IsAlwaysReachable_(BasicBlock *BB) {
  54. if (Value *V = ValueMap.Get(BB))
  55. if (IsConstantTrue(V))
  56. return true;
  57. return false;
  58. }
  59. bool DxilValueCache::MayBranchTo(BasicBlock *A, BasicBlock *B) {
  60. BranchInst *Br = dyn_cast<BranchInst>(A->getTerminator());
  61. if (!Br) return false;
  62. if (Br->isUnconditional() && Br->getSuccessor(0) == B)
  63. return true;
  64. if (ConstantInt *C = dyn_cast<ConstantInt>(TryGetCachedValue(Br->getCondition()))) {
  65. unsigned SuccIndex = C->getLimitedValue() != 0 ? 0 : 1;
  66. return Br->getSuccessor(SuccIndex) == B;
  67. }
  68. return true;
  69. }
  70. bool DxilValueCache::IsUnreachable_(BasicBlock *BB) {
  71. if (Value *V = ValueMap.Get(BB))
  72. if (IsConstantFalse(V))
  73. return true;
  74. return false;
  75. }
  76. Value *DxilValueCache::ProcessAndSimplify_PHI(Instruction *I, DominatorTree *DT) {
  77. PHINode *PN = cast<PHINode>(I);
  78. BasicBlock *SoleIncoming = nullptr;
  79. bool Unreachable = true;
  80. Value *Simplified = nullptr;
  81. for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
  82. BasicBlock *PredBB = PN->getIncomingBlock(i);
  83. if (IsUnreachable_(PredBB))
  84. continue;
  85. Unreachable = false;
  86. if (MayBranchTo(PredBB, PN->getParent())) {
  87. if (SoleIncoming) {
  88. SoleIncoming = nullptr;
  89. break;
  90. }
  91. SoleIncoming = PredBB;
  92. }
  93. }
  94. if (Unreachable) {
  95. return UndefValue::get(I->getType());
  96. }
  97. if (SoleIncoming) {
  98. Value *V = TryGetCachedValue(PN->getIncomingValueForBlock(SoleIncoming));
  99. if (isa<Constant>(V))
  100. Simplified = V;
  101. else if (Instruction *I = dyn_cast<Instruction>(V)) {
  102. // If this is an instruction, we have to make sure it
  103. // dominates this PHI.
  104. // There are several conditions that qualify:
  105. // 1. There's only one predecessor
  106. // 2. If the instruction is in the entry block, then it must dominate
  107. // 3. If we are provided with a Dominator tree, and it decides that
  108. // it dominates.
  109. if (PN->getNumIncomingValues() == 1 ||
  110. IsEntryBlock(I->getParent()) ||
  111. (DT && DT->dominates(I, PN)))
  112. {
  113. Simplified = I;
  114. }
  115. }
  116. }
  117. // If we coulnd't deduce it, run the LLVM stock simplification to see
  118. // if we could do anything.
  119. if (!Simplified)
  120. Simplified = llvm::SimplifyInstruction(I, I->getModule()->getDataLayout());
  121. // One last step, to check if we have anything cached for whatever we
  122. // simplified to.
  123. if (Simplified)
  124. Simplified = TryGetCachedValue(Simplified);
  125. return Simplified;
  126. }
  127. Value *DxilValueCache::ProcessAndSimplify_Br(Instruction *I, DominatorTree *DT) {
  128. // The *only* reason we're paying special attention to the
  129. // branch inst, is to mark certain Basic Blocks as always
  130. // reachable or unreachable.
  131. BranchInst *Br = cast<BranchInst>(I);
  132. BasicBlock *BB = Br->getParent();
  133. if (Br->isConditional()) {
  134. BasicBlock *TrueSucc = Br->getSuccessor(0);
  135. BasicBlock *FalseSucc = Br->getSuccessor(1);
  136. Value *Cond = TryGetCachedValue(Br->getCondition());
  137. if (IsUnreachable_(BB)) {
  138. if (FalseSucc->getSinglePredecessor())
  139. MarkUnreachable(FalseSucc);
  140. if (TrueSucc->getSinglePredecessor())
  141. MarkUnreachable(TrueSucc);
  142. }
  143. else if (IsConstantTrue(Cond)) {
  144. if (IsAlwaysReachable_(BB)) {
  145. MarkAlwaysReachable(TrueSucc);
  146. }
  147. if (FalseSucc->getSinglePredecessor())
  148. MarkUnreachable(FalseSucc);
  149. }
  150. else if (IsConstantFalse(Cond)) {
  151. if (IsAlwaysReachable_(BB)) {
  152. MarkAlwaysReachable(FalseSucc);
  153. }
  154. if (TrueSucc->getSinglePredecessor())
  155. MarkUnreachable(TrueSucc);
  156. }
  157. }
  158. else {
  159. BasicBlock *Succ = Br->getSuccessor(0);
  160. if (IsAlwaysReachable_(BB))
  161. MarkAlwaysReachable(Succ);
  162. else if (Succ->getSinglePredecessor() && IsUnreachable_(BB))
  163. MarkUnreachable(Succ);
  164. }
  165. return nullptr;
  166. }
  167. Value *DxilValueCache::ProcessAndSimplify_Load(Instruction *I, DominatorTree *DT) {
  168. LoadInst *LI = cast<LoadInst>(I);
  169. Value *V = TryGetCachedValue(LI->getPointerOperand());
  170. if (Constant *ConstPtr = dyn_cast<Constant>(V)) {
  171. const DataLayout &DL = I->getModule()->getDataLayout();
  172. return llvm::ConstantFoldLoadFromConstPtr(ConstPtr, DL);
  173. }
  174. return nullptr;
  175. }
  176. Value *DxilValueCache::SimplifyAndCacheResult(Instruction *I, DominatorTree *DT) {
  177. const DataLayout &DL = I->getModule()->getDataLayout();
  178. Value *Simplified = nullptr;
  179. if (Instruction::Br == I->getOpcode()) {
  180. Simplified = ProcessAndSimplify_Br(I, DT);
  181. }
  182. else if (Instruction::PHI == I->getOpcode()) {
  183. Simplified = ProcessAndSimplify_PHI(I, DT);
  184. }
  185. else if (Instruction::Load == I->getOpcode()) {
  186. Simplified = ProcessAndSimplify_Load(I, DT);
  187. }
  188. else if (Instruction::GetElementPtr == I->getOpcode()) {
  189. SmallVector<Value *, 4> Ops;
  190. for (unsigned i = 0; i < I->getNumOperands(); i++)
  191. Ops.push_back(TryGetCachedValue(I->getOperand(i)));
  192. Simplified = llvm::SimplifyGEPInst(Ops, DL, nullptr, DT);
  193. }
  194. else if (Instruction::Call == I->getOpcode()) {
  195. Module *M = I->getModule();
  196. CallInst *CI = cast<CallInst>(I);
  197. Value *Callee = CI->getCalledValue();
  198. Function *CalledFunction = dyn_cast<Function>(Callee);
  199. if (CalledFunction && CalledFunction->getName() == hlsl::DXIL::kDxBreakFuncName) {
  200. llvm::Type *i1Ty = llvm::Type::getInt1Ty(M->getContext());
  201. Simplified = llvm::ConstantInt::get(i1Ty, 1);
  202. }
  203. else {
  204. SmallVector<Value *,16> Args;
  205. for (unsigned i = 0; i < CI->getNumArgOperands(); i++) {
  206. Args.push_back(TryGetCachedValue(CI->getArgOperand(i)));
  207. }
  208. if (CalledFunction && hlsl::CanSimplify(CalledFunction)) {
  209. Simplified = hlsl::SimplifyDxilCall(CalledFunction, Args, CI, /* MayInsert */ false);
  210. }
  211. else {
  212. Simplified = llvm::SimplifyCall(Callee, Args, DL, nullptr, DT);
  213. }
  214. }
  215. }
  216. // The rest of the checks use LLVM stock simplifications
  217. else if (I->isBinaryOp()) {
  218. Simplified =
  219. llvm::SimplifyBinOp(
  220. I->getOpcode(),
  221. TryGetCachedValue(I->getOperand(0)),
  222. TryGetCachedValue(I->getOperand(1)),
  223. DL);
  224. }
  225. else if (GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(I)) {
  226. SmallVector<Value *, 4> Values;
  227. for (Value *V : Gep->operand_values()) {
  228. Values.push_back(TryGetCachedValue(V));
  229. }
  230. Simplified =
  231. llvm::SimplifyGEPInst(Values, DL, nullptr, DT, nullptr, nullptr);
  232. }
  233. else if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
  234. Simplified =
  235. llvm::SimplifyCmpInst(Cmp->getPredicate(),
  236. TryGetCachedValue(I->getOperand(0)),
  237. TryGetCachedValue(I->getOperand(1)),
  238. DL);
  239. }
  240. else if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
  241. Simplified =
  242. llvm::SimplifySelectInst(
  243. TryGetCachedValue(Select->getCondition()),
  244. TryGetCachedValue(Select->getTrueValue()),
  245. TryGetCachedValue(Select->getFalseValue()),
  246. DL
  247. );
  248. }
  249. else if (ExtractElementInst *IE = dyn_cast<ExtractElementInst>(I)) {
  250. Simplified =
  251. llvm::SimplifyExtractElementInst(
  252. TryGetCachedValue(IE->getVectorOperand()),
  253. TryGetCachedValue(IE->getIndexOperand()),
  254. DL, nullptr, DT);
  255. }
  256. else if (CastInst *Cast = dyn_cast<CastInst>(I)) {
  257. Simplified =
  258. llvm::SimplifyCastInst(
  259. Cast->getOpcode(),
  260. TryGetCachedValue(Cast->getOperand(0)),
  261. Cast->getType(), DL);
  262. }
  263. if (Simplified && isa<Constant>(Simplified))
  264. ValueMap.Set(I, Simplified);
  265. return Simplified;
  266. }
  267. bool DxilValueCache::WeakValueMap::Seen(Value *V) {
  268. auto FindIt = Map.find(V);
  269. if (FindIt == Map.end())
  270. return false;
  271. auto &Entry = FindIt->second;
  272. if (Entry.IsStale())
  273. return false;
  274. return Entry.Value;
  275. }
  276. Value *DxilValueCache::WeakValueMap::Get(Value *V) {
  277. auto FindIt = Map.find(V);
  278. if (FindIt == Map.end())
  279. return nullptr;
  280. auto &Entry = FindIt->second;
  281. if (Entry.IsStale())
  282. return nullptr;
  283. Value *Result = Entry.Value;
  284. if (Result == GetSentinel(V->getContext()))
  285. return nullptr;
  286. return Result;
  287. }
  288. void DxilValueCache::WeakValueMap::SetSentinel(Value *Key) {
  289. Map[Key].Set(Key, GetSentinel(Key->getContext()));
  290. }
  291. Value *DxilValueCache::WeakValueMap::GetSentinel(LLVMContext &Ctx) {
  292. if (!Sentinel) {
  293. Sentinel.reset( PHINode::Create(Type::getInt1Ty(Ctx), 0) );
  294. }
  295. return Sentinel.get();
  296. }
  297. void DxilValueCache::WeakValueMap::ResetUnknowns() {
  298. if (!Sentinel)
  299. return;
  300. for (auto it = Map.begin(); it != Map.end(); it++) {
  301. if (it->second.Value == Sentinel.get())
  302. it->second.Value = nullptr;
  303. }
  304. }
  305. LLVM_DUMP_METHOD
  306. void DxilValueCache::WeakValueMap::dump() const {
  307. for (auto It = Map.begin(), E = Map.end(); It != E; It++) {
  308. const Value *Key = It->first;
  309. if (It->second.IsStale())
  310. continue;
  311. const Value *V = It->second.Value;
  312. bool IsSentinel = Sentinel && V == Sentinel.get();
  313. if (const BasicBlock *BB = dyn_cast<BasicBlock>(Key)) {
  314. dbgs() << "[BB]" << BB->getName() << " -> ";
  315. if (IsSentinel)
  316. dbgs() << "NO_VALUE";
  317. else {
  318. if (IsConstantTrue(V))
  319. dbgs() << "Always Reachable!";
  320. else if (IsConstantFalse(V))
  321. dbgs() << "Never Reachable!";
  322. }
  323. }
  324. else {
  325. dbgs() << Key->getName() << " -> ";
  326. if (IsSentinel)
  327. dbgs() << "NO_VALUE";
  328. else
  329. dbgs() << *V;
  330. }
  331. dbgs() << "\n";
  332. }
  333. }
  334. void DxilValueCache::WeakValueMap::Set(Value *Key, Value *V) {
  335. Map[Key].Set(Key, V);
  336. }
  337. // If there's a cached value, return it. Otherwise, return
  338. // the value itself.
  339. Value *DxilValueCache::TryGetCachedValue(Value *V) {
  340. if (Value *Simplified = ValueMap.Get(V))
  341. return Simplified;
  342. return V;
  343. }
  344. DxilValueCache::DxilValueCache() : ImmutablePass(ID) {
  345. initializeDxilValueCachePass(*PassRegistry::getPassRegistry());
  346. }
  347. const char *DxilValueCache::getPassName() const {
  348. return "Dxil Value Cache";
  349. }
  350. Value *DxilValueCache::GetValue(Value *V, DominatorTree *DT) {
  351. if (dyn_cast<Constant>(V))
  352. return V;
  353. if (Value *NewV = ValueMap.Get(V))
  354. return NewV;
  355. return ProcessValue(V, DT);
  356. }
  357. Constant *DxilValueCache::GetConstValue(Value *V, DominatorTree *DT) {
  358. if (Value *NewV = GetValue(V))
  359. return dyn_cast<Constant>(NewV);
  360. return nullptr;
  361. }
  362. ConstantInt *DxilValueCache::GetConstInt(Value *V, DominatorTree *DT) {
  363. if (Value *NewV = GetValue(V))
  364. return dyn_cast<ConstantInt>(NewV);
  365. return nullptr;
  366. }
  367. bool DxilValueCache::IsAlwaysReachable(BasicBlock *BB, DominatorTree *DT) {
  368. ProcessValue(BB, DT);
  369. return IsAlwaysReachable_(BB);
  370. }
  371. bool DxilValueCache::IsUnreachable(BasicBlock *BB, DominatorTree *DT) {
  372. ProcessValue(BB, DT);
  373. return IsUnreachable_(BB);
  374. }
  375. LLVM_DUMP_METHOD
  376. void DxilValueCache::dump() const {
  377. ValueMap.dump();
  378. }
  379. void DxilValueCache::getAnalysisUsage(AnalysisUsage &AU) const {
  380. AU.setPreservesAll();
  381. }
  382. Value *DxilValueCache::ProcessValue(Value *NewV, DominatorTree *DT) {
  383. Value *Result = nullptr;
  384. SmallVector<Value *, 16> WorkList;
  385. // Although we accept all values for convenience, we only process
  386. // Instructions.
  387. if (Instruction *I = dyn_cast<Instruction>(NewV)) {
  388. WorkList.push_back(I);
  389. }
  390. else if (BasicBlock *BB = dyn_cast<BasicBlock>(NewV)) {
  391. WorkList.push_back(BB->getTerminator());
  392. WorkList.push_back(BB);
  393. }
  394. else {
  395. return nullptr;
  396. }
  397. // Unconditionally process this one instruction, whether we've seen
  398. // it or not. The simplification might be able to do something to
  399. // simplify it even when we don't have its value cached.
  400. // This is a basic DFS setup.
  401. while (WorkList.size()) {
  402. Value *V = WorkList.back();
  403. // If we haven't seen this value, go in and push things it depends on
  404. // into the worklist.
  405. if (!ValueMap.Seen(V)) {
  406. ValueMap.SetSentinel(V);
  407. if (Instruction *I = dyn_cast<Instruction>(V)) {
  408. for (Use &U : I->operands()) {
  409. Instruction *UseI = dyn_cast<Instruction>(U.get());
  410. if (!UseI)
  411. continue;
  412. if (!ValueMap.Seen(UseI))
  413. WorkList.push_back(UseI);
  414. }
  415. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  416. for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
  417. BasicBlock *BB = PN->getIncomingBlock(i);
  418. TerminatorInst *Term = BB->getTerminator();
  419. if (!ValueMap.Seen(Term))
  420. WorkList.push_back(Term);
  421. if (!ValueMap.Seen(BB))
  422. WorkList.push_back(BB);
  423. }
  424. }
  425. }
  426. else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
  427. if (IsEntryBlock(BB)) {
  428. MarkAlwaysReachable(BB);
  429. }
  430. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; PI++) {
  431. BasicBlock *PredBB = *PI;
  432. TerminatorInst *Term = PredBB->getTerminator();
  433. if (!ValueMap.Seen(Term))
  434. WorkList.push_back(Term);
  435. if (!ValueMap.Seen(PredBB))
  436. WorkList.push_back(PredBB);
  437. }
  438. }
  439. }
  440. // If we've seen this values, all its dependencies must have been processed
  441. // as well.
  442. else {
  443. WorkList.pop_back();
  444. if (Instruction *I = dyn_cast<Instruction>(V)) {
  445. Value *SimplifiedValue = SimplifyAndCacheResult(I, DT);
  446. // Set the result if this is the input inst.
  447. // SimplifyInst may not have cached the value
  448. // so we return it directly.
  449. if (I == NewV)
  450. Result = SimplifiedValue;
  451. }
  452. else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
  453. // Deduce the basic block's reachability based on
  454. // other analysis.
  455. if (!IsEntryBlock(BB)) {
  456. bool AllNeverReachable = true;
  457. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; PI++) {
  458. if (!IsUnreachable_(BB)) {
  459. AllNeverReachable = false;
  460. break;
  461. }
  462. }
  463. if (AllNeverReachable)
  464. MarkUnreachable(BB);
  465. }
  466. }
  467. }
  468. }
  469. return Result;
  470. }
  471. char DxilValueCache::ID;
  472. Pass *llvm::createDxilValueCachePass() {
  473. return new DxilValueCache();
  474. }
  475. INITIALIZE_PASS(DxilValueCache, DEBUG_TYPE, "Dxil Value Cache", false, false)