LLVM API Documentation

Local.cpp
Go to the documentation of this file.
00001 //===-- Local.cpp - Functions to perform local transformations ------------===//
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 family of functions perform various local transformations to the
00011 // program.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Transforms/Utils/Local.h"
00016 #include "llvm/ADT/DenseMap.h"
00017 #include "llvm/ADT/STLExtras.h"
00018 #include "llvm/ADT/SmallPtrSet.h"
00019 #include "llvm/ADT/Statistic.h"
00020 #include "llvm/Analysis/LibCallSemantics.h"
00021 #include "llvm/Analysis/InstructionSimplify.h"
00022 #include "llvm/Analysis/MemoryBuiltins.h"
00023 #include "llvm/Analysis/ValueTracking.h"
00024 #include "llvm/IR/CFG.h"
00025 #include "llvm/IR/Constants.h"
00026 #include "llvm/IR/DIBuilder.h"
00027 #include "llvm/IR/DataLayout.h"
00028 #include "llvm/IR/DebugInfo.h"
00029 #include "llvm/IR/DerivedTypes.h"
00030 #include "llvm/IR/Dominators.h"
00031 #include "llvm/IR/GetElementPtrTypeIterator.h"
00032 #include "llvm/IR/GlobalAlias.h"
00033 #include "llvm/IR/GlobalVariable.h"
00034 #include "llvm/IR/IRBuilder.h"
00035 #include "llvm/IR/Instructions.h"
00036 #include "llvm/IR/IntrinsicInst.h"
00037 #include "llvm/IR/Intrinsics.h"
00038 #include "llvm/IR/MDBuilder.h"
00039 #include "llvm/IR/Metadata.h"
00040 #include "llvm/IR/Operator.h"
00041 #include "llvm/IR/ValueHandle.h"
00042 #include "llvm/Support/Debug.h"
00043 #include "llvm/Support/MathExtras.h"
00044 #include "llvm/Support/raw_ostream.h"
00045 using namespace llvm;
00046 
00047 #define DEBUG_TYPE "local"
00048 
00049 STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
00050 
00051 //===----------------------------------------------------------------------===//
00052 //  Local constant propagation.
00053 //
00054 
00055 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
00056 /// constant value, convert it into an unconditional branch to the constant
00057 /// destination.  This is a nontrivial operation because the successors of this
00058 /// basic block must have their PHI nodes updated.
00059 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
00060 /// conditions and indirectbr addresses this might make dead if
00061 /// DeleteDeadConditions is true.
00062 bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
00063                                   const TargetLibraryInfo *TLI) {
00064   TerminatorInst *T = BB->getTerminator();
00065   IRBuilder<> Builder(T);
00066 
00067   // Branch - See if we are conditional jumping on constant
00068   if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
00069     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
00070     BasicBlock *Dest1 = BI->getSuccessor(0);
00071     BasicBlock *Dest2 = BI->getSuccessor(1);
00072 
00073     if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
00074       // Are we branching on constant?
00075       // YES.  Change to unconditional branch...
00076       BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
00077       BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
00078 
00079       //cerr << "Function: " << T->getParent()->getParent()
00080       //     << "\nRemoving branch from " << T->getParent()
00081       //     << "\n\nTo: " << OldDest << endl;
00082 
00083       // Let the basic block know that we are letting go of it.  Based on this,
00084       // it will adjust it's PHI nodes.
00085       OldDest->removePredecessor(BB);
00086 
00087       // Replace the conditional branch with an unconditional one.
00088       Builder.CreateBr(Destination);
00089       BI->eraseFromParent();
00090       return true;
00091     }
00092 
00093     if (Dest2 == Dest1) {       // Conditional branch to same location?
00094       // This branch matches something like this:
00095       //     br bool %cond, label %Dest, label %Dest
00096       // and changes it into:  br label %Dest
00097 
00098       // Let the basic block know that we are letting go of one copy of it.
00099       assert(BI->getParent() && "Terminator not inserted in block!");
00100       Dest1->removePredecessor(BI->getParent());
00101 
00102       // Replace the conditional branch with an unconditional one.
00103       Builder.CreateBr(Dest1);
00104       Value *Cond = BI->getCondition();
00105       BI->eraseFromParent();
00106       if (DeleteDeadConditions)
00107         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
00108       return true;
00109     }
00110     return false;
00111   }
00112 
00113   if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
00114     // If we are switching on a constant, we can convert the switch to an
00115     // unconditional branch.
00116     ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
00117     BasicBlock *DefaultDest = SI->getDefaultDest();
00118     BasicBlock *TheOnlyDest = DefaultDest;
00119 
00120     // If the default is unreachable, ignore it when searching for TheOnlyDest.
00121     if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
00122         SI->getNumCases() > 0) {
00123       TheOnlyDest = SI->case_begin().getCaseSuccessor();
00124     }
00125 
00126     // Figure out which case it goes to.
00127     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
00128          i != e; ++i) {
00129       // Found case matching a constant operand?
00130       if (i.getCaseValue() == CI) {
00131         TheOnlyDest = i.getCaseSuccessor();
00132         break;
00133       }
00134 
00135       // Check to see if this branch is going to the same place as the default
00136       // dest.  If so, eliminate it as an explicit compare.
00137       if (i.getCaseSuccessor() == DefaultDest) {
00138         MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
00139         unsigned NCases = SI->getNumCases();
00140         // Fold the case metadata into the default if there will be any branches
00141         // left, unless the metadata doesn't match the switch.
00142         if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
00143           // Collect branch weights into a vector.
00144           SmallVector<uint32_t, 8> Weights;
00145           for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
00146                ++MD_i) {
00147             ConstantInt *CI =
00148                 mdconst::dyn_extract<ConstantInt>(MD->getOperand(MD_i));
00149             assert(CI);
00150             Weights.push_back(CI->getValue().getZExtValue());
00151           }
00152           // Merge weight of this case to the default weight.
00153           unsigned idx = i.getCaseIndex();
00154           Weights[0] += Weights[idx+1];
00155           // Remove weight for this case.
00156           std::swap(Weights[idx+1], Weights.back());
00157           Weights.pop_back();
00158           SI->setMetadata(LLVMContext::MD_prof,
00159                           MDBuilder(BB->getContext()).
00160                           createBranchWeights(Weights));
00161         }
00162         // Remove this entry.
00163         DefaultDest->removePredecessor(SI->getParent());
00164         SI->removeCase(i);
00165         --i; --e;
00166         continue;
00167       }
00168 
00169       // Otherwise, check to see if the switch only branches to one destination.
00170       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
00171       // destinations.
00172       if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = nullptr;
00173     }
00174 
00175     if (CI && !TheOnlyDest) {
00176       // Branching on a constant, but not any of the cases, go to the default
00177       // successor.
00178       TheOnlyDest = SI->getDefaultDest();
00179     }
00180 
00181     // If we found a single destination that we can fold the switch into, do so
00182     // now.
00183     if (TheOnlyDest) {
00184       // Insert the new branch.
00185       Builder.CreateBr(TheOnlyDest);
00186       BasicBlock *BB = SI->getParent();
00187 
00188       // Remove entries from PHI nodes which we no longer branch to...
00189       for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
00190         // Found case matching a constant operand?
00191         BasicBlock *Succ = SI->getSuccessor(i);
00192         if (Succ == TheOnlyDest)
00193           TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
00194         else
00195           Succ->removePredecessor(BB);
00196       }
00197 
00198       // Delete the old switch.
00199       Value *Cond = SI->getCondition();
00200       SI->eraseFromParent();
00201       if (DeleteDeadConditions)
00202         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
00203       return true;
00204     }
00205 
00206     if (SI->getNumCases() == 1) {
00207       // Otherwise, we can fold this switch into a conditional branch
00208       // instruction if it has only one non-default destination.
00209       SwitchInst::CaseIt FirstCase = SI->case_begin();
00210       Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
00211           FirstCase.getCaseValue(), "cond");
00212 
00213       // Insert the new branch.
00214       BranchInst *NewBr = Builder.CreateCondBr(Cond,
00215                                                FirstCase.getCaseSuccessor(),
00216                                                SI->getDefaultDest());
00217       MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
00218       if (MD && MD->getNumOperands() == 3) {
00219         ConstantInt *SICase =
00220             mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
00221         ConstantInt *SIDef =
00222             mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
00223         assert(SICase && SIDef);
00224         // The TrueWeight should be the weight for the single case of SI.
00225         NewBr->setMetadata(LLVMContext::MD_prof,
00226                         MDBuilder(BB->getContext()).
00227                         createBranchWeights(SICase->getValue().getZExtValue(),
00228                                             SIDef->getValue().getZExtValue()));
00229       }
00230 
00231       // Delete the old switch.
00232       SI->eraseFromParent();
00233       return true;
00234     }
00235     return false;
00236   }
00237 
00238   if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
00239     // indirectbr blockaddress(@F, @BB) -> br label @BB
00240     if (BlockAddress *BA =
00241           dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
00242       BasicBlock *TheOnlyDest = BA->getBasicBlock();
00243       // Insert the new branch.
00244       Builder.CreateBr(TheOnlyDest);
00245 
00246       for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
00247         if (IBI->getDestination(i) == TheOnlyDest)
00248           TheOnlyDest = nullptr;
00249         else
00250           IBI->getDestination(i)->removePredecessor(IBI->getParent());
00251       }
00252       Value *Address = IBI->getAddress();
00253       IBI->eraseFromParent();
00254       if (DeleteDeadConditions)
00255         RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
00256 
00257       // If we didn't find our destination in the IBI successor list, then we
00258       // have undefined behavior.  Replace the unconditional branch with an
00259       // 'unreachable' instruction.
00260       if (TheOnlyDest) {
00261         BB->getTerminator()->eraseFromParent();
00262         new UnreachableInst(BB->getContext(), BB);
00263       }
00264 
00265       return true;
00266     }
00267   }
00268 
00269   return false;
00270 }
00271 
00272 
00273 //===----------------------------------------------------------------------===//
00274 //  Local dead code elimination.
00275 //
00276 
00277 /// isInstructionTriviallyDead - Return true if the result produced by the
00278 /// instruction is not used, and the instruction has no side effects.
00279 ///
00280 bool llvm::isInstructionTriviallyDead(Instruction *I,
00281                                       const TargetLibraryInfo *TLI) {
00282   if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
00283 
00284   // We don't want the landingpad instruction removed by anything this general.
00285   if (isa<LandingPadInst>(I))
00286     return false;
00287 
00288   // We don't want debug info removed by anything this general, unless
00289   // debug info is empty.
00290   if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
00291     if (DDI->getAddress())
00292       return false;
00293     return true;
00294   }
00295   if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
00296     if (DVI->getValue())
00297       return false;
00298     return true;
00299   }
00300 
00301   if (!I->mayHaveSideEffects()) return true;
00302 
00303   // Special case intrinsics that "may have side effects" but can be deleted
00304   // when dead.
00305   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00306     // Safe to delete llvm.stacksave if dead.
00307     if (II->getIntrinsicID() == Intrinsic::stacksave)
00308       return true;
00309 
00310     // Lifetime intrinsics are dead when their right-hand is undef.
00311     if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
00312         II->getIntrinsicID() == Intrinsic::lifetime_end)
00313       return isa<UndefValue>(II->getArgOperand(1));
00314 
00315     // Assumptions are dead if their condition is trivially true.
00316     if (II->getIntrinsicID() == Intrinsic::assume) {
00317       if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
00318         return !Cond->isZero();
00319 
00320       return false;
00321     }
00322   }
00323 
00324   if (isAllocLikeFn(I, TLI)) return true;
00325 
00326   if (CallInst *CI = isFreeCall(I, TLI))
00327     if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
00328       return C->isNullValue() || isa<UndefValue>(C);
00329 
00330   return false;
00331 }
00332 
00333 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
00334 /// trivially dead instruction, delete it.  If that makes any of its operands
00335 /// trivially dead, delete them too, recursively.  Return true if any
00336 /// instructions were deleted.
00337 bool
00338 llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
00339                                                  const TargetLibraryInfo *TLI) {
00340   Instruction *I = dyn_cast<Instruction>(V);
00341   if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
00342     return false;
00343 
00344   SmallVector<Instruction*, 16> DeadInsts;
00345   DeadInsts.push_back(I);
00346 
00347   do {
00348     I = DeadInsts.pop_back_val();
00349 
00350     // Null out all of the instruction's operands to see if any operand becomes
00351     // dead as we go.
00352     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
00353       Value *OpV = I->getOperand(i);
00354       I->setOperand(i, nullptr);
00355 
00356       if (!OpV->use_empty()) continue;
00357 
00358       // If the operand is an instruction that became dead as we nulled out the
00359       // operand, and if it is 'trivially' dead, delete it in a future loop
00360       // iteration.
00361       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
00362         if (isInstructionTriviallyDead(OpI, TLI))
00363           DeadInsts.push_back(OpI);
00364     }
00365 
00366     I->eraseFromParent();
00367   } while (!DeadInsts.empty());
00368 
00369   return true;
00370 }
00371 
00372 /// areAllUsesEqual - Check whether the uses of a value are all the same.
00373 /// This is similar to Instruction::hasOneUse() except this will also return
00374 /// true when there are no uses or multiple uses that all refer to the same
00375 /// value.
00376 static bool areAllUsesEqual(Instruction *I) {
00377   Value::user_iterator UI = I->user_begin();
00378   Value::user_iterator UE = I->user_end();
00379   if (UI == UE)
00380     return true;
00381 
00382   User *TheUse = *UI;
00383   for (++UI; UI != UE; ++UI) {
00384     if (*UI != TheUse)
00385       return false;
00386   }
00387   return true;
00388 }
00389 
00390 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
00391 /// dead PHI node, due to being a def-use chain of single-use nodes that
00392 /// either forms a cycle or is terminated by a trivially dead instruction,
00393 /// delete it.  If that makes any of its operands trivially dead, delete them
00394 /// too, recursively.  Return true if a change was made.
00395 bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
00396                                         const TargetLibraryInfo *TLI) {
00397   SmallPtrSet<Instruction*, 4> Visited;
00398   for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
00399        I = cast<Instruction>(*I->user_begin())) {
00400     if (I->use_empty())
00401       return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
00402 
00403     // If we find an instruction more than once, we're on a cycle that
00404     // won't prove fruitful.
00405     if (!Visited.insert(I).second) {
00406       // Break the cycle and delete the instruction and its operands.
00407       I->replaceAllUsesWith(UndefValue::get(I->getType()));
00408       (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
00409       return true;
00410     }
00411   }
00412   return false;
00413 }
00414 
00415 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
00416 /// simplify any instructions in it and recursively delete dead instructions.
00417 ///
00418 /// This returns true if it changed the code, note that it can delete
00419 /// instructions in other blocks as well in this block.
00420 bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const DataLayout *TD,
00421                                        const TargetLibraryInfo *TLI) {
00422   bool MadeChange = false;
00423 
00424 #ifndef NDEBUG
00425   // In debug builds, ensure that the terminator of the block is never replaced
00426   // or deleted by these simplifications. The idea of simplification is that it
00427   // cannot introduce new instructions, and there is no way to replace the
00428   // terminator of a block without introducing a new instruction.
00429   AssertingVH<Instruction> TerminatorVH(--BB->end());
00430 #endif
00431 
00432   for (BasicBlock::iterator BI = BB->begin(), E = --BB->end(); BI != E; ) {
00433     assert(!BI->isTerminator());
00434     Instruction *Inst = BI++;
00435 
00436     WeakVH BIHandle(BI);
00437     if (recursivelySimplifyInstruction(Inst, TD, TLI)) {
00438       MadeChange = true;
00439       if (BIHandle != BI)
00440         BI = BB->begin();
00441       continue;
00442     }
00443 
00444     MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
00445     if (BIHandle != BI)
00446       BI = BB->begin();
00447   }
00448   return MadeChange;
00449 }
00450 
00451 //===----------------------------------------------------------------------===//
00452 //  Control Flow Graph Restructuring.
00453 //
00454 
00455 
00456 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
00457 /// method is called when we're about to delete Pred as a predecessor of BB.  If
00458 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
00459 ///
00460 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
00461 /// nodes that collapse into identity values.  For example, if we have:
00462 ///   x = phi(1, 0, 0, 0)
00463 ///   y = and x, z
00464 ///
00465 /// .. and delete the predecessor corresponding to the '1', this will attempt to
00466 /// recursively fold the and to 0.
00467 void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
00468                                         DataLayout *TD) {
00469   // This only adjusts blocks with PHI nodes.
00470   if (!isa<PHINode>(BB->begin()))
00471     return;
00472 
00473   // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
00474   // them down.  This will leave us with single entry phi nodes and other phis
00475   // that can be removed.
00476   BB->removePredecessor(Pred, true);
00477 
00478   WeakVH PhiIt = &BB->front();
00479   while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
00480     PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
00481     Value *OldPhiIt = PhiIt;
00482 
00483     if (!recursivelySimplifyInstruction(PN, TD))
00484       continue;
00485 
00486     // If recursive simplification ended up deleting the next PHI node we would
00487     // iterate to, then our iterator is invalid, restart scanning from the top
00488     // of the block.
00489     if (PhiIt != OldPhiIt) PhiIt = &BB->front();
00490   }
00491 }
00492 
00493 
00494 /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
00495 /// predecessor is known to have one successor (DestBB!).  Eliminate the edge
00496 /// between them, moving the instructions in the predecessor into DestBB and
00497 /// deleting the predecessor block.
00498 ///
00499 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, DominatorTree *DT) {
00500   // If BB has single-entry PHI nodes, fold them.
00501   while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
00502     Value *NewVal = PN->getIncomingValue(0);
00503     // Replace self referencing PHI with undef, it must be dead.
00504     if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
00505     PN->replaceAllUsesWith(NewVal);
00506     PN->eraseFromParent();
00507   }
00508 
00509   BasicBlock *PredBB = DestBB->getSinglePredecessor();
00510   assert(PredBB && "Block doesn't have a single predecessor!");
00511 
00512   // Zap anything that took the address of DestBB.  Not doing this will give the
00513   // address an invalid value.
00514   if (DestBB->hasAddressTaken()) {
00515     BlockAddress *BA = BlockAddress::get(DestBB);
00516     Constant *Replacement =
00517       ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
00518     BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
00519                                                      BA->getType()));
00520     BA->destroyConstant();
00521   }
00522 
00523   // Anything that branched to PredBB now branches to DestBB.
00524   PredBB->replaceAllUsesWith(DestBB);
00525 
00526   // Splice all the instructions from PredBB to DestBB.
00527   PredBB->getTerminator()->eraseFromParent();
00528   DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
00529 
00530   // If the PredBB is the entry block of the function, move DestBB up to
00531   // become the entry block after we erase PredBB.
00532   if (PredBB == &DestBB->getParent()->getEntryBlock())
00533     DestBB->moveAfter(PredBB);
00534 
00535   if (DT) {
00536     BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
00537     DT->changeImmediateDominator(DestBB, PredBBIDom);
00538     DT->eraseNode(PredBB);
00539   }
00540   // Nuke BB.
00541   PredBB->eraseFromParent();
00542 }
00543 
00544 /// CanMergeValues - Return true if we can choose one of these values to use
00545 /// in place of the other. Note that we will always choose the non-undef
00546 /// value to keep.
00547 static bool CanMergeValues(Value *First, Value *Second) {
00548   return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
00549 }
00550 
00551 /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
00552 /// almost-empty BB ending in an unconditional branch to Succ, into Succ.
00553 ///
00554 /// Assumption: Succ is the single successor for BB.
00555 ///
00556 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
00557   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
00558 
00559   DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
00560         << Succ->getName() << "\n");
00561   // Shortcut, if there is only a single predecessor it must be BB and merging
00562   // is always safe
00563   if (Succ->getSinglePredecessor()) return true;
00564 
00565   // Make a list of the predecessors of BB
00566   SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
00567 
00568   // Look at all the phi nodes in Succ, to see if they present a conflict when
00569   // merging these blocks
00570   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
00571     PHINode *PN = cast<PHINode>(I);
00572 
00573     // If the incoming value from BB is again a PHINode in
00574     // BB which has the same incoming value for *PI as PN does, we can
00575     // merge the phi nodes and then the blocks can still be merged
00576     PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
00577     if (BBPN && BBPN->getParent() == BB) {
00578       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
00579         BasicBlock *IBB = PN->getIncomingBlock(PI);
00580         if (BBPreds.count(IBB) &&
00581             !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
00582                             PN->getIncomingValue(PI))) {
00583           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
00584                 << Succ->getName() << " is conflicting with "
00585                 << BBPN->getName() << " with regard to common predecessor "
00586                 << IBB->getName() << "\n");
00587           return false;
00588         }
00589       }
00590     } else {
00591       Value* Val = PN->getIncomingValueForBlock(BB);
00592       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
00593         // See if the incoming value for the common predecessor is equal to the
00594         // one for BB, in which case this phi node will not prevent the merging
00595         // of the block.
00596         BasicBlock *IBB = PN->getIncomingBlock(PI);
00597         if (BBPreds.count(IBB) &&
00598             !CanMergeValues(Val, PN->getIncomingValue(PI))) {
00599           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
00600                 << Succ->getName() << " is conflicting with regard to common "
00601                 << "predecessor " << IBB->getName() << "\n");
00602           return false;
00603         }
00604       }
00605     }
00606   }
00607 
00608   return true;
00609 }
00610 
00611 typedef SmallVector<BasicBlock *, 16> PredBlockVector;
00612 typedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
00613 
00614 /// \brief Determines the value to use as the phi node input for a block.
00615 ///
00616 /// Select between \p OldVal any value that we know flows from \p BB
00617 /// to a particular phi on the basis of which one (if either) is not
00618 /// undef. Update IncomingValues based on the selected value.
00619 ///
00620 /// \param OldVal The value we are considering selecting.
00621 /// \param BB The block that the value flows in from.
00622 /// \param IncomingValues A map from block-to-value for other phi inputs
00623 /// that we have examined.
00624 ///
00625 /// \returns the selected value.
00626 static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
00627                                           IncomingValueMap &IncomingValues) {
00628   if (!isa<UndefValue>(OldVal)) {
00629     assert((!IncomingValues.count(BB) ||
00630             IncomingValues.find(BB)->second == OldVal) &&
00631            "Expected OldVal to match incoming value from BB!");
00632 
00633     IncomingValues.insert(std::make_pair(BB, OldVal));
00634     return OldVal;
00635   }
00636 
00637   IncomingValueMap::const_iterator It = IncomingValues.find(BB);
00638   if (It != IncomingValues.end()) return It->second;
00639 
00640   return OldVal;
00641 }
00642 
00643 /// \brief Create a map from block to value for the operands of a
00644 /// given phi.
00645 ///
00646 /// Create a map from block to value for each non-undef value flowing
00647 /// into \p PN.
00648 ///
00649 /// \param PN The phi we are collecting the map for.
00650 /// \param IncomingValues [out] The map from block to value for this phi.
00651 static void gatherIncomingValuesToPhi(PHINode *PN,
00652                                       IncomingValueMap &IncomingValues) {
00653   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00654     BasicBlock *BB = PN->getIncomingBlock(i);
00655     Value *V = PN->getIncomingValue(i);
00656 
00657     if (!isa<UndefValue>(V))
00658       IncomingValues.insert(std::make_pair(BB, V));
00659   }
00660 }
00661 
00662 /// \brief Replace the incoming undef values to a phi with the values
00663 /// from a block-to-value map.
00664 ///
00665 /// \param PN The phi we are replacing the undefs in.
00666 /// \param IncomingValues A map from block to value.
00667 static void replaceUndefValuesInPhi(PHINode *PN,
00668                                     const IncomingValueMap &IncomingValues) {
00669   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00670     Value *V = PN->getIncomingValue(i);
00671 
00672     if (!isa<UndefValue>(V)) continue;
00673 
00674     BasicBlock *BB = PN->getIncomingBlock(i);
00675     IncomingValueMap::const_iterator It = IncomingValues.find(BB);
00676     if (It == IncomingValues.end()) continue;
00677 
00678     PN->setIncomingValue(i, It->second);
00679   }
00680 }
00681 
00682 /// \brief Replace a value flowing from a block to a phi with
00683 /// potentially multiple instances of that value flowing from the
00684 /// block's predecessors to the phi.
00685 ///
00686 /// \param BB The block with the value flowing into the phi.
00687 /// \param BBPreds The predecessors of BB.
00688 /// \param PN The phi that we are updating.
00689 static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
00690                                                 const PredBlockVector &BBPreds,
00691                                                 PHINode *PN) {
00692   Value *OldVal = PN->removeIncomingValue(BB, false);
00693   assert(OldVal && "No entry in PHI for Pred BB!");
00694 
00695   IncomingValueMap IncomingValues;
00696 
00697   // We are merging two blocks - BB, and the block containing PN - and
00698   // as a result we need to redirect edges from the predecessors of BB
00699   // to go to the block containing PN, and update PN
00700   // accordingly. Since we allow merging blocks in the case where the
00701   // predecessor and successor blocks both share some predecessors,
00702   // and where some of those common predecessors might have undef
00703   // values flowing into PN, we want to rewrite those values to be
00704   // consistent with the non-undef values.
00705 
00706   gatherIncomingValuesToPhi(PN, IncomingValues);
00707 
00708   // If this incoming value is one of the PHI nodes in BB, the new entries
00709   // in the PHI node are the entries from the old PHI.
00710   if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
00711     PHINode *OldValPN = cast<PHINode>(OldVal);
00712     for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
00713       // Note that, since we are merging phi nodes and BB and Succ might
00714       // have common predecessors, we could end up with a phi node with
00715       // identical incoming branches. This will be cleaned up later (and
00716       // will trigger asserts if we try to clean it up now, without also
00717       // simplifying the corresponding conditional branch).
00718       BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
00719       Value *PredVal = OldValPN->getIncomingValue(i);
00720       Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
00721                                                     IncomingValues);
00722 
00723       // And add a new incoming value for this predecessor for the
00724       // newly retargeted branch.
00725       PN->addIncoming(Selected, PredBB);
00726     }
00727   } else {
00728     for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
00729       // Update existing incoming values in PN for this
00730       // predecessor of BB.
00731       BasicBlock *PredBB = BBPreds[i];
00732       Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
00733                                                     IncomingValues);
00734 
00735       // And add a new incoming value for this predecessor for the
00736       // newly retargeted branch.
00737       PN->addIncoming(Selected, PredBB);
00738     }
00739   }
00740 
00741   replaceUndefValuesInPhi(PN, IncomingValues);
00742 }
00743 
00744 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
00745 /// unconditional branch, and contains no instructions other than PHI nodes,
00746 /// potential side-effect free intrinsics and the branch.  If possible,
00747 /// eliminate BB by rewriting all the predecessors to branch to the successor
00748 /// block and return true.  If we can't transform, return false.
00749 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
00750   assert(BB != &BB->getParent()->getEntryBlock() &&
00751          "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
00752 
00753   // We can't eliminate infinite loops.
00754   BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
00755   if (BB == Succ) return false;
00756 
00757   // Check to see if merging these blocks would cause conflicts for any of the
00758   // phi nodes in BB or Succ. If not, we can safely merge.
00759   if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
00760 
00761   // Check for cases where Succ has multiple predecessors and a PHI node in BB
00762   // has uses which will not disappear when the PHI nodes are merged.  It is
00763   // possible to handle such cases, but difficult: it requires checking whether
00764   // BB dominates Succ, which is non-trivial to calculate in the case where
00765   // Succ has multiple predecessors.  Also, it requires checking whether
00766   // constructing the necessary self-referential PHI node doesn't introduce any
00767   // conflicts; this isn't too difficult, but the previous code for doing this
00768   // was incorrect.
00769   //
00770   // Note that if this check finds a live use, BB dominates Succ, so BB is
00771   // something like a loop pre-header (or rarely, a part of an irreducible CFG);
00772   // folding the branch isn't profitable in that case anyway.
00773   if (!Succ->getSinglePredecessor()) {
00774     BasicBlock::iterator BBI = BB->begin();
00775     while (isa<PHINode>(*BBI)) {
00776       for (Use &U : BBI->uses()) {
00777         if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
00778           if (PN->getIncomingBlock(U) != BB)
00779             return false;
00780         } else {
00781           return false;
00782         }
00783       }
00784       ++BBI;
00785     }
00786   }
00787 
00788   DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
00789 
00790   if (isa<PHINode>(Succ->begin())) {
00791     // If there is more than one pred of succ, and there are PHI nodes in
00792     // the successor, then we need to add incoming edges for the PHI nodes
00793     //
00794     const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
00795 
00796     // Loop over all of the PHI nodes in the successor of BB.
00797     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
00798       PHINode *PN = cast<PHINode>(I);
00799 
00800       redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
00801     }
00802   }
00803 
00804   if (Succ->getSinglePredecessor()) {
00805     // BB is the only predecessor of Succ, so Succ will end up with exactly
00806     // the same predecessors BB had.
00807 
00808     // Copy over any phi, debug or lifetime instruction.
00809     BB->getTerminator()->eraseFromParent();
00810     Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
00811   } else {
00812     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
00813       // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
00814       assert(PN->use_empty() && "There shouldn't be any uses here!");
00815       PN->eraseFromParent();
00816     }
00817   }
00818 
00819   // Everything that jumped to BB now goes to Succ.
00820   BB->replaceAllUsesWith(Succ);
00821   if (!Succ->hasName()) Succ->takeName(BB);
00822   BB->eraseFromParent();              // Delete the old basic block.
00823   return true;
00824 }
00825 
00826 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
00827 /// nodes in this block. This doesn't try to be clever about PHI nodes
00828 /// which differ only in the order of the incoming values, but instcombine
00829 /// orders them so it usually won't matter.
00830 ///
00831 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
00832   bool Changed = false;
00833 
00834   // This implementation doesn't currently consider undef operands
00835   // specially. Theoretically, two phis which are identical except for
00836   // one having an undef where the other doesn't could be collapsed.
00837 
00838   // Map from PHI hash values to PHI nodes. If multiple PHIs have
00839   // the same hash value, the element is the first PHI in the
00840   // linked list in CollisionMap.
00841   DenseMap<uintptr_t, PHINode *> HashMap;
00842 
00843   // Maintain linked lists of PHI nodes with common hash values.
00844   DenseMap<PHINode *, PHINode *> CollisionMap;
00845 
00846   // Examine each PHI.
00847   for (BasicBlock::iterator I = BB->begin();
00848        PHINode *PN = dyn_cast<PHINode>(I++); ) {
00849     // Compute a hash value on the operands. Instcombine will likely have sorted
00850     // them, which helps expose duplicates, but we have to check all the
00851     // operands to be safe in case instcombine hasn't run.
00852     uintptr_t Hash = 0;
00853     // This hash algorithm is quite weak as hash functions go, but it seems
00854     // to do a good enough job for this particular purpose, and is very quick.
00855     for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
00856       Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
00857       Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
00858     }
00859     for (PHINode::block_iterator I = PN->block_begin(), E = PN->block_end();
00860          I != E; ++I) {
00861       Hash ^= reinterpret_cast<uintptr_t>(static_cast<BasicBlock *>(*I));
00862       Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
00863     }
00864     // Avoid colliding with the DenseMap sentinels ~0 and ~0-1.
00865     Hash >>= 1;
00866     // If we've never seen this hash value before, it's a unique PHI.
00867     std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
00868       HashMap.insert(std::make_pair(Hash, PN));
00869     if (Pair.second) continue;
00870     // Otherwise it's either a duplicate or a hash collision.
00871     for (PHINode *OtherPN = Pair.first->second; ; ) {
00872       if (OtherPN->isIdenticalTo(PN)) {
00873         // A duplicate. Replace this PHI with its duplicate.
00874         PN->replaceAllUsesWith(OtherPN);
00875         PN->eraseFromParent();
00876         Changed = true;
00877         break;
00878       }
00879       // A non-duplicate hash collision.
00880       DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
00881       if (I == CollisionMap.end()) {
00882         // Set this PHI to be the head of the linked list of colliding PHIs.
00883         PHINode *Old = Pair.first->second;
00884         Pair.first->second = PN;
00885         CollisionMap[PN] = Old;
00886         break;
00887       }
00888       // Proceed to the next PHI in the list.
00889       OtherPN = I->second;
00890     }
00891   }
00892 
00893   return Changed;
00894 }
00895 
00896 /// enforceKnownAlignment - If the specified pointer points to an object that
00897 /// we control, modify the object's alignment to PrefAlign. This isn't
00898 /// often possible though. If alignment is important, a more reliable approach
00899 /// is to simply align all global variables and allocation instructions to
00900 /// their preferred alignment from the beginning.
00901 ///
00902 static unsigned enforceKnownAlignment(Value *V, unsigned Align,
00903                                       unsigned PrefAlign, const DataLayout *TD) {
00904   V = V->stripPointerCasts();
00905 
00906   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
00907     // If the preferred alignment is greater than the natural stack alignment
00908     // then don't round up. This avoids dynamic stack realignment.
00909     if (TD && TD->exceedsNaturalStackAlignment(PrefAlign))
00910       return Align;
00911     // If there is a requested alignment and if this is an alloca, round up.
00912     if (AI->getAlignment() >= PrefAlign)
00913       return AI->getAlignment();
00914     AI->setAlignment(PrefAlign);
00915     return PrefAlign;
00916   }
00917 
00918   if (auto *GO = dyn_cast<GlobalObject>(V)) {
00919     // If there is a large requested alignment and we can, bump up the alignment
00920     // of the global.
00921     if (GO->isDeclaration())
00922       return Align;
00923     // If the memory we set aside for the global may not be the memory used by
00924     // the final program then it is impossible for us to reliably enforce the
00925     // preferred alignment.
00926     if (GO->isWeakForLinker())
00927       return Align;
00928 
00929     if (GO->getAlignment() >= PrefAlign)
00930       return GO->getAlignment();
00931     // We can only increase the alignment of the global if it has no alignment
00932     // specified or if it is not assigned a section.  If it is assigned a
00933     // section, the global could be densely packed with other objects in the
00934     // section, increasing the alignment could cause padding issues.
00935     if (!GO->hasSection() || GO->getAlignment() == 0)
00936       GO->setAlignment(PrefAlign);
00937     return GO->getAlignment();
00938   }
00939 
00940   return Align;
00941 }
00942 
00943 /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
00944 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
00945 /// and it is more than the alignment of the ultimate object, see if we can
00946 /// increase the alignment of the ultimate object, making this check succeed.
00947 unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
00948                                           const DataLayout *DL,
00949                                           AssumptionCache *AC,
00950                                           const Instruction *CxtI,
00951                                           const DominatorTree *DT) {
00952   assert(V->getType()->isPointerTy() &&
00953          "getOrEnforceKnownAlignment expects a pointer!");
00954   unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(V->getType()) : 64;
00955 
00956   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00957   computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC, CxtI, DT);
00958   unsigned TrailZ = KnownZero.countTrailingOnes();
00959 
00960   // Avoid trouble with ridiculously large TrailZ values, such as
00961   // those computed from a null pointer.
00962   TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
00963 
00964   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
00965 
00966   // LLVM doesn't support alignments larger than this currently.
00967   Align = std::min(Align, +Value::MaximumAlignment);
00968 
00969   if (PrefAlign > Align)
00970     Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
00971 
00972   // We don't need to make any adjustment.
00973   return Align;
00974 }
00975 
00976 ///===---------------------------------------------------------------------===//
00977 ///  Dbg Intrinsic utilities
00978 ///
00979 
00980 /// See if there is a dbg.value intrinsic for DIVar before I.
00981 static bool LdStHasDebugValue(DIVariable &DIVar, Instruction *I) {
00982   // Since we can't guarantee that the original dbg.declare instrinsic
00983   // is removed by LowerDbgDeclare(), we need to make sure that we are
00984   // not inserting the same dbg.value intrinsic over and over.
00985   llvm::BasicBlock::InstListType::iterator PrevI(I);
00986   if (PrevI != I->getParent()->getInstList().begin()) {
00987     --PrevI;
00988     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
00989       if (DVI->getValue() == I->getOperand(0) &&
00990           DVI->getOffset() == 0 &&
00991           DVI->getVariable() == DIVar)
00992         return true;
00993   }
00994   return false;
00995 }
00996 
00997 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
00998 /// that has an associated llvm.dbg.decl intrinsic.
00999 bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
01000                                            StoreInst *SI, DIBuilder &Builder) {
01001   DIVariable DIVar(DDI->getVariable());
01002   DIExpression DIExpr(DDI->getExpression());
01003   assert((!DIVar || DIVar.isVariable()) &&
01004          "Variable in DbgDeclareInst should be either null or a DIVariable.");
01005   if (!DIVar)
01006     return false;
01007 
01008   if (LdStHasDebugValue(DIVar, SI))
01009     return true;
01010 
01011   Instruction *DbgVal = nullptr;
01012   // If an argument is zero extended then use argument directly. The ZExt
01013   // may be zapped by an optimization pass in future.
01014   Argument *ExtendedArg = nullptr;
01015   if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
01016     ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
01017   if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
01018     ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
01019   if (ExtendedArg)
01020     DbgVal = Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, DIExpr, SI);
01021   else
01022     DbgVal = Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar,
01023                                              DIExpr, SI);
01024   DbgVal->setDebugLoc(DDI->getDebugLoc());
01025   return true;
01026 }
01027 
01028 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
01029 /// that has an associated llvm.dbg.decl intrinsic.
01030 bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
01031                                            LoadInst *LI, DIBuilder &Builder) {
01032   DIVariable DIVar(DDI->getVariable());
01033   DIExpression DIExpr(DDI->getExpression());
01034   assert((!DIVar || DIVar.isVariable()) &&
01035          "Variable in DbgDeclareInst should be either null or a DIVariable.");
01036   if (!DIVar)
01037     return false;
01038 
01039   if (LdStHasDebugValue(DIVar, LI))
01040     return true;
01041 
01042   Instruction *DbgVal =
01043       Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0, DIVar, DIExpr, LI);
01044   DbgVal->setDebugLoc(DDI->getDebugLoc());
01045   return true;
01046 }
01047 
01048 /// Determine whether this alloca is either a VLA or an array.
01049 static bool isArray(AllocaInst *AI) {
01050   return AI->isArrayAllocation() ||
01051     AI->getType()->getElementType()->isArrayTy();
01052 }
01053 
01054 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
01055 /// of llvm.dbg.value intrinsics.
01056 bool llvm::LowerDbgDeclare(Function &F) {
01057   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
01058   SmallVector<DbgDeclareInst *, 4> Dbgs;
01059   for (auto &FI : F)
01060     for (BasicBlock::iterator BI : FI)
01061       if (auto DDI = dyn_cast<DbgDeclareInst>(BI))
01062         Dbgs.push_back(DDI);
01063 
01064   if (Dbgs.empty())
01065     return false;
01066 
01067   for (auto &I : Dbgs) {
01068     DbgDeclareInst *DDI = I;
01069     AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
01070     // If this is an alloca for a scalar variable, insert a dbg.value
01071     // at each load and store to the alloca and erase the dbg.declare.
01072     // The dbg.values allow tracking a variable even if it is not
01073     // stored on the stack, while the dbg.declare can only describe
01074     // the stack slot (and at a lexical-scope granularity). Later
01075     // passes will attempt to elide the stack slot.
01076     if (AI && !isArray(AI)) {
01077       for (User *U : AI->users())
01078         if (StoreInst *SI = dyn_cast<StoreInst>(U))
01079           ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
01080         else if (LoadInst *LI = dyn_cast<LoadInst>(U))
01081           ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
01082         else if (CallInst *CI = dyn_cast<CallInst>(U)) {
01083           // This is a call by-value or some other instruction that
01084           // takes a pointer to the variable. Insert a *value*
01085           // intrinsic that describes the alloca.
01086           auto DbgVal = DIB.insertDbgValueIntrinsic(
01087               AI, 0, DIVariable(DDI->getVariable()),
01088               DIExpression(DDI->getExpression()), CI);
01089           DbgVal->setDebugLoc(DDI->getDebugLoc());
01090         }
01091       DDI->eraseFromParent();
01092     }
01093   }
01094   return true;
01095 }
01096 
01097 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
01098 /// alloca 'V', if any.
01099 DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
01100   if (auto *L = LocalAsMetadata::getIfExists(V))
01101     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
01102       for (User *U : MDV->users())
01103         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
01104           return DDI;
01105 
01106   return nullptr;
01107 }
01108 
01109 bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
01110                                       DIBuilder &Builder, bool Deref) {
01111   DbgDeclareInst *DDI = FindAllocaDbgDeclare(AI);
01112   if (!DDI)
01113     return false;
01114   DebugLoc Loc = DDI->getDebugLoc();
01115   DIVariable DIVar(DDI->getVariable());
01116   DIExpression DIExpr(DDI->getExpression());
01117   assert((!DIVar || DIVar.isVariable()) &&
01118          "Variable in DbgDeclareInst should be either null or a DIVariable.");
01119   if (!DIVar)
01120     return false;
01121 
01122   if (Deref) {
01123     // Create a copy of the original DIDescriptor for user variable, prepending
01124     // "deref" operation to a list of address elements, as new llvm.dbg.declare
01125     // will take a value storing address of the memory for variable, not
01126     // alloca itself.
01127     SmallVector<uint64_t, 4> NewDIExpr;
01128     NewDIExpr.push_back(dwarf::DW_OP_deref);
01129     if (DIExpr)
01130       for (unsigned i = 0, n = DIExpr.getNumElements(); i < n; ++i)
01131         NewDIExpr.push_back(DIExpr.getElement(i));
01132     DIExpr = Builder.createExpression(NewDIExpr);
01133   }
01134 
01135   // Insert llvm.dbg.declare in the same basic block as the original alloca,
01136   // and remove old llvm.dbg.declare.
01137   BasicBlock *BB = AI->getParent();
01138   Builder.insertDeclare(NewAllocaAddress, DIVar, DIExpr, BB)
01139     ->setDebugLoc(Loc);
01140   DDI->eraseFromParent();
01141   return true;
01142 }
01143 
01144 /// changeToUnreachable - Insert an unreachable instruction before the specified
01145 /// instruction, making it and the rest of the code in the block dead.
01146 static void changeToUnreachable(Instruction *I, bool UseLLVMTrap) {
01147   BasicBlock *BB = I->getParent();
01148   // Loop over all of the successors, removing BB's entry from any PHI
01149   // nodes.
01150   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
01151     (*SI)->removePredecessor(BB);
01152 
01153   // Insert a call to llvm.trap right before this.  This turns the undefined
01154   // behavior into a hard fail instead of falling through into random code.
01155   if (UseLLVMTrap) {
01156     Function *TrapFn =
01157       Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
01158     CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
01159     CallTrap->setDebugLoc(I->getDebugLoc());
01160   }
01161   new UnreachableInst(I->getContext(), I);
01162 
01163   // All instructions after this are dead.
01164   BasicBlock::iterator BBI = I, BBE = BB->end();
01165   while (BBI != BBE) {
01166     if (!BBI->use_empty())
01167       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
01168     BB->getInstList().erase(BBI++);
01169   }
01170 }
01171 
01172 /// changeToCall - Convert the specified invoke into a normal call.
01173 static void changeToCall(InvokeInst *II) {
01174   SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
01175   CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, "", II);
01176   NewCall->takeName(II);
01177   NewCall->setCallingConv(II->getCallingConv());
01178   NewCall->setAttributes(II->getAttributes());
01179   NewCall->setDebugLoc(II->getDebugLoc());
01180   II->replaceAllUsesWith(NewCall);
01181 
01182   // Follow the call by a branch to the normal destination.
01183   BranchInst::Create(II->getNormalDest(), II);
01184 
01185   // Update PHI nodes in the unwind destination
01186   II->getUnwindDest()->removePredecessor(II->getParent());
01187   II->eraseFromParent();
01188 }
01189 
01190 static bool markAliveBlocks(BasicBlock *BB,
01191                             SmallPtrSetImpl<BasicBlock*> &Reachable) {
01192 
01193   SmallVector<BasicBlock*, 128> Worklist;
01194   Worklist.push_back(BB);
01195   Reachable.insert(BB);
01196   bool Changed = false;
01197   do {
01198     BB = Worklist.pop_back_val();
01199 
01200     // Do a quick scan of the basic block, turning any obviously unreachable
01201     // instructions into LLVM unreachable insts.  The instruction combining pass
01202     // canonicalizes unreachable insts into stores to null or undef.
01203     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
01204       // Assumptions that are known to be false are equivalent to unreachable.
01205       // Also, if the condition is undefined, then we make the choice most
01206       // beneficial to the optimizer, and choose that to also be unreachable.
01207       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI))
01208         if (II->getIntrinsicID() == Intrinsic::assume) {
01209           bool MakeUnreachable = false;
01210           if (isa<UndefValue>(II->getArgOperand(0)))
01211             MakeUnreachable = true;
01212           else if (ConstantInt *Cond =
01213                    dyn_cast<ConstantInt>(II->getArgOperand(0)))
01214             MakeUnreachable = Cond->isZero();
01215 
01216           if (MakeUnreachable) {
01217             // Don't insert a call to llvm.trap right before the unreachable.
01218             changeToUnreachable(BBI, false);
01219             Changed = true;
01220             break;
01221           }
01222         }
01223 
01224       if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
01225         if (CI->doesNotReturn()) {
01226           // If we found a call to a no-return function, insert an unreachable
01227           // instruction after it.  Make sure there isn't *already* one there
01228           // though.
01229           ++BBI;
01230           if (!isa<UnreachableInst>(BBI)) {
01231             // Don't insert a call to llvm.trap right before the unreachable.
01232             changeToUnreachable(BBI, false);
01233             Changed = true;
01234           }
01235           break;
01236         }
01237       }
01238 
01239       // Store to undef and store to null are undefined and used to signal that
01240       // they should be changed to unreachable by passes that can't modify the
01241       // CFG.
01242       if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
01243         // Don't touch volatile stores.
01244         if (SI->isVolatile()) continue;
01245 
01246         Value *Ptr = SI->getOperand(1);
01247 
01248         if (isa<UndefValue>(Ptr) ||
01249             (isa<ConstantPointerNull>(Ptr) &&
01250              SI->getPointerAddressSpace() == 0)) {
01251           changeToUnreachable(SI, true);
01252           Changed = true;
01253           break;
01254         }
01255       }
01256     }
01257 
01258     // Turn invokes that call 'nounwind' functions into ordinary calls.
01259     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
01260       Value *Callee = II->getCalledValue();
01261       if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
01262         changeToUnreachable(II, true);
01263         Changed = true;
01264       } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(II)) {
01265         if (II->use_empty() && II->onlyReadsMemory()) {
01266           // jump to the normal destination branch.
01267           BranchInst::Create(II->getNormalDest(), II);
01268           II->getUnwindDest()->removePredecessor(II->getParent());
01269           II->eraseFromParent();
01270         } else
01271           changeToCall(II);
01272         Changed = true;
01273       }
01274     }
01275 
01276     Changed |= ConstantFoldTerminator(BB, true);
01277     for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
01278       if (Reachable.insert(*SI).second)
01279         Worklist.push_back(*SI);
01280   } while (!Worklist.empty());
01281   return Changed;
01282 }
01283 
01284 /// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
01285 /// if they are in a dead cycle.  Return true if a change was made, false
01286 /// otherwise.
01287 bool llvm::removeUnreachableBlocks(Function &F) {
01288   SmallPtrSet<BasicBlock*, 128> Reachable;
01289   bool Changed = markAliveBlocks(F.begin(), Reachable);
01290 
01291   // If there are unreachable blocks in the CFG...
01292   if (Reachable.size() == F.size())
01293     return Changed;
01294 
01295   assert(Reachable.size() < F.size());
01296   NumRemoved += F.size()-Reachable.size();
01297 
01298   // Loop over all of the basic blocks that are not reachable, dropping all of
01299   // their internal references...
01300   for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
01301     if (Reachable.count(BB))
01302       continue;
01303 
01304     for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
01305       if (Reachable.count(*SI))
01306         (*SI)->removePredecessor(BB);
01307     BB->dropAllReferences();
01308   }
01309 
01310   for (Function::iterator I = ++F.begin(); I != F.end();)
01311     if (!Reachable.count(I))
01312       I = F.getBasicBlockList().erase(I);
01313     else
01314       ++I;
01315 
01316   return true;
01317 }
01318 
01319 void llvm::combineMetadata(Instruction *K, const Instruction *J, ArrayRef<unsigned> KnownIDs) {
01320   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
01321   K->dropUnknownMetadata(KnownIDs);
01322   K->getAllMetadataOtherThanDebugLoc(Metadata);
01323   for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
01324     unsigned Kind = Metadata[i].first;
01325     MDNode *JMD = J->getMetadata(Kind);
01326     MDNode *KMD = Metadata[i].second;
01327 
01328     switch (Kind) {
01329       default:
01330         K->setMetadata(Kind, nullptr); // Remove unknown metadata
01331         break;
01332       case LLVMContext::MD_dbg:
01333         llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
01334       case LLVMContext::MD_tbaa:
01335         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
01336         break;
01337       case LLVMContext::MD_alias_scope:
01338         K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
01339         break;
01340       case LLVMContext::MD_noalias:
01341         K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
01342         break;
01343       case LLVMContext::MD_range:
01344         K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
01345         break;
01346       case LLVMContext::MD_fpmath:
01347         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
01348         break;
01349       case LLVMContext::MD_invariant_load:
01350         // Only set the !invariant.load if it is present in both instructions.
01351         K->setMetadata(Kind, JMD);
01352         break;
01353       case LLVMContext::MD_nonnull:
01354         // Only set the !nonnull if it is present in both instructions.
01355         K->setMetadata(Kind, JMD);
01356         break;
01357     }
01358   }
01359 }