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/DenseSet.h"
00018 #include "llvm/ADT/Hashing.h"
00019 #include "llvm/ADT/STLExtras.h"
00020 #include "llvm/ADT/SetVector.h"
00021 #include "llvm/ADT/SmallPtrSet.h"
00022 #include "llvm/ADT/Statistic.h"
00023 #include "llvm/Analysis/EHPersonalities.h"
00024 #include "llvm/Analysis/InstructionSimplify.h"
00025 #include "llvm/Analysis/MemoryBuiltins.h"
00026 #include "llvm/Analysis/LazyValueInfo.h"
00027 #include "llvm/Analysis/ValueTracking.h"
00028 #include "llvm/IR/CFG.h"
00029 #include "llvm/IR/Constants.h"
00030 #include "llvm/IR/DIBuilder.h"
00031 #include "llvm/IR/DataLayout.h"
00032 #include "llvm/IR/DebugInfo.h"
00033 #include "llvm/IR/DerivedTypes.h"
00034 #include "llvm/IR/Dominators.h"
00035 #include "llvm/IR/GetElementPtrTypeIterator.h"
00036 #include "llvm/IR/GlobalAlias.h"
00037 #include "llvm/IR/GlobalVariable.h"
00038 #include "llvm/IR/IRBuilder.h"
00039 #include "llvm/IR/Instructions.h"
00040 #include "llvm/IR/IntrinsicInst.h"
00041 #include "llvm/IR/Intrinsics.h"
00042 #include "llvm/IR/MDBuilder.h"
00043 #include "llvm/IR/Metadata.h"
00044 #include "llvm/IR/Operator.h"
00045 #include "llvm/IR/ValueHandle.h"
00046 #include "llvm/Support/Debug.h"
00047 #include "llvm/Support/MathExtras.h"
00048 #include "llvm/Support/raw_ostream.h"
00049 using namespace llvm;
00050 
00051 #define DEBUG_TYPE "local"
00052 
00053 STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
00054 
00055 //===----------------------------------------------------------------------===//
00056 //  Local constant propagation.
00057 //
00058 
00059 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
00060 /// constant value, convert it into an unconditional branch to the constant
00061 /// destination.  This is a nontrivial operation because the successors of this
00062 /// basic block must have their PHI nodes updated.
00063 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
00064 /// conditions and indirectbr addresses this might make dead if
00065 /// DeleteDeadConditions is true.
00066 bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
00067                                   const TargetLibraryInfo *TLI) {
00068   TerminatorInst *T = BB->getTerminator();
00069   IRBuilder<> Builder(T);
00070 
00071   // Branch - See if we are conditional jumping on constant
00072   if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
00073     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
00074     BasicBlock *Dest1 = BI->getSuccessor(0);
00075     BasicBlock *Dest2 = BI->getSuccessor(1);
00076 
00077     if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
00078       // Are we branching on constant?
00079       // YES.  Change to unconditional branch...
00080       BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
00081       BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
00082 
00083       //cerr << "Function: " << T->getParent()->getParent()
00084       //     << "\nRemoving branch from " << T->getParent()
00085       //     << "\n\nTo: " << OldDest << endl;
00086 
00087       // Let the basic block know that we are letting go of it.  Based on this,
00088       // it will adjust it's PHI nodes.
00089       OldDest->removePredecessor(BB);
00090 
00091       // Replace the conditional branch with an unconditional one.
00092       Builder.CreateBr(Destination);
00093       BI->eraseFromParent();
00094       return true;
00095     }
00096 
00097     if (Dest2 == Dest1) {       // Conditional branch to same location?
00098       // This branch matches something like this:
00099       //     br bool %cond, label %Dest, label %Dest
00100       // and changes it into:  br label %Dest
00101 
00102       // Let the basic block know that we are letting go of one copy of it.
00103       assert(BI->getParent() && "Terminator not inserted in block!");
00104       Dest1->removePredecessor(BI->getParent());
00105 
00106       // Replace the conditional branch with an unconditional one.
00107       Builder.CreateBr(Dest1);
00108       Value *Cond = BI->getCondition();
00109       BI->eraseFromParent();
00110       if (DeleteDeadConditions)
00111         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
00112       return true;
00113     }
00114     return false;
00115   }
00116 
00117   if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
00118     // If we are switching on a constant, we can convert the switch to an
00119     // unconditional branch.
00120     ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
00121     BasicBlock *DefaultDest = SI->getDefaultDest();
00122     BasicBlock *TheOnlyDest = DefaultDest;
00123 
00124     // If the default is unreachable, ignore it when searching for TheOnlyDest.
00125     if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
00126         SI->getNumCases() > 0) {
00127       TheOnlyDest = SI->case_begin().getCaseSuccessor();
00128     }
00129 
00130     // Figure out which case it goes to.
00131     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
00132          i != e; ++i) {
00133       // Found case matching a constant operand?
00134       if (i.getCaseValue() == CI) {
00135         TheOnlyDest = i.getCaseSuccessor();
00136         break;
00137       }
00138 
00139       // Check to see if this branch is going to the same place as the default
00140       // dest.  If so, eliminate it as an explicit compare.
00141       if (i.getCaseSuccessor() == DefaultDest) {
00142         MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
00143         unsigned NCases = SI->getNumCases();
00144         // Fold the case metadata into the default if there will be any branches
00145         // left, unless the metadata doesn't match the switch.
00146         if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
00147           // Collect branch weights into a vector.
00148           SmallVector<uint32_t, 8> Weights;
00149           for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
00150                ++MD_i) {
00151             ConstantInt *CI =
00152                 mdconst::dyn_extract<ConstantInt>(MD->getOperand(MD_i));
00153             assert(CI);
00154             Weights.push_back(CI->getValue().getZExtValue());
00155           }
00156           // Merge weight of this case to the default weight.
00157           unsigned idx = i.getCaseIndex();
00158           Weights[0] += Weights[idx+1];
00159           // Remove weight for this case.
00160           std::swap(Weights[idx+1], Weights.back());
00161           Weights.pop_back();
00162           SI->setMetadata(LLVMContext::MD_prof,
00163                           MDBuilder(BB->getContext()).
00164                           createBranchWeights(Weights));
00165         }
00166         // Remove this entry.
00167         DefaultDest->removePredecessor(SI->getParent());
00168         SI->removeCase(i);
00169         --i; --e;
00170         continue;
00171       }
00172 
00173       // Otherwise, check to see if the switch only branches to one destination.
00174       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
00175       // destinations.
00176       if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = nullptr;
00177     }
00178 
00179     if (CI && !TheOnlyDest) {
00180       // Branching on a constant, but not any of the cases, go to the default
00181       // successor.
00182       TheOnlyDest = SI->getDefaultDest();
00183     }
00184 
00185     // If we found a single destination that we can fold the switch into, do so
00186     // now.
00187     if (TheOnlyDest) {
00188       // Insert the new branch.
00189       Builder.CreateBr(TheOnlyDest);
00190       BasicBlock *BB = SI->getParent();
00191 
00192       // Remove entries from PHI nodes which we no longer branch to...
00193       for (BasicBlock *Succ : SI->successors()) {
00194         // Found case matching a constant operand?
00195         if (Succ == TheOnlyDest)
00196           TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
00197         else
00198           Succ->removePredecessor(BB);
00199       }
00200 
00201       // Delete the old switch.
00202       Value *Cond = SI->getCondition();
00203       SI->eraseFromParent();
00204       if (DeleteDeadConditions)
00205         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
00206       return true;
00207     }
00208 
00209     if (SI->getNumCases() == 1) {
00210       // Otherwise, we can fold this switch into a conditional branch
00211       // instruction if it has only one non-default destination.
00212       SwitchInst::CaseIt FirstCase = SI->case_begin();
00213       Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
00214           FirstCase.getCaseValue(), "cond");
00215 
00216       // Insert the new branch.
00217       BranchInst *NewBr = Builder.CreateCondBr(Cond,
00218                                                FirstCase.getCaseSuccessor(),
00219                                                SI->getDefaultDest());
00220       MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
00221       if (MD && MD->getNumOperands() == 3) {
00222         ConstantInt *SICase =
00223             mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
00224         ConstantInt *SIDef =
00225             mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
00226         assert(SICase && SIDef);
00227         // The TrueWeight should be the weight for the single case of SI.
00228         NewBr->setMetadata(LLVMContext::MD_prof,
00229                         MDBuilder(BB->getContext()).
00230                         createBranchWeights(SICase->getValue().getZExtValue(),
00231                                             SIDef->getValue().getZExtValue()));
00232       }
00233 
00234       // Update make.implicit metadata to the newly-created conditional branch.
00235       MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
00236       if (MakeImplicitMD)
00237         NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
00238 
00239       // Delete the old switch.
00240       SI->eraseFromParent();
00241       return true;
00242     }
00243     return false;
00244   }
00245 
00246   if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
00247     // indirectbr blockaddress(@F, @BB) -> br label @BB
00248     if (BlockAddress *BA =
00249           dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
00250       BasicBlock *TheOnlyDest = BA->getBasicBlock();
00251       // Insert the new branch.
00252       Builder.CreateBr(TheOnlyDest);
00253 
00254       for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
00255         if (IBI->getDestination(i) == TheOnlyDest)
00256           TheOnlyDest = nullptr;
00257         else
00258           IBI->getDestination(i)->removePredecessor(IBI->getParent());
00259       }
00260       Value *Address = IBI->getAddress();
00261       IBI->eraseFromParent();
00262       if (DeleteDeadConditions)
00263         RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
00264 
00265       // If we didn't find our destination in the IBI successor list, then we
00266       // have undefined behavior.  Replace the unconditional branch with an
00267       // 'unreachable' instruction.
00268       if (TheOnlyDest) {
00269         BB->getTerminator()->eraseFromParent();
00270         new UnreachableInst(BB->getContext(), BB);
00271       }
00272 
00273       return true;
00274     }
00275   }
00276 
00277   return false;
00278 }
00279 
00280 
00281 //===----------------------------------------------------------------------===//
00282 //  Local dead code elimination.
00283 //
00284 
00285 /// isInstructionTriviallyDead - Return true if the result produced by the
00286 /// instruction is not used, and the instruction has no side effects.
00287 ///
00288 bool llvm::isInstructionTriviallyDead(Instruction *I,
00289                                       const TargetLibraryInfo *TLI) {
00290   if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
00291 
00292   // We don't want the landingpad-like instructions removed by anything this
00293   // general.
00294   if (I->isEHPad())
00295     return false;
00296 
00297   // We don't want debug info removed by anything this general, unless
00298   // debug info is empty.
00299   if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
00300     if (DDI->getAddress())
00301       return false;
00302     return true;
00303   }
00304   if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
00305     if (DVI->getValue())
00306       return false;
00307     return true;
00308   }
00309 
00310   if (!I->mayHaveSideEffects()) return true;
00311 
00312   // Special case intrinsics that "may have side effects" but can be deleted
00313   // when dead.
00314   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00315     // Safe to delete llvm.stacksave if dead.
00316     if (II->getIntrinsicID() == Intrinsic::stacksave)
00317       return true;
00318 
00319     // Lifetime intrinsics are dead when their right-hand is undef.
00320     if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
00321         II->getIntrinsicID() == Intrinsic::lifetime_end)
00322       return isa<UndefValue>(II->getArgOperand(1));
00323 
00324     // Assumptions are dead if their condition is trivially true.
00325     if (II->getIntrinsicID() == Intrinsic::assume) {
00326       if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
00327         return !Cond->isZero();
00328 
00329       return false;
00330     }
00331   }
00332 
00333   if (isAllocLikeFn(I, TLI)) return true;
00334 
00335   if (CallInst *CI = isFreeCall(I, TLI))
00336     if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
00337       return C->isNullValue() || isa<UndefValue>(C);
00338 
00339   return false;
00340 }
00341 
00342 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
00343 /// trivially dead instruction, delete it.  If that makes any of its operands
00344 /// trivially dead, delete them too, recursively.  Return true if any
00345 /// instructions were deleted.
00346 bool
00347 llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
00348                                                  const TargetLibraryInfo *TLI) {
00349   Instruction *I = dyn_cast<Instruction>(V);
00350   if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
00351     return false;
00352 
00353   SmallVector<Instruction*, 16> DeadInsts;
00354   DeadInsts.push_back(I);
00355 
00356   do {
00357     I = DeadInsts.pop_back_val();
00358 
00359     // Null out all of the instruction's operands to see if any operand becomes
00360     // dead as we go.
00361     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
00362       Value *OpV = I->getOperand(i);
00363       I->setOperand(i, nullptr);
00364 
00365       if (!OpV->use_empty()) continue;
00366 
00367       // If the operand is an instruction that became dead as we nulled out the
00368       // operand, and if it is 'trivially' dead, delete it in a future loop
00369       // iteration.
00370       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
00371         if (isInstructionTriviallyDead(OpI, TLI))
00372           DeadInsts.push_back(OpI);
00373     }
00374 
00375     I->eraseFromParent();
00376   } while (!DeadInsts.empty());
00377 
00378   return true;
00379 }
00380 
00381 /// areAllUsesEqual - Check whether the uses of a value are all the same.
00382 /// This is similar to Instruction::hasOneUse() except this will also return
00383 /// true when there are no uses or multiple uses that all refer to the same
00384 /// value.
00385 static bool areAllUsesEqual(Instruction *I) {
00386   Value::user_iterator UI = I->user_begin();
00387   Value::user_iterator UE = I->user_end();
00388   if (UI == UE)
00389     return true;
00390 
00391   User *TheUse = *UI;
00392   for (++UI; UI != UE; ++UI) {
00393     if (*UI != TheUse)
00394       return false;
00395   }
00396   return true;
00397 }
00398 
00399 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
00400 /// dead PHI node, due to being a def-use chain of single-use nodes that
00401 /// either forms a cycle or is terminated by a trivially dead instruction,
00402 /// delete it.  If that makes any of its operands trivially dead, delete them
00403 /// too, recursively.  Return true if a change was made.
00404 bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
00405                                         const TargetLibraryInfo *TLI) {
00406   SmallPtrSet<Instruction*, 4> Visited;
00407   for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
00408        I = cast<Instruction>(*I->user_begin())) {
00409     if (I->use_empty())
00410       return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
00411 
00412     // If we find an instruction more than once, we're on a cycle that
00413     // won't prove fruitful.
00414     if (!Visited.insert(I).second) {
00415       // Break the cycle and delete the instruction and its operands.
00416       I->replaceAllUsesWith(UndefValue::get(I->getType()));
00417       (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
00418       return true;
00419     }
00420   }
00421   return false;
00422 }
00423 
00424 static bool
00425 simplifyAndDCEInstruction(Instruction *I,
00426                           SmallSetVector<Instruction *, 16> &WorkList,
00427                           const DataLayout &DL,
00428                           const TargetLibraryInfo *TLI) {
00429   if (isInstructionTriviallyDead(I, TLI)) {
00430     // Null out all of the instruction's operands to see if any operand becomes
00431     // dead as we go.
00432     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
00433       Value *OpV = I->getOperand(i);
00434       I->setOperand(i, nullptr);
00435 
00436       if (!OpV->use_empty() || I == OpV)
00437         continue;
00438 
00439       // If the operand is an instruction that became dead as we nulled out the
00440       // operand, and if it is 'trivially' dead, delete it in a future loop
00441       // iteration.
00442       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
00443         if (isInstructionTriviallyDead(OpI, TLI))
00444           WorkList.insert(OpI);
00445     }
00446 
00447     I->eraseFromParent();
00448 
00449     return true;
00450   }
00451 
00452   if (Value *SimpleV = SimplifyInstruction(I, DL)) {
00453     // Add the users to the worklist. CAREFUL: an instruction can use itself,
00454     // in the case of a phi node.
00455     for (User *U : I->users())
00456       if (U != I)
00457         WorkList.insert(cast<Instruction>(U));
00458 
00459     // Replace the instruction with its simplified value.
00460     I->replaceAllUsesWith(SimpleV);
00461     I->eraseFromParent();
00462     return true;
00463   }
00464   return false;
00465 }
00466 
00467 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
00468 /// simplify any instructions in it and recursively delete dead instructions.
00469 ///
00470 /// This returns true if it changed the code, note that it can delete
00471 /// instructions in other blocks as well in this block.
00472 bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
00473                                        const TargetLibraryInfo *TLI) {
00474   bool MadeChange = false;
00475   const DataLayout &DL = BB->getModule()->getDataLayout();
00476 
00477 #ifndef NDEBUG
00478   // In debug builds, ensure that the terminator of the block is never replaced
00479   // or deleted by these simplifications. The idea of simplification is that it
00480   // cannot introduce new instructions, and there is no way to replace the
00481   // terminator of a block without introducing a new instruction.
00482   AssertingVH<Instruction> TerminatorVH(&BB->back());
00483 #endif
00484 
00485   SmallSetVector<Instruction *, 16> WorkList;
00486   // Iterate over the original function, only adding insts to the worklist
00487   // if they actually need to be revisited. This avoids having to pre-init
00488   // the worklist with the entire function's worth of instructions.
00489   for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end()); BI != E;) {
00490     assert(!BI->isTerminator());
00491     Instruction *I = &*BI;
00492     ++BI;
00493 
00494     // We're visiting this instruction now, so make sure it's not in the
00495     // worklist from an earlier visit.
00496     if (!WorkList.count(I))
00497       MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
00498   }
00499 
00500   while (!WorkList.empty()) {
00501     Instruction *I = WorkList.pop_back_val();
00502     MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
00503   }
00504   return MadeChange;
00505 }
00506 
00507 //===----------------------------------------------------------------------===//
00508 //  Control Flow Graph Restructuring.
00509 //
00510 
00511 
00512 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
00513 /// method is called when we're about to delete Pred as a predecessor of BB.  If
00514 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
00515 ///
00516 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
00517 /// nodes that collapse into identity values.  For example, if we have:
00518 ///   x = phi(1, 0, 0, 0)
00519 ///   y = and x, z
00520 ///
00521 /// .. and delete the predecessor corresponding to the '1', this will attempt to
00522 /// recursively fold the and to 0.
00523 void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred) {
00524   // This only adjusts blocks with PHI nodes.
00525   if (!isa<PHINode>(BB->begin()))
00526     return;
00527 
00528   // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
00529   // them down.  This will leave us with single entry phi nodes and other phis
00530   // that can be removed.
00531   BB->removePredecessor(Pred, true);
00532 
00533   WeakVH PhiIt = &BB->front();
00534   while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
00535     PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
00536     Value *OldPhiIt = PhiIt;
00537 
00538     if (!recursivelySimplifyInstruction(PN))
00539       continue;
00540 
00541     // If recursive simplification ended up deleting the next PHI node we would
00542     // iterate to, then our iterator is invalid, restart scanning from the top
00543     // of the block.
00544     if (PhiIt != OldPhiIt) PhiIt = &BB->front();
00545   }
00546 }
00547 
00548 
00549 /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
00550 /// predecessor is known to have one successor (DestBB!).  Eliminate the edge
00551 /// between them, moving the instructions in the predecessor into DestBB and
00552 /// deleting the predecessor block.
00553 ///
00554 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, DominatorTree *DT) {
00555   // If BB has single-entry PHI nodes, fold them.
00556   while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
00557     Value *NewVal = PN->getIncomingValue(0);
00558     // Replace self referencing PHI with undef, it must be dead.
00559     if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
00560     PN->replaceAllUsesWith(NewVal);
00561     PN->eraseFromParent();
00562   }
00563 
00564   BasicBlock *PredBB = DestBB->getSinglePredecessor();
00565   assert(PredBB && "Block doesn't have a single predecessor!");
00566 
00567   // Zap anything that took the address of DestBB.  Not doing this will give the
00568   // address an invalid value.
00569   if (DestBB->hasAddressTaken()) {
00570     BlockAddress *BA = BlockAddress::get(DestBB);
00571     Constant *Replacement =
00572       ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
00573     BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
00574                                                      BA->getType()));
00575     BA->destroyConstant();
00576   }
00577 
00578   // Anything that branched to PredBB now branches to DestBB.
00579   PredBB->replaceAllUsesWith(DestBB);
00580 
00581   // Splice all the instructions from PredBB to DestBB.
00582   PredBB->getTerminator()->eraseFromParent();
00583   DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
00584 
00585   // If the PredBB is the entry block of the function, move DestBB up to
00586   // become the entry block after we erase PredBB.
00587   if (PredBB == &DestBB->getParent()->getEntryBlock())
00588     DestBB->moveAfter(PredBB);
00589 
00590   if (DT) {
00591     BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
00592     DT->changeImmediateDominator(DestBB, PredBBIDom);
00593     DT->eraseNode(PredBB);
00594   }
00595   // Nuke BB.
00596   PredBB->eraseFromParent();
00597 }
00598 
00599 /// CanMergeValues - Return true if we can choose one of these values to use
00600 /// in place of the other. Note that we will always choose the non-undef
00601 /// value to keep.
00602 static bool CanMergeValues(Value *First, Value *Second) {
00603   return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
00604 }
00605 
00606 /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
00607 /// almost-empty BB ending in an unconditional branch to Succ, into Succ.
00608 ///
00609 /// Assumption: Succ is the single successor for BB.
00610 ///
00611 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
00612   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
00613 
00614   DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
00615         << Succ->getName() << "\n");
00616   // Shortcut, if there is only a single predecessor it must be BB and merging
00617   // is always safe
00618   if (Succ->getSinglePredecessor()) return true;
00619 
00620   // Make a list of the predecessors of BB
00621   SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
00622 
00623   // Look at all the phi nodes in Succ, to see if they present a conflict when
00624   // merging these blocks
00625   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
00626     PHINode *PN = cast<PHINode>(I);
00627 
00628     // If the incoming value from BB is again a PHINode in
00629     // BB which has the same incoming value for *PI as PN does, we can
00630     // merge the phi nodes and then the blocks can still be merged
00631     PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
00632     if (BBPN && BBPN->getParent() == BB) {
00633       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
00634         BasicBlock *IBB = PN->getIncomingBlock(PI);
00635         if (BBPreds.count(IBB) &&
00636             !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
00637                             PN->getIncomingValue(PI))) {
00638           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
00639                 << Succ->getName() << " is conflicting with "
00640                 << BBPN->getName() << " with regard to common predecessor "
00641                 << IBB->getName() << "\n");
00642           return false;
00643         }
00644       }
00645     } else {
00646       Value* Val = PN->getIncomingValueForBlock(BB);
00647       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
00648         // See if the incoming value for the common predecessor is equal to the
00649         // one for BB, in which case this phi node will not prevent the merging
00650         // of the block.
00651         BasicBlock *IBB = PN->getIncomingBlock(PI);
00652         if (BBPreds.count(IBB) &&
00653             !CanMergeValues(Val, PN->getIncomingValue(PI))) {
00654           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
00655                 << Succ->getName() << " is conflicting with regard to common "
00656                 << "predecessor " << IBB->getName() << "\n");
00657           return false;
00658         }
00659       }
00660     }
00661   }
00662 
00663   return true;
00664 }
00665 
00666 typedef SmallVector<BasicBlock *, 16> PredBlockVector;
00667 typedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
00668 
00669 /// \brief Determines the value to use as the phi node input for a block.
00670 ///
00671 /// Select between \p OldVal any value that we know flows from \p BB
00672 /// to a particular phi on the basis of which one (if either) is not
00673 /// undef. Update IncomingValues based on the selected value.
00674 ///
00675 /// \param OldVal The value we are considering selecting.
00676 /// \param BB The block that the value flows in from.
00677 /// \param IncomingValues A map from block-to-value for other phi inputs
00678 /// that we have examined.
00679 ///
00680 /// \returns the selected value.
00681 static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
00682                                           IncomingValueMap &IncomingValues) {
00683   if (!isa<UndefValue>(OldVal)) {
00684     assert((!IncomingValues.count(BB) ||
00685             IncomingValues.find(BB)->second == OldVal) &&
00686            "Expected OldVal to match incoming value from BB!");
00687 
00688     IncomingValues.insert(std::make_pair(BB, OldVal));
00689     return OldVal;
00690   }
00691 
00692   IncomingValueMap::const_iterator It = IncomingValues.find(BB);
00693   if (It != IncomingValues.end()) return It->second;
00694 
00695   return OldVal;
00696 }
00697 
00698 /// \brief Create a map from block to value for the operands of a
00699 /// given phi.
00700 ///
00701 /// Create a map from block to value for each non-undef value flowing
00702 /// into \p PN.
00703 ///
00704 /// \param PN The phi we are collecting the map for.
00705 /// \param IncomingValues [out] The map from block to value for this phi.
00706 static void gatherIncomingValuesToPhi(PHINode *PN,
00707                                       IncomingValueMap &IncomingValues) {
00708   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00709     BasicBlock *BB = PN->getIncomingBlock(i);
00710     Value *V = PN->getIncomingValue(i);
00711 
00712     if (!isa<UndefValue>(V))
00713       IncomingValues.insert(std::make_pair(BB, V));
00714   }
00715 }
00716 
00717 /// \brief Replace the incoming undef values to a phi with the values
00718 /// from a block-to-value map.
00719 ///
00720 /// \param PN The phi we are replacing the undefs in.
00721 /// \param IncomingValues A map from block to value.
00722 static void replaceUndefValuesInPhi(PHINode *PN,
00723                                     const IncomingValueMap &IncomingValues) {
00724   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00725     Value *V = PN->getIncomingValue(i);
00726 
00727     if (!isa<UndefValue>(V)) continue;
00728 
00729     BasicBlock *BB = PN->getIncomingBlock(i);
00730     IncomingValueMap::const_iterator It = IncomingValues.find(BB);
00731     if (It == IncomingValues.end()) continue;
00732 
00733     PN->setIncomingValue(i, It->second);
00734   }
00735 }
00736 
00737 /// \brief Replace a value flowing from a block to a phi with
00738 /// potentially multiple instances of that value flowing from the
00739 /// block's predecessors to the phi.
00740 ///
00741 /// \param BB The block with the value flowing into the phi.
00742 /// \param BBPreds The predecessors of BB.
00743 /// \param PN The phi that we are updating.
00744 static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
00745                                                 const PredBlockVector &BBPreds,
00746                                                 PHINode *PN) {
00747   Value *OldVal = PN->removeIncomingValue(BB, false);
00748   assert(OldVal && "No entry in PHI for Pred BB!");
00749 
00750   IncomingValueMap IncomingValues;
00751 
00752   // We are merging two blocks - BB, and the block containing PN - and
00753   // as a result we need to redirect edges from the predecessors of BB
00754   // to go to the block containing PN, and update PN
00755   // accordingly. Since we allow merging blocks in the case where the
00756   // predecessor and successor blocks both share some predecessors,
00757   // and where some of those common predecessors might have undef
00758   // values flowing into PN, we want to rewrite those values to be
00759   // consistent with the non-undef values.
00760 
00761   gatherIncomingValuesToPhi(PN, IncomingValues);
00762 
00763   // If this incoming value is one of the PHI nodes in BB, the new entries
00764   // in the PHI node are the entries from the old PHI.
00765   if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
00766     PHINode *OldValPN = cast<PHINode>(OldVal);
00767     for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
00768       // Note that, since we are merging phi nodes and BB and Succ might
00769       // have common predecessors, we could end up with a phi node with
00770       // identical incoming branches. This will be cleaned up later (and
00771       // will trigger asserts if we try to clean it up now, without also
00772       // simplifying the corresponding conditional branch).
00773       BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
00774       Value *PredVal = OldValPN->getIncomingValue(i);
00775       Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
00776                                                     IncomingValues);
00777 
00778       // And add a new incoming value for this predecessor for the
00779       // newly retargeted branch.
00780       PN->addIncoming(Selected, PredBB);
00781     }
00782   } else {
00783     for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
00784       // Update existing incoming values in PN for this
00785       // predecessor of BB.
00786       BasicBlock *PredBB = BBPreds[i];
00787       Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
00788                                                     IncomingValues);
00789 
00790       // And add a new incoming value for this predecessor for the
00791       // newly retargeted branch.
00792       PN->addIncoming(Selected, PredBB);
00793     }
00794   }
00795 
00796   replaceUndefValuesInPhi(PN, IncomingValues);
00797 }
00798 
00799 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
00800 /// unconditional branch, and contains no instructions other than PHI nodes,
00801 /// potential side-effect free intrinsics and the branch.  If possible,
00802 /// eliminate BB by rewriting all the predecessors to branch to the successor
00803 /// block and return true.  If we can't transform, return false.
00804 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
00805   assert(BB != &BB->getParent()->getEntryBlock() &&
00806          "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
00807 
00808   // We can't eliminate infinite loops.
00809   BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
00810   if (BB == Succ) return false;
00811 
00812   // Check to see if merging these blocks would cause conflicts for any of the
00813   // phi nodes in BB or Succ. If not, we can safely merge.
00814   if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
00815 
00816   // Check for cases where Succ has multiple predecessors and a PHI node in BB
00817   // has uses which will not disappear when the PHI nodes are merged.  It is
00818   // possible to handle such cases, but difficult: it requires checking whether
00819   // BB dominates Succ, which is non-trivial to calculate in the case where
00820   // Succ has multiple predecessors.  Also, it requires checking whether
00821   // constructing the necessary self-referential PHI node doesn't introduce any
00822   // conflicts; this isn't too difficult, but the previous code for doing this
00823   // was incorrect.
00824   //
00825   // Note that if this check finds a live use, BB dominates Succ, so BB is
00826   // something like a loop pre-header (or rarely, a part of an irreducible CFG);
00827   // folding the branch isn't profitable in that case anyway.
00828   if (!Succ->getSinglePredecessor()) {
00829     BasicBlock::iterator BBI = BB->begin();
00830     while (isa<PHINode>(*BBI)) {
00831       for (Use &U : BBI->uses()) {
00832         if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
00833           if (PN->getIncomingBlock(U) != BB)
00834             return false;
00835         } else {
00836           return false;
00837         }
00838       }
00839       ++BBI;
00840     }
00841   }
00842 
00843   DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
00844 
00845   if (isa<PHINode>(Succ->begin())) {
00846     // If there is more than one pred of succ, and there are PHI nodes in
00847     // the successor, then we need to add incoming edges for the PHI nodes
00848     //
00849     const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
00850 
00851     // Loop over all of the PHI nodes in the successor of BB.
00852     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
00853       PHINode *PN = cast<PHINode>(I);
00854 
00855       redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
00856     }
00857   }
00858 
00859   if (Succ->getSinglePredecessor()) {
00860     // BB is the only predecessor of Succ, so Succ will end up with exactly
00861     // the same predecessors BB had.
00862 
00863     // Copy over any phi, debug or lifetime instruction.
00864     BB->getTerminator()->eraseFromParent();
00865     Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
00866                                BB->getInstList());
00867   } else {
00868     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
00869       // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
00870       assert(PN->use_empty() && "There shouldn't be any uses here!");
00871       PN->eraseFromParent();
00872     }
00873   }
00874 
00875   // Everything that jumped to BB now goes to Succ.
00876   BB->replaceAllUsesWith(Succ);
00877   if (!Succ->hasName()) Succ->takeName(BB);
00878   BB->eraseFromParent();              // Delete the old basic block.
00879   return true;
00880 }
00881 
00882 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
00883 /// nodes in this block. This doesn't try to be clever about PHI nodes
00884 /// which differ only in the order of the incoming values, but instcombine
00885 /// orders them so it usually won't matter.
00886 ///
00887 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
00888   // This implementation doesn't currently consider undef operands
00889   // specially. Theoretically, two phis which are identical except for
00890   // one having an undef where the other doesn't could be collapsed.
00891 
00892   struct PHIDenseMapInfo {
00893     static PHINode *getEmptyKey() {
00894       return DenseMapInfo<PHINode *>::getEmptyKey();
00895     }
00896     static PHINode *getTombstoneKey() {
00897       return DenseMapInfo<PHINode *>::getTombstoneKey();
00898     }
00899     static unsigned getHashValue(PHINode *PN) {
00900       // Compute a hash value on the operands. Instcombine will likely have
00901       // sorted them, which helps expose duplicates, but we have to check all
00902       // the operands to be safe in case instcombine hasn't run.
00903       return static_cast<unsigned>(hash_combine(
00904           hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
00905           hash_combine_range(PN->block_begin(), PN->block_end())));
00906     }
00907     static bool isEqual(PHINode *LHS, PHINode *RHS) {
00908       if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
00909           RHS == getEmptyKey() || RHS == getTombstoneKey())
00910         return LHS == RHS;
00911       return LHS->isIdenticalTo(RHS);
00912     }
00913   };
00914 
00915   // Set of unique PHINodes.
00916   DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
00917 
00918   // Examine each PHI.
00919   bool Changed = false;
00920   for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
00921     auto Inserted = PHISet.insert(PN);
00922     if (!Inserted.second) {
00923       // A duplicate. Replace this PHI with its duplicate.
00924       PN->replaceAllUsesWith(*Inserted.first);
00925       PN->eraseFromParent();
00926       Changed = true;
00927 
00928       // The RAUW can change PHIs that we already visited. Start over from the
00929       // beginning.
00930       PHISet.clear();
00931       I = BB->begin();
00932     }
00933   }
00934 
00935   return Changed;
00936 }
00937 
00938 /// enforceKnownAlignment - If the specified pointer points to an object that
00939 /// we control, modify the object's alignment to PrefAlign. This isn't
00940 /// often possible though. If alignment is important, a more reliable approach
00941 /// is to simply align all global variables and allocation instructions to
00942 /// their preferred alignment from the beginning.
00943 ///
00944 static unsigned enforceKnownAlignment(Value *V, unsigned Align,
00945                                       unsigned PrefAlign,
00946                                       const DataLayout &DL) {
00947   assert(PrefAlign > Align);
00948 
00949   V = V->stripPointerCasts();
00950 
00951   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
00952     // TODO: ideally, computeKnownBits ought to have used
00953     // AllocaInst::getAlignment() in its computation already, making
00954     // the below max redundant. But, as it turns out,
00955     // stripPointerCasts recurses through infinite layers of bitcasts,
00956     // while computeKnownBits is not allowed to traverse more than 6
00957     // levels.
00958     Align = std::max(AI->getAlignment(), Align);
00959     if (PrefAlign <= Align)
00960       return Align;
00961 
00962     // If the preferred alignment is greater than the natural stack alignment
00963     // then don't round up. This avoids dynamic stack realignment.
00964     if (DL.exceedsNaturalStackAlignment(PrefAlign))
00965       return Align;
00966     AI->setAlignment(PrefAlign);
00967     return PrefAlign;
00968   }
00969 
00970   if (auto *GO = dyn_cast<GlobalObject>(V)) {
00971     // TODO: as above, this shouldn't be necessary.
00972     Align = std::max(GO->getAlignment(), Align);
00973     if (PrefAlign <= Align)
00974       return Align;
00975 
00976     // If there is a large requested alignment and we can, bump up the alignment
00977     // of the global.  If the memory we set aside for the global may not be the
00978     // memory used by the final program then it is impossible for us to reliably
00979     // enforce the preferred alignment.
00980     if (!GO->canIncreaseAlignment())
00981       return Align;
00982 
00983     GO->setAlignment(PrefAlign);
00984     return PrefAlign;
00985   }
00986 
00987   return Align;
00988 }
00989 
00990 /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
00991 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
00992 /// and it is more than the alignment of the ultimate object, see if we can
00993 /// increase the alignment of the ultimate object, making this check succeed.
00994 unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
00995                                           const DataLayout &DL,
00996                                           const Instruction *CxtI,
00997                                           AssumptionCache *AC,
00998                                           const DominatorTree *DT) {
00999   assert(V->getType()->isPointerTy() &&
01000          "getOrEnforceKnownAlignment expects a pointer!");
01001   unsigned BitWidth = DL.getPointerTypeSizeInBits(V->getType());
01002 
01003   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
01004   computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC, CxtI, DT);
01005   unsigned TrailZ = KnownZero.countTrailingOnes();
01006 
01007   // Avoid trouble with ridiculously large TrailZ values, such as
01008   // those computed from a null pointer.
01009   TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
01010 
01011   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
01012 
01013   // LLVM doesn't support alignments larger than this currently.
01014   Align = std::min(Align, +Value::MaximumAlignment);
01015 
01016   if (PrefAlign > Align)
01017     Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
01018 
01019   // We don't need to make any adjustment.
01020   return Align;
01021 }
01022 
01023 ///===---------------------------------------------------------------------===//
01024 ///  Dbg Intrinsic utilities
01025 ///
01026 
01027 /// See if there is a dbg.value intrinsic for DIVar before I.
01028 static bool LdStHasDebugValue(const DILocalVariable *DIVar, Instruction *I) {
01029   // Since we can't guarantee that the original dbg.declare instrinsic
01030   // is removed by LowerDbgDeclare(), we need to make sure that we are
01031   // not inserting the same dbg.value intrinsic over and over.
01032   llvm::BasicBlock::InstListType::iterator PrevI(I);
01033   if (PrevI != I->getParent()->getInstList().begin()) {
01034     --PrevI;
01035     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
01036       if (DVI->getValue() == I->getOperand(0) &&
01037           DVI->getOffset() == 0 &&
01038           DVI->getVariable() == DIVar)
01039         return true;
01040   }
01041   return false;
01042 }
01043 
01044 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
01045 /// that has an associated llvm.dbg.decl intrinsic.
01046 bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
01047                                            StoreInst *SI, DIBuilder &Builder) {
01048   auto *DIVar = DDI->getVariable();
01049   auto *DIExpr = DDI->getExpression();
01050   assert(DIVar && "Missing variable");
01051 
01052   if (LdStHasDebugValue(DIVar, SI))
01053     return true;
01054 
01055   // If an argument is zero extended then use argument directly. The ZExt
01056   // may be zapped by an optimization pass in future.
01057   Argument *ExtendedArg = nullptr;
01058   if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
01059     ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
01060   if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
01061     ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
01062   if (ExtendedArg) {
01063     // We're now only describing a subset of the variable. The piece we're
01064     // describing will always be smaller than the variable size, because
01065     // VariableSize == Size of Alloca described by DDI. Since SI stores
01066     // to the alloca described by DDI, if it's first operand is an extend,
01067     // we're guaranteed that before extension, the value was narrower than
01068     // the size of the alloca, hence the size of the described variable.
01069     SmallVector<uint64_t, 3> NewDIExpr;
01070     unsigned PieceOffset = 0;
01071     // If this already is a bit piece, we drop the bit piece from the expression
01072     // and record the offset.
01073     if (DIExpr->isBitPiece()) {
01074       NewDIExpr.append(DIExpr->elements_begin(), DIExpr->elements_end()-3);
01075       PieceOffset = DIExpr->getBitPieceOffset();
01076     } else {
01077       NewDIExpr.append(DIExpr->elements_begin(), DIExpr->elements_end());
01078     }
01079     NewDIExpr.push_back(dwarf::DW_OP_bit_piece);
01080     NewDIExpr.push_back(PieceOffset); //Offset
01081     const DataLayout &DL = DDI->getModule()->getDataLayout();
01082     NewDIExpr.push_back(DL.getTypeSizeInBits(ExtendedArg->getType())); // Size
01083     Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar,
01084                                     Builder.createExpression(NewDIExpr),
01085                                     DDI->getDebugLoc(), SI);
01086   }
01087   else
01088     Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, DIExpr,
01089                                     DDI->getDebugLoc(), SI);
01090   return true;
01091 }
01092 
01093 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
01094 /// that has an associated llvm.dbg.decl intrinsic.
01095 bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
01096                                            LoadInst *LI, DIBuilder &Builder) {
01097   auto *DIVar = DDI->getVariable();
01098   auto *DIExpr = DDI->getExpression();
01099   assert(DIVar && "Missing variable");
01100 
01101   if (LdStHasDebugValue(DIVar, LI))
01102     return true;
01103 
01104   // We are now tracking the loaded value instead of the address. In the
01105   // future if multi-location support is added to the IR, it might be
01106   // preferable to keep tracking both the loaded value and the original
01107   // address in case the alloca can not be elided.
01108   Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
01109       LI, 0, DIVar, DIExpr, DDI->getDebugLoc(), (Instruction *)nullptr);
01110   DbgValue->insertAfter(LI);
01111   return true;
01112 }
01113 
01114 /// Determine whether this alloca is either a VLA or an array.
01115 static bool isArray(AllocaInst *AI) {
01116   return AI->isArrayAllocation() ||
01117     AI->getType()->getElementType()->isArrayTy();
01118 }
01119 
01120 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
01121 /// of llvm.dbg.value intrinsics.
01122 bool llvm::LowerDbgDeclare(Function &F) {
01123   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
01124   SmallVector<DbgDeclareInst *, 4> Dbgs;
01125   for (auto &FI : F)
01126     for (Instruction &BI : FI)
01127       if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
01128         Dbgs.push_back(DDI);
01129 
01130   if (Dbgs.empty())
01131     return false;
01132 
01133   for (auto &I : Dbgs) {
01134     DbgDeclareInst *DDI = I;
01135     AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
01136     // If this is an alloca for a scalar variable, insert a dbg.value
01137     // at each load and store to the alloca and erase the dbg.declare.
01138     // The dbg.values allow tracking a variable even if it is not
01139     // stored on the stack, while the dbg.declare can only describe
01140     // the stack slot (and at a lexical-scope granularity). Later
01141     // passes will attempt to elide the stack slot.
01142     if (AI && !isArray(AI)) {
01143       for (auto &AIUse : AI->uses()) {
01144         User *U = AIUse.getUser();
01145         if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
01146           if (AIUse.getOperandNo() == 1)
01147             ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
01148         } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
01149           ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
01150         } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
01151           // This is a call by-value or some other instruction that
01152           // takes a pointer to the variable. Insert a *value*
01153           // intrinsic that describes the alloca.
01154           SmallVector<uint64_t, 1> NewDIExpr;
01155           auto *DIExpr = DDI->getExpression();
01156           NewDIExpr.push_back(dwarf::DW_OP_deref);
01157           NewDIExpr.append(DIExpr->elements_begin(), DIExpr->elements_end());
01158           DIB.insertDbgValueIntrinsic(AI, 0, DDI->getVariable(),
01159                                       DIB.createExpression(NewDIExpr),
01160                                       DDI->getDebugLoc(), CI);
01161         }
01162       }
01163       DDI->eraseFromParent();
01164     }
01165   }
01166   return true;
01167 }
01168 
01169 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
01170 /// alloca 'V', if any.
01171 DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
01172   if (auto *L = LocalAsMetadata::getIfExists(V))
01173     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
01174       for (User *U : MDV->users())
01175         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
01176           return DDI;
01177 
01178   return nullptr;
01179 }
01180 
01181 bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
01182                              Instruction *InsertBefore, DIBuilder &Builder,
01183                              bool Deref, int Offset) {
01184   DbgDeclareInst *DDI = FindAllocaDbgDeclare(Address);
01185   if (!DDI)
01186     return false;
01187   DebugLoc Loc = DDI->getDebugLoc();
01188   auto *DIVar = DDI->getVariable();
01189   auto *DIExpr = DDI->getExpression();
01190   assert(DIVar && "Missing variable");
01191 
01192   if (Deref || Offset) {
01193     // Create a copy of the original DIDescriptor for user variable, prepending
01194     // "deref" operation to a list of address elements, as new llvm.dbg.declare
01195     // will take a value storing address of the memory for variable, not
01196     // alloca itself.
01197     SmallVector<uint64_t, 4> NewDIExpr;
01198     if (Deref)
01199       NewDIExpr.push_back(dwarf::DW_OP_deref);
01200     if (Offset > 0) {
01201       NewDIExpr.push_back(dwarf::DW_OP_plus);
01202       NewDIExpr.push_back(Offset);
01203     } else if (Offset < 0) {
01204       NewDIExpr.push_back(dwarf::DW_OP_minus);
01205       NewDIExpr.push_back(-Offset);
01206     }
01207     if (DIExpr)
01208       NewDIExpr.append(DIExpr->elements_begin(), DIExpr->elements_end());
01209     DIExpr = Builder.createExpression(NewDIExpr);
01210   }
01211 
01212   // Insert llvm.dbg.declare immediately after the original alloca, and remove
01213   // old llvm.dbg.declare.
01214   Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
01215   DDI->eraseFromParent();
01216   return true;
01217 }
01218 
01219 bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
01220                                       DIBuilder &Builder, bool Deref, int Offset) {
01221   return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder,
01222                            Deref, Offset);
01223 }
01224 
01225 unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
01226   unsigned NumDeadInst = 0;
01227   // Delete the instructions backwards, as it has a reduced likelihood of
01228   // having to update as many def-use and use-def chains.
01229   Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
01230   while (EndInst != BB->begin()) {
01231     // Delete the next to last instruction.
01232     Instruction *Inst = &*--EndInst->getIterator();
01233     if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
01234       Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
01235     if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
01236       EndInst = Inst;
01237       continue;
01238     }
01239     if (!isa<DbgInfoIntrinsic>(Inst))
01240       ++NumDeadInst;
01241     Inst->eraseFromParent();
01242   }
01243   return NumDeadInst;
01244 }
01245 
01246 unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap) {
01247   BasicBlock *BB = I->getParent();
01248   // Loop over all of the successors, removing BB's entry from any PHI
01249   // nodes.
01250   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
01251     (*SI)->removePredecessor(BB);
01252 
01253   // Insert a call to llvm.trap right before this.  This turns the undefined
01254   // behavior into a hard fail instead of falling through into random code.
01255   if (UseLLVMTrap) {
01256     Function *TrapFn =
01257       Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
01258     CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
01259     CallTrap->setDebugLoc(I->getDebugLoc());
01260   }
01261   new UnreachableInst(I->getContext(), I);
01262 
01263   // All instructions after this are dead.
01264   unsigned NumInstrsRemoved = 0;
01265   BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
01266   while (BBI != BBE) {
01267     if (!BBI->use_empty())
01268       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
01269     BB->getInstList().erase(BBI++);
01270     ++NumInstrsRemoved;
01271   }
01272   return NumInstrsRemoved;
01273 }
01274 
01275 /// changeToCall - Convert the specified invoke into a normal call.
01276 static void changeToCall(InvokeInst *II) {
01277   SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end());
01278   SmallVector<OperandBundleDef, 1> OpBundles;
01279   II->getOperandBundlesAsDefs(OpBundles);
01280   CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, OpBundles,
01281                                        "", II);
01282   NewCall->takeName(II);
01283   NewCall->setCallingConv(II->getCallingConv());
01284   NewCall->setAttributes(II->getAttributes());
01285   NewCall->setDebugLoc(II->getDebugLoc());
01286   II->replaceAllUsesWith(NewCall);
01287 
01288   // Follow the call by a branch to the normal destination.
01289   BranchInst::Create(II->getNormalDest(), II);
01290 
01291   // Update PHI nodes in the unwind destination
01292   II->getUnwindDest()->removePredecessor(II->getParent());
01293   II->eraseFromParent();
01294 }
01295 
01296 static bool markAliveBlocks(Function &F,
01297                             SmallPtrSetImpl<BasicBlock*> &Reachable) {
01298 
01299   SmallVector<BasicBlock*, 128> Worklist;
01300   BasicBlock *BB = &F.front();
01301   Worklist.push_back(BB);
01302   Reachable.insert(BB);
01303   bool Changed = false;
01304   do {
01305     BB = Worklist.pop_back_val();
01306 
01307     // Do a quick scan of the basic block, turning any obviously unreachable
01308     // instructions into LLVM unreachable insts.  The instruction combining pass
01309     // canonicalizes unreachable insts into stores to null or undef.
01310     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
01311       // Assumptions that are known to be false are equivalent to unreachable.
01312       // Also, if the condition is undefined, then we make the choice most
01313       // beneficial to the optimizer, and choose that to also be unreachable.
01314       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI))
01315         if (II->getIntrinsicID() == Intrinsic::assume) {
01316           bool MakeUnreachable = false;
01317           if (isa<UndefValue>(II->getArgOperand(0)))
01318             MakeUnreachable = true;
01319           else if (ConstantInt *Cond =
01320                    dyn_cast<ConstantInt>(II->getArgOperand(0)))
01321             MakeUnreachable = Cond->isZero();
01322 
01323           if (MakeUnreachable) {
01324             // Don't insert a call to llvm.trap right before the unreachable.
01325             changeToUnreachable(&*BBI, false);
01326             Changed = true;
01327             break;
01328           }
01329         }
01330 
01331       if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
01332         if (CI->doesNotReturn()) {
01333           // If we found a call to a no-return function, insert an unreachable
01334           // instruction after it.  Make sure there isn't *already* one there
01335           // though.
01336           ++BBI;
01337           if (!isa<UnreachableInst>(BBI)) {
01338             // Don't insert a call to llvm.trap right before the unreachable.
01339             changeToUnreachable(&*BBI, false);
01340             Changed = true;
01341           }
01342           break;
01343         }
01344       }
01345 
01346       // Store to undef and store to null are undefined and used to signal that
01347       // they should be changed to unreachable by passes that can't modify the
01348       // CFG.
01349       if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
01350         // Don't touch volatile stores.
01351         if (SI->isVolatile()) continue;
01352 
01353         Value *Ptr = SI->getOperand(1);
01354 
01355         if (isa<UndefValue>(Ptr) ||
01356             (isa<ConstantPointerNull>(Ptr) &&
01357              SI->getPointerAddressSpace() == 0)) {
01358           changeToUnreachable(SI, true);
01359           Changed = true;
01360           break;
01361         }
01362       }
01363     }
01364 
01365     TerminatorInst *Terminator = BB->getTerminator();
01366     if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
01367       // Turn invokes that call 'nounwind' functions into ordinary calls.
01368       Value *Callee = II->getCalledValue();
01369       if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
01370         changeToUnreachable(II, true);
01371         Changed = true;
01372       } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
01373         if (II->use_empty() && II->onlyReadsMemory()) {
01374           // jump to the normal destination branch.
01375           BranchInst::Create(II->getNormalDest(), II);
01376           II->getUnwindDest()->removePredecessor(II->getParent());
01377           II->eraseFromParent();
01378         } else
01379           changeToCall(II);
01380         Changed = true;
01381       }
01382     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
01383       // Remove catchpads which cannot be reached.
01384       struct CatchPadDenseMapInfo {
01385         static CatchPadInst *getEmptyKey() {
01386           return DenseMapInfo<CatchPadInst *>::getEmptyKey();
01387         }
01388         static CatchPadInst *getTombstoneKey() {
01389           return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
01390         }
01391         static unsigned getHashValue(CatchPadInst *CatchPad) {
01392           return static_cast<unsigned>(hash_combine_range(
01393               CatchPad->value_op_begin(), CatchPad->value_op_end()));
01394         }
01395         static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
01396           if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
01397               RHS == getEmptyKey() || RHS == getTombstoneKey())
01398             return LHS == RHS;
01399           return LHS->isIdenticalTo(RHS);
01400         }
01401       };
01402 
01403       // Set of unique CatchPads.
01404       SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
01405                     CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
01406           HandlerSet;
01407       detail::DenseSetEmpty Empty;
01408       for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
01409                                              E = CatchSwitch->handler_end();
01410            I != E; ++I) {
01411         BasicBlock *HandlerBB = *I;
01412         auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
01413         if (!HandlerSet.insert({CatchPad, Empty}).second) {
01414           CatchSwitch->removeHandler(I);
01415           --I;
01416           --E;
01417           Changed = true;
01418         }
01419       }
01420     }
01421 
01422     Changed |= ConstantFoldTerminator(BB, true);
01423     for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
01424       if (Reachable.insert(*SI).second)
01425         Worklist.push_back(*SI);
01426   } while (!Worklist.empty());
01427   return Changed;
01428 }
01429 
01430 void llvm::removeUnwindEdge(BasicBlock *BB) {
01431   TerminatorInst *TI = BB->getTerminator();
01432 
01433   if (auto *II = dyn_cast<InvokeInst>(TI)) {
01434     changeToCall(II);
01435     return;
01436   }
01437 
01438   TerminatorInst *NewTI;
01439   BasicBlock *UnwindDest;
01440 
01441   if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
01442     NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
01443     UnwindDest = CRI->getUnwindDest();
01444   } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
01445     auto *NewCatchSwitch = CatchSwitchInst::Create(
01446         CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
01447         CatchSwitch->getName(), CatchSwitch);
01448     for (BasicBlock *PadBB : CatchSwitch->handlers())
01449       NewCatchSwitch->addHandler(PadBB);
01450 
01451     NewTI = NewCatchSwitch;
01452     UnwindDest = CatchSwitch->getUnwindDest();
01453   } else {
01454     llvm_unreachable("Could not find unwind successor");
01455   }
01456 
01457   NewTI->takeName(TI);
01458   NewTI->setDebugLoc(TI->getDebugLoc());
01459   UnwindDest->removePredecessor(BB);
01460   TI->replaceAllUsesWith(NewTI);
01461   TI->eraseFromParent();
01462 }
01463 
01464 /// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
01465 /// if they are in a dead cycle.  Return true if a change was made, false
01466 /// otherwise.
01467 bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI) {
01468   SmallPtrSet<BasicBlock*, 128> Reachable;
01469   bool Changed = markAliveBlocks(F, Reachable);
01470 
01471   // If there are unreachable blocks in the CFG...
01472   if (Reachable.size() == F.size())
01473     return Changed;
01474 
01475   assert(Reachable.size() < F.size());
01476   NumRemoved += F.size()-Reachable.size();
01477 
01478   // Loop over all of the basic blocks that are not reachable, dropping all of
01479   // their internal references...
01480   for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
01481     if (Reachable.count(&*BB))
01482       continue;
01483 
01484     for (succ_iterator SI = succ_begin(&*BB), SE = succ_end(&*BB); SI != SE;
01485          ++SI)
01486       if (Reachable.count(*SI))
01487         (*SI)->removePredecessor(&*BB);
01488     if (LVI)
01489       LVI->eraseBlock(&*BB);
01490     BB->dropAllReferences();
01491   }
01492 
01493   for (Function::iterator I = ++F.begin(); I != F.end();)
01494     if (!Reachable.count(&*I))
01495       I = F.getBasicBlockList().erase(I);
01496     else
01497       ++I;
01498 
01499   return true;
01500 }
01501 
01502 void llvm::combineMetadata(Instruction *K, const Instruction *J,
01503                            ArrayRef<unsigned> KnownIDs) {
01504   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
01505   K->dropUnknownNonDebugMetadata(KnownIDs);
01506   K->getAllMetadataOtherThanDebugLoc(Metadata);
01507   for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
01508     unsigned Kind = Metadata[i].first;
01509     MDNode *JMD = J->getMetadata(Kind);
01510     MDNode *KMD = Metadata[i].second;
01511 
01512     switch (Kind) {
01513       default:
01514         K->setMetadata(Kind, nullptr); // Remove unknown metadata
01515         break;
01516       case LLVMContext::MD_dbg:
01517         llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
01518       case LLVMContext::MD_tbaa:
01519         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
01520         break;
01521       case LLVMContext::MD_alias_scope:
01522         K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
01523         break;
01524       case LLVMContext::MD_noalias:
01525         K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
01526         break;
01527       case LLVMContext::MD_range:
01528         K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
01529         break;
01530       case LLVMContext::MD_fpmath:
01531         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
01532         break;
01533       case LLVMContext::MD_invariant_load:
01534         // Only set the !invariant.load if it is present in both instructions.
01535         K->setMetadata(Kind, JMD);
01536         break;
01537       case LLVMContext::MD_nonnull:
01538         // Only set the !nonnull if it is present in both instructions.
01539         K->setMetadata(Kind, JMD);
01540         break;
01541       case LLVMContext::MD_invariant_group:
01542         // Preserve !invariant.group in K.
01543         break;
01544       case LLVMContext::MD_align:
01545         K->setMetadata(Kind, 
01546           MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
01547         break;
01548       case LLVMContext::MD_dereferenceable:
01549       case LLVMContext::MD_dereferenceable_or_null:
01550         K->setMetadata(Kind, 
01551           MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
01552         break;
01553     }
01554   }
01555   // Set !invariant.group from J if J has it. If both instructions have it
01556   // then we will just pick it from J - even when they are different.
01557   // Also make sure that K is load or store - f.e. combining bitcast with load
01558   // could produce bitcast with invariant.group metadata, which is invalid.
01559   // FIXME: we should try to preserve both invariant.group md if they are
01560   // different, but right now instruction can only have one invariant.group.
01561   if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
01562     if (isa<LoadInst>(K) || isa<StoreInst>(K))
01563       K->setMetadata(LLVMContext::MD_invariant_group, JMD);
01564 }
01565 
01566 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
01567                                         DominatorTree &DT,
01568                                         const BasicBlockEdge &Root) {
01569   assert(From->getType() == To->getType());
01570   
01571   unsigned Count = 0;
01572   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
01573        UI != UE; ) {
01574     Use &U = *UI++;
01575     if (DT.dominates(Root, U)) {
01576       U.set(To);
01577       DEBUG(dbgs() << "Replace dominated use of '"
01578             << From->getName() << "' as "
01579             << *To << " in " << *U << "\n");
01580       ++Count;
01581     }
01582   }
01583   return Count;
01584 }
01585 
01586 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
01587                                         DominatorTree &DT,
01588                                         const BasicBlock *BB) {
01589   assert(From->getType() == To->getType());
01590 
01591   unsigned Count = 0;
01592   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
01593        UI != UE;) {
01594     Use &U = *UI++;
01595     auto *I = cast<Instruction>(U.getUser());
01596     if (DT.properlyDominates(BB, I->getParent())) {
01597       U.set(To);
01598       DEBUG(dbgs() << "Replace dominated use of '" << From->getName() << "' as "
01599                    << *To << " in " << *U << "\n");
01600       ++Count;
01601     }
01602   }
01603   return Count;
01604 }
01605 
01606 bool llvm::callsGCLeafFunction(ImmutableCallSite CS) {
01607   if (isa<IntrinsicInst>(CS.getInstruction()))
01608     // Most LLVM intrinsics are things which can never take a safepoint.
01609     // As a result, we don't need to have the stack parsable at the
01610     // callsite.  This is a highly useful optimization since intrinsic
01611     // calls are fairly prevalent, particularly in debug builds.
01612     return true;
01613 
01614   // Check if the function is specifically marked as a gc leaf function.
01615   if (CS.hasFnAttr("gc-leaf-function"))
01616     return true;
01617   if (const Function *F = CS.getCalledFunction())
01618     return F->hasFnAttribute("gc-leaf-function");
01619 
01620   return false;
01621 }
01622 
01623 /// A potential constituent of a bitreverse or bswap expression. See
01624 /// collectBitParts for a fuller explanation.
01625 struct BitPart {
01626   BitPart(Value *P, unsigned BW) : Provider(P) {
01627     Provenance.resize(BW);
01628   }
01629 
01630   /// The Value that this is a bitreverse/bswap of.
01631   Value *Provider;
01632   /// The "provenance" of each bit. Provenance[A] = B means that bit A
01633   /// in Provider becomes bit B in the result of this expression.
01634   SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
01635 
01636   enum { Unset = -1 };
01637 };
01638 
01639 /// Analyze the specified subexpression and see if it is capable of providing
01640 /// pieces of a bswap or bitreverse. The subexpression provides a potential
01641 /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
01642 /// the output of the expression came from a corresponding bit in some other
01643 /// value. This function is recursive, and the end result is a mapping of
01644 /// bitnumber to bitnumber. It is the caller's responsibility to validate that
01645 /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
01646 ///
01647 /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
01648 /// that the expression deposits the low byte of %X into the high byte of the
01649 /// result and that all other bits are zero. This expression is accepted and a
01650 /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
01651 /// [0-7].
01652 ///
01653 /// To avoid revisiting values, the BitPart results are memoized into the
01654 /// provided map. To avoid unnecessary copying of BitParts, BitParts are
01655 /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
01656 /// store BitParts objects, not pointers. As we need the concept of a nullptr
01657 /// BitParts (Value has been analyzed and the analysis failed), we an Optional
01658 /// type instead to provide the same functionality.
01659 ///
01660 /// Because we pass around references into \c BPS, we must use a container that
01661 /// does not invalidate internal references (std::map instead of DenseMap).
01662 ///
01663 static const Optional<BitPart> &
01664 collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
01665                 std::map<Value *, Optional<BitPart>> &BPS) {
01666   auto I = BPS.find(V);
01667   if (I != BPS.end())
01668     return I->second;
01669 
01670   auto &Result = BPS[V] = None;
01671   auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
01672 
01673   if (Instruction *I = dyn_cast<Instruction>(V)) {
01674     // If this is an or instruction, it may be an inner node of the bswap.
01675     if (I->getOpcode() == Instruction::Or) {
01676       auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
01677                                 MatchBitReversals, BPS);
01678       auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
01679                                 MatchBitReversals, BPS);
01680       if (!A || !B)
01681         return Result;
01682 
01683       // Try and merge the two together.
01684       if (!A->Provider || A->Provider != B->Provider)
01685         return Result;
01686 
01687       Result = BitPart(A->Provider, BitWidth);
01688       for (unsigned i = 0; i < A->Provenance.size(); ++i) {
01689         if (A->Provenance[i] != BitPart::Unset &&
01690             B->Provenance[i] != BitPart::Unset &&
01691             A->Provenance[i] != B->Provenance[i])
01692           return Result = None;
01693 
01694         if (A->Provenance[i] == BitPart::Unset)
01695           Result->Provenance[i] = B->Provenance[i];
01696         else
01697           Result->Provenance[i] = A->Provenance[i];
01698       }
01699 
01700       return Result;
01701     }
01702 
01703     // If this is a logical shift by a constant, recurse then shift the result.
01704     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
01705       unsigned BitShift =
01706           cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
01707       // Ensure the shift amount is defined.
01708       if (BitShift > BitWidth)
01709         return Result;
01710 
01711       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
01712                                   MatchBitReversals, BPS);
01713       if (!Res)
01714         return Result;
01715       Result = Res;
01716 
01717       // Perform the "shift" on BitProvenance.
01718       auto &P = Result->Provenance;
01719       if (I->getOpcode() == Instruction::Shl) {
01720         P.erase(std::prev(P.end(), BitShift), P.end());
01721         P.insert(P.begin(), BitShift, BitPart::Unset);
01722       } else {
01723         P.erase(P.begin(), std::next(P.begin(), BitShift));
01724         P.insert(P.end(), BitShift, BitPart::Unset);
01725       }
01726 
01727       return Result;
01728     }
01729 
01730     // If this is a logical 'and' with a mask that clears bits, recurse then
01731     // unset the appropriate bits.
01732     if (I->getOpcode() == Instruction::And &&
01733         isa<ConstantInt>(I->getOperand(1))) {
01734       APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
01735       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
01736 
01737       // Check that the mask allows a multiple of 8 bits for a bswap, for an
01738       // early exit.
01739       unsigned NumMaskedBits = AndMask.countPopulation();
01740       if (!MatchBitReversals && NumMaskedBits % 8 != 0)
01741         return Result;
01742       
01743       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
01744                                   MatchBitReversals, BPS);
01745       if (!Res)
01746         return Result;
01747       Result = Res;
01748 
01749       for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
01750         // If the AndMask is zero for this bit, clear the bit.
01751         if ((AndMask & Bit) == 0)
01752           Result->Provenance[i] = BitPart::Unset;
01753 
01754       return Result;
01755     }
01756   }
01757 
01758   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
01759   // the input value to the bswap/bitreverse.
01760   Result = BitPart(V, BitWidth);
01761   for (unsigned i = 0; i < BitWidth; ++i)
01762     Result->Provenance[i] = i;
01763   return Result;
01764 }
01765 
01766 static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
01767                                           unsigned BitWidth) {
01768   if (From % 8 != To % 8)
01769     return false;
01770   // Convert from bit indices to byte indices and check for a byte reversal.
01771   From >>= 3;
01772   To >>= 3;
01773   BitWidth >>= 3;
01774   return From == BitWidth - To - 1;
01775 }
01776 
01777 static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
01778                                                unsigned BitWidth) {
01779   return From == BitWidth - To - 1;
01780 }
01781 
01782 /// Given an OR instruction, check to see if this is a bitreverse
01783 /// idiom. If so, insert the new intrinsic and return true.
01784 bool llvm::recognizeBitReverseOrBSwapIdiom(
01785     Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
01786     SmallVectorImpl<Instruction *> &InsertedInsts) {
01787   if (Operator::getOpcode(I) != Instruction::Or)
01788     return false;
01789   if (!MatchBSwaps && !MatchBitReversals)
01790     return false;
01791   IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
01792   if (!ITy || ITy->getBitWidth() > 128)
01793     return false;   // Can't do vectors or integers > 128 bits.
01794   unsigned BW = ITy->getBitWidth();
01795 
01796   // Try to find all the pieces corresponding to the bswap.
01797   std::map<Value *, Optional<BitPart>> BPS;
01798   auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS);
01799   if (!Res)
01800     return false;
01801   auto &BitProvenance = Res->Provenance;
01802 
01803   // Now, is the bit permutation correct for a bswap or a bitreverse? We can
01804   // only byteswap values with an even number of bytes.
01805   bool OKForBSwap = BW % 16 == 0, OKForBitReverse = true;
01806   for (unsigned i = 0; i < BW; ++i) {
01807     OKForBSwap &= bitTransformIsCorrectForBSwap(BitProvenance[i], i, BW);
01808     OKForBitReverse &=
01809         bitTransformIsCorrectForBitReverse(BitProvenance[i], i, BW);
01810   }
01811 
01812   Intrinsic::ID Intrin;
01813   if (OKForBSwap && MatchBSwaps)
01814     Intrin = Intrinsic::bswap;
01815   else if (OKForBitReverse && MatchBitReversals)
01816     Intrin = Intrinsic::bitreverse;
01817   else
01818     return false;
01819 
01820   Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
01821   InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
01822   return true;
01823 }