LLVM  mainline
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/InstructionSimplify.h"
00021 #include "llvm/Analysis/LibCallSemantics.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,
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, 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   // This only adjusts blocks with PHI nodes.
00469   if (!isa<PHINode>(BB->begin()))
00470     return;
00471 
00472   // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
00473   // them down.  This will leave us with single entry phi nodes and other phis
00474   // that can be removed.
00475   BB->removePredecessor(Pred, true);
00476 
00477   WeakVH PhiIt = &BB->front();
00478   while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
00479     PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
00480     Value *OldPhiIt = PhiIt;
00481 
00482     if (!recursivelySimplifyInstruction(PN))
00483       continue;
00484 
00485     // If recursive simplification ended up deleting the next PHI node we would
00486     // iterate to, then our iterator is invalid, restart scanning from the top
00487     // of the block.
00488     if (PhiIt != OldPhiIt) PhiIt = &BB->front();
00489   }
00490 }
00491 
00492 
00493 /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
00494 /// predecessor is known to have one successor (DestBB!).  Eliminate the edge
00495 /// between them, moving the instructions in the predecessor into DestBB and
00496 /// deleting the predecessor block.
00497 ///
00498 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, DominatorTree *DT) {
00499   // If BB has single-entry PHI nodes, fold them.
00500   while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
00501     Value *NewVal = PN->getIncomingValue(0);
00502     // Replace self referencing PHI with undef, it must be dead.
00503     if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
00504     PN->replaceAllUsesWith(NewVal);
00505     PN->eraseFromParent();
00506   }
00507 
00508   BasicBlock *PredBB = DestBB->getSinglePredecessor();
00509   assert(PredBB && "Block doesn't have a single predecessor!");
00510 
00511   // Zap anything that took the address of DestBB.  Not doing this will give the
00512   // address an invalid value.
00513   if (DestBB->hasAddressTaken()) {
00514     BlockAddress *BA = BlockAddress::get(DestBB);
00515     Constant *Replacement =
00516       ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
00517     BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
00518                                                      BA->getType()));
00519     BA->destroyConstant();
00520   }
00521 
00522   // Anything that branched to PredBB now branches to DestBB.
00523   PredBB->replaceAllUsesWith(DestBB);
00524 
00525   // Splice all the instructions from PredBB to DestBB.
00526   PredBB->getTerminator()->eraseFromParent();
00527   DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
00528 
00529   // If the PredBB is the entry block of the function, move DestBB up to
00530   // become the entry block after we erase PredBB.
00531   if (PredBB == &DestBB->getParent()->getEntryBlock())
00532     DestBB->moveAfter(PredBB);
00533 
00534   if (DT) {
00535     BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
00536     DT->changeImmediateDominator(DestBB, PredBBIDom);
00537     DT->eraseNode(PredBB);
00538   }
00539   // Nuke BB.
00540   PredBB->eraseFromParent();
00541 }
00542 
00543 /// CanMergeValues - Return true if we can choose one of these values to use
00544 /// in place of the other. Note that we will always choose the non-undef
00545 /// value to keep.
00546 static bool CanMergeValues(Value *First, Value *Second) {
00547   return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
00548 }
00549 
00550 /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
00551 /// almost-empty BB ending in an unconditional branch to Succ, into Succ.
00552 ///
00553 /// Assumption: Succ is the single successor for BB.
00554 ///
00555 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
00556   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
00557 
00558   DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
00559         << Succ->getName() << "\n");
00560   // Shortcut, if there is only a single predecessor it must be BB and merging
00561   // is always safe
00562   if (Succ->getSinglePredecessor()) return true;
00563 
00564   // Make a list of the predecessors of BB
00565   SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
00566 
00567   // Look at all the phi nodes in Succ, to see if they present a conflict when
00568   // merging these blocks
00569   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
00570     PHINode *PN = cast<PHINode>(I);
00571 
00572     // If the incoming value from BB is again a PHINode in
00573     // BB which has the same incoming value for *PI as PN does, we can
00574     // merge the phi nodes and then the blocks can still be merged
00575     PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
00576     if (BBPN && BBPN->getParent() == BB) {
00577       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
00578         BasicBlock *IBB = PN->getIncomingBlock(PI);
00579         if (BBPreds.count(IBB) &&
00580             !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
00581                             PN->getIncomingValue(PI))) {
00582           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
00583                 << Succ->getName() << " is conflicting with "
00584                 << BBPN->getName() << " with regard to common predecessor "
00585                 << IBB->getName() << "\n");
00586           return false;
00587         }
00588       }
00589     } else {
00590       Value* Val = PN->getIncomingValueForBlock(BB);
00591       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
00592         // See if the incoming value for the common predecessor is equal to the
00593         // one for BB, in which case this phi node will not prevent the merging
00594         // of the block.
00595         BasicBlock *IBB = PN->getIncomingBlock(PI);
00596         if (BBPreds.count(IBB) &&
00597             !CanMergeValues(Val, PN->getIncomingValue(PI))) {
00598           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
00599                 << Succ->getName() << " is conflicting with regard to common "
00600                 << "predecessor " << IBB->getName() << "\n");
00601           return false;
00602         }
00603       }
00604     }
00605   }
00606 
00607   return true;
00608 }
00609 
00610 typedef SmallVector<BasicBlock *, 16> PredBlockVector;
00611 typedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
00612 
00613 /// \brief Determines the value to use as the phi node input for a block.
00614 ///
00615 /// Select between \p OldVal any value that we know flows from \p BB
00616 /// to a particular phi on the basis of which one (if either) is not
00617 /// undef. Update IncomingValues based on the selected value.
00618 ///
00619 /// \param OldVal The value we are considering selecting.
00620 /// \param BB The block that the value flows in from.
00621 /// \param IncomingValues A map from block-to-value for other phi inputs
00622 /// that we have examined.
00623 ///
00624 /// \returns the selected value.
00625 static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
00626                                           IncomingValueMap &IncomingValues) {
00627   if (!isa<UndefValue>(OldVal)) {
00628     assert((!IncomingValues.count(BB) ||
00629             IncomingValues.find(BB)->second == OldVal) &&
00630            "Expected OldVal to match incoming value from BB!");
00631 
00632     IncomingValues.insert(std::make_pair(BB, OldVal));
00633     return OldVal;
00634   }
00635 
00636   IncomingValueMap::const_iterator It = IncomingValues.find(BB);
00637   if (It != IncomingValues.end()) return It->second;
00638 
00639   return OldVal;
00640 }
00641 
00642 /// \brief Create a map from block to value for the operands of a
00643 /// given phi.
00644 ///
00645 /// Create a map from block to value for each non-undef value flowing
00646 /// into \p PN.
00647 ///
00648 /// \param PN The phi we are collecting the map for.
00649 /// \param IncomingValues [out] The map from block to value for this phi.
00650 static void gatherIncomingValuesToPhi(PHINode *PN,
00651                                       IncomingValueMap &IncomingValues) {
00652   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00653     BasicBlock *BB = PN->getIncomingBlock(i);
00654     Value *V = PN->getIncomingValue(i);
00655 
00656     if (!isa<UndefValue>(V))
00657       IncomingValues.insert(std::make_pair(BB, V));
00658   }
00659 }
00660 
00661 /// \brief Replace the incoming undef values to a phi with the values
00662 /// from a block-to-value map.
00663 ///
00664 /// \param PN The phi we are replacing the undefs in.
00665 /// \param IncomingValues A map from block to value.
00666 static void replaceUndefValuesInPhi(PHINode *PN,
00667                                     const IncomingValueMap &IncomingValues) {
00668   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00669     Value *V = PN->getIncomingValue(i);
00670 
00671     if (!isa<UndefValue>(V)) continue;
00672 
00673     BasicBlock *BB = PN->getIncomingBlock(i);
00674     IncomingValueMap::const_iterator It = IncomingValues.find(BB);
00675     if (It == IncomingValues.end()) continue;
00676 
00677     PN->setIncomingValue(i, It->second);
00678   }
00679 }
00680 
00681 /// \brief Replace a value flowing from a block to a phi with
00682 /// potentially multiple instances of that value flowing from the
00683 /// block's predecessors to the phi.
00684 ///
00685 /// \param BB The block with the value flowing into the phi.
00686 /// \param BBPreds The predecessors of BB.
00687 /// \param PN The phi that we are updating.
00688 static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
00689                                                 const PredBlockVector &BBPreds,
00690                                                 PHINode *PN) {
00691   Value *OldVal = PN->removeIncomingValue(BB, false);
00692   assert(OldVal && "No entry in PHI for Pred BB!");
00693 
00694   IncomingValueMap IncomingValues;
00695 
00696   // We are merging two blocks - BB, and the block containing PN - and
00697   // as a result we need to redirect edges from the predecessors of BB
00698   // to go to the block containing PN, and update PN
00699   // accordingly. Since we allow merging blocks in the case where the
00700   // predecessor and successor blocks both share some predecessors,
00701   // and where some of those common predecessors might have undef
00702   // values flowing into PN, we want to rewrite those values to be
00703   // consistent with the non-undef values.
00704 
00705   gatherIncomingValuesToPhi(PN, IncomingValues);
00706 
00707   // If this incoming value is one of the PHI nodes in BB, the new entries
00708   // in the PHI node are the entries from the old PHI.
00709   if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
00710     PHINode *OldValPN = cast<PHINode>(OldVal);
00711     for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
00712       // Note that, since we are merging phi nodes and BB and Succ might
00713       // have common predecessors, we could end up with a phi node with
00714       // identical incoming branches. This will be cleaned up later (and
00715       // will trigger asserts if we try to clean it up now, without also
00716       // simplifying the corresponding conditional branch).
00717       BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
00718       Value *PredVal = OldValPN->getIncomingValue(i);
00719       Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
00720                                                     IncomingValues);
00721 
00722       // And add a new incoming value for this predecessor for the
00723       // newly retargeted branch.
00724       PN->addIncoming(Selected, PredBB);
00725     }
00726   } else {
00727     for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
00728       // Update existing incoming values in PN for this
00729       // predecessor of BB.
00730       BasicBlock *PredBB = BBPreds[i];
00731       Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
00732                                                     IncomingValues);
00733 
00734       // And add a new incoming value for this predecessor for the
00735       // newly retargeted branch.
00736       PN->addIncoming(Selected, PredBB);
00737     }
00738   }
00739 
00740   replaceUndefValuesInPhi(PN, IncomingValues);
00741 }
00742 
00743 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
00744 /// unconditional branch, and contains no instructions other than PHI nodes,
00745 /// potential side-effect free intrinsics and the branch.  If possible,
00746 /// eliminate BB by rewriting all the predecessors to branch to the successor
00747 /// block and return true.  If we can't transform, return false.
00748 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
00749   assert(BB != &BB->getParent()->getEntryBlock() &&
00750          "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
00751 
00752   // We can't eliminate infinite loops.
00753   BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
00754   if (BB == Succ) return false;
00755 
00756   // Check to see if merging these blocks would cause conflicts for any of the
00757   // phi nodes in BB or Succ. If not, we can safely merge.
00758   if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
00759 
00760   // Check for cases where Succ has multiple predecessors and a PHI node in BB
00761   // has uses which will not disappear when the PHI nodes are merged.  It is
00762   // possible to handle such cases, but difficult: it requires checking whether
00763   // BB dominates Succ, which is non-trivial to calculate in the case where
00764   // Succ has multiple predecessors.  Also, it requires checking whether
00765   // constructing the necessary self-referential PHI node doesn't introduce any
00766   // conflicts; this isn't too difficult, but the previous code for doing this
00767   // was incorrect.
00768   //
00769   // Note that if this check finds a live use, BB dominates Succ, so BB is
00770   // something like a loop pre-header (or rarely, a part of an irreducible CFG);
00771   // folding the branch isn't profitable in that case anyway.
00772   if (!Succ->getSinglePredecessor()) {
00773     BasicBlock::iterator BBI = BB->begin();
00774     while (isa<PHINode>(*BBI)) {
00775       for (Use &U : BBI->uses()) {
00776         if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
00777           if (PN->getIncomingBlock(U) != BB)
00778             return false;
00779         } else {
00780           return false;
00781         }
00782       }
00783       ++BBI;
00784     }
00785   }
00786 
00787   DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
00788 
00789   if (isa<PHINode>(Succ->begin())) {
00790     // If there is more than one pred of succ, and there are PHI nodes in
00791     // the successor, then we need to add incoming edges for the PHI nodes
00792     //
00793     const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
00794 
00795     // Loop over all of the PHI nodes in the successor of BB.
00796     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
00797       PHINode *PN = cast<PHINode>(I);
00798 
00799       redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
00800     }
00801   }
00802 
00803   if (Succ->getSinglePredecessor()) {
00804     // BB is the only predecessor of Succ, so Succ will end up with exactly
00805     // the same predecessors BB had.
00806 
00807     // Copy over any phi, debug or lifetime instruction.
00808     BB->getTerminator()->eraseFromParent();
00809     Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
00810   } else {
00811     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
00812       // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
00813       assert(PN->use_empty() && "There shouldn't be any uses here!");
00814       PN->eraseFromParent();
00815     }
00816   }
00817 
00818   // Everything that jumped to BB now goes to Succ.
00819   BB->replaceAllUsesWith(Succ);
00820   if (!Succ->hasName()) Succ->takeName(BB);
00821   BB->eraseFromParent();              // Delete the old basic block.
00822   return true;
00823 }
00824 
00825 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
00826 /// nodes in this block. This doesn't try to be clever about PHI nodes
00827 /// which differ only in the order of the incoming values, but instcombine
00828 /// orders them so it usually won't matter.
00829 ///
00830 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
00831   bool Changed = false;
00832 
00833   // This implementation doesn't currently consider undef operands
00834   // specially. Theoretically, two phis which are identical except for
00835   // one having an undef where the other doesn't could be collapsed.
00836 
00837   // Map from PHI hash values to PHI nodes. If multiple PHIs have
00838   // the same hash value, the element is the first PHI in the
00839   // linked list in CollisionMap.
00840   DenseMap<uintptr_t, PHINode *> HashMap;
00841 
00842   // Maintain linked lists of PHI nodes with common hash values.
00843   DenseMap<PHINode *, PHINode *> CollisionMap;
00844 
00845   // Examine each PHI.
00846   for (BasicBlock::iterator I = BB->begin();
00847        PHINode *PN = dyn_cast<PHINode>(I++); ) {
00848     // Compute a hash value on the operands. Instcombine will likely have sorted
00849     // them, which helps expose duplicates, but we have to check all the
00850     // operands to be safe in case instcombine hasn't run.
00851     uintptr_t Hash = 0;
00852     // This hash algorithm is quite weak as hash functions go, but it seems
00853     // to do a good enough job for this particular purpose, and is very quick.
00854     for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
00855       Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
00856       Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
00857     }
00858     for (PHINode::block_iterator I = PN->block_begin(), E = PN->block_end();
00859          I != E; ++I) {
00860       Hash ^= reinterpret_cast<uintptr_t>(static_cast<BasicBlock *>(*I));
00861       Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
00862     }
00863     // Avoid colliding with the DenseMap sentinels ~0 and ~0-1.
00864     Hash >>= 1;
00865     // If we've never seen this hash value before, it's a unique PHI.
00866     std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
00867       HashMap.insert(std::make_pair(Hash, PN));
00868     if (Pair.second) continue;
00869     // Otherwise it's either a duplicate or a hash collision.
00870     for (PHINode *OtherPN = Pair.first->second; ; ) {
00871       if (OtherPN->isIdenticalTo(PN)) {
00872         // A duplicate. Replace this PHI with its duplicate.
00873         PN->replaceAllUsesWith(OtherPN);
00874         PN->eraseFromParent();
00875         Changed = true;
00876         break;
00877       }
00878       // A non-duplicate hash collision.
00879       DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
00880       if (I == CollisionMap.end()) {
00881         // Set this PHI to be the head of the linked list of colliding PHIs.
00882         PHINode *Old = Pair.first->second;
00883         Pair.first->second = PN;
00884         CollisionMap[PN] = Old;
00885         break;
00886       }
00887       // Proceed to the next PHI in the list.
00888       OtherPN = I->second;
00889     }
00890   }
00891 
00892   return Changed;
00893 }
00894 
00895 /// enforceKnownAlignment - If the specified pointer points to an object that
00896 /// we control, modify the object's alignment to PrefAlign. This isn't
00897 /// often possible though. If alignment is important, a more reliable approach
00898 /// is to simply align all global variables and allocation instructions to
00899 /// their preferred alignment from the beginning.
00900 ///
00901 static unsigned enforceKnownAlignment(Value *V, unsigned Align,
00902                                       unsigned PrefAlign,
00903                                       const DataLayout &DL) {
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 (DL.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                                           const Instruction *CxtI,
00950                                           AssumptionCache *AC,
00951                                           const DominatorTree *DT) {
00952   assert(V->getType()->isPointerTy() &&
00953          "getOrEnforceKnownAlignment expects a pointer!");
00954   unsigned BitWidth = DL.getPointerTypeSizeInBits(V->getType());
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(const DILocalVariable *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   auto *DIVar = DDI->getVariable();
01002   auto *DIExpr = DDI->getExpression();
01003   assert(DIVar && "Missing variable");
01004 
01005   if (LdStHasDebugValue(DIVar, SI))
01006     return true;
01007 
01008   // If an argument is zero extended then use argument directly. The ZExt
01009   // may be zapped by an optimization pass in future.
01010   Argument *ExtendedArg = nullptr;
01011   if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
01012     ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
01013   if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
01014     ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
01015   if (ExtendedArg)
01016     Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, DIExpr,
01017                                     DDI->getDebugLoc(), SI);
01018   else
01019     Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, DIExpr,
01020                                     DDI->getDebugLoc(), SI);
01021   return true;
01022 }
01023 
01024 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
01025 /// that has an associated llvm.dbg.decl intrinsic.
01026 bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
01027                                            LoadInst *LI, DIBuilder &Builder) {
01028   auto *DIVar = DDI->getVariable();
01029   auto *DIExpr = DDI->getExpression();
01030   assert(DIVar && "Missing variable");
01031 
01032   if (LdStHasDebugValue(DIVar, LI))
01033     return true;
01034 
01035   Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0, DIVar, DIExpr,
01036                                   DDI->getDebugLoc(), LI);
01037   return true;
01038 }
01039 
01040 /// Determine whether this alloca is either a VLA or an array.
01041 static bool isArray(AllocaInst *AI) {
01042   return AI->isArrayAllocation() ||
01043     AI->getType()->getElementType()->isArrayTy();
01044 }
01045 
01046 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
01047 /// of llvm.dbg.value intrinsics.
01048 bool llvm::LowerDbgDeclare(Function &F) {
01049   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
01050   SmallVector<DbgDeclareInst *, 4> Dbgs;
01051   for (auto &FI : F)
01052     for (BasicBlock::iterator BI : FI)
01053       if (auto DDI = dyn_cast<DbgDeclareInst>(BI))
01054         Dbgs.push_back(DDI);
01055 
01056   if (Dbgs.empty())
01057     return false;
01058 
01059   for (auto &I : Dbgs) {
01060     DbgDeclareInst *DDI = I;
01061     AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
01062     // If this is an alloca for a scalar variable, insert a dbg.value
01063     // at each load and store to the alloca and erase the dbg.declare.
01064     // The dbg.values allow tracking a variable even if it is not
01065     // stored on the stack, while the dbg.declare can only describe
01066     // the stack slot (and at a lexical-scope granularity). Later
01067     // passes will attempt to elide the stack slot.
01068     if (AI && !isArray(AI)) {
01069       for (User *U : AI->users())
01070         if (StoreInst *SI = dyn_cast<StoreInst>(U))
01071           ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
01072         else if (LoadInst *LI = dyn_cast<LoadInst>(U))
01073           ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
01074         else if (CallInst *CI = dyn_cast<CallInst>(U)) {
01075           // This is a call by-value or some other instruction that
01076           // takes a pointer to the variable. Insert a *value*
01077           // intrinsic that describes the alloca.
01078           DIB.insertDbgValueIntrinsic(AI, 0, DDI->getVariable(),
01079                                       DDI->getExpression(), DDI->getDebugLoc(),
01080                                       CI);
01081         }
01082       DDI->eraseFromParent();
01083     }
01084   }
01085   return true;
01086 }
01087 
01088 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
01089 /// alloca 'V', if any.
01090 DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
01091   if (auto *L = LocalAsMetadata::getIfExists(V))
01092     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
01093       for (User *U : MDV->users())
01094         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
01095           return DDI;
01096 
01097   return nullptr;
01098 }
01099 
01100 bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
01101                                       DIBuilder &Builder, bool Deref) {
01102   DbgDeclareInst *DDI = FindAllocaDbgDeclare(AI);
01103   if (!DDI)
01104     return false;
01105   DebugLoc Loc = DDI->getDebugLoc();
01106   auto *DIVar = DDI->getVariable();
01107   auto *DIExpr = DDI->getExpression();
01108   assert(DIVar && "Missing variable");
01109 
01110   if (Deref) {
01111     // Create a copy of the original DIDescriptor for user variable, prepending
01112     // "deref" operation to a list of address elements, as new llvm.dbg.declare
01113     // will take a value storing address of the memory for variable, not
01114     // alloca itself.
01115     SmallVector<uint64_t, 4> NewDIExpr;
01116     NewDIExpr.push_back(dwarf::DW_OP_deref);
01117     if (DIExpr)
01118       NewDIExpr.append(DIExpr->elements_begin(), DIExpr->elements_end());
01119     DIExpr = Builder.createExpression(NewDIExpr);
01120   }
01121 
01122   // Insert llvm.dbg.declare in the same basic block as the original alloca,
01123   // and remove old llvm.dbg.declare.
01124   BasicBlock *BB = AI->getParent();
01125   Builder.insertDeclare(NewAllocaAddress, DIVar, DIExpr, Loc, BB);
01126   DDI->eraseFromParent();
01127   return true;
01128 }
01129 
01130 /// changeToUnreachable - Insert an unreachable instruction before the specified
01131 /// instruction, making it and the rest of the code in the block dead.
01132 static void changeToUnreachable(Instruction *I, bool UseLLVMTrap) {
01133   BasicBlock *BB = I->getParent();
01134   // Loop over all of the successors, removing BB's entry from any PHI
01135   // nodes.
01136   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
01137     (*SI)->removePredecessor(BB);
01138 
01139   // Insert a call to llvm.trap right before this.  This turns the undefined
01140   // behavior into a hard fail instead of falling through into random code.
01141   if (UseLLVMTrap) {
01142     Function *TrapFn =
01143       Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
01144     CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
01145     CallTrap->setDebugLoc(I->getDebugLoc());
01146   }
01147   new UnreachableInst(I->getContext(), I);
01148 
01149   // All instructions after this are dead.
01150   BasicBlock::iterator BBI = I, BBE = BB->end();
01151   while (BBI != BBE) {
01152     if (!BBI->use_empty())
01153       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
01154     BB->getInstList().erase(BBI++);
01155   }
01156 }
01157 
01158 /// changeToCall - Convert the specified invoke into a normal call.
01159 static void changeToCall(InvokeInst *II) {
01160   SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
01161   CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, "", II);
01162   NewCall->takeName(II);
01163   NewCall->setCallingConv(II->getCallingConv());
01164   NewCall->setAttributes(II->getAttributes());
01165   NewCall->setDebugLoc(II->getDebugLoc());
01166   II->replaceAllUsesWith(NewCall);
01167 
01168   // Follow the call by a branch to the normal destination.
01169   BranchInst::Create(II->getNormalDest(), II);
01170 
01171   // Update PHI nodes in the unwind destination
01172   II->getUnwindDest()->removePredecessor(II->getParent());
01173   II->eraseFromParent();
01174 }
01175 
01176 static bool markAliveBlocks(BasicBlock *BB,
01177                             SmallPtrSetImpl<BasicBlock*> &Reachable) {
01178 
01179   SmallVector<BasicBlock*, 128> Worklist;
01180   Worklist.push_back(BB);
01181   Reachable.insert(BB);
01182   bool Changed = false;
01183   do {
01184     BB = Worklist.pop_back_val();
01185 
01186     // Do a quick scan of the basic block, turning any obviously unreachable
01187     // instructions into LLVM unreachable insts.  The instruction combining pass
01188     // canonicalizes unreachable insts into stores to null or undef.
01189     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
01190       // Assumptions that are known to be false are equivalent to unreachable.
01191       // Also, if the condition is undefined, then we make the choice most
01192       // beneficial to the optimizer, and choose that to also be unreachable.
01193       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI))
01194         if (II->getIntrinsicID() == Intrinsic::assume) {
01195           bool MakeUnreachable = false;
01196           if (isa<UndefValue>(II->getArgOperand(0)))
01197             MakeUnreachable = true;
01198           else if (ConstantInt *Cond =
01199                    dyn_cast<ConstantInt>(II->getArgOperand(0)))
01200             MakeUnreachable = Cond->isZero();
01201 
01202           if (MakeUnreachable) {
01203             // Don't insert a call to llvm.trap right before the unreachable.
01204             changeToUnreachable(BBI, false);
01205             Changed = true;
01206             break;
01207           }
01208         }
01209 
01210       if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
01211         if (CI->doesNotReturn()) {
01212           // If we found a call to a no-return function, insert an unreachable
01213           // instruction after it.  Make sure there isn't *already* one there
01214           // though.
01215           ++BBI;
01216           if (!isa<UnreachableInst>(BBI)) {
01217             // Don't insert a call to llvm.trap right before the unreachable.
01218             changeToUnreachable(BBI, false);
01219             Changed = true;
01220           }
01221           break;
01222         }
01223       }
01224 
01225       // Store to undef and store to null are undefined and used to signal that
01226       // they should be changed to unreachable by passes that can't modify the
01227       // CFG.
01228       if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
01229         // Don't touch volatile stores.
01230         if (SI->isVolatile()) continue;
01231 
01232         Value *Ptr = SI->getOperand(1);
01233 
01234         if (isa<UndefValue>(Ptr) ||
01235             (isa<ConstantPointerNull>(Ptr) &&
01236              SI->getPointerAddressSpace() == 0)) {
01237           changeToUnreachable(SI, true);
01238           Changed = true;
01239           break;
01240         }
01241       }
01242     }
01243 
01244     // Turn invokes that call 'nounwind' functions into ordinary calls.
01245     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
01246       Value *Callee = II->getCalledValue();
01247       if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
01248         changeToUnreachable(II, true);
01249         Changed = true;
01250       } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(II)) {
01251         if (II->use_empty() && II->onlyReadsMemory()) {
01252           // jump to the normal destination branch.
01253           BranchInst::Create(II->getNormalDest(), II);
01254           II->getUnwindDest()->removePredecessor(II->getParent());
01255           II->eraseFromParent();
01256         } else
01257           changeToCall(II);
01258         Changed = true;
01259       }
01260     }
01261 
01262     Changed |= ConstantFoldTerminator(BB, true);
01263     for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
01264       if (Reachable.insert(*SI).second)
01265         Worklist.push_back(*SI);
01266   } while (!Worklist.empty());
01267   return Changed;
01268 }
01269 
01270 /// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
01271 /// if they are in a dead cycle.  Return true if a change was made, false
01272 /// otherwise.
01273 bool llvm::removeUnreachableBlocks(Function &F) {
01274   SmallPtrSet<BasicBlock*, 128> Reachable;
01275   bool Changed = markAliveBlocks(F.begin(), Reachable);
01276 
01277   // If there are unreachable blocks in the CFG...
01278   if (Reachable.size() == F.size())
01279     return Changed;
01280 
01281   assert(Reachable.size() < F.size());
01282   NumRemoved += F.size()-Reachable.size();
01283 
01284   // Loop over all of the basic blocks that are not reachable, dropping all of
01285   // their internal references...
01286   for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
01287     if (Reachable.count(BB))
01288       continue;
01289 
01290     for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
01291       if (Reachable.count(*SI))
01292         (*SI)->removePredecessor(BB);
01293     BB->dropAllReferences();
01294   }
01295 
01296   for (Function::iterator I = ++F.begin(); I != F.end();)
01297     if (!Reachable.count(I))
01298       I = F.getBasicBlockList().erase(I);
01299     else
01300       ++I;
01301 
01302   return true;
01303 }
01304 
01305 void llvm::combineMetadata(Instruction *K, const Instruction *J, ArrayRef<unsigned> KnownIDs) {
01306   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
01307   K->dropUnknownMetadata(KnownIDs);
01308   K->getAllMetadataOtherThanDebugLoc(Metadata);
01309   for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
01310     unsigned Kind = Metadata[i].first;
01311     MDNode *JMD = J->getMetadata(Kind);
01312     MDNode *KMD = Metadata[i].second;
01313 
01314     switch (Kind) {
01315       default:
01316         K->setMetadata(Kind, nullptr); // Remove unknown metadata
01317         break;
01318       case LLVMContext::MD_dbg:
01319         llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
01320       case LLVMContext::MD_tbaa:
01321         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
01322         break;
01323       case LLVMContext::MD_alias_scope:
01324         K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
01325         break;
01326       case LLVMContext::MD_noalias:
01327         K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
01328         break;
01329       case LLVMContext::MD_range:
01330         K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
01331         break;
01332       case LLVMContext::MD_fpmath:
01333         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
01334         break;
01335       case LLVMContext::MD_invariant_load:
01336         // Only set the !invariant.load if it is present in both instructions.
01337         K->setMetadata(Kind, JMD);
01338         break;
01339       case LLVMContext::MD_nonnull:
01340         // Only set the !nonnull if it is present in both instructions.
01341         K->setMetadata(Kind, JMD);
01342         break;
01343     }
01344   }
01345 }
01346 
01347 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
01348                                         DominatorTree &DT,
01349                                         const BasicBlockEdge &Root) {
01350   assert(From->getType() == To->getType());
01351   
01352   unsigned Count = 0;
01353   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
01354        UI != UE; ) {
01355     Use &U = *UI++;
01356     if (DT.dominates(Root, U)) {
01357       U.set(To);
01358       DEBUG(dbgs() << "Replace dominated use of '"
01359             << From->getName() << "' as "
01360             << *To << " in " << *U << "\n");
01361       ++Count;
01362     }
01363   }
01364   return Count;
01365 }