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/ValueTracking.h"
16#include "llvm/Constants.h"
17#include "llvm/Instructions.h"
18#include "llvm/Analysis/Dominators.h"
19#include "llvm/Analysis/InstructionSimplify.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#ifndef NDEBUG
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() << "Non phi translatable instruction found in PHITransAddr:\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 (Value::use_iterator UI = PHIIn->use_begin(), E = PHIIn->use_end();
206         UI != E; ++UI) {
207      if (CastInst *CastI = dyn_cast<CastInst>(*UI))
208        if (CastI->getOpcode() == Cast->getOpcode() &&
209            CastI->getType() == Cast->getType() &&
210            (!DT || DT->dominates(CastI->getParent(), PredBB)))
211          return CastI;
212    }
213    return 0;
214  }
215
216  // Handle getelementptr with at least one PHI translatable operand.
217  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
218    SmallVector<Value*, 8> GEPOps;
219    bool AnyChanged = false;
220    for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
221      Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB, DT);
222      if (GEPOp == 0) return 0;
223
224      AnyChanged |= GEPOp != GEP->getOperand(i);
225      GEPOps.push_back(GEPOp);
226    }
227
228    if (!AnyChanged)
229      return GEP;
230
231    // Simplify the GEP to handle 'gep x, 0' -> x etc.
232    if (Value *V = SimplifyGEPInst(GEPOps, TD, TLI, DT)) {
233      for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
234        RemoveInstInputs(GEPOps[i], InstInputs);
235
236      return AddAsInput(V);
237    }
238
239    // Scan to see if we have this GEP available.
240    Value *APHIOp = GEPOps[0];
241    for (Value::use_iterator UI = APHIOp->use_begin(), E = APHIOp->use_end();
242         UI != E; ++UI) {
243      if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI))
244        if (GEPI->getType() == GEP->getType() &&
245            GEPI->getNumOperands() == GEPOps.size() &&
246            GEPI->getParent()->getParent() == CurBB->getParent() &&
247            (!DT || DT->dominates(GEPI->getParent(), PredBB))) {
248          bool Mismatch = false;
249          for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
250            if (GEPI->getOperand(i) != GEPOps[i]) {
251              Mismatch = true;
252              break;
253            }
254          if (!Mismatch)
255            return GEPI;
256        }
257    }
258    return 0;
259  }
260
261  // Handle add with a constant RHS.
262  if (Inst->getOpcode() == Instruction::Add &&
263      isa<ConstantInt>(Inst->getOperand(1))) {
264    // PHI translate the LHS.
265    Constant *RHS = cast<ConstantInt>(Inst->getOperand(1));
266    bool isNSW = cast<BinaryOperator>(Inst)->hasNoSignedWrap();
267    bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap();
268
269    Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB, DT);
270    if (LHS == 0) return 0;
271
272    // If the PHI translated LHS is an add of a constant, fold the immediates.
273    if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS))
274      if (BOp->getOpcode() == Instruction::Add)
275        if (ConstantInt *CI = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
276          LHS = BOp->getOperand(0);
277          RHS = ConstantExpr::getAdd(RHS, CI);
278          isNSW = isNUW = false;
279
280          // If the old 'LHS' was an input, add the new 'LHS' as an input.
281          if (std::count(InstInputs.begin(), InstInputs.end(), BOp)) {
282            RemoveInstInputs(BOp, InstInputs);
283            AddAsInput(LHS);
284          }
285        }
286
287    // See if the add simplifies away.
288    if (Value *Res = SimplifyAddInst(LHS, RHS, isNSW, isNUW, TD, TLI, DT)) {
289      // If we simplified the operands, the LHS is no longer an input, but Res
290      // is.
291      RemoveInstInputs(LHS, InstInputs);
292      return AddAsInput(Res);
293    }
294
295    // If we didn't modify the add, just return it.
296    if (LHS == Inst->getOperand(0) && RHS == Inst->getOperand(1))
297      return Inst;
298
299    // Otherwise, see if we have this add available somewhere.
300    for (Value::use_iterator UI = LHS->use_begin(), E = LHS->use_end();
301         UI != E; ++UI) {
302      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*UI))
303        if (BO->getOpcode() == Instruction::Add &&
304            BO->getOperand(0) == LHS && BO->getOperand(1) == RHS &&
305            BO->getParent()->getParent() == CurBB->getParent() &&
306            (!DT || DT->dominates(BO->getParent(), PredBB)))
307          return BO;
308    }
309
310    return 0;
311  }
312
313  // Otherwise, we failed.
314  return 0;
315}
316
317
318/// PHITranslateValue - PHI translate the current address up the CFG from
319/// CurBB to Pred, updating our state to reflect any needed changes.  If the
320/// dominator tree DT is non-null, the translated value must dominate
321/// PredBB.  This returns true on failure and sets Addr to null.
322bool PHITransAddr::PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB,
323                                     const DominatorTree *DT) {
324  assert(Verify() && "Invalid PHITransAddr!");
325  Addr = PHITranslateSubExpr(Addr, CurBB, PredBB, DT);
326  assert(Verify() && "Invalid PHITransAddr!");
327
328  if (DT) {
329    // Make sure the value is live in the predecessor.
330    if (Instruction *Inst = dyn_cast_or_null<Instruction>(Addr))
331      if (!DT->dominates(Inst->getParent(), PredBB))
332        Addr = 0;
333  }
334
335  return Addr == 0;
336}
337
338/// PHITranslateWithInsertion - PHI translate this value into the specified
339/// predecessor block, inserting a computation of the value if it is
340/// unavailable.
341///
342/// All newly created instructions are added to the NewInsts list.  This
343/// returns null on failure.
344///
345Value *PHITransAddr::
346PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
347                          const DominatorTree &DT,
348                          SmallVectorImpl<Instruction*> &NewInsts) {
349  unsigned NISize = NewInsts.size();
350
351  // Attempt to PHI translate with insertion.
352  Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts);
353
354  // If successful, return the new value.
355  if (Addr) return Addr;
356
357  // If not, destroy any intermediate instructions inserted.
358  while (NewInsts.size() != NISize)
359    NewInsts.pop_back_val()->eraseFromParent();
360  return 0;
361}
362
363
364/// InsertPHITranslatedPointer - Insert a computation of the PHI translated
365/// version of 'V' for the edge PredBB->CurBB into the end of the PredBB
366/// block.  All newly created instructions are added to the NewInsts list.
367/// This returns null on failure.
368///
369Value *PHITransAddr::
370InsertPHITranslatedSubExpr(Value *InVal, BasicBlock *CurBB,
371                           BasicBlock *PredBB, const DominatorTree &DT,
372                           SmallVectorImpl<Instruction*> &NewInsts) {
373  // See if we have a version of this value already available and dominating
374  // PredBB.  If so, there is no need to insert a new instance of it.
375  PHITransAddr Tmp(InVal, TD);
376  if (!Tmp.PHITranslateValue(CurBB, PredBB, &DT))
377    return Tmp.getAddr();
378
379  // If we don't have an available version of this value, it must be an
380  // instruction.
381  Instruction *Inst = cast<Instruction>(InVal);
382
383  // Handle cast of PHI translatable value.
384  if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
385    if (!isSafeToSpeculativelyExecute(Cast)) return 0;
386    Value *OpVal = InsertPHITranslatedSubExpr(Cast->getOperand(0),
387                                              CurBB, PredBB, DT, NewInsts);
388    if (OpVal == 0) return 0;
389
390    // Otherwise insert a cast at the end of PredBB.
391    CastInst *New = CastInst::Create(Cast->getOpcode(),
392                                     OpVal, InVal->getType(),
393                                     InVal->getName()+".phi.trans.insert",
394                                     PredBB->getTerminator());
395    NewInsts.push_back(New);
396    return New;
397  }
398
399  // Handle getelementptr with at least one PHI operand.
400  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
401    SmallVector<Value*, 8> GEPOps;
402    BasicBlock *CurBB = GEP->getParent();
403    for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
404      Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i),
405                                                CurBB, PredBB, DT, NewInsts);
406      if (OpVal == 0) return 0;
407      GEPOps.push_back(OpVal);
408    }
409
410    GetElementPtrInst *Result =
411      GetElementPtrInst::Create(GEPOps[0], makeArrayRef(GEPOps).slice(1),
412                                InVal->getName()+".phi.trans.insert",
413                                PredBB->getTerminator());
414    Result->setIsInBounds(GEP->isInBounds());
415    NewInsts.push_back(Result);
416    return Result;
417  }
418
419#if 0
420  // FIXME: This code works, but it is unclear that we actually want to insert
421  // a big chain of computation in order to make a value available in a block.
422  // This needs to be evaluated carefully to consider its cost trade offs.
423
424  // Handle add with a constant RHS.
425  if (Inst->getOpcode() == Instruction::Add &&
426      isa<ConstantInt>(Inst->getOperand(1))) {
427    // PHI translate the LHS.
428    Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0),
429                                              CurBB, PredBB, DT, NewInsts);
430    if (OpVal == 0) return 0;
431
432    BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1),
433                                           InVal->getName()+".phi.trans.insert",
434                                                    PredBB->getTerminator());
435    Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap());
436    Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap());
437    NewInsts.push_back(Res);
438    return Res;
439  }
440#endif
441
442  return 0;
443}
444