1 //===- PHITransAddr.cpp - PHI Translation for Addresses -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the PHITransAddr class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Analysis/PHITransAddr.h"
15 #include "llvm/Analysis/InstructionSimplify.h"
16 #include "llvm/Analysis/ValueTracking.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/Dominators.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
25 static bool CanPHITrans(Instruction *Inst) {
26 if (isa<PHINode>(Inst) ||
27 isa<GetElementPtrInst>(Inst))
30 if (isa<CastInst>(Inst) &&
31 isSafeToSpeculativelyExecute(Inst))
34 if (Inst->getOpcode() == Instruction::Add &&
35 isa<ConstantInt>(Inst->getOperand(1)))
38 // cerr << "MEMDEP: Could not PHI translate: " << *Pointer;
39 // if (isa<BitCastInst>(PtrInst) || isa<GetElementPtrInst>(PtrInst))
40 // cerr << "OP:\t\t\t\t" << *PtrInst->getOperand(0);
44 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
45 void PHITransAddr::dump() const {
47 dbgs() << "PHITransAddr: null\n";
50 dbgs() << "PHITransAddr: " << *Addr << "\n";
51 for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
52 dbgs() << " Input #" << i << " is " << *InstInputs[i] << "\n";
57 static bool VerifySubExpr(Value *Expr,
58 SmallVectorImpl<Instruction*> &InstInputs) {
59 // If this is a non-instruction value, there is nothing to do.
60 Instruction *I = dyn_cast<Instruction>(Expr);
63 // If it's an instruction, it is either in Tmp or its operands recursively
65 SmallVectorImpl<Instruction*>::iterator Entry =
66 std::find(InstInputs.begin(), InstInputs.end(), I);
67 if (Entry != InstInputs.end()) {
68 InstInputs.erase(Entry);
72 // If it isn't in the InstInputs list it is a subexpr incorporated into the
73 // address. Sanity check that it is phi translatable.
74 if (!CanPHITrans(I)) {
75 errs() << "Instruction in PHITransAddr is not phi-translatable:\n";
77 llvm_unreachable("Either something is missing from InstInputs or "
78 "CanPHITrans is wrong.");
81 // Validate the operands of the instruction.
82 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
83 if (!VerifySubExpr(I->getOperand(i), InstInputs))
89 /// Verify - Check internal consistency of this data structure. If the
90 /// structure is valid, it returns true. If invalid, it prints errors and
92 bool PHITransAddr::Verify() const {
93 if (!Addr) return true;
95 SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());
97 if (!VerifySubExpr(Addr, Tmp))
101 errs() << "PHITransAddr contains extra instructions:\n";
102 for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
103 errs() << " InstInput #" << i << " is " << *InstInputs[i] << "\n";
104 llvm_unreachable("This is unexpected.");
112 /// IsPotentiallyPHITranslatable - If this needs PHI translation, return true
113 /// if we have some hope of doing it. This should be used as a filter to
114 /// avoid calling PHITranslateValue in hopeless situations.
115 bool PHITransAddr::IsPotentiallyPHITranslatable() const {
116 // If the input value is not an instruction, or if it is not defined in CurBB,
117 // then we don't need to phi translate it.
118 Instruction *Inst = dyn_cast<Instruction>(Addr);
119 return !Inst || CanPHITrans(Inst);
123 static void RemoveInstInputs(Value *V,
124 SmallVectorImpl<Instruction*> &InstInputs) {
125 Instruction *I = dyn_cast<Instruction>(V);
128 // If the instruction is in the InstInputs list, remove it.
129 SmallVectorImpl<Instruction*>::iterator Entry =
130 std::find(InstInputs.begin(), InstInputs.end(), I);
131 if (Entry != InstInputs.end()) {
132 InstInputs.erase(Entry);
136 assert(!isa<PHINode>(I) && "Error, removing something that isn't an input");
138 // Otherwise, it must have instruction inputs itself. Zap them recursively.
139 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
140 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
141 RemoveInstInputs(Op, InstInputs);
145 Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB,
147 const DominatorTree *DT) {
148 // If this is a non-instruction value, it can't require PHI translation.
149 Instruction *Inst = dyn_cast<Instruction>(V);
152 // Determine whether 'Inst' is an input to our PHI translatable expression.
153 bool isInput = std::count(InstInputs.begin(), InstInputs.end(), Inst);
155 // Handle inputs instructions if needed.
157 if (Inst->getParent() != CurBB) {
158 // If it is an input defined in a different block, then it remains an
163 // If 'Inst' is defined in this block and is an input that needs to be phi
164 // translated, we need to incorporate the value into the expression or fail.
166 // In either case, the instruction itself isn't an input any longer.
167 InstInputs.erase(std::find(InstInputs.begin(), InstInputs.end(), Inst));
169 // If this is a PHI, go ahead and translate it.
170 if (PHINode *PN = dyn_cast<PHINode>(Inst))
171 return AddAsInput(PN->getIncomingValueForBlock(PredBB));
173 // If this is a non-phi value, and it is analyzable, we can incorporate it
174 // into the expression by making all instruction operands be inputs.
175 if (!CanPHITrans(Inst))
178 // All instruction operands are now inputs (and of course, they may also be
179 // defined in this block, so they may need to be phi translated themselves.
180 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
181 if (Instruction *Op = dyn_cast<Instruction>(Inst->getOperand(i)))
182 InstInputs.push_back(Op);
185 // Ok, it must be an intermediate result (either because it started that way
186 // or because we just incorporated it into the expression). See if its
187 // operands need to be phi translated, and if so, reconstruct it.
189 if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
190 if (!isSafeToSpeculativelyExecute(Cast)) return nullptr;
191 Value *PHIIn = PHITranslateSubExpr(Cast->getOperand(0), CurBB, PredBB, DT);
192 if (!PHIIn) return nullptr;
193 if (PHIIn == Cast->getOperand(0))
196 // Find an available version of this cast.
198 // Constants are trivial to find.
199 if (Constant *C = dyn_cast<Constant>(PHIIn))
200 return AddAsInput(ConstantExpr::getCast(Cast->getOpcode(),
201 C, Cast->getType()));
203 // Otherwise we have to see if a casted version of the incoming pointer
204 // is available. If so, we can use it, otherwise we have to fail.
205 for (User *U : PHIIn->users()) {
206 if (CastInst *CastI = dyn_cast<CastInst>(U))
207 if (CastI->getOpcode() == Cast->getOpcode() &&
208 CastI->getType() == Cast->getType() &&
209 (!DT || DT->dominates(CastI->getParent(), PredBB)))
215 // Handle getelementptr with at least one PHI translatable operand.
216 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
217 SmallVector<Value*, 8> GEPOps;
218 bool AnyChanged = false;
219 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
220 Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB, DT);
221 if (!GEPOp) return nullptr;
223 AnyChanged |= GEPOp != GEP->getOperand(i);
224 GEPOps.push_back(GEPOp);
230 // Simplify the GEP to handle 'gep x, 0' -> x etc.
231 if (Value *V = SimplifyGEPInst(GEPOps, DL, TLI, DT, AC)) {
232 for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
233 RemoveInstInputs(GEPOps[i], InstInputs);
235 return AddAsInput(V);
238 // Scan to see if we have this GEP available.
239 Value *APHIOp = GEPOps[0];
240 for (User *U : APHIOp->users()) {
241 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
242 if (GEPI->getType() == GEP->getType() &&
243 GEPI->getNumOperands() == GEPOps.size() &&
244 GEPI->getParent()->getParent() == CurBB->getParent() &&
245 (!DT || DT->dominates(GEPI->getParent(), PredBB))) {
246 bool Mismatch = false;
247 for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
248 if (GEPI->getOperand(i) != GEPOps[i]) {
259 // Handle add with a constant RHS.
260 if (Inst->getOpcode() == Instruction::Add &&
261 isa<ConstantInt>(Inst->getOperand(1))) {
262 // PHI translate the LHS.
263 Constant *RHS = cast<ConstantInt>(Inst->getOperand(1));
264 bool isNSW = cast<BinaryOperator>(Inst)->hasNoSignedWrap();
265 bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap();
267 Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB, DT);
268 if (!LHS) return nullptr;
270 // If the PHI translated LHS is an add of a constant, fold the immediates.
271 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS))
272 if (BOp->getOpcode() == Instruction::Add)
273 if (ConstantInt *CI = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
274 LHS = BOp->getOperand(0);
275 RHS = ConstantExpr::getAdd(RHS, CI);
276 isNSW = isNUW = false;
278 // If the old 'LHS' was an input, add the new 'LHS' as an input.
279 if (std::count(InstInputs.begin(), InstInputs.end(), BOp)) {
280 RemoveInstInputs(BOp, InstInputs);
285 // See if the add simplifies away.
286 if (Value *Res = SimplifyAddInst(LHS, RHS, isNSW, isNUW, DL, TLI, DT, AC)) {
287 // If we simplified the operands, the LHS is no longer an input, but Res
289 RemoveInstInputs(LHS, InstInputs);
290 return AddAsInput(Res);
293 // If we didn't modify the add, just return it.
294 if (LHS == Inst->getOperand(0) && RHS == Inst->getOperand(1))
297 // Otherwise, see if we have this add available somewhere.
298 for (User *U : LHS->users()) {
299 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U))
300 if (BO->getOpcode() == Instruction::Add &&
301 BO->getOperand(0) == LHS && BO->getOperand(1) == RHS &&
302 BO->getParent()->getParent() == CurBB->getParent() &&
303 (!DT || DT->dominates(BO->getParent(), PredBB)))
310 // Otherwise, we failed.
315 /// PHITranslateValue - PHI translate the current address up the CFG from
316 /// CurBB to Pred, updating our state to reflect any needed changes. If the
317 /// dominator tree DT is non-null, the translated value must dominate
318 /// PredBB. This returns true on failure and sets Addr to null.
319 bool PHITransAddr::PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB,
320 const DominatorTree *DT) {
321 assert(Verify() && "Invalid PHITransAddr!");
322 Addr = PHITranslateSubExpr(Addr, CurBB, PredBB, DT);
323 assert(Verify() && "Invalid PHITransAddr!");
326 // Make sure the value is live in the predecessor.
327 if (Instruction *Inst = dyn_cast_or_null<Instruction>(Addr))
328 if (!DT->dominates(Inst->getParent(), PredBB))
332 return Addr == nullptr;
335 /// PHITranslateWithInsertion - PHI translate this value into the specified
336 /// predecessor block, inserting a computation of the value if it is
339 /// All newly created instructions are added to the NewInsts list. This
340 /// returns null on failure.
342 Value *PHITransAddr::
343 PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
344 const DominatorTree &DT,
345 SmallVectorImpl<Instruction*> &NewInsts) {
346 unsigned NISize = NewInsts.size();
348 // Attempt to PHI translate with insertion.
349 Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts);
351 // If successful, return the new value.
352 if (Addr) return Addr;
354 // If not, destroy any intermediate instructions inserted.
355 while (NewInsts.size() != NISize)
356 NewInsts.pop_back_val()->eraseFromParent();
361 /// InsertPHITranslatedPointer - Insert a computation of the PHI translated
362 /// version of 'V' for the edge PredBB->CurBB into the end of the PredBB
363 /// block. All newly created instructions are added to the NewInsts list.
364 /// This returns null on failure.
366 Value *PHITransAddr::
367 InsertPHITranslatedSubExpr(Value *InVal, BasicBlock *CurBB,
368 BasicBlock *PredBB, const DominatorTree &DT,
369 SmallVectorImpl<Instruction*> &NewInsts) {
370 // See if we have a version of this value already available and dominating
371 // PredBB. If so, there is no need to insert a new instance of it.
372 PHITransAddr Tmp(InVal, DL, AC);
373 if (!Tmp.PHITranslateValue(CurBB, PredBB, &DT))
374 return Tmp.getAddr();
376 // If we don't have an available version of this value, it must be an
378 Instruction *Inst = cast<Instruction>(InVal);
380 // Handle cast of PHI translatable value.
381 if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
382 if (!isSafeToSpeculativelyExecute(Cast)) return nullptr;
383 Value *OpVal = InsertPHITranslatedSubExpr(Cast->getOperand(0),
384 CurBB, PredBB, DT, NewInsts);
385 if (!OpVal) return nullptr;
387 // Otherwise insert a cast at the end of PredBB.
388 CastInst *New = CastInst::Create(Cast->getOpcode(),
389 OpVal, InVal->getType(),
390 InVal->getName()+".phi.trans.insert",
391 PredBB->getTerminator());
392 NewInsts.push_back(New);
396 // Handle getelementptr with at least one PHI operand.
397 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
398 SmallVector<Value*, 8> GEPOps;
399 BasicBlock *CurBB = GEP->getParent();
400 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
401 Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i),
402 CurBB, PredBB, DT, NewInsts);
403 if (!OpVal) return nullptr;
404 GEPOps.push_back(OpVal);
407 GetElementPtrInst *Result = GetElementPtrInst::Create(
408 GEP->getSourceElementType(), GEPOps[0], makeArrayRef(GEPOps).slice(1),
409 InVal->getName() + ".phi.trans.insert", PredBB->getTerminator());
410 Result->setIsInBounds(GEP->isInBounds());
411 NewInsts.push_back(Result);
416 // FIXME: This code works, but it is unclear that we actually want to insert
417 // a big chain of computation in order to make a value available in a block.
418 // This needs to be evaluated carefully to consider its cost trade offs.
420 // Handle add with a constant RHS.
421 if (Inst->getOpcode() == Instruction::Add &&
422 isa<ConstantInt>(Inst->getOperand(1))) {
423 // PHI translate the LHS.
424 Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0),
425 CurBB, PredBB, DT, NewInsts);
426 if (OpVal == 0) return 0;
428 BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1),
429 InVal->getName()+".phi.trans.insert",
430 PredBB->getTerminator());
431 Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap());
432 Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap());
433 NewInsts.push_back(Res);