LLVM API Documentation

PHITransAddr.cpp
Go to the documentation of this file.
00001 //===- PHITransAddr.cpp - PHI Translation for Addresses -------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the PHITransAddr class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Analysis/PHITransAddr.h"
00015 #include "llvm/Analysis/InstructionSimplify.h"
00016 #include "llvm/Analysis/ValueTracking.h"
00017 #include "llvm/IR/Constants.h"
00018 #include "llvm/IR/Dominators.h"
00019 #include "llvm/IR/Instructions.h"
00020 #include "llvm/Support/Debug.h"
00021 #include "llvm/Support/ErrorHandling.h"
00022 #include "llvm/Support/raw_ostream.h"
00023 using namespace llvm;
00024 
00025 static bool CanPHITrans(Instruction *Inst) {
00026   if (isa<PHINode>(Inst) ||
00027       isa<GetElementPtrInst>(Inst))
00028     return true;
00029 
00030   if (isa<CastInst>(Inst) &&
00031       isSafeToSpeculativelyExecute(Inst))
00032     return true;
00033 
00034   if (Inst->getOpcode() == Instruction::Add &&
00035       isa<ConstantInt>(Inst->getOperand(1)))
00036     return true;
00037 
00038   //   cerr << "MEMDEP: Could not PHI translate: " << *Pointer;
00039   //   if (isa<BitCastInst>(PtrInst) || isa<GetElementPtrInst>(PtrInst))
00040   //     cerr << "OP:\t\t\t\t" << *PtrInst->getOperand(0);
00041   return false;
00042 }
00043 
00044 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00045 void PHITransAddr::dump() const {
00046   if (!Addr) {
00047     dbgs() << "PHITransAddr: null\n";
00048     return;
00049   }
00050   dbgs() << "PHITransAddr: " << *Addr << "\n";
00051   for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
00052     dbgs() << "  Input #" << i << " is " << *InstInputs[i] << "\n";
00053 }
00054 #endif
00055 
00056 
00057 static bool VerifySubExpr(Value *Expr,
00058                           SmallVectorImpl<Instruction*> &InstInputs) {
00059   // If this is a non-instruction value, there is nothing to do.
00060   Instruction *I = dyn_cast<Instruction>(Expr);
00061   if (!I) return true;
00062 
00063   // If it's an instruction, it is either in Tmp or its operands recursively
00064   // are.
00065   SmallVectorImpl<Instruction*>::iterator Entry =
00066     std::find(InstInputs.begin(), InstInputs.end(), I);
00067   if (Entry != InstInputs.end()) {
00068     InstInputs.erase(Entry);
00069     return true;
00070   }
00071 
00072   // If it isn't in the InstInputs list it is a subexpr incorporated into the
00073   // address.  Sanity check that it is phi translatable.
00074   if (!CanPHITrans(I)) {
00075     errs() << "Instruction in PHITransAddr is not phi-translatable:\n";
00076     errs() << *I << '\n';
00077     llvm_unreachable("Either something is missing from InstInputs or "
00078                      "CanPHITrans is wrong.");
00079   }
00080 
00081   // Validate the operands of the instruction.
00082   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00083     if (!VerifySubExpr(I->getOperand(i), InstInputs))
00084       return false;
00085 
00086   return true;
00087 }
00088 
00089 /// Verify - Check internal consistency of this data structure.  If the
00090 /// structure is valid, it returns true.  If invalid, it prints errors and
00091 /// returns false.
00092 bool PHITransAddr::Verify() const {
00093   if (!Addr) return true;
00094 
00095   SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());
00096 
00097   if (!VerifySubExpr(Addr, Tmp))
00098     return false;
00099 
00100   if (!Tmp.empty()) {
00101     errs() << "PHITransAddr contains extra instructions:\n";
00102     for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
00103       errs() << "  InstInput #" << i << " is " << *InstInputs[i] << "\n";
00104     llvm_unreachable("This is unexpected.");
00105   }
00106 
00107   // a-ok.
00108   return true;
00109 }
00110 
00111 
00112 /// IsPotentiallyPHITranslatable - If this needs PHI translation, return true
00113 /// if we have some hope of doing it.  This should be used as a filter to
00114 /// avoid calling PHITranslateValue in hopeless situations.
00115 bool PHITransAddr::IsPotentiallyPHITranslatable() const {
00116   // If the input value is not an instruction, or if it is not defined in CurBB,
00117   // then we don't need to phi translate it.
00118   Instruction *Inst = dyn_cast<Instruction>(Addr);
00119   return !Inst || CanPHITrans(Inst);
00120 }
00121 
00122 
00123 static void RemoveInstInputs(Value *V,
00124                              SmallVectorImpl<Instruction*> &InstInputs) {
00125   Instruction *I = dyn_cast<Instruction>(V);
00126   if (!I) return;
00127 
00128   // If the instruction is in the InstInputs list, remove it.
00129   SmallVectorImpl<Instruction*>::iterator Entry =
00130     std::find(InstInputs.begin(), InstInputs.end(), I);
00131   if (Entry != InstInputs.end()) {
00132     InstInputs.erase(Entry);
00133     return;
00134   }
00135 
00136   assert(!isa<PHINode>(I) && "Error, removing something that isn't an input");
00137 
00138   // Otherwise, it must have instruction inputs itself.  Zap them recursively.
00139   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
00140     if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
00141       RemoveInstInputs(Op, InstInputs);
00142   }
00143 }
00144 
00145 Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB,
00146                                          BasicBlock *PredBB,
00147                                          const DominatorTree *DT) {
00148   // If this is a non-instruction value, it can't require PHI translation.
00149   Instruction *Inst = dyn_cast<Instruction>(V);
00150   if (!Inst) return V;
00151 
00152   // Determine whether 'Inst' is an input to our PHI translatable expression.
00153   bool isInput = std::count(InstInputs.begin(), InstInputs.end(), Inst);
00154 
00155   // Handle inputs instructions if needed.
00156   if (isInput) {
00157     if (Inst->getParent() != CurBB) {
00158       // If it is an input defined in a different block, then it remains an
00159       // input.
00160       return Inst;
00161     }
00162 
00163     // If 'Inst' is defined in this block and is an input that needs to be phi
00164     // translated, we need to incorporate the value into the expression or fail.
00165 
00166     // In either case, the instruction itself isn't an input any longer.
00167     InstInputs.erase(std::find(InstInputs.begin(), InstInputs.end(), Inst));
00168 
00169     // If this is a PHI, go ahead and translate it.
00170     if (PHINode *PN = dyn_cast<PHINode>(Inst))
00171       return AddAsInput(PN->getIncomingValueForBlock(PredBB));
00172 
00173     // If this is a non-phi value, and it is analyzable, we can incorporate it
00174     // into the expression by making all instruction operands be inputs.
00175     if (!CanPHITrans(Inst))
00176       return nullptr;
00177 
00178     // All instruction operands are now inputs (and of course, they may also be
00179     // defined in this block, so they may need to be phi translated themselves.
00180     for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
00181       if (Instruction *Op = dyn_cast<Instruction>(Inst->getOperand(i)))
00182         InstInputs.push_back(Op);
00183   }
00184 
00185   // Ok, it must be an intermediate result (either because it started that way
00186   // or because we just incorporated it into the expression).  See if its
00187   // operands need to be phi translated, and if so, reconstruct it.
00188 
00189   if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
00190     if (!isSafeToSpeculativelyExecute(Cast)) return nullptr;
00191     Value *PHIIn = PHITranslateSubExpr(Cast->getOperand(0), CurBB, PredBB, DT);
00192     if (!PHIIn) return nullptr;
00193     if (PHIIn == Cast->getOperand(0))
00194       return Cast;
00195 
00196     // Find an available version of this cast.
00197 
00198     // Constants are trivial to find.
00199     if (Constant *C = dyn_cast<Constant>(PHIIn))
00200       return AddAsInput(ConstantExpr::getCast(Cast->getOpcode(),
00201                                               C, Cast->getType()));
00202 
00203     // Otherwise we have to see if a casted version of the incoming pointer
00204     // is available.  If so, we can use it, otherwise we have to fail.
00205     for (User *U : PHIIn->users()) {
00206       if (CastInst *CastI = dyn_cast<CastInst>(U))
00207         if (CastI->getOpcode() == Cast->getOpcode() &&
00208             CastI->getType() == Cast->getType() &&
00209             (!DT || DT->dominates(CastI->getParent(), PredBB)))
00210           return CastI;
00211     }
00212     return nullptr;
00213   }
00214 
00215   // Handle getelementptr with at least one PHI translatable operand.
00216   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
00217     SmallVector<Value*, 8> GEPOps;
00218     bool AnyChanged = false;
00219     for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
00220       Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB, DT);
00221       if (!GEPOp) return nullptr;
00222 
00223       AnyChanged |= GEPOp != GEP->getOperand(i);
00224       GEPOps.push_back(GEPOp);
00225     }
00226 
00227     if (!AnyChanged)
00228       return GEP;
00229 
00230     // Simplify the GEP to handle 'gep x, 0' -> x etc.
00231     if (Value *V = SimplifyGEPInst(GEPOps, DL, TLI, DT, AT)) {
00232       for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
00233         RemoveInstInputs(GEPOps[i], InstInputs);
00234 
00235       return AddAsInput(V);
00236     }
00237 
00238     // Scan to see if we have this GEP available.
00239     Value *APHIOp = GEPOps[0];
00240     for (User *U : APHIOp->users()) {
00241       if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
00242         if (GEPI->getType() == GEP->getType() &&
00243             GEPI->getNumOperands() == GEPOps.size() &&
00244             GEPI->getParent()->getParent() == CurBB->getParent() &&
00245             (!DT || DT->dominates(GEPI->getParent(), PredBB))) {
00246           bool Mismatch = false;
00247           for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
00248             if (GEPI->getOperand(i) != GEPOps[i]) {
00249               Mismatch = true;
00250               break;
00251             }
00252           if (!Mismatch)
00253             return GEPI;
00254         }
00255     }
00256     return nullptr;
00257   }
00258 
00259   // Handle add with a constant RHS.
00260   if (Inst->getOpcode() == Instruction::Add &&
00261       isa<ConstantInt>(Inst->getOperand(1))) {
00262     // PHI translate the LHS.
00263     Constant *RHS = cast<ConstantInt>(Inst->getOperand(1));
00264     bool isNSW = cast<BinaryOperator>(Inst)->hasNoSignedWrap();
00265     bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap();
00266 
00267     Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB, DT);
00268     if (!LHS) return nullptr;
00269 
00270     // If the PHI translated LHS is an add of a constant, fold the immediates.
00271     if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS))
00272       if (BOp->getOpcode() == Instruction::Add)
00273         if (ConstantInt *CI = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
00274           LHS = BOp->getOperand(0);
00275           RHS = ConstantExpr::getAdd(RHS, CI);
00276           isNSW = isNUW = false;
00277 
00278           // If the old 'LHS' was an input, add the new 'LHS' as an input.
00279           if (std::count(InstInputs.begin(), InstInputs.end(), BOp)) {
00280             RemoveInstInputs(BOp, InstInputs);
00281             AddAsInput(LHS);
00282           }
00283         }
00284 
00285     // See if the add simplifies away.
00286     if (Value *Res = SimplifyAddInst(LHS, RHS, isNSW, isNUW, DL, TLI, DT, AT)) {
00287       // If we simplified the operands, the LHS is no longer an input, but Res
00288       // is.
00289       RemoveInstInputs(LHS, InstInputs);
00290       return AddAsInput(Res);
00291     }
00292 
00293     // If we didn't modify the add, just return it.
00294     if (LHS == Inst->getOperand(0) && RHS == Inst->getOperand(1))
00295       return Inst;
00296 
00297     // Otherwise, see if we have this add available somewhere.
00298     for (User *U : LHS->users()) {
00299       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U))
00300         if (BO->getOpcode() == Instruction::Add &&
00301             BO->getOperand(0) == LHS && BO->getOperand(1) == RHS &&
00302             BO->getParent()->getParent() == CurBB->getParent() &&
00303             (!DT || DT->dominates(BO->getParent(), PredBB)))
00304           return BO;
00305     }
00306 
00307     return nullptr;
00308   }
00309 
00310   // Otherwise, we failed.
00311   return nullptr;
00312 }
00313 
00314 
00315 /// PHITranslateValue - PHI translate the current address up the CFG from
00316 /// CurBB to Pred, updating our state to reflect any needed changes.  If the
00317 /// dominator tree DT is non-null, the translated value must dominate
00318 /// PredBB.  This returns true on failure and sets Addr to null.
00319 bool PHITransAddr::PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB,
00320                                      const DominatorTree *DT) {
00321   assert(Verify() && "Invalid PHITransAddr!");
00322   Addr = PHITranslateSubExpr(Addr, CurBB, PredBB, DT);
00323   assert(Verify() && "Invalid PHITransAddr!");
00324 
00325   if (DT) {
00326     // Make sure the value is live in the predecessor.
00327     if (Instruction *Inst = dyn_cast_or_null<Instruction>(Addr))
00328       if (!DT->dominates(Inst->getParent(), PredBB))
00329         Addr = nullptr;
00330   }
00331 
00332   return Addr == nullptr;
00333 }
00334 
00335 /// PHITranslateWithInsertion - PHI translate this value into the specified
00336 /// predecessor block, inserting a computation of the value if it is
00337 /// unavailable.
00338 ///
00339 /// All newly created instructions are added to the NewInsts list.  This
00340 /// returns null on failure.
00341 ///
00342 Value *PHITransAddr::
00343 PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
00344                           const DominatorTree &DT,
00345                           SmallVectorImpl<Instruction*> &NewInsts) {
00346   unsigned NISize = NewInsts.size();
00347 
00348   // Attempt to PHI translate with insertion.
00349   Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts);
00350 
00351   // If successful, return the new value.
00352   if (Addr) return Addr;
00353 
00354   // If not, destroy any intermediate instructions inserted.
00355   while (NewInsts.size() != NISize)
00356     NewInsts.pop_back_val()->eraseFromParent();
00357   return nullptr;
00358 }
00359 
00360 
00361 /// InsertPHITranslatedPointer - Insert a computation of the PHI translated
00362 /// version of 'V' for the edge PredBB->CurBB into the end of the PredBB
00363 /// block.  All newly created instructions are added to the NewInsts list.
00364 /// This returns null on failure.
00365 ///
00366 Value *PHITransAddr::
00367 InsertPHITranslatedSubExpr(Value *InVal, BasicBlock *CurBB,
00368                            BasicBlock *PredBB, const DominatorTree &DT,
00369                            SmallVectorImpl<Instruction*> &NewInsts) {
00370   // See if we have a version of this value already available and dominating
00371   // PredBB.  If so, there is no need to insert a new instance of it.
00372   PHITransAddr Tmp(InVal, DL, AT);
00373   if (!Tmp.PHITranslateValue(CurBB, PredBB, &DT))
00374     return Tmp.getAddr();
00375 
00376   // If we don't have an available version of this value, it must be an
00377   // instruction.
00378   Instruction *Inst = cast<Instruction>(InVal);
00379 
00380   // Handle cast of PHI translatable value.
00381   if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
00382     if (!isSafeToSpeculativelyExecute(Cast)) return nullptr;
00383     Value *OpVal = InsertPHITranslatedSubExpr(Cast->getOperand(0),
00384                                               CurBB, PredBB, DT, NewInsts);
00385     if (!OpVal) return nullptr;
00386 
00387     // Otherwise insert a cast at the end of PredBB.
00388     CastInst *New = CastInst::Create(Cast->getOpcode(),
00389                                      OpVal, InVal->getType(),
00390                                      InVal->getName()+".phi.trans.insert",
00391                                      PredBB->getTerminator());
00392     NewInsts.push_back(New);
00393     return New;
00394   }
00395 
00396   // Handle getelementptr with at least one PHI operand.
00397   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
00398     SmallVector<Value*, 8> GEPOps;
00399     BasicBlock *CurBB = GEP->getParent();
00400     for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
00401       Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i),
00402                                                 CurBB, PredBB, DT, NewInsts);
00403       if (!OpVal) return nullptr;
00404       GEPOps.push_back(OpVal);
00405     }
00406 
00407     GetElementPtrInst *Result =
00408       GetElementPtrInst::Create(GEPOps[0], makeArrayRef(GEPOps).slice(1),
00409                                 InVal->getName()+".phi.trans.insert",
00410                                 PredBB->getTerminator());
00411     Result->setIsInBounds(GEP->isInBounds());
00412     NewInsts.push_back(Result);
00413     return Result;
00414   }
00415 
00416 #if 0
00417   // FIXME: This code works, but it is unclear that we actually want to insert
00418   // a big chain of computation in order to make a value available in a block.
00419   // This needs to be evaluated carefully to consider its cost trade offs.
00420 
00421   // Handle add with a constant RHS.
00422   if (Inst->getOpcode() == Instruction::Add &&
00423       isa<ConstantInt>(Inst->getOperand(1))) {
00424     // PHI translate the LHS.
00425     Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0),
00426                                               CurBB, PredBB, DT, NewInsts);
00427     if (OpVal == 0) return 0;
00428 
00429     BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1),
00430                                            InVal->getName()+".phi.trans.insert",
00431                                                     PredBB->getTerminator());
00432     Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap());
00433     Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap());
00434     NewInsts.push_back(Res);
00435     return Res;
00436   }
00437 #endif
00438 
00439   return nullptr;
00440 }