PHITransAddr.cpp revision 36b56886974eae4f9c5ebc96befd3e7bfe5de338
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
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"
23using namespace llvm;
24
25static bool CanPHITrans(Instruction *Inst) {
26  if (isa<PHINode>(Inst) ||
27      isa<GetElementPtrInst>(Inst))
28    return true;
29
30  if (isa<CastInst>(Inst) &&
31      isSafeToSpeculativelyExecute(Inst))
32    return true;
33
34  if (Inst->getOpcode() == Instruction::Add &&
35      isa<ConstantInt>(Inst->getOperand(1)))
36    return true;
37
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);
41  return false;
42}
43
44#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
45void PHITransAddr::dump() const {
46  if (Addr == 0) {
47    dbgs() << "PHITransAddr: null\n";
48    return;
49  }
50  dbgs() << "PHITransAddr: " << *Addr << "\n";
51  for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
52    dbgs() << "  Input #" << i << " is " << *InstInputs[i] << "\n";
53}
54#endif
55
56
57static 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);
61  if (I == 0) return true;
62
63  // If it's an instruction, it is either in Tmp or its operands recursively
64  // are.
65  SmallVectorImpl<Instruction*>::iterator Entry =
66    std::find(InstInputs.begin(), InstInputs.end(), I);
67  if (Entry != InstInputs.end()) {
68    InstInputs.erase(Entry);
69    return true;
70  }
71
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";
76    errs() << *I << '\n';
77    llvm_unreachable("Either something is missing from InstInputs or "
78                     "CanPHITrans is wrong.");
79  }
80
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))
84      return false;
85
86  return true;
87}
88
89/// Verify - Check internal consistency of this data structure.  If the
90/// structure is valid, it returns true.  If invalid, it prints errors and
91/// returns false.
92bool PHITransAddr::Verify() const {
93  if (Addr == 0) return true;
94
95  SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());
96
97  if (!VerifySubExpr(Addr, Tmp))
98    return false;
99
100  if (!Tmp.empty()) {
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.");
105  }
106
107  // a-ok.
108  return true;
109}
110
111
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.
115bool 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 == 0 || CanPHITrans(Inst);
120}
121
122
123static void RemoveInstInputs(Value *V,
124                             SmallVectorImpl<Instruction*> &InstInputs) {
125  Instruction *I = dyn_cast<Instruction>(V);
126  if (I == 0) return;
127
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);
133    return;
134  }
135
136  assert(!isa<PHINode>(I) && "Error, removing something that isn't an input");
137
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);
142  }
143}
144
145Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB,
146                                         BasicBlock *PredBB,
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);
150  if (Inst == 0) return V;
151
152  // Determine whether 'Inst' is an input to our PHI translatable expression.
153  bool isInput = std::count(InstInputs.begin(), InstInputs.end(), Inst);
154
155  // Handle inputs instructions if needed.
156  if (isInput) {
157    if (Inst->getParent() != CurBB) {
158      // If it is an input defined in a different block, then it remains an
159      // input.
160      return Inst;
161    }
162
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.
165
166    // In either case, the instruction itself isn't an input any longer.
167    InstInputs.erase(std::find(InstInputs.begin(), InstInputs.end(), Inst));
168
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));
172
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))
176      return 0;
177
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);
183  }
184
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.
188
189  if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
190    if (!isSafeToSpeculativelyExecute(Cast)) return 0;
191    Value *PHIIn = PHITranslateSubExpr(Cast->getOperand(0), CurBB, PredBB, DT);
192    if (PHIIn == 0) return 0;
193    if (PHIIn == Cast->getOperand(0))
194      return Cast;
195
196    // Find an available version of this cast.
197
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()));
202
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)))
210          return CastI;
211    }
212    return 0;
213  }
214
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 == 0) return 0;
222
223      AnyChanged |= GEPOp != GEP->getOperand(i);
224      GEPOps.push_back(GEPOp);
225    }
226
227    if (!AnyChanged)
228      return GEP;
229
230    // Simplify the GEP to handle 'gep x, 0' -> x etc.
231    if (Value *V = SimplifyGEPInst(GEPOps, DL, TLI, DT)) {
232      for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
233        RemoveInstInputs(GEPOps[i], InstInputs);
234
235      return AddAsInput(V);
236    }
237
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]) {
249              Mismatch = true;
250              break;
251            }
252          if (!Mismatch)
253            return GEPI;
254        }
255    }
256    return 0;
257  }
258
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();
266
267    Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB, DT);
268    if (LHS == 0) return 0;
269
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;
277
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);
281            AddAsInput(LHS);
282          }
283        }
284
285    // See if the add simplifies away.
286    if (Value *Res = SimplifyAddInst(LHS, RHS, isNSW, isNUW, DL, TLI, DT)) {
287      // If we simplified the operands, the LHS is no longer an input, but Res
288      // is.
289      RemoveInstInputs(LHS, InstInputs);
290      return AddAsInput(Res);
291    }
292
293    // If we didn't modify the add, just return it.
294    if (LHS == Inst->getOperand(0) && RHS == Inst->getOperand(1))
295      return Inst;
296
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)))
304          return BO;
305    }
306
307    return 0;
308  }
309
310  // Otherwise, we failed.
311  return 0;
312}
313
314
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.
319bool 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!");
324
325  if (DT) {
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))
329        Addr = 0;
330  }
331
332  return Addr == 0;
333}
334
335/// PHITranslateWithInsertion - PHI translate this value into the specified
336/// predecessor block, inserting a computation of the value if it is
337/// unavailable.
338///
339/// All newly created instructions are added to the NewInsts list.  This
340/// returns null on failure.
341///
342Value *PHITransAddr::
343PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
344                          const DominatorTree &DT,
345                          SmallVectorImpl<Instruction*> &NewInsts) {
346  unsigned NISize = NewInsts.size();
347
348  // Attempt to PHI translate with insertion.
349  Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts);
350
351  // If successful, return the new value.
352  if (Addr) return Addr;
353
354  // If not, destroy any intermediate instructions inserted.
355  while (NewInsts.size() != NISize)
356    NewInsts.pop_back_val()->eraseFromParent();
357  return 0;
358}
359
360
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.
365///
366Value *PHITransAddr::
367InsertPHITranslatedSubExpr(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);
373  if (!Tmp.PHITranslateValue(CurBB, PredBB, &DT))
374    return Tmp.getAddr();
375
376  // If we don't have an available version of this value, it must be an
377  // instruction.
378  Instruction *Inst = cast<Instruction>(InVal);
379
380  // Handle cast of PHI translatable value.
381  if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
382    if (!isSafeToSpeculativelyExecute(Cast)) return 0;
383    Value *OpVal = InsertPHITranslatedSubExpr(Cast->getOperand(0),
384                                              CurBB, PredBB, DT, NewInsts);
385    if (OpVal == 0) return 0;
386
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);
393    return New;
394  }
395
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 == 0) return 0;
404      GEPOps.push_back(OpVal);
405    }
406
407    GetElementPtrInst *Result =
408      GetElementPtrInst::Create(GEPOps[0], makeArrayRef(GEPOps).slice(1),
409                                InVal->getName()+".phi.trans.insert",
410                                PredBB->getTerminator());
411    Result->setIsInBounds(GEP->isInBounds());
412    NewInsts.push_back(Result);
413    return Result;
414  }
415
416#if 0
417  // FIXME: This code works, but it is unclear that we actually want to insert
418  // a big chain of computation in order to make a value available in a block.
419  // This needs to be evaluated carefully to consider its cost trade offs.
420
421  // Handle add with a constant RHS.
422  if (Inst->getOpcode() == Instruction::Add &&
423      isa<ConstantInt>(Inst->getOperand(1))) {
424    // PHI translate the LHS.
425    Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0),
426                                              CurBB, PredBB, DT, NewInsts);
427    if (OpVal == 0) return 0;
428
429    BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1),
430                                           InVal->getName()+".phi.trans.insert",
431                                                    PredBB->getTerminator());
432    Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap());
433    Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap());
434    NewInsts.push_back(Res);
435    return Res;
436  }
437#endif
438
439  return 0;
440}
441