PHITransAddr.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. //===- PHITransAddr.cpp - PHI Translation for Addresses -------------------===//
  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 the PHITransAddr class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Analysis/PHITransAddr.h"
  14. #include "llvm/Analysis/InstructionSimplify.h"
  15. #include "llvm/Analysis/ValueTracking.h"
  16. #include "llvm/IR/Constants.h"
  17. #include "llvm/IR/Dominators.h"
  18. #include "llvm/IR/Instructions.h"
  19. #include "llvm/Support/Debug.h"
  20. #include "llvm/Support/ErrorHandling.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. using namespace llvm;
  23. static bool CanPHITrans(Instruction *Inst) {
  24. if (isa<PHINode>(Inst) ||
  25. isa<GetElementPtrInst>(Inst))
  26. return true;
  27. if (isa<CastInst>(Inst) &&
  28. isSafeToSpeculativelyExecute(Inst))
  29. return true;
  30. if (Inst->getOpcode() == Instruction::Add &&
  31. isa<ConstantInt>(Inst->getOperand(1)))
  32. return true;
  33. // cerr << "MEMDEP: Could not PHI translate: " << *Pointer;
  34. // if (isa<BitCastInst>(PtrInst) || isa<GetElementPtrInst>(PtrInst))
  35. // cerr << "OP:\t\t\t\t" << *PtrInst->getOperand(0);
  36. return false;
  37. }
  38. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  39. void PHITransAddr::dump() const {
  40. if (!Addr) {
  41. dbgs() << "PHITransAddr: null\n";
  42. return;
  43. }
  44. dbgs() << "PHITransAddr: " << *Addr << "\n";
  45. for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
  46. dbgs() << " Input #" << i << " is " << *InstInputs[i] << "\n";
  47. }
  48. #endif
  49. static bool VerifySubExpr(Value *Expr,
  50. SmallVectorImpl<Instruction*> &InstInputs) {
  51. // If this is a non-instruction value, there is nothing to do.
  52. Instruction *I = dyn_cast<Instruction>(Expr);
  53. if (!I) return true;
  54. // If it's an instruction, it is either in Tmp or its operands recursively
  55. // are.
  56. SmallVectorImpl<Instruction*>::iterator Entry =
  57. std::find(InstInputs.begin(), InstInputs.end(), I);
  58. if (Entry != InstInputs.end()) {
  59. InstInputs.erase(Entry);
  60. return true;
  61. }
  62. // If it isn't in the InstInputs list it is a subexpr incorporated into the
  63. // address. Sanity check that it is phi translatable.
  64. if (!CanPHITrans(I)) {
  65. errs() << "Instruction in PHITransAddr is not phi-translatable:\n";
  66. errs() << *I << '\n';
  67. llvm_unreachable("Either something is missing from InstInputs or "
  68. "CanPHITrans is wrong.");
  69. }
  70. // Validate the operands of the instruction.
  71. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  72. if (!VerifySubExpr(I->getOperand(i), InstInputs))
  73. return false;
  74. return true;
  75. }
  76. /// Verify - Check internal consistency of this data structure. If the
  77. /// structure is valid, it returns true. If invalid, it prints errors and
  78. /// returns false.
  79. bool PHITransAddr::Verify() const {
  80. if (!Addr) return true;
  81. SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());
  82. if (!VerifySubExpr(Addr, Tmp))
  83. return false;
  84. if (!Tmp.empty()) {
  85. errs() << "PHITransAddr contains extra instructions:\n";
  86. for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
  87. errs() << " InstInput #" << i << " is " << *InstInputs[i] << "\n";
  88. llvm_unreachable("This is unexpected.");
  89. }
  90. // a-ok.
  91. return true;
  92. }
  93. /// IsPotentiallyPHITranslatable - If this needs PHI translation, return true
  94. /// if we have some hope of doing it. This should be used as a filter to
  95. /// avoid calling PHITranslateValue in hopeless situations.
  96. bool PHITransAddr::IsPotentiallyPHITranslatable() const {
  97. // If the input value is not an instruction, or if it is not defined in CurBB,
  98. // then we don't need to phi translate it.
  99. Instruction *Inst = dyn_cast<Instruction>(Addr);
  100. return !Inst || CanPHITrans(Inst);
  101. }
  102. static void RemoveInstInputs(Value *V,
  103. SmallVectorImpl<Instruction*> &InstInputs) {
  104. Instruction *I = dyn_cast<Instruction>(V);
  105. if (!I) return;
  106. // If the instruction is in the InstInputs list, remove it.
  107. SmallVectorImpl<Instruction*>::iterator Entry =
  108. std::find(InstInputs.begin(), InstInputs.end(), I);
  109. if (Entry != InstInputs.end()) {
  110. InstInputs.erase(Entry);
  111. return;
  112. }
  113. assert(!isa<PHINode>(I) && "Error, removing something that isn't an input");
  114. // Otherwise, it must have instruction inputs itself. Zap them recursively.
  115. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  116. if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
  117. RemoveInstInputs(Op, InstInputs);
  118. }
  119. }
  120. Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB,
  121. BasicBlock *PredBB,
  122. const DominatorTree *DT) {
  123. // If this is a non-instruction value, it can't require PHI translation.
  124. Instruction *Inst = dyn_cast<Instruction>(V);
  125. if (!Inst) return V;
  126. // Determine whether 'Inst' is an input to our PHI translatable expression.
  127. bool isInput = std::count(InstInputs.begin(), InstInputs.end(), Inst);
  128. // Handle inputs instructions if needed.
  129. if (isInput) {
  130. if (Inst->getParent() != CurBB) {
  131. // If it is an input defined in a different block, then it remains an
  132. // input.
  133. return Inst;
  134. }
  135. // If 'Inst' is defined in this block and is an input that needs to be phi
  136. // translated, we need to incorporate the value into the expression or fail.
  137. // In either case, the instruction itself isn't an input any longer.
  138. InstInputs.erase(std::find(InstInputs.begin(), InstInputs.end(), Inst));
  139. // If this is a PHI, go ahead and translate it.
  140. if (PHINode *PN = dyn_cast<PHINode>(Inst))
  141. return AddAsInput(PN->getIncomingValueForBlock(PredBB));
  142. // If this is a non-phi value, and it is analyzable, we can incorporate it
  143. // into the expression by making all instruction operands be inputs.
  144. if (!CanPHITrans(Inst))
  145. return nullptr;
  146. // All instruction operands are now inputs (and of course, they may also be
  147. // defined in this block, so they may need to be phi translated themselves.
  148. for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
  149. if (Instruction *Op = dyn_cast<Instruction>(Inst->getOperand(i)))
  150. InstInputs.push_back(Op);
  151. }
  152. // Ok, it must be an intermediate result (either because it started that way
  153. // or because we just incorporated it into the expression). See if its
  154. // operands need to be phi translated, and if so, reconstruct it.
  155. if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
  156. if (!isSafeToSpeculativelyExecute(Cast)) return nullptr;
  157. Value *PHIIn = PHITranslateSubExpr(Cast->getOperand(0), CurBB, PredBB, DT);
  158. if (!PHIIn) return nullptr;
  159. if (PHIIn == Cast->getOperand(0))
  160. return Cast;
  161. // Find an available version of this cast.
  162. // Constants are trivial to find.
  163. if (Constant *C = dyn_cast<Constant>(PHIIn))
  164. return AddAsInput(ConstantExpr::getCast(Cast->getOpcode(),
  165. C, Cast->getType()));
  166. // Otherwise we have to see if a casted version of the incoming pointer
  167. // is available. If so, we can use it, otherwise we have to fail.
  168. for (User *U : PHIIn->users()) {
  169. if (CastInst *CastI = dyn_cast<CastInst>(U))
  170. if (CastI->getOpcode() == Cast->getOpcode() &&
  171. CastI->getType() == Cast->getType() &&
  172. (!DT || DT->dominates(CastI->getParent(), PredBB)))
  173. return CastI;
  174. }
  175. return nullptr;
  176. }
  177. // Handle getelementptr with at least one PHI translatable operand.
  178. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
  179. SmallVector<Value*, 8> GEPOps;
  180. bool AnyChanged = false;
  181. for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
  182. Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB, DT);
  183. if (!GEPOp) return nullptr;
  184. AnyChanged |= GEPOp != GEP->getOperand(i);
  185. GEPOps.push_back(GEPOp);
  186. }
  187. if (!AnyChanged)
  188. return GEP;
  189. // Simplify the GEP to handle 'gep x, 0' -> x etc.
  190. if (Value *V = SimplifyGEPInst(GEPOps, DL, TLI, DT, AC)) {
  191. for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
  192. RemoveInstInputs(GEPOps[i], InstInputs);
  193. return AddAsInput(V);
  194. }
  195. // Scan to see if we have this GEP available.
  196. Value *APHIOp = GEPOps[0];
  197. for (User *U : APHIOp->users()) {
  198. if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
  199. if (GEPI->getType() == GEP->getType() &&
  200. GEPI->getNumOperands() == GEPOps.size() &&
  201. GEPI->getParent()->getParent() == CurBB->getParent() &&
  202. (!DT || DT->dominates(GEPI->getParent(), PredBB))) {
  203. bool Mismatch = false;
  204. for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
  205. if (GEPI->getOperand(i) != GEPOps[i]) {
  206. Mismatch = true;
  207. break;
  208. }
  209. if (!Mismatch)
  210. return GEPI;
  211. }
  212. }
  213. return nullptr;
  214. }
  215. // Handle add with a constant RHS.
  216. if (Inst->getOpcode() == Instruction::Add &&
  217. isa<ConstantInt>(Inst->getOperand(1))) {
  218. // PHI translate the LHS.
  219. Constant *RHS = cast<ConstantInt>(Inst->getOperand(1));
  220. bool isNSW = cast<BinaryOperator>(Inst)->hasNoSignedWrap();
  221. bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap();
  222. Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB, DT);
  223. if (!LHS) return nullptr;
  224. // If the PHI translated LHS is an add of a constant, fold the immediates.
  225. if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS))
  226. if (BOp->getOpcode() == Instruction::Add)
  227. if (ConstantInt *CI = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
  228. LHS = BOp->getOperand(0);
  229. RHS = ConstantExpr::getAdd(RHS, CI);
  230. isNSW = isNUW = false;
  231. // If the old 'LHS' was an input, add the new 'LHS' as an input.
  232. if (std::count(InstInputs.begin(), InstInputs.end(), BOp)) {
  233. RemoveInstInputs(BOp, InstInputs);
  234. AddAsInput(LHS);
  235. }
  236. }
  237. // See if the add simplifies away.
  238. if (Value *Res = SimplifyAddInst(LHS, RHS, isNSW, isNUW, DL, TLI, DT, AC)) {
  239. // If we simplified the operands, the LHS is no longer an input, but Res
  240. // is.
  241. RemoveInstInputs(LHS, InstInputs);
  242. return AddAsInput(Res);
  243. }
  244. // If we didn't modify the add, just return it.
  245. if (LHS == Inst->getOperand(0) && RHS == Inst->getOperand(1))
  246. return Inst;
  247. // Otherwise, see if we have this add available somewhere.
  248. for (User *U : LHS->users()) {
  249. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U))
  250. if (BO->getOpcode() == Instruction::Add &&
  251. BO->getOperand(0) == LHS && BO->getOperand(1) == RHS &&
  252. BO->getParent()->getParent() == CurBB->getParent() &&
  253. (!DT || DT->dominates(BO->getParent(), PredBB)))
  254. return BO;
  255. }
  256. return nullptr;
  257. }
  258. // Otherwise, we failed.
  259. return nullptr;
  260. }
  261. /// PHITranslateValue - PHI translate the current address up the CFG from
  262. /// CurBB to Pred, updating our state to reflect any needed changes. If the
  263. /// dominator tree DT is non-null, the translated value must dominate
  264. /// PredBB. This returns true on failure and sets Addr to null.
  265. bool PHITransAddr::PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB,
  266. const DominatorTree *DT) {
  267. assert(Verify() && "Invalid PHITransAddr!");
  268. Addr = PHITranslateSubExpr(Addr, CurBB, PredBB, DT);
  269. assert(Verify() && "Invalid PHITransAddr!");
  270. if (DT) {
  271. // Make sure the value is live in the predecessor.
  272. if (Instruction *Inst = dyn_cast_or_null<Instruction>(Addr))
  273. if (!DT->dominates(Inst->getParent(), PredBB))
  274. Addr = nullptr;
  275. }
  276. return Addr == nullptr;
  277. }
  278. /// PHITranslateWithInsertion - PHI translate this value into the specified
  279. /// predecessor block, inserting a computation of the value if it is
  280. /// unavailable.
  281. ///
  282. /// All newly created instructions are added to the NewInsts list. This
  283. /// returns null on failure.
  284. ///
  285. Value *PHITransAddr::
  286. PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
  287. const DominatorTree &DT,
  288. SmallVectorImpl<Instruction*> &NewInsts) {
  289. unsigned NISize = NewInsts.size();
  290. // Attempt to PHI translate with insertion.
  291. Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts);
  292. // If successful, return the new value.
  293. if (Addr) return Addr;
  294. // If not, destroy any intermediate instructions inserted.
  295. while (NewInsts.size() != NISize)
  296. NewInsts.pop_back_val()->eraseFromParent();
  297. return nullptr;
  298. }
  299. /// InsertPHITranslatedPointer - Insert a computation of the PHI translated
  300. /// version of 'V' for the edge PredBB->CurBB into the end of the PredBB
  301. /// block. All newly created instructions are added to the NewInsts list.
  302. /// This returns null on failure.
  303. ///
  304. Value *PHITransAddr::
  305. InsertPHITranslatedSubExpr(Value *InVal, BasicBlock *CurBB,
  306. BasicBlock *PredBB, const DominatorTree &DT,
  307. SmallVectorImpl<Instruction*> &NewInsts) {
  308. // See if we have a version of this value already available and dominating
  309. // PredBB. If so, there is no need to insert a new instance of it.
  310. PHITransAddr Tmp(InVal, DL, AC);
  311. if (!Tmp.PHITranslateValue(CurBB, PredBB, &DT))
  312. return Tmp.getAddr();
  313. // If we don't have an available version of this value, it must be an
  314. // instruction.
  315. Instruction *Inst = cast<Instruction>(InVal);
  316. // Handle cast of PHI translatable value.
  317. if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
  318. if (!isSafeToSpeculativelyExecute(Cast)) return nullptr;
  319. Value *OpVal = InsertPHITranslatedSubExpr(Cast->getOperand(0),
  320. CurBB, PredBB, DT, NewInsts);
  321. if (!OpVal) return nullptr;
  322. // Otherwise insert a cast at the end of PredBB.
  323. CastInst *New = CastInst::Create(Cast->getOpcode(),
  324. OpVal, InVal->getType(),
  325. InVal->getName()+".phi.trans.insert",
  326. PredBB->getTerminator());
  327. NewInsts.push_back(New);
  328. return New;
  329. }
  330. // Handle getelementptr with at least one PHI operand.
  331. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
  332. SmallVector<Value*, 8> GEPOps;
  333. BasicBlock *CurBB = GEP->getParent();
  334. for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
  335. Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i),
  336. CurBB, PredBB, DT, NewInsts);
  337. if (!OpVal) return nullptr;
  338. GEPOps.push_back(OpVal);
  339. }
  340. GetElementPtrInst *Result = GetElementPtrInst::Create(
  341. GEP->getSourceElementType(), GEPOps[0], makeArrayRef(GEPOps).slice(1),
  342. InVal->getName() + ".phi.trans.insert", PredBB->getTerminator());
  343. Result->setIsInBounds(GEP->isInBounds());
  344. NewInsts.push_back(Result);
  345. return Result;
  346. }
  347. #if 0
  348. // FIXME: This code works, but it is unclear that we actually want to insert
  349. // a big chain of computation in order to make a value available in a block.
  350. // This needs to be evaluated carefully to consider its cost trade offs.
  351. // Handle add with a constant RHS.
  352. if (Inst->getOpcode() == Instruction::Add &&
  353. isa<ConstantInt>(Inst->getOperand(1))) {
  354. // PHI translate the LHS.
  355. Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0),
  356. CurBB, PredBB, DT, NewInsts);
  357. if (OpVal == 0) return 0;
  358. BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1),
  359. InVal->getName()+".phi.trans.insert",
  360. PredBB->getTerminator());
  361. Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap());
  362. Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap());
  363. NewInsts.push_back(Res);
  364. return Res;
  365. }
  366. #endif
  367. return nullptr;
  368. }