PHITransAddr.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. //===- PHITransAddr.cpp - PHI Translation for Addresses -------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the PHITransAddr class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Analysis/PHITransAddr.h"
  13. #include "llvm/Analysis/InstructionSimplify.h"
  14. #include "llvm/Analysis/ValueTracking.h"
  15. #include "llvm/Config/llvm-config.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. LLVM_DUMP_METHOD 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 = find(InstInputs, I);
  57. if (Entry != InstInputs.end()) {
  58. InstInputs.erase(Entry);
  59. return true;
  60. }
  61. // If it isn't in the InstInputs list it is a subexpr incorporated into the
  62. // address. Validate that it is phi translatable.
  63. if (!CanPHITrans(I)) {
  64. errs() << "Instruction in PHITransAddr is not phi-translatable:\n";
  65. errs() << *I << '\n';
  66. llvm_unreachable("Either something is missing from InstInputs or "
  67. "CanPHITrans is wrong.");
  68. }
  69. // Validate the operands of the instruction.
  70. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  71. if (!VerifySubExpr(I->getOperand(i), InstInputs))
  72. return false;
  73. return true;
  74. }
  75. /// Verify - Check internal consistency of this data structure. If the
  76. /// structure is valid, it returns true. If invalid, it prints errors and
  77. /// returns false.
  78. bool PHITransAddr::Verify() const {
  79. if (!Addr) return true;
  80. SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());
  81. if (!VerifySubExpr(Addr, Tmp))
  82. return false;
  83. if (!Tmp.empty()) {
  84. errs() << "PHITransAddr contains extra instructions:\n";
  85. for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
  86. errs() << " InstInput #" << i << " is " << *InstInputs[i] << "\n";
  87. llvm_unreachable("This is unexpected.");
  88. }
  89. // a-ok.
  90. return true;
  91. }
  92. /// IsPotentiallyPHITranslatable - If this needs PHI translation, return true
  93. /// if we have some hope of doing it. This should be used as a filter to
  94. /// avoid calling PHITranslateValue in hopeless situations.
  95. bool PHITransAddr::IsPotentiallyPHITranslatable() const {
  96. // If the input value is not an instruction, or if it is not defined in CurBB,
  97. // then we don't need to phi translate it.
  98. Instruction *Inst = dyn_cast<Instruction>(Addr);
  99. return !Inst || CanPHITrans(Inst);
  100. }
  101. static void RemoveInstInputs(Value *V,
  102. SmallVectorImpl<Instruction*> &InstInputs) {
  103. Instruction *I = dyn_cast<Instruction>(V);
  104. if (!I) return;
  105. // If the instruction is in the InstInputs list, remove it.
  106. SmallVectorImpl<Instruction *>::iterator Entry = find(InstInputs, I);
  107. if (Entry != InstInputs.end()) {
  108. InstInputs.erase(Entry);
  109. return;
  110. }
  111. assert(!isa<PHINode>(I) && "Error, removing something that isn't an input");
  112. // Otherwise, it must have instruction inputs itself. Zap them recursively.
  113. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  114. if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
  115. RemoveInstInputs(Op, InstInputs);
  116. }
  117. }
  118. Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB,
  119. BasicBlock *PredBB,
  120. const DominatorTree *DT) {
  121. // If this is a non-instruction value, it can't require PHI translation.
  122. Instruction *Inst = dyn_cast<Instruction>(V);
  123. if (!Inst) return V;
  124. // Determine whether 'Inst' is an input to our PHI translatable expression.
  125. bool isInput = is_contained(InstInputs, Inst);
  126. // Handle inputs instructions if needed.
  127. if (isInput) {
  128. if (Inst->getParent() != CurBB) {
  129. // If it is an input defined in a different block, then it remains an
  130. // input.
  131. return Inst;
  132. }
  133. // If 'Inst' is defined in this block and is an input that needs to be phi
  134. // translated, we need to incorporate the value into the expression or fail.
  135. // In either case, the instruction itself isn't an input any longer.
  136. InstInputs.erase(find(InstInputs, Inst));
  137. // If this is a PHI, go ahead and translate it.
  138. if (PHINode *PN = dyn_cast<PHINode>(Inst))
  139. return AddAsInput(PN->getIncomingValueForBlock(PredBB));
  140. // If this is a non-phi value, and it is analyzable, we can incorporate it
  141. // into the expression by making all instruction operands be inputs.
  142. if (!CanPHITrans(Inst))
  143. return nullptr;
  144. // All instruction operands are now inputs (and of course, they may also be
  145. // defined in this block, so they may need to be phi translated themselves.
  146. for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
  147. if (Instruction *Op = dyn_cast<Instruction>(Inst->getOperand(i)))
  148. InstInputs.push_back(Op);
  149. }
  150. // Ok, it must be an intermediate result (either because it started that way
  151. // or because we just incorporated it into the expression). See if its
  152. // operands need to be phi translated, and if so, reconstruct it.
  153. if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
  154. if (!isSafeToSpeculativelyExecute(Cast)) return nullptr;
  155. Value *PHIIn = PHITranslateSubExpr(Cast->getOperand(0), CurBB, PredBB, DT);
  156. if (!PHIIn) return nullptr;
  157. if (PHIIn == Cast->getOperand(0))
  158. return Cast;
  159. // Find an available version of this cast.
  160. // Constants are trivial to find.
  161. if (Constant *C = dyn_cast<Constant>(PHIIn))
  162. return AddAsInput(ConstantExpr::getCast(Cast->getOpcode(),
  163. C, Cast->getType()));
  164. // Otherwise we have to see if a casted version of the incoming pointer
  165. // is available. If so, we can use it, otherwise we have to fail.
  166. for (User *U : PHIIn->users()) {
  167. if (CastInst *CastI = dyn_cast<CastInst>(U))
  168. if (CastI->getOpcode() == Cast->getOpcode() &&
  169. CastI->getType() == Cast->getType() &&
  170. (!DT || DT->dominates(CastI->getParent(), PredBB)))
  171. return CastI;
  172. }
  173. return nullptr;
  174. }
  175. // Handle getelementptr with at least one PHI translatable operand.
  176. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
  177. SmallVector<Value*, 8> GEPOps;
  178. bool AnyChanged = false;
  179. for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
  180. Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB, DT);
  181. if (!GEPOp) return nullptr;
  182. AnyChanged |= GEPOp != GEP->getOperand(i);
  183. GEPOps.push_back(GEPOp);
  184. }
  185. if (!AnyChanged)
  186. return GEP;
  187. // Simplify the GEP to handle 'gep x, 0' -> x etc.
  188. if (Value *V = SimplifyGEPInst(GEP->getSourceElementType(), GEPOps[0],
  189. ArrayRef<Value *>(GEPOps).slice(1),
  190. GEP->isInBounds(), {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. if (std::equal(GEPOps.begin(), GEPOps.end(), GEPI->op_begin()))
  204. return GEPI;
  205. }
  206. }
  207. return nullptr;
  208. }
  209. // Handle add with a constant RHS.
  210. if (Inst->getOpcode() == Instruction::Add &&
  211. isa<ConstantInt>(Inst->getOperand(1))) {
  212. // PHI translate the LHS.
  213. Constant *RHS = cast<ConstantInt>(Inst->getOperand(1));
  214. bool isNSW = cast<BinaryOperator>(Inst)->hasNoSignedWrap();
  215. bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap();
  216. Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB, DT);
  217. if (!LHS) return nullptr;
  218. // If the PHI translated LHS is an add of a constant, fold the immediates.
  219. if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS))
  220. if (BOp->getOpcode() == Instruction::Add)
  221. if (ConstantInt *CI = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
  222. LHS = BOp->getOperand(0);
  223. RHS = ConstantExpr::getAdd(RHS, CI);
  224. isNSW = isNUW = false;
  225. // If the old 'LHS' was an input, add the new 'LHS' as an input.
  226. if (is_contained(InstInputs, BOp)) {
  227. RemoveInstInputs(BOp, InstInputs);
  228. AddAsInput(LHS);
  229. }
  230. }
  231. // See if the add simplifies away.
  232. if (Value *Res = SimplifyAddInst(LHS, RHS, isNSW, isNUW, {DL, TLI, DT, AC})) {
  233. // If we simplified the operands, the LHS is no longer an input, but Res
  234. // is.
  235. RemoveInstInputs(LHS, InstInputs);
  236. return AddAsInput(Res);
  237. }
  238. // If we didn't modify the add, just return it.
  239. if (LHS == Inst->getOperand(0) && RHS == Inst->getOperand(1))
  240. return Inst;
  241. // Otherwise, see if we have this add available somewhere.
  242. for (User *U : LHS->users()) {
  243. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U))
  244. if (BO->getOpcode() == Instruction::Add &&
  245. BO->getOperand(0) == LHS && BO->getOperand(1) == RHS &&
  246. BO->getParent()->getParent() == CurBB->getParent() &&
  247. (!DT || DT->dominates(BO->getParent(), PredBB)))
  248. return BO;
  249. }
  250. return nullptr;
  251. }
  252. // Otherwise, we failed.
  253. return nullptr;
  254. }
  255. /// PHITranslateValue - PHI translate the current address up the CFG from
  256. /// CurBB to Pred, updating our state to reflect any needed changes. If
  257. /// 'MustDominate' is true, the translated value must dominate
  258. /// PredBB. This returns true on failure and sets Addr to null.
  259. bool PHITransAddr::PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB,
  260. const DominatorTree *DT,
  261. bool MustDominate) {
  262. assert(DT || !MustDominate);
  263. assert(Verify() && "Invalid PHITransAddr!");
  264. if (DT && DT->isReachableFromEntry(PredBB))
  265. Addr =
  266. PHITranslateSubExpr(Addr, CurBB, PredBB, MustDominate ? DT : nullptr);
  267. else
  268. Addr = nullptr;
  269. assert(Verify() && "Invalid PHITransAddr!");
  270. if (MustDominate)
  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. return Addr == nullptr;
  276. }
  277. /// PHITranslateWithInsertion - PHI translate this value into the specified
  278. /// predecessor block, inserting a computation of the value if it is
  279. /// unavailable.
  280. ///
  281. /// All newly created instructions are added to the NewInsts list. This
  282. /// returns null on failure.
  283. ///
  284. Value *PHITransAddr::
  285. PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
  286. const DominatorTree &DT,
  287. SmallVectorImpl<Instruction*> &NewInsts) {
  288. unsigned NISize = NewInsts.size();
  289. // Attempt to PHI translate with insertion.
  290. Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts);
  291. // If successful, return the new value.
  292. if (Addr) return Addr;
  293. // If not, destroy any intermediate instructions inserted.
  294. while (NewInsts.size() != NISize)
  295. NewInsts.pop_back_val()->eraseFromParent();
  296. return nullptr;
  297. }
  298. /// InsertPHITranslatedPointer - Insert a computation of the PHI translated
  299. /// version of 'V' for the edge PredBB->CurBB into the end of the PredBB
  300. /// block. All newly created instructions are added to the NewInsts list.
  301. /// This returns null on failure.
  302. ///
  303. Value *PHITransAddr::
  304. InsertPHITranslatedSubExpr(Value *InVal, BasicBlock *CurBB,
  305. BasicBlock *PredBB, const DominatorTree &DT,
  306. SmallVectorImpl<Instruction*> &NewInsts) {
  307. // See if we have a version of this value already available and dominating
  308. // PredBB. If so, there is no need to insert a new instance of it.
  309. PHITransAddr Tmp(InVal, DL, AC);
  310. if (!Tmp.PHITranslateValue(CurBB, PredBB, &DT, /*MustDominate=*/true))
  311. return Tmp.getAddr();
  312. // We don't need to PHI translate values which aren't instructions.
  313. auto *Inst = dyn_cast<Instruction>(InVal);
  314. if (!Inst)
  315. return nullptr;
  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(), OpVal, InVal->getType(),
  324. InVal->getName() + ".phi.trans.insert",
  325. PredBB->getTerminator());
  326. New->setDebugLoc(Inst->getDebugLoc());
  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->setDebugLoc(Inst->getDebugLoc());
  344. Result->setIsInBounds(GEP->isInBounds());
  345. NewInsts.push_back(Result);
  346. return Result;
  347. }
  348. #if 0
  349. // FIXME: This code works, but it is unclear that we actually want to insert
  350. // a big chain of computation in order to make a value available in a block.
  351. // This needs to be evaluated carefully to consider its cost trade offs.
  352. // Handle add with a constant RHS.
  353. if (Inst->getOpcode() == Instruction::Add &&
  354. isa<ConstantInt>(Inst->getOperand(1))) {
  355. // PHI translate the LHS.
  356. Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0),
  357. CurBB, PredBB, DT, NewInsts);
  358. if (OpVal == 0) return 0;
  359. BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1),
  360. InVal->getName()+".phi.trans.insert",
  361. PredBB->getTerminator());
  362. Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap());
  363. Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap());
  364. NewInsts.push_back(Res);
  365. return Res;
  366. }
  367. #endif
  368. return nullptr;
  369. }