IR: Split Metadata from Value
[oota-llvm.git] / lib / Transforms / Utils / Local.cpp
1 //===-- Local.cpp - Functions to perform local transformations ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This family of functions perform various local transformations to the
11 // program.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/MemoryBuiltins.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/CFG.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DIBuilder.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/GetElementPtrTypeIterator.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/MDBuilder.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/ValueHandle.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/raw_ostream.h"
44 using namespace llvm;
45
46 #define DEBUG_TYPE "local"
47
48 STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
49
50 //===----------------------------------------------------------------------===//
51 //  Local constant propagation.
52 //
53
54 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
55 /// constant value, convert it into an unconditional branch to the constant
56 /// destination.  This is a nontrivial operation because the successors of this
57 /// basic block must have their PHI nodes updated.
58 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
59 /// conditions and indirectbr addresses this might make dead if
60 /// DeleteDeadConditions is true.
61 bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
62                                   const TargetLibraryInfo *TLI) {
63   TerminatorInst *T = BB->getTerminator();
64   IRBuilder<> Builder(T);
65
66   // Branch - See if we are conditional jumping on constant
67   if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
68     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
69     BasicBlock *Dest1 = BI->getSuccessor(0);
70     BasicBlock *Dest2 = BI->getSuccessor(1);
71
72     if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
73       // Are we branching on constant?
74       // YES.  Change to unconditional branch...
75       BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
76       BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
77
78       //cerr << "Function: " << T->getParent()->getParent()
79       //     << "\nRemoving branch from " << T->getParent()
80       //     << "\n\nTo: " << OldDest << endl;
81
82       // Let the basic block know that we are letting go of it.  Based on this,
83       // it will adjust it's PHI nodes.
84       OldDest->removePredecessor(BB);
85
86       // Replace the conditional branch with an unconditional one.
87       Builder.CreateBr(Destination);
88       BI->eraseFromParent();
89       return true;
90     }
91
92     if (Dest2 == Dest1) {       // Conditional branch to same location?
93       // This branch matches something like this:
94       //     br bool %cond, label %Dest, label %Dest
95       // and changes it into:  br label %Dest
96
97       // Let the basic block know that we are letting go of one copy of it.
98       assert(BI->getParent() && "Terminator not inserted in block!");
99       Dest1->removePredecessor(BI->getParent());
100
101       // Replace the conditional branch with an unconditional one.
102       Builder.CreateBr(Dest1);
103       Value *Cond = BI->getCondition();
104       BI->eraseFromParent();
105       if (DeleteDeadConditions)
106         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
107       return true;
108     }
109     return false;
110   }
111
112   if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
113     // If we are switching on a constant, we can convert the switch into a
114     // single branch instruction!
115     ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
116     BasicBlock *TheOnlyDest = SI->getDefaultDest();
117     BasicBlock *DefaultDest = TheOnlyDest;
118
119     // Figure out which case it goes to.
120     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
121          i != e; ++i) {
122       // Found case matching a constant operand?
123       if (i.getCaseValue() == CI) {
124         TheOnlyDest = i.getCaseSuccessor();
125         break;
126       }
127
128       // Check to see if this branch is going to the same place as the default
129       // dest.  If so, eliminate it as an explicit compare.
130       if (i.getCaseSuccessor() == DefaultDest) {
131         MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
132         unsigned NCases = SI->getNumCases();
133         // Fold the case metadata into the default if there will be any branches
134         // left, unless the metadata doesn't match the switch.
135         if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
136           // Collect branch weights into a vector.
137           SmallVector<uint32_t, 8> Weights;
138           for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
139                ++MD_i) {
140             ConstantInt *CI =
141                 mdconst::dyn_extract<ConstantInt>(MD->getOperand(MD_i));
142             assert(CI);
143             Weights.push_back(CI->getValue().getZExtValue());
144           }
145           // Merge weight of this case to the default weight.
146           unsigned idx = i.getCaseIndex();
147           Weights[0] += Weights[idx+1];
148           // Remove weight for this case.
149           std::swap(Weights[idx+1], Weights.back());
150           Weights.pop_back();
151           SI->setMetadata(LLVMContext::MD_prof,
152                           MDBuilder(BB->getContext()).
153                           createBranchWeights(Weights));
154         }
155         // Remove this entry.
156         DefaultDest->removePredecessor(SI->getParent());
157         SI->removeCase(i);
158         --i; --e;
159         continue;
160       }
161
162       // Otherwise, check to see if the switch only branches to one destination.
163       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
164       // destinations.
165       if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = nullptr;
166     }
167
168     if (CI && !TheOnlyDest) {
169       // Branching on a constant, but not any of the cases, go to the default
170       // successor.
171       TheOnlyDest = SI->getDefaultDest();
172     }
173
174     // If we found a single destination that we can fold the switch into, do so
175     // now.
176     if (TheOnlyDest) {
177       // Insert the new branch.
178       Builder.CreateBr(TheOnlyDest);
179       BasicBlock *BB = SI->getParent();
180
181       // Remove entries from PHI nodes which we no longer branch to...
182       for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
183         // Found case matching a constant operand?
184         BasicBlock *Succ = SI->getSuccessor(i);
185         if (Succ == TheOnlyDest)
186           TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
187         else
188           Succ->removePredecessor(BB);
189       }
190
191       // Delete the old switch.
192       Value *Cond = SI->getCondition();
193       SI->eraseFromParent();
194       if (DeleteDeadConditions)
195         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
196       return true;
197     }
198
199     if (SI->getNumCases() == 1) {
200       // Otherwise, we can fold this switch into a conditional branch
201       // instruction if it has only one non-default destination.
202       SwitchInst::CaseIt FirstCase = SI->case_begin();
203       Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
204           FirstCase.getCaseValue(), "cond");
205
206       // Insert the new branch.
207       BranchInst *NewBr = Builder.CreateCondBr(Cond,
208                                                FirstCase.getCaseSuccessor(),
209                                                SI->getDefaultDest());
210       MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
211       if (MD && MD->getNumOperands() == 3) {
212         ConstantInt *SICase =
213             mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
214         ConstantInt *SIDef =
215             mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
216         assert(SICase && SIDef);
217         // The TrueWeight should be the weight for the single case of SI.
218         NewBr->setMetadata(LLVMContext::MD_prof,
219                         MDBuilder(BB->getContext()).
220                         createBranchWeights(SICase->getValue().getZExtValue(),
221                                             SIDef->getValue().getZExtValue()));
222       }
223
224       // Delete the old switch.
225       SI->eraseFromParent();
226       return true;
227     }
228     return false;
229   }
230
231   if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
232     // indirectbr blockaddress(@F, @BB) -> br label @BB
233     if (BlockAddress *BA =
234           dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
235       BasicBlock *TheOnlyDest = BA->getBasicBlock();
236       // Insert the new branch.
237       Builder.CreateBr(TheOnlyDest);
238
239       for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
240         if (IBI->getDestination(i) == TheOnlyDest)
241           TheOnlyDest = nullptr;
242         else
243           IBI->getDestination(i)->removePredecessor(IBI->getParent());
244       }
245       Value *Address = IBI->getAddress();
246       IBI->eraseFromParent();
247       if (DeleteDeadConditions)
248         RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
249
250       // If we didn't find our destination in the IBI successor list, then we
251       // have undefined behavior.  Replace the unconditional branch with an
252       // 'unreachable' instruction.
253       if (TheOnlyDest) {
254         BB->getTerminator()->eraseFromParent();
255         new UnreachableInst(BB->getContext(), BB);
256       }
257
258       return true;
259     }
260   }
261
262   return false;
263 }
264
265
266 //===----------------------------------------------------------------------===//
267 //  Local dead code elimination.
268 //
269
270 /// isInstructionTriviallyDead - Return true if the result produced by the
271 /// instruction is not used, and the instruction has no side effects.
272 ///
273 bool llvm::isInstructionTriviallyDead(Instruction *I,
274                                       const TargetLibraryInfo *TLI) {
275   if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
276
277   // We don't want the landingpad instruction removed by anything this general.
278   if (isa<LandingPadInst>(I))
279     return false;
280
281   // We don't want debug info removed by anything this general, unless
282   // debug info is empty.
283   if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
284     if (DDI->getAddress())
285       return false;
286     return true;
287   }
288   if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
289     if (DVI->getValue())
290       return false;
291     return true;
292   }
293
294   if (!I->mayHaveSideEffects()) return true;
295
296   // Special case intrinsics that "may have side effects" but can be deleted
297   // when dead.
298   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
299     // Safe to delete llvm.stacksave if dead.
300     if (II->getIntrinsicID() == Intrinsic::stacksave)
301       return true;
302
303     // Lifetime intrinsics are dead when their right-hand is undef.
304     if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
305         II->getIntrinsicID() == Intrinsic::lifetime_end)
306       return isa<UndefValue>(II->getArgOperand(1));
307
308     // Assumptions are dead if their condition is trivially true.
309     if (II->getIntrinsicID() == Intrinsic::assume) {
310       if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
311         return !Cond->isZero();
312
313       return false;
314     }
315   }
316
317   if (isAllocLikeFn(I, TLI)) return true;
318
319   if (CallInst *CI = isFreeCall(I, TLI))
320     if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
321       return C->isNullValue() || isa<UndefValue>(C);
322
323   return false;
324 }
325
326 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
327 /// trivially dead instruction, delete it.  If that makes any of its operands
328 /// trivially dead, delete them too, recursively.  Return true if any
329 /// instructions were deleted.
330 bool
331 llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
332                                                  const TargetLibraryInfo *TLI) {
333   Instruction *I = dyn_cast<Instruction>(V);
334   if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
335     return false;
336
337   SmallVector<Instruction*, 16> DeadInsts;
338   DeadInsts.push_back(I);
339
340   do {
341     I = DeadInsts.pop_back_val();
342
343     // Null out all of the instruction's operands to see if any operand becomes
344     // dead as we go.
345     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
346       Value *OpV = I->getOperand(i);
347       I->setOperand(i, nullptr);
348
349       if (!OpV->use_empty()) continue;
350
351       // If the operand is an instruction that became dead as we nulled out the
352       // operand, and if it is 'trivially' dead, delete it in a future loop
353       // iteration.
354       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
355         if (isInstructionTriviallyDead(OpI, TLI))
356           DeadInsts.push_back(OpI);
357     }
358
359     I->eraseFromParent();
360   } while (!DeadInsts.empty());
361
362   return true;
363 }
364
365 /// areAllUsesEqual - Check whether the uses of a value are all the same.
366 /// This is similar to Instruction::hasOneUse() except this will also return
367 /// true when there are no uses or multiple uses that all refer to the same
368 /// value.
369 static bool areAllUsesEqual(Instruction *I) {
370   Value::user_iterator UI = I->user_begin();
371   Value::user_iterator UE = I->user_end();
372   if (UI == UE)
373     return true;
374
375   User *TheUse = *UI;
376   for (++UI; UI != UE; ++UI) {
377     if (*UI != TheUse)
378       return false;
379   }
380   return true;
381 }
382
383 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
384 /// dead PHI node, due to being a def-use chain of single-use nodes that
385 /// either forms a cycle or is terminated by a trivially dead instruction,
386 /// delete it.  If that makes any of its operands trivially dead, delete them
387 /// too, recursively.  Return true if a change was made.
388 bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
389                                         const TargetLibraryInfo *TLI) {
390   SmallPtrSet<Instruction*, 4> Visited;
391   for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
392        I = cast<Instruction>(*I->user_begin())) {
393     if (I->use_empty())
394       return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
395
396     // If we find an instruction more than once, we're on a cycle that
397     // won't prove fruitful.
398     if (!Visited.insert(I).second) {
399       // Break the cycle and delete the instruction and its operands.
400       I->replaceAllUsesWith(UndefValue::get(I->getType()));
401       (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
402       return true;
403     }
404   }
405   return false;
406 }
407
408 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
409 /// simplify any instructions in it and recursively delete dead instructions.
410 ///
411 /// This returns true if it changed the code, note that it can delete
412 /// instructions in other blocks as well in this block.
413 bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const DataLayout *TD,
414                                        const TargetLibraryInfo *TLI) {
415   bool MadeChange = false;
416
417 #ifndef NDEBUG
418   // In debug builds, ensure that the terminator of the block is never replaced
419   // or deleted by these simplifications. The idea of simplification is that it
420   // cannot introduce new instructions, and there is no way to replace the
421   // terminator of a block without introducing a new instruction.
422   AssertingVH<Instruction> TerminatorVH(--BB->end());
423 #endif
424
425   for (BasicBlock::iterator BI = BB->begin(), E = --BB->end(); BI != E; ) {
426     assert(!BI->isTerminator());
427     Instruction *Inst = BI++;
428
429     WeakVH BIHandle(BI);
430     if (recursivelySimplifyInstruction(Inst, TD, TLI)) {
431       MadeChange = true;
432       if (BIHandle != BI)
433         BI = BB->begin();
434       continue;
435     }
436
437     MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
438     if (BIHandle != BI)
439       BI = BB->begin();
440   }
441   return MadeChange;
442 }
443
444 //===----------------------------------------------------------------------===//
445 //  Control Flow Graph Restructuring.
446 //
447
448
449 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
450 /// method is called when we're about to delete Pred as a predecessor of BB.  If
451 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
452 ///
453 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
454 /// nodes that collapse into identity values.  For example, if we have:
455 ///   x = phi(1, 0, 0, 0)
456 ///   y = and x, z
457 ///
458 /// .. and delete the predecessor corresponding to the '1', this will attempt to
459 /// recursively fold the and to 0.
460 void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
461                                         DataLayout *TD) {
462   // This only adjusts blocks with PHI nodes.
463   if (!isa<PHINode>(BB->begin()))
464     return;
465
466   // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
467   // them down.  This will leave us with single entry phi nodes and other phis
468   // that can be removed.
469   BB->removePredecessor(Pred, true);
470
471   WeakVH PhiIt = &BB->front();
472   while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
473     PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
474     Value *OldPhiIt = PhiIt;
475
476     if (!recursivelySimplifyInstruction(PN, TD))
477       continue;
478
479     // If recursive simplification ended up deleting the next PHI node we would
480     // iterate to, then our iterator is invalid, restart scanning from the top
481     // of the block.
482     if (PhiIt != OldPhiIt) PhiIt = &BB->front();
483   }
484 }
485
486
487 /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
488 /// predecessor is known to have one successor (DestBB!).  Eliminate the edge
489 /// between them, moving the instructions in the predecessor into DestBB and
490 /// deleting the predecessor block.
491 ///
492 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
493   // If BB has single-entry PHI nodes, fold them.
494   while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
495     Value *NewVal = PN->getIncomingValue(0);
496     // Replace self referencing PHI with undef, it must be dead.
497     if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
498     PN->replaceAllUsesWith(NewVal);
499     PN->eraseFromParent();
500   }
501
502   BasicBlock *PredBB = DestBB->getSinglePredecessor();
503   assert(PredBB && "Block doesn't have a single predecessor!");
504
505   // Zap anything that took the address of DestBB.  Not doing this will give the
506   // address an invalid value.
507   if (DestBB->hasAddressTaken()) {
508     BlockAddress *BA = BlockAddress::get(DestBB);
509     Constant *Replacement =
510       ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
511     BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
512                                                      BA->getType()));
513     BA->destroyConstant();
514   }
515
516   // Anything that branched to PredBB now branches to DestBB.
517   PredBB->replaceAllUsesWith(DestBB);
518
519   // Splice all the instructions from PredBB to DestBB.
520   PredBB->getTerminator()->eraseFromParent();
521   DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
522
523   // If the PredBB is the entry block of the function, move DestBB up to
524   // become the entry block after we erase PredBB.
525   if (PredBB == &DestBB->getParent()->getEntryBlock())
526     DestBB->moveAfter(PredBB);
527
528   if (P) {
529     if (DominatorTreeWrapperPass *DTWP =
530             P->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
531       DominatorTree &DT = DTWP->getDomTree();
532       BasicBlock *PredBBIDom = DT.getNode(PredBB)->getIDom()->getBlock();
533       DT.changeImmediateDominator(DestBB, PredBBIDom);
534       DT.eraseNode(PredBB);
535     }
536   }
537   // Nuke BB.
538   PredBB->eraseFromParent();
539 }
540
541 /// CanMergeValues - Return true if we can choose one of these values to use
542 /// in place of the other. Note that we will always choose the non-undef
543 /// value to keep.
544 static bool CanMergeValues(Value *First, Value *Second) {
545   return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
546 }
547
548 /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
549 /// almost-empty BB ending in an unconditional branch to Succ, into Succ.
550 ///
551 /// Assumption: Succ is the single successor for BB.
552 ///
553 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
554   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
555
556   DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
557         << Succ->getName() << "\n");
558   // Shortcut, if there is only a single predecessor it must be BB and merging
559   // is always safe
560   if (Succ->getSinglePredecessor()) return true;
561
562   // Make a list of the predecessors of BB
563   SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
564
565   // Look at all the phi nodes in Succ, to see if they present a conflict when
566   // merging these blocks
567   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
568     PHINode *PN = cast<PHINode>(I);
569
570     // If the incoming value from BB is again a PHINode in
571     // BB which has the same incoming value for *PI as PN does, we can
572     // merge the phi nodes and then the blocks can still be merged
573     PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
574     if (BBPN && BBPN->getParent() == BB) {
575       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
576         BasicBlock *IBB = PN->getIncomingBlock(PI);
577         if (BBPreds.count(IBB) &&
578             !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
579                             PN->getIncomingValue(PI))) {
580           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
581                 << Succ->getName() << " is conflicting with "
582                 << BBPN->getName() << " with regard to common predecessor "
583                 << IBB->getName() << "\n");
584           return false;
585         }
586       }
587     } else {
588       Value* Val = PN->getIncomingValueForBlock(BB);
589       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
590         // See if the incoming value for the common predecessor is equal to the
591         // one for BB, in which case this phi node will not prevent the merging
592         // of the block.
593         BasicBlock *IBB = PN->getIncomingBlock(PI);
594         if (BBPreds.count(IBB) &&
595             !CanMergeValues(Val, PN->getIncomingValue(PI))) {
596           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
597                 << Succ->getName() << " is conflicting with regard to common "
598                 << "predecessor " << IBB->getName() << "\n");
599           return false;
600         }
601       }
602     }
603   }
604
605   return true;
606 }
607
608 typedef SmallVector<BasicBlock *, 16> PredBlockVector;
609 typedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
610
611 /// \brief Determines the value to use as the phi node input for a block.
612 ///
613 /// Select between \p OldVal any value that we know flows from \p BB
614 /// to a particular phi on the basis of which one (if either) is not
615 /// undef. Update IncomingValues based on the selected value.
616 ///
617 /// \param OldVal The value we are considering selecting.
618 /// \param BB The block that the value flows in from.
619 /// \param IncomingValues A map from block-to-value for other phi inputs
620 /// that we have examined.
621 ///
622 /// \returns the selected value.
623 static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
624                                           IncomingValueMap &IncomingValues) {
625   if (!isa<UndefValue>(OldVal)) {
626     assert((!IncomingValues.count(BB) ||
627             IncomingValues.find(BB)->second == OldVal) &&
628            "Expected OldVal to match incoming value from BB!");
629
630     IncomingValues.insert(std::make_pair(BB, OldVal));
631     return OldVal;
632   }
633
634   IncomingValueMap::const_iterator It = IncomingValues.find(BB);
635   if (It != IncomingValues.end()) return It->second;
636
637   return OldVal;
638 }
639
640 /// \brief Create a map from block to value for the operands of a
641 /// given phi.
642 ///
643 /// Create a map from block to value for each non-undef value flowing
644 /// into \p PN.
645 ///
646 /// \param PN The phi we are collecting the map for.
647 /// \param IncomingValues [out] The map from block to value for this phi.
648 static void gatherIncomingValuesToPhi(PHINode *PN,
649                                       IncomingValueMap &IncomingValues) {
650   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
651     BasicBlock *BB = PN->getIncomingBlock(i);
652     Value *V = PN->getIncomingValue(i);
653
654     if (!isa<UndefValue>(V))
655       IncomingValues.insert(std::make_pair(BB, V));
656   }
657 }
658
659 /// \brief Replace the incoming undef values to a phi with the values
660 /// from a block-to-value map.
661 ///
662 /// \param PN The phi we are replacing the undefs in.
663 /// \param IncomingValues A map from block to value.
664 static void replaceUndefValuesInPhi(PHINode *PN,
665                                     const IncomingValueMap &IncomingValues) {
666   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
667     Value *V = PN->getIncomingValue(i);
668
669     if (!isa<UndefValue>(V)) continue;
670
671     BasicBlock *BB = PN->getIncomingBlock(i);
672     IncomingValueMap::const_iterator It = IncomingValues.find(BB);
673     if (It == IncomingValues.end()) continue;
674
675     PN->setIncomingValue(i, It->second);
676   }
677 }
678
679 /// \brief Replace a value flowing from a block to a phi with
680 /// potentially multiple instances of that value flowing from the
681 /// block's predecessors to the phi.
682 ///
683 /// \param BB The block with the value flowing into the phi.
684 /// \param BBPreds The predecessors of BB.
685 /// \param PN The phi that we are updating.
686 static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
687                                                 const PredBlockVector &BBPreds,
688                                                 PHINode *PN) {
689   Value *OldVal = PN->removeIncomingValue(BB, false);
690   assert(OldVal && "No entry in PHI for Pred BB!");
691
692   IncomingValueMap IncomingValues;
693
694   // We are merging two blocks - BB, and the block containing PN - and
695   // as a result we need to redirect edges from the predecessors of BB
696   // to go to the block containing PN, and update PN
697   // accordingly. Since we allow merging blocks in the case where the
698   // predecessor and successor blocks both share some predecessors,
699   // and where some of those common predecessors might have undef
700   // values flowing into PN, we want to rewrite those values to be
701   // consistent with the non-undef values.
702
703   gatherIncomingValuesToPhi(PN, IncomingValues);
704
705   // If this incoming value is one of the PHI nodes in BB, the new entries
706   // in the PHI node are the entries from the old PHI.
707   if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
708     PHINode *OldValPN = cast<PHINode>(OldVal);
709     for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
710       // Note that, since we are merging phi nodes and BB and Succ might
711       // have common predecessors, we could end up with a phi node with
712       // identical incoming branches. This will be cleaned up later (and
713       // will trigger asserts if we try to clean it up now, without also
714       // simplifying the corresponding conditional branch).
715       BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
716       Value *PredVal = OldValPN->getIncomingValue(i);
717       Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
718                                                     IncomingValues);
719
720       // And add a new incoming value for this predecessor for the
721       // newly retargeted branch.
722       PN->addIncoming(Selected, PredBB);
723     }
724   } else {
725     for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
726       // Update existing incoming values in PN for this
727       // predecessor of BB.
728       BasicBlock *PredBB = BBPreds[i];
729       Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
730                                                     IncomingValues);
731
732       // And add a new incoming value for this predecessor for the
733       // newly retargeted branch.
734       PN->addIncoming(Selected, PredBB);
735     }
736   }
737
738   replaceUndefValuesInPhi(PN, IncomingValues);
739 }
740
741 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
742 /// unconditional branch, and contains no instructions other than PHI nodes,
743 /// potential side-effect free intrinsics and the branch.  If possible,
744 /// eliminate BB by rewriting all the predecessors to branch to the successor
745 /// block and return true.  If we can't transform, return false.
746 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
747   assert(BB != &BB->getParent()->getEntryBlock() &&
748          "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
749
750   // We can't eliminate infinite loops.
751   BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
752   if (BB == Succ) return false;
753
754   // Check to see if merging these blocks would cause conflicts for any of the
755   // phi nodes in BB or Succ. If not, we can safely merge.
756   if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
757
758   // Check for cases where Succ has multiple predecessors and a PHI node in BB
759   // has uses which will not disappear when the PHI nodes are merged.  It is
760   // possible to handle such cases, but difficult: it requires checking whether
761   // BB dominates Succ, which is non-trivial to calculate in the case where
762   // Succ has multiple predecessors.  Also, it requires checking whether
763   // constructing the necessary self-referential PHI node doesn't introduce any
764   // conflicts; this isn't too difficult, but the previous code for doing this
765   // was incorrect.
766   //
767   // Note that if this check finds a live use, BB dominates Succ, so BB is
768   // something like a loop pre-header (or rarely, a part of an irreducible CFG);
769   // folding the branch isn't profitable in that case anyway.
770   if (!Succ->getSinglePredecessor()) {
771     BasicBlock::iterator BBI = BB->begin();
772     while (isa<PHINode>(*BBI)) {
773       for (Use &U : BBI->uses()) {
774         if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
775           if (PN->getIncomingBlock(U) != BB)
776             return false;
777         } else {
778           return false;
779         }
780       }
781       ++BBI;
782     }
783   }
784
785   DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
786
787   if (isa<PHINode>(Succ->begin())) {
788     // If there is more than one pred of succ, and there are PHI nodes in
789     // the successor, then we need to add incoming edges for the PHI nodes
790     //
791     const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
792
793     // Loop over all of the PHI nodes in the successor of BB.
794     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
795       PHINode *PN = cast<PHINode>(I);
796
797       redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
798     }
799   }
800
801   if (Succ->getSinglePredecessor()) {
802     // BB is the only predecessor of Succ, so Succ will end up with exactly
803     // the same predecessors BB had.
804
805     // Copy over any phi, debug or lifetime instruction.
806     BB->getTerminator()->eraseFromParent();
807     Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
808   } else {
809     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
810       // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
811       assert(PN->use_empty() && "There shouldn't be any uses here!");
812       PN->eraseFromParent();
813     }
814   }
815
816   // Everything that jumped to BB now goes to Succ.
817   BB->replaceAllUsesWith(Succ);
818   if (!Succ->hasName()) Succ->takeName(BB);
819   BB->eraseFromParent();              // Delete the old basic block.
820   return true;
821 }
822
823 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
824 /// nodes in this block. This doesn't try to be clever about PHI nodes
825 /// which differ only in the order of the incoming values, but instcombine
826 /// orders them so it usually won't matter.
827 ///
828 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
829   bool Changed = false;
830
831   // This implementation doesn't currently consider undef operands
832   // specially. Theoretically, two phis which are identical except for
833   // one having an undef where the other doesn't could be collapsed.
834
835   // Map from PHI hash values to PHI nodes. If multiple PHIs have
836   // the same hash value, the element is the first PHI in the
837   // linked list in CollisionMap.
838   DenseMap<uintptr_t, PHINode *> HashMap;
839
840   // Maintain linked lists of PHI nodes with common hash values.
841   DenseMap<PHINode *, PHINode *> CollisionMap;
842
843   // Examine each PHI.
844   for (BasicBlock::iterator I = BB->begin();
845        PHINode *PN = dyn_cast<PHINode>(I++); ) {
846     // Compute a hash value on the operands. Instcombine will likely have sorted
847     // them, which helps expose duplicates, but we have to check all the
848     // operands to be safe in case instcombine hasn't run.
849     uintptr_t Hash = 0;
850     // This hash algorithm is quite weak as hash functions go, but it seems
851     // to do a good enough job for this particular purpose, and is very quick.
852     for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
853       Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
854       Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
855     }
856     for (PHINode::block_iterator I = PN->block_begin(), E = PN->block_end();
857          I != E; ++I) {
858       Hash ^= reinterpret_cast<uintptr_t>(static_cast<BasicBlock *>(*I));
859       Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
860     }
861     // Avoid colliding with the DenseMap sentinels ~0 and ~0-1.
862     Hash >>= 1;
863     // If we've never seen this hash value before, it's a unique PHI.
864     std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
865       HashMap.insert(std::make_pair(Hash, PN));
866     if (Pair.second) continue;
867     // Otherwise it's either a duplicate or a hash collision.
868     for (PHINode *OtherPN = Pair.first->second; ; ) {
869       if (OtherPN->isIdenticalTo(PN)) {
870         // A duplicate. Replace this PHI with its duplicate.
871         PN->replaceAllUsesWith(OtherPN);
872         PN->eraseFromParent();
873         Changed = true;
874         break;
875       }
876       // A non-duplicate hash collision.
877       DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
878       if (I == CollisionMap.end()) {
879         // Set this PHI to be the head of the linked list of colliding PHIs.
880         PHINode *Old = Pair.first->second;
881         Pair.first->second = PN;
882         CollisionMap[PN] = Old;
883         break;
884       }
885       // Proceed to the next PHI in the list.
886       OtherPN = I->second;
887     }
888   }
889
890   return Changed;
891 }
892
893 /// enforceKnownAlignment - If the specified pointer points to an object that
894 /// we control, modify the object's alignment to PrefAlign. This isn't
895 /// often possible though. If alignment is important, a more reliable approach
896 /// is to simply align all global variables and allocation instructions to
897 /// their preferred alignment from the beginning.
898 ///
899 static unsigned enforceKnownAlignment(Value *V, unsigned Align,
900                                       unsigned PrefAlign, const DataLayout *TD) {
901   V = V->stripPointerCasts();
902
903   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
904     // If the preferred alignment is greater than the natural stack alignment
905     // then don't round up. This avoids dynamic stack realignment.
906     if (TD && TD->exceedsNaturalStackAlignment(PrefAlign))
907       return Align;
908     // If there is a requested alignment and if this is an alloca, round up.
909     if (AI->getAlignment() >= PrefAlign)
910       return AI->getAlignment();
911     AI->setAlignment(PrefAlign);
912     return PrefAlign;
913   }
914
915   if (auto *GO = dyn_cast<GlobalObject>(V)) {
916     // If there is a large requested alignment and we can, bump up the alignment
917     // of the global.
918     if (GO->isDeclaration())
919       return Align;
920     // If the memory we set aside for the global may not be the memory used by
921     // the final program then it is impossible for us to reliably enforce the
922     // preferred alignment.
923     if (GO->isWeakForLinker())
924       return Align;
925
926     if (GO->getAlignment() >= PrefAlign)
927       return GO->getAlignment();
928     // We can only increase the alignment of the global if it has no alignment
929     // specified or if it is not assigned a section.  If it is assigned a
930     // section, the global could be densely packed with other objects in the
931     // section, increasing the alignment could cause padding issues.
932     if (!GO->hasSection() || GO->getAlignment() == 0)
933       GO->setAlignment(PrefAlign);
934     return GO->getAlignment();
935   }
936
937   return Align;
938 }
939
940 /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
941 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
942 /// and it is more than the alignment of the ultimate object, see if we can
943 /// increase the alignment of the ultimate object, making this check succeed.
944 unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
945                                           const DataLayout *DL,
946                                           AssumptionTracker *AT,
947                                           const Instruction *CxtI,
948                                           const DominatorTree *DT) {
949   assert(V->getType()->isPointerTy() &&
950          "getOrEnforceKnownAlignment expects a pointer!");
951   unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(V->getType()) : 64;
952
953   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
954   computeKnownBits(V, KnownZero, KnownOne, DL, 0, AT, CxtI, DT);
955   unsigned TrailZ = KnownZero.countTrailingOnes();
956
957   // Avoid trouble with ridiculously large TrailZ values, such as
958   // those computed from a null pointer.
959   TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
960
961   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
962
963   // LLVM doesn't support alignments larger than this currently.
964   Align = std::min(Align, +Value::MaximumAlignment);
965
966   if (PrefAlign > Align)
967     Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
968
969   // We don't need to make any adjustment.
970   return Align;
971 }
972
973 ///===---------------------------------------------------------------------===//
974 ///  Dbg Intrinsic utilities
975 ///
976
977 /// See if there is a dbg.value intrinsic for DIVar before I.
978 static bool LdStHasDebugValue(DIVariable &DIVar, Instruction *I) {
979   // Since we can't guarantee that the original dbg.declare instrinsic
980   // is removed by LowerDbgDeclare(), we need to make sure that we are
981   // not inserting the same dbg.value intrinsic over and over.
982   llvm::BasicBlock::InstListType::iterator PrevI(I);
983   if (PrevI != I->getParent()->getInstList().begin()) {
984     --PrevI;
985     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
986       if (DVI->getValue() == I->getOperand(0) &&
987           DVI->getOffset() == 0 &&
988           DVI->getVariable() == DIVar)
989         return true;
990   }
991   return false;
992 }
993
994 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
995 /// that has an associated llvm.dbg.decl intrinsic.
996 bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
997                                            StoreInst *SI, DIBuilder &Builder) {
998   DIVariable DIVar(DDI->getVariable());
999   DIExpression DIExpr(DDI->getExpression());
1000   assert((!DIVar || DIVar.isVariable()) &&
1001          "Variable in DbgDeclareInst should be either null or a DIVariable.");
1002   if (!DIVar)
1003     return false;
1004
1005   if (LdStHasDebugValue(DIVar, SI))
1006     return true;
1007
1008   Instruction *DbgVal = nullptr;
1009   // If an argument is zero extended then use argument directly. The ZExt
1010   // may be zapped by an optimization pass in future.
1011   Argument *ExtendedArg = nullptr;
1012   if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1013     ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
1014   if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1015     ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
1016   if (ExtendedArg)
1017     DbgVal = Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, DIExpr, SI);
1018   else
1019     DbgVal = Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar,
1020                                              DIExpr, SI);
1021   DbgVal->setDebugLoc(DDI->getDebugLoc());
1022   return true;
1023 }
1024
1025 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
1026 /// that has an associated llvm.dbg.decl intrinsic.
1027 bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
1028                                            LoadInst *LI, DIBuilder &Builder) {
1029   DIVariable DIVar(DDI->getVariable());
1030   DIExpression DIExpr(DDI->getExpression());
1031   assert((!DIVar || DIVar.isVariable()) &&
1032          "Variable in DbgDeclareInst should be either null or a DIVariable.");
1033   if (!DIVar)
1034     return false;
1035
1036   if (LdStHasDebugValue(DIVar, LI))
1037     return true;
1038
1039   Instruction *DbgVal =
1040       Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0, DIVar, DIExpr, LI);
1041   DbgVal->setDebugLoc(DDI->getDebugLoc());
1042   return true;
1043 }
1044
1045 /// Determine whether this alloca is either a VLA or an array.
1046 static bool isArray(AllocaInst *AI) {
1047   return AI->isArrayAllocation() ||
1048     AI->getType()->getElementType()->isArrayTy();
1049 }
1050
1051 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1052 /// of llvm.dbg.value intrinsics.
1053 bool llvm::LowerDbgDeclare(Function &F) {
1054   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
1055   SmallVector<DbgDeclareInst *, 4> Dbgs;
1056   for (auto &FI : F)
1057     for (BasicBlock::iterator BI : FI)
1058       if (auto DDI = dyn_cast<DbgDeclareInst>(BI))
1059         Dbgs.push_back(DDI);
1060
1061   if (Dbgs.empty())
1062     return false;
1063
1064   for (auto &I : Dbgs) {
1065     DbgDeclareInst *DDI = I;
1066     AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1067     // If this is an alloca for a scalar variable, insert a dbg.value
1068     // at each load and store to the alloca and erase the dbg.declare.
1069     // The dbg.values allow tracking a variable even if it is not
1070     // stored on the stack, while the dbg.declare can only describe
1071     // the stack slot (and at a lexical-scope granularity). Later
1072     // passes will attempt to elide the stack slot.
1073     if (AI && !isArray(AI)) {
1074       for (User *U : AI->users())
1075         if (StoreInst *SI = dyn_cast<StoreInst>(U))
1076           ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1077         else if (LoadInst *LI = dyn_cast<LoadInst>(U))
1078           ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1079         else if (CallInst *CI = dyn_cast<CallInst>(U)) {
1080           // This is a call by-value or some other instruction that
1081           // takes a pointer to the variable. Insert a *value*
1082           // intrinsic that describes the alloca.
1083           auto DbgVal = DIB.insertDbgValueIntrinsic(
1084               AI, 0, DIVariable(DDI->getVariable()),
1085               DIExpression(DDI->getExpression()), CI);
1086           DbgVal->setDebugLoc(DDI->getDebugLoc());
1087         }
1088       DDI->eraseFromParent();
1089     }
1090   }
1091   return true;
1092 }
1093
1094 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
1095 /// alloca 'V', if any.
1096 DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
1097   if (auto *L = LocalAsMetadata::getIfExists(V))
1098     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1099       for (User *U : MDV->users())
1100         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1101           return DDI;
1102
1103   return nullptr;
1104 }
1105
1106 bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1107                                       DIBuilder &Builder) {
1108   DbgDeclareInst *DDI = FindAllocaDbgDeclare(AI);
1109   if (!DDI)
1110     return false;
1111   DIVariable DIVar(DDI->getVariable());
1112   DIExpression DIExpr(DDI->getExpression());
1113   assert((!DIVar || DIVar.isVariable()) &&
1114          "Variable in DbgDeclareInst should be either null or a DIVariable.");
1115   if (!DIVar)
1116     return false;
1117
1118   // Create a copy of the original DIDescriptor for user variable, prepending
1119   // "deref" operation to a list of address elements, as new llvm.dbg.declare
1120   // will take a value storing address of the memory for variable, not
1121   // alloca itself.
1122   SmallVector<int64_t, 4> NewDIExpr;
1123   if (DIExpr) {
1124     for (unsigned i = 0, n = DIExpr.getNumElements(); i < n; ++i) {
1125       NewDIExpr.push_back(DIExpr.getElement(i));
1126     }
1127   }
1128   NewDIExpr.insert(NewDIExpr.begin(), dwarf::DW_OP_deref);
1129
1130   // Insert llvm.dbg.declare in the same basic block as the original alloca,
1131   // and remove old llvm.dbg.declare.
1132   BasicBlock *BB = AI->getParent();
1133   Builder.insertDeclare(NewAllocaAddress, DIVar,
1134                         Builder.createExpression(NewDIExpr), BB);
1135   DDI->eraseFromParent();
1136   return true;
1137 }
1138
1139 /// changeToUnreachable - Insert an unreachable instruction before the specified
1140 /// instruction, making it and the rest of the code in the block dead.
1141 static void changeToUnreachable(Instruction *I, bool UseLLVMTrap) {
1142   BasicBlock *BB = I->getParent();
1143   // Loop over all of the successors, removing BB's entry from any PHI
1144   // nodes.
1145   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
1146     (*SI)->removePredecessor(BB);
1147
1148   // Insert a call to llvm.trap right before this.  This turns the undefined
1149   // behavior into a hard fail instead of falling through into random code.
1150   if (UseLLVMTrap) {
1151     Function *TrapFn =
1152       Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
1153     CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
1154     CallTrap->setDebugLoc(I->getDebugLoc());
1155   }
1156   new UnreachableInst(I->getContext(), I);
1157
1158   // All instructions after this are dead.
1159   BasicBlock::iterator BBI = I, BBE = BB->end();
1160   while (BBI != BBE) {
1161     if (!BBI->use_empty())
1162       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
1163     BB->getInstList().erase(BBI++);
1164   }
1165 }
1166
1167 /// changeToCall - Convert the specified invoke into a normal call.
1168 static void changeToCall(InvokeInst *II) {
1169   SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
1170   CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, "", II);
1171   NewCall->takeName(II);
1172   NewCall->setCallingConv(II->getCallingConv());
1173   NewCall->setAttributes(II->getAttributes());
1174   NewCall->setDebugLoc(II->getDebugLoc());
1175   II->replaceAllUsesWith(NewCall);
1176
1177   // Follow the call by a branch to the normal destination.
1178   BranchInst::Create(II->getNormalDest(), II);
1179
1180   // Update PHI nodes in the unwind destination
1181   II->getUnwindDest()->removePredecessor(II->getParent());
1182   II->eraseFromParent();
1183 }
1184
1185 static bool markAliveBlocks(BasicBlock *BB,
1186                             SmallPtrSetImpl<BasicBlock*> &Reachable) {
1187
1188   SmallVector<BasicBlock*, 128> Worklist;
1189   Worklist.push_back(BB);
1190   Reachable.insert(BB);
1191   bool Changed = false;
1192   do {
1193     BB = Worklist.pop_back_val();
1194
1195     // Do a quick scan of the basic block, turning any obviously unreachable
1196     // instructions into LLVM unreachable insts.  The instruction combining pass
1197     // canonicalizes unreachable insts into stores to null or undef.
1198     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
1199       // Assumptions that are known to be false are equivalent to unreachable.
1200       // Also, if the condition is undefined, then we make the choice most
1201       // beneficial to the optimizer, and choose that to also be unreachable.
1202       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI))
1203         if (II->getIntrinsicID() == Intrinsic::assume) {
1204           bool MakeUnreachable = false;
1205           if (isa<UndefValue>(II->getArgOperand(0)))
1206             MakeUnreachable = true;
1207           else if (ConstantInt *Cond =
1208                    dyn_cast<ConstantInt>(II->getArgOperand(0)))
1209             MakeUnreachable = Cond->isZero();
1210
1211           if (MakeUnreachable) {
1212             // Don't insert a call to llvm.trap right before the unreachable.
1213             changeToUnreachable(BBI, false);
1214             Changed = true;
1215             break;
1216           }
1217         }
1218
1219       if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
1220         if (CI->doesNotReturn()) {
1221           // If we found a call to a no-return function, insert an unreachable
1222           // instruction after it.  Make sure there isn't *already* one there
1223           // though.
1224           ++BBI;
1225           if (!isa<UnreachableInst>(BBI)) {
1226             // Don't insert a call to llvm.trap right before the unreachable.
1227             changeToUnreachable(BBI, false);
1228             Changed = true;
1229           }
1230           break;
1231         }
1232       }
1233
1234       // Store to undef and store to null are undefined and used to signal that
1235       // they should be changed to unreachable by passes that can't modify the
1236       // CFG.
1237       if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
1238         // Don't touch volatile stores.
1239         if (SI->isVolatile()) continue;
1240
1241         Value *Ptr = SI->getOperand(1);
1242
1243         if (isa<UndefValue>(Ptr) ||
1244             (isa<ConstantPointerNull>(Ptr) &&
1245              SI->getPointerAddressSpace() == 0)) {
1246           changeToUnreachable(SI, true);
1247           Changed = true;
1248           break;
1249         }
1250       }
1251     }
1252
1253     // Turn invokes that call 'nounwind' functions into ordinary calls.
1254     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
1255       Value *Callee = II->getCalledValue();
1256       if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
1257         changeToUnreachable(II, true);
1258         Changed = true;
1259       } else if (II->doesNotThrow()) {
1260         if (II->use_empty() && II->onlyReadsMemory()) {
1261           // jump to the normal destination branch.
1262           BranchInst::Create(II->getNormalDest(), II);
1263           II->getUnwindDest()->removePredecessor(II->getParent());
1264           II->eraseFromParent();
1265         } else
1266           changeToCall(II);
1267         Changed = true;
1268       }
1269     }
1270
1271     Changed |= ConstantFoldTerminator(BB, true);
1272     for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
1273       if (Reachable.insert(*SI).second)
1274         Worklist.push_back(*SI);
1275   } while (!Worklist.empty());
1276   return Changed;
1277 }
1278
1279 /// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
1280 /// if they are in a dead cycle.  Return true if a change was made, false
1281 /// otherwise.
1282 bool llvm::removeUnreachableBlocks(Function &F) {
1283   SmallPtrSet<BasicBlock*, 128> Reachable;
1284   bool Changed = markAliveBlocks(F.begin(), Reachable);
1285
1286   // If there are unreachable blocks in the CFG...
1287   if (Reachable.size() == F.size())
1288     return Changed;
1289
1290   assert(Reachable.size() < F.size());
1291   NumRemoved += F.size()-Reachable.size();
1292
1293   // Loop over all of the basic blocks that are not reachable, dropping all of
1294   // their internal references...
1295   for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
1296     if (Reachable.count(BB))
1297       continue;
1298
1299     for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
1300       if (Reachable.count(*SI))
1301         (*SI)->removePredecessor(BB);
1302     BB->dropAllReferences();
1303   }
1304
1305   for (Function::iterator I = ++F.begin(); I != F.end();)
1306     if (!Reachable.count(I))
1307       I = F.getBasicBlockList().erase(I);
1308     else
1309       ++I;
1310
1311   return true;
1312 }
1313
1314 void llvm::combineMetadata(Instruction *K, const Instruction *J, ArrayRef<unsigned> KnownIDs) {
1315   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
1316   K->dropUnknownMetadata(KnownIDs);
1317   K->getAllMetadataOtherThanDebugLoc(Metadata);
1318   for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
1319     unsigned Kind = Metadata[i].first;
1320     MDNode *JMD = J->getMetadata(Kind);
1321     MDNode *KMD = Metadata[i].second;
1322
1323     switch (Kind) {
1324       default:
1325         K->setMetadata(Kind, nullptr); // Remove unknown metadata
1326         break;
1327       case LLVMContext::MD_dbg:
1328         llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
1329       case LLVMContext::MD_tbaa:
1330         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
1331         break;
1332       case LLVMContext::MD_alias_scope:
1333       case LLVMContext::MD_noalias:
1334         K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
1335         break;
1336       case LLVMContext::MD_range:
1337         K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
1338         break;
1339       case LLVMContext::MD_fpmath:
1340         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
1341         break;
1342       case LLVMContext::MD_invariant_load:
1343         // Only set the !invariant.load if it is present in both instructions.
1344         K->setMetadata(Kind, JMD);
1345         break;
1346       case LLVMContext::MD_nonnull:
1347         // Only set the !nonnull if it is present in both instructions.
1348         K->setMetadata(Kind, JMD);
1349         break;
1350     }
1351   }
1352 }