xref: /llvm-project/llvm/lib/Transforms/Utils/Local.cpp (revision 9e66c4ec127ef6e73f1bafe06fe3fba45d59feee)
1 //===- Local.cpp - Functions to perform local transformations -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This family of functions perform various local transformations to the
10 // program.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Utils/Local.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DenseMapInfo.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/Hashing.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/TinyPtrVector.h"
28 #include "llvm/Analysis/ConstantFolding.h"
29 #include "llvm/Analysis/DomTreeUpdater.h"
30 #include "llvm/Analysis/EHPersonalities.h"
31 #include "llvm/Analysis/InstructionSimplify.h"
32 #include "llvm/Analysis/LazyValueInfo.h"
33 #include "llvm/Analysis/MemoryBuiltins.h"
34 #include "llvm/Analysis/MemorySSAUpdater.h"
35 #include "llvm/Analysis/TargetLibraryInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/Analysis/VectorUtils.h"
38 #include "llvm/BinaryFormat/Dwarf.h"
39 #include "llvm/IR/Argument.h"
40 #include "llvm/IR/Attributes.h"
41 #include "llvm/IR/BasicBlock.h"
42 #include "llvm/IR/CFG.h"
43 #include "llvm/IR/CallSite.h"
44 #include "llvm/IR/Constant.h"
45 #include "llvm/IR/ConstantRange.h"
46 #include "llvm/IR/Constants.h"
47 #include "llvm/IR/DIBuilder.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugInfoMetadata.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Dominators.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GetElementPtrTypeIterator.h"
55 #include "llvm/IR/GlobalObject.h"
56 #include "llvm/IR/IRBuilder.h"
57 #include "llvm/IR/InstrTypes.h"
58 #include "llvm/IR/Instruction.h"
59 #include "llvm/IR/Instructions.h"
60 #include "llvm/IR/IntrinsicInst.h"
61 #include "llvm/IR/Intrinsics.h"
62 #include "llvm/IR/LLVMContext.h"
63 #include "llvm/IR/MDBuilder.h"
64 #include "llvm/IR/Metadata.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #include "llvm/Support/Casting.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/KnownBits.h"
77 #include "llvm/Support/raw_ostream.h"
78 #include "llvm/Transforms/Utils/ValueMapper.h"
79 #include <algorithm>
80 #include <cassert>
81 #include <climits>
82 #include <cstdint>
83 #include <iterator>
84 #include <map>
85 #include <utility>
86 
87 using namespace llvm;
88 using namespace llvm::PatternMatch;
89 
90 #define DEBUG_TYPE "local"
91 
92 STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
93 
94 // Max recursion depth for collectBitParts used when detecting bswap and
95 // bitreverse idioms
96 static const unsigned BitPartRecursionMaxDepth = 64;
97 
98 //===----------------------------------------------------------------------===//
99 //  Local constant propagation.
100 //
101 
102 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
103 /// constant value, convert it into an unconditional branch to the constant
104 /// destination.  This is a nontrivial operation because the successors of this
105 /// basic block must have their PHI nodes updated.
106 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
107 /// conditions and indirectbr addresses this might make dead if
108 /// DeleteDeadConditions is true.
109 bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
110                                   const TargetLibraryInfo *TLI,
111                                   DomTreeUpdater *DTU) {
112   Instruction *T = BB->getTerminator();
113   IRBuilder<> Builder(T);
114 
115   // Branch - See if we are conditional jumping on constant
116   if (auto *BI = dyn_cast<BranchInst>(T)) {
117     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
118     BasicBlock *Dest1 = BI->getSuccessor(0);
119     BasicBlock *Dest2 = BI->getSuccessor(1);
120 
121     if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
122       // Are we branching on constant?
123       // YES.  Change to unconditional branch...
124       BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
125       BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
126 
127       // Let the basic block know that we are letting go of it.  Based on this,
128       // it will adjust it's PHI nodes.
129       OldDest->removePredecessor(BB);
130 
131       // Replace the conditional branch with an unconditional one.
132       Builder.CreateBr(Destination);
133       BI->eraseFromParent();
134       if (DTU)
135         DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, OldDest}});
136       return true;
137     }
138 
139     if (Dest2 == Dest1) {       // Conditional branch to same location?
140       // This branch matches something like this:
141       //     br bool %cond, label %Dest, label %Dest
142       // and changes it into:  br label %Dest
143 
144       // Let the basic block know that we are letting go of one copy of it.
145       assert(BI->getParent() && "Terminator not inserted in block!");
146       Dest1->removePredecessor(BI->getParent());
147 
148       // Replace the conditional branch with an unconditional one.
149       Builder.CreateBr(Dest1);
150       Value *Cond = BI->getCondition();
151       BI->eraseFromParent();
152       if (DeleteDeadConditions)
153         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
154       return true;
155     }
156     return false;
157   }
158 
159   if (auto *SI = dyn_cast<SwitchInst>(T)) {
160     // If we are switching on a constant, we can convert the switch to an
161     // unconditional branch.
162     auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
163     BasicBlock *DefaultDest = SI->getDefaultDest();
164     BasicBlock *TheOnlyDest = DefaultDest;
165 
166     // If the default is unreachable, ignore it when searching for TheOnlyDest.
167     if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
168         SI->getNumCases() > 0) {
169       TheOnlyDest = SI->case_begin()->getCaseSuccessor();
170     }
171 
172     // Figure out which case it goes to.
173     for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
174       // Found case matching a constant operand?
175       if (i->getCaseValue() == CI) {
176         TheOnlyDest = i->getCaseSuccessor();
177         break;
178       }
179 
180       // Check to see if this branch is going to the same place as the default
181       // dest.  If so, eliminate it as an explicit compare.
182       if (i->getCaseSuccessor() == DefaultDest) {
183         MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
184         unsigned NCases = SI->getNumCases();
185         // Fold the case metadata into the default if there will be any branches
186         // left, unless the metadata doesn't match the switch.
187         if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
188           // Collect branch weights into a vector.
189           SmallVector<uint32_t, 8> Weights;
190           for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
191                ++MD_i) {
192             auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
193             Weights.push_back(CI->getValue().getZExtValue());
194           }
195           // Merge weight of this case to the default weight.
196           unsigned idx = i->getCaseIndex();
197           Weights[0] += Weights[idx+1];
198           // Remove weight for this case.
199           std::swap(Weights[idx+1], Weights.back());
200           Weights.pop_back();
201           SI->setMetadata(LLVMContext::MD_prof,
202                           MDBuilder(BB->getContext()).
203                           createBranchWeights(Weights));
204         }
205         // Remove this entry.
206         BasicBlock *ParentBB = SI->getParent();
207         DefaultDest->removePredecessor(ParentBB);
208         i = SI->removeCase(i);
209         e = SI->case_end();
210         if (DTU)
211           DTU->applyUpdatesPermissive(
212               {{DominatorTree::Delete, ParentBB, DefaultDest}});
213         continue;
214       }
215 
216       // Otherwise, check to see if the switch only branches to one destination.
217       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
218       // destinations.
219       if (i->getCaseSuccessor() != TheOnlyDest)
220         TheOnlyDest = nullptr;
221 
222       // Increment this iterator as we haven't removed the case.
223       ++i;
224     }
225 
226     if (CI && !TheOnlyDest) {
227       // Branching on a constant, but not any of the cases, go to the default
228       // successor.
229       TheOnlyDest = SI->getDefaultDest();
230     }
231 
232     // If we found a single destination that we can fold the switch into, do so
233     // now.
234     if (TheOnlyDest) {
235       // Insert the new branch.
236       Builder.CreateBr(TheOnlyDest);
237       BasicBlock *BB = SI->getParent();
238       std::vector <DominatorTree::UpdateType> Updates;
239       if (DTU)
240         Updates.reserve(SI->getNumSuccessors() - 1);
241 
242       // Remove entries from PHI nodes which we no longer branch to...
243       for (BasicBlock *Succ : successors(SI)) {
244         // Found case matching a constant operand?
245         if (Succ == TheOnlyDest) {
246           TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
247         } else {
248           Succ->removePredecessor(BB);
249           if (DTU)
250             Updates.push_back({DominatorTree::Delete, BB, Succ});
251         }
252       }
253 
254       // Delete the old switch.
255       Value *Cond = SI->getCondition();
256       SI->eraseFromParent();
257       if (DeleteDeadConditions)
258         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
259       if (DTU)
260         DTU->applyUpdatesPermissive(Updates);
261       return true;
262     }
263 
264     if (SI->getNumCases() == 1) {
265       // Otherwise, we can fold this switch into a conditional branch
266       // instruction if it has only one non-default destination.
267       auto FirstCase = *SI->case_begin();
268       Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
269           FirstCase.getCaseValue(), "cond");
270 
271       // Insert the new branch.
272       BranchInst *NewBr = Builder.CreateCondBr(Cond,
273                                                FirstCase.getCaseSuccessor(),
274                                                SI->getDefaultDest());
275       MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
276       if (MD && MD->getNumOperands() == 3) {
277         ConstantInt *SICase =
278             mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
279         ConstantInt *SIDef =
280             mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
281         assert(SICase && SIDef);
282         // The TrueWeight should be the weight for the single case of SI.
283         NewBr->setMetadata(LLVMContext::MD_prof,
284                         MDBuilder(BB->getContext()).
285                         createBranchWeights(SICase->getValue().getZExtValue(),
286                                             SIDef->getValue().getZExtValue()));
287       }
288 
289       // Update make.implicit metadata to the newly-created conditional branch.
290       MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
291       if (MakeImplicitMD)
292         NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
293 
294       // Delete the old switch.
295       SI->eraseFromParent();
296       return true;
297     }
298     return false;
299   }
300 
301   if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {
302     // indirectbr blockaddress(@F, @BB) -> br label @BB
303     if (auto *BA =
304           dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
305       BasicBlock *TheOnlyDest = BA->getBasicBlock();
306       std::vector <DominatorTree::UpdateType> Updates;
307       if (DTU)
308         Updates.reserve(IBI->getNumDestinations() - 1);
309 
310       // Insert the new branch.
311       Builder.CreateBr(TheOnlyDest);
312 
313       for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
314         if (IBI->getDestination(i) == TheOnlyDest) {
315           TheOnlyDest = nullptr;
316         } else {
317           BasicBlock *ParentBB = IBI->getParent();
318           BasicBlock *DestBB = IBI->getDestination(i);
319           DestBB->removePredecessor(ParentBB);
320           if (DTU)
321             Updates.push_back({DominatorTree::Delete, ParentBB, DestBB});
322         }
323       }
324       Value *Address = IBI->getAddress();
325       IBI->eraseFromParent();
326       if (DeleteDeadConditions)
327         // Delete pointer cast instructions.
328         RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
329 
330       // Also zap the blockaddress constant if there are no users remaining,
331       // otherwise the destination is still marked as having its address taken.
332       if (BA->use_empty())
333         BA->destroyConstant();
334 
335       // If we didn't find our destination in the IBI successor list, then we
336       // have undefined behavior.  Replace the unconditional branch with an
337       // 'unreachable' instruction.
338       if (TheOnlyDest) {
339         BB->getTerminator()->eraseFromParent();
340         new UnreachableInst(BB->getContext(), BB);
341       }
342 
343       if (DTU)
344         DTU->applyUpdatesPermissive(Updates);
345       return true;
346     }
347   }
348 
349   return false;
350 }
351 
352 //===----------------------------------------------------------------------===//
353 //  Local dead code elimination.
354 //
355 
356 /// isInstructionTriviallyDead - Return true if the result produced by the
357 /// instruction is not used, and the instruction has no side effects.
358 ///
359 bool llvm::isInstructionTriviallyDead(Instruction *I,
360                                       const TargetLibraryInfo *TLI) {
361   if (!I->use_empty())
362     return false;
363   return wouldInstructionBeTriviallyDead(I, TLI);
364 }
365 
366 bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
367                                            const TargetLibraryInfo *TLI) {
368   if (I->isTerminator())
369     return false;
370 
371   // We don't want the landingpad-like instructions removed by anything this
372   // general.
373   if (I->isEHPad())
374     return false;
375 
376   // We don't want debug info removed by anything this general, unless
377   // debug info is empty.
378   if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
379     if (DDI->getAddress())
380       return false;
381     return true;
382   }
383   if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
384     if (DVI->getValue())
385       return false;
386     return true;
387   }
388   if (DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
389     if (DLI->getLabel())
390       return false;
391     return true;
392   }
393 
394   if (!I->mayHaveSideEffects())
395     return true;
396 
397   // Special case intrinsics that "may have side effects" but can be deleted
398   // when dead.
399   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
400     // Safe to delete llvm.stacksave and launder.invariant.group if dead.
401     if (II->getIntrinsicID() == Intrinsic::stacksave ||
402         II->getIntrinsicID() == Intrinsic::launder_invariant_group)
403       return true;
404 
405     // Lifetime intrinsics are dead when their right-hand is undef.
406     if (II->isLifetimeStartOrEnd())
407       return isa<UndefValue>(II->getArgOperand(1));
408 
409     // Assumptions are dead if their condition is trivially true.  Guards on
410     // true are operationally no-ops.  In the future we can consider more
411     // sophisticated tradeoffs for guards considering potential for check
412     // widening, but for now we keep things simple.
413     if (II->getIntrinsicID() == Intrinsic::assume ||
414         II->getIntrinsicID() == Intrinsic::experimental_guard) {
415       if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
416         return !Cond->isZero();
417 
418       return false;
419     }
420   }
421 
422   if (isAllocLikeFn(I, TLI))
423     return true;
424 
425   if (CallInst *CI = isFreeCall(I, TLI))
426     if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
427       return C->isNullValue() || isa<UndefValue>(C);
428 
429   if (auto *Call = dyn_cast<CallBase>(I))
430     if (isMathLibCallNoop(Call, TLI))
431       return true;
432 
433   return false;
434 }
435 
436 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
437 /// trivially dead instruction, delete it.  If that makes any of its operands
438 /// trivially dead, delete them too, recursively.  Return true if any
439 /// instructions were deleted.
440 bool llvm::RecursivelyDeleteTriviallyDeadInstructions(
441     Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU) {
442   Instruction *I = dyn_cast<Instruction>(V);
443   if (!I || !isInstructionTriviallyDead(I, TLI))
444     return false;
445 
446   SmallVector<WeakTrackingVH, 16> DeadInsts;
447   DeadInsts.push_back(I);
448   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU);
449 
450   return true;
451 }
452 
453 void llvm::RecursivelyDeleteTriviallyDeadInstructions(
454     SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
455     MemorySSAUpdater *MSSAU) {
456   // Process the dead instruction list until empty.
457   while (!DeadInsts.empty()) {
458     Value *V = DeadInsts.pop_back_val();
459     Instruction *I = cast_or_null<Instruction>(V);
460     if (!I)
461       continue;
462     assert(isInstructionTriviallyDead(I, TLI) &&
463            "Live instruction found in dead worklist!");
464     assert(I->use_empty() && "Instructions with uses are not dead.");
465 
466     // Don't lose the debug info while deleting the instructions.
467     salvageDebugInfo(*I);
468 
469     // Null out all of the instruction's operands to see if any operand becomes
470     // dead as we go.
471     for (Use &OpU : I->operands()) {
472       Value *OpV = OpU.get();
473       OpU.set(nullptr);
474 
475       if (!OpV->use_empty())
476         continue;
477 
478       // If the operand is an instruction that became dead as we nulled out the
479       // operand, and if it is 'trivially' dead, delete it in a future loop
480       // iteration.
481       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
482         if (isInstructionTriviallyDead(OpI, TLI))
483           DeadInsts.push_back(OpI);
484     }
485     if (MSSAU)
486       MSSAU->removeMemoryAccess(I);
487 
488     I->eraseFromParent();
489   }
490 }
491 
492 bool llvm::replaceDbgUsesWithUndef(Instruction *I) {
493   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
494   findDbgUsers(DbgUsers, I);
495   for (auto *DII : DbgUsers) {
496     Value *Undef = UndefValue::get(I->getType());
497     DII->setOperand(0, MetadataAsValue::get(DII->getContext(),
498                                             ValueAsMetadata::get(Undef)));
499   }
500   return !DbgUsers.empty();
501 }
502 
503 /// areAllUsesEqual - Check whether the uses of a value are all the same.
504 /// This is similar to Instruction::hasOneUse() except this will also return
505 /// true when there are no uses or multiple uses that all refer to the same
506 /// value.
507 static bool areAllUsesEqual(Instruction *I) {
508   Value::user_iterator UI = I->user_begin();
509   Value::user_iterator UE = I->user_end();
510   if (UI == UE)
511     return true;
512 
513   User *TheUse = *UI;
514   for (++UI; UI != UE; ++UI) {
515     if (*UI != TheUse)
516       return false;
517   }
518   return true;
519 }
520 
521 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
522 /// dead PHI node, due to being a def-use chain of single-use nodes that
523 /// either forms a cycle or is terminated by a trivially dead instruction,
524 /// delete it.  If that makes any of its operands trivially dead, delete them
525 /// too, recursively.  Return true if a change was made.
526 bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
527                                         const TargetLibraryInfo *TLI,
528                                         llvm::MemorySSAUpdater *MSSAU) {
529   SmallPtrSet<Instruction*, 4> Visited;
530   for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
531        I = cast<Instruction>(*I->user_begin())) {
532     if (I->use_empty())
533       return RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
534 
535     // If we find an instruction more than once, we're on a cycle that
536     // won't prove fruitful.
537     if (!Visited.insert(I).second) {
538       // Break the cycle and delete the instruction and its operands.
539       I->replaceAllUsesWith(UndefValue::get(I->getType()));
540       (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
541       return true;
542     }
543   }
544   return false;
545 }
546 
547 static bool
548 simplifyAndDCEInstruction(Instruction *I,
549                           SmallSetVector<Instruction *, 16> &WorkList,
550                           const DataLayout &DL,
551                           const TargetLibraryInfo *TLI) {
552   if (isInstructionTriviallyDead(I, TLI)) {
553     salvageDebugInfo(*I);
554 
555     // Null out all of the instruction's operands to see if any operand becomes
556     // dead as we go.
557     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
558       Value *OpV = I->getOperand(i);
559       I->setOperand(i, nullptr);
560 
561       if (!OpV->use_empty() || I == OpV)
562         continue;
563 
564       // If the operand is an instruction that became dead as we nulled out the
565       // operand, and if it is 'trivially' dead, delete it in a future loop
566       // iteration.
567       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
568         if (isInstructionTriviallyDead(OpI, TLI))
569           WorkList.insert(OpI);
570     }
571 
572     I->eraseFromParent();
573 
574     return true;
575   }
576 
577   if (Value *SimpleV = SimplifyInstruction(I, DL)) {
578     // Add the users to the worklist. CAREFUL: an instruction can use itself,
579     // in the case of a phi node.
580     for (User *U : I->users()) {
581       if (U != I) {
582         WorkList.insert(cast<Instruction>(U));
583       }
584     }
585 
586     // Replace the instruction with its simplified value.
587     bool Changed = false;
588     if (!I->use_empty()) {
589       I->replaceAllUsesWith(SimpleV);
590       Changed = true;
591     }
592     if (isInstructionTriviallyDead(I, TLI)) {
593       I->eraseFromParent();
594       Changed = true;
595     }
596     return Changed;
597   }
598   return false;
599 }
600 
601 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
602 /// simplify any instructions in it and recursively delete dead instructions.
603 ///
604 /// This returns true if it changed the code, note that it can delete
605 /// instructions in other blocks as well in this block.
606 bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
607                                        const TargetLibraryInfo *TLI) {
608   bool MadeChange = false;
609   const DataLayout &DL = BB->getModule()->getDataLayout();
610 
611 #ifndef NDEBUG
612   // In debug builds, ensure that the terminator of the block is never replaced
613   // or deleted by these simplifications. The idea of simplification is that it
614   // cannot introduce new instructions, and there is no way to replace the
615   // terminator of a block without introducing a new instruction.
616   AssertingVH<Instruction> TerminatorVH(&BB->back());
617 #endif
618 
619   SmallSetVector<Instruction *, 16> WorkList;
620   // Iterate over the original function, only adding insts to the worklist
621   // if they actually need to be revisited. This avoids having to pre-init
622   // the worklist with the entire function's worth of instructions.
623   for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
624        BI != E;) {
625     assert(!BI->isTerminator());
626     Instruction *I = &*BI;
627     ++BI;
628 
629     // We're visiting this instruction now, so make sure it's not in the
630     // worklist from an earlier visit.
631     if (!WorkList.count(I))
632       MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
633   }
634 
635   while (!WorkList.empty()) {
636     Instruction *I = WorkList.pop_back_val();
637     MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
638   }
639   return MadeChange;
640 }
641 
642 //===----------------------------------------------------------------------===//
643 //  Control Flow Graph Restructuring.
644 //
645 
646 void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
647                                         DomTreeUpdater *DTU) {
648   // This only adjusts blocks with PHI nodes.
649   if (!isa<PHINode>(BB->begin()))
650     return;
651 
652   // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
653   // them down.  This will leave us with single entry phi nodes and other phis
654   // that can be removed.
655   BB->removePredecessor(Pred, true);
656 
657   WeakTrackingVH PhiIt = &BB->front();
658   while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
659     PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
660     Value *OldPhiIt = PhiIt;
661 
662     if (!recursivelySimplifyInstruction(PN))
663       continue;
664 
665     // If recursive simplification ended up deleting the next PHI node we would
666     // iterate to, then our iterator is invalid, restart scanning from the top
667     // of the block.
668     if (PhiIt != OldPhiIt) PhiIt = &BB->front();
669   }
670   if (DTU)
671     DTU->applyUpdatesPermissive({{DominatorTree::Delete, Pred, BB}});
672 }
673 
674 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
675                                        DomTreeUpdater *DTU) {
676 
677   // If BB has single-entry PHI nodes, fold them.
678   while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
679     Value *NewVal = PN->getIncomingValue(0);
680     // Replace self referencing PHI with undef, it must be dead.
681     if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
682     PN->replaceAllUsesWith(NewVal);
683     PN->eraseFromParent();
684   }
685 
686   BasicBlock *PredBB = DestBB->getSinglePredecessor();
687   assert(PredBB && "Block doesn't have a single predecessor!");
688 
689   bool ReplaceEntryBB = false;
690   if (PredBB == &DestBB->getParent()->getEntryBlock())
691     ReplaceEntryBB = true;
692 
693   // DTU updates: Collect all the edges that enter
694   // PredBB. These dominator edges will be redirected to DestBB.
695   SmallVector<DominatorTree::UpdateType, 32> Updates;
696 
697   if (DTU) {
698     Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
699     for (auto I = pred_begin(PredBB), E = pred_end(PredBB); I != E; ++I) {
700       Updates.push_back({DominatorTree::Delete, *I, PredBB});
701       // This predecessor of PredBB may already have DestBB as a successor.
702       if (llvm::find(successors(*I), DestBB) == succ_end(*I))
703         Updates.push_back({DominatorTree::Insert, *I, DestBB});
704     }
705   }
706 
707   // Zap anything that took the address of DestBB.  Not doing this will give the
708   // address an invalid value.
709   if (DestBB->hasAddressTaken()) {
710     BlockAddress *BA = BlockAddress::get(DestBB);
711     Constant *Replacement =
712       ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
713     BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
714                                                      BA->getType()));
715     BA->destroyConstant();
716   }
717 
718   // Anything that branched to PredBB now branches to DestBB.
719   PredBB->replaceAllUsesWith(DestBB);
720 
721   // Splice all the instructions from PredBB to DestBB.
722   PredBB->getTerminator()->eraseFromParent();
723   DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
724   new UnreachableInst(PredBB->getContext(), PredBB);
725 
726   // If the PredBB is the entry block of the function, move DestBB up to
727   // become the entry block after we erase PredBB.
728   if (ReplaceEntryBB)
729     DestBB->moveAfter(PredBB);
730 
731   if (DTU) {
732     assert(PredBB->getInstList().size() == 1 &&
733            isa<UnreachableInst>(PredBB->getTerminator()) &&
734            "The successor list of PredBB isn't empty before "
735            "applying corresponding DTU updates.");
736     DTU->applyUpdatesPermissive(Updates);
737     DTU->deleteBB(PredBB);
738     // Recalculation of DomTree is needed when updating a forward DomTree and
739     // the Entry BB is replaced.
740     if (ReplaceEntryBB && DTU->hasDomTree()) {
741       // The entry block was removed and there is no external interface for
742       // the dominator tree to be notified of this change. In this corner-case
743       // we recalculate the entire tree.
744       DTU->recalculate(*(DestBB->getParent()));
745     }
746   }
747 
748   else {
749     PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.
750   }
751 }
752 
753 /// Return true if we can choose one of these values to use in place of the
754 /// other. Note that we will always choose the non-undef value to keep.
755 static bool CanMergeValues(Value *First, Value *Second) {
756   return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
757 }
758 
759 /// Return true if we can fold BB, an almost-empty BB ending in an unconditional
760 /// branch to Succ, into Succ.
761 ///
762 /// Assumption: Succ is the single successor for BB.
763 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
764   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
765 
766   LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
767                     << Succ->getName() << "\n");
768   // Shortcut, if there is only a single predecessor it must be BB and merging
769   // is always safe
770   if (Succ->getSinglePredecessor()) return true;
771 
772   // Make a list of the predecessors of BB
773   SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
774 
775   // Look at all the phi nodes in Succ, to see if they present a conflict when
776   // merging these blocks
777   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
778     PHINode *PN = cast<PHINode>(I);
779 
780     // If the incoming value from BB is again a PHINode in
781     // BB which has the same incoming value for *PI as PN does, we can
782     // merge the phi nodes and then the blocks can still be merged
783     PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
784     if (BBPN && BBPN->getParent() == BB) {
785       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
786         BasicBlock *IBB = PN->getIncomingBlock(PI);
787         if (BBPreds.count(IBB) &&
788             !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
789                             PN->getIncomingValue(PI))) {
790           LLVM_DEBUG(dbgs()
791                      << "Can't fold, phi node " << PN->getName() << " in "
792                      << Succ->getName() << " is conflicting with "
793                      << BBPN->getName() << " with regard to common predecessor "
794                      << IBB->getName() << "\n");
795           return false;
796         }
797       }
798     } else {
799       Value* Val = PN->getIncomingValueForBlock(BB);
800       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
801         // See if the incoming value for the common predecessor is equal to the
802         // one for BB, in which case this phi node will not prevent the merging
803         // of the block.
804         BasicBlock *IBB = PN->getIncomingBlock(PI);
805         if (BBPreds.count(IBB) &&
806             !CanMergeValues(Val, PN->getIncomingValue(PI))) {
807           LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()
808                             << " in " << Succ->getName()
809                             << " is conflicting with regard to common "
810                             << "predecessor " << IBB->getName() << "\n");
811           return false;
812         }
813       }
814     }
815   }
816 
817   return true;
818 }
819 
820 using PredBlockVector = SmallVector<BasicBlock *, 16>;
821 using IncomingValueMap = DenseMap<BasicBlock *, Value *>;
822 
823 /// Determines the value to use as the phi node input for a block.
824 ///
825 /// Select between \p OldVal any value that we know flows from \p BB
826 /// to a particular phi on the basis of which one (if either) is not
827 /// undef. Update IncomingValues based on the selected value.
828 ///
829 /// \param OldVal The value we are considering selecting.
830 /// \param BB The block that the value flows in from.
831 /// \param IncomingValues A map from block-to-value for other phi inputs
832 /// that we have examined.
833 ///
834 /// \returns the selected value.
835 static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
836                                           IncomingValueMap &IncomingValues) {
837   if (!isa<UndefValue>(OldVal)) {
838     assert((!IncomingValues.count(BB) ||
839             IncomingValues.find(BB)->second == OldVal) &&
840            "Expected OldVal to match incoming value from BB!");
841 
842     IncomingValues.insert(std::make_pair(BB, OldVal));
843     return OldVal;
844   }
845 
846   IncomingValueMap::const_iterator It = IncomingValues.find(BB);
847   if (It != IncomingValues.end()) return It->second;
848 
849   return OldVal;
850 }
851 
852 /// Create a map from block to value for the operands of a
853 /// given phi.
854 ///
855 /// Create a map from block to value for each non-undef value flowing
856 /// into \p PN.
857 ///
858 /// \param PN The phi we are collecting the map for.
859 /// \param IncomingValues [out] The map from block to value for this phi.
860 static void gatherIncomingValuesToPhi(PHINode *PN,
861                                       IncomingValueMap &IncomingValues) {
862   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
863     BasicBlock *BB = PN->getIncomingBlock(i);
864     Value *V = PN->getIncomingValue(i);
865 
866     if (!isa<UndefValue>(V))
867       IncomingValues.insert(std::make_pair(BB, V));
868   }
869 }
870 
871 /// Replace the incoming undef values to a phi with the values
872 /// from a block-to-value map.
873 ///
874 /// \param PN The phi we are replacing the undefs in.
875 /// \param IncomingValues A map from block to value.
876 static void replaceUndefValuesInPhi(PHINode *PN,
877                                     const IncomingValueMap &IncomingValues) {
878   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
879     Value *V = PN->getIncomingValue(i);
880 
881     if (!isa<UndefValue>(V)) continue;
882 
883     BasicBlock *BB = PN->getIncomingBlock(i);
884     IncomingValueMap::const_iterator It = IncomingValues.find(BB);
885     if (It == IncomingValues.end()) continue;
886 
887     PN->setIncomingValue(i, It->second);
888   }
889 }
890 
891 /// Replace a value flowing from a block to a phi with
892 /// potentially multiple instances of that value flowing from the
893 /// block's predecessors to the phi.
894 ///
895 /// \param BB The block with the value flowing into the phi.
896 /// \param BBPreds The predecessors of BB.
897 /// \param PN The phi that we are updating.
898 static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
899                                                 const PredBlockVector &BBPreds,
900                                                 PHINode *PN) {
901   Value *OldVal = PN->removeIncomingValue(BB, false);
902   assert(OldVal && "No entry in PHI for Pred BB!");
903 
904   IncomingValueMap IncomingValues;
905 
906   // We are merging two blocks - BB, and the block containing PN - and
907   // as a result we need to redirect edges from the predecessors of BB
908   // to go to the block containing PN, and update PN
909   // accordingly. Since we allow merging blocks in the case where the
910   // predecessor and successor blocks both share some predecessors,
911   // and where some of those common predecessors might have undef
912   // values flowing into PN, we want to rewrite those values to be
913   // consistent with the non-undef values.
914 
915   gatherIncomingValuesToPhi(PN, IncomingValues);
916 
917   // If this incoming value is one of the PHI nodes in BB, the new entries
918   // in the PHI node are the entries from the old PHI.
919   if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
920     PHINode *OldValPN = cast<PHINode>(OldVal);
921     for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
922       // Note that, since we are merging phi nodes and BB and Succ might
923       // have common predecessors, we could end up with a phi node with
924       // identical incoming branches. This will be cleaned up later (and
925       // will trigger asserts if we try to clean it up now, without also
926       // simplifying the corresponding conditional branch).
927       BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
928       Value *PredVal = OldValPN->getIncomingValue(i);
929       Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
930                                                     IncomingValues);
931 
932       // And add a new incoming value for this predecessor for the
933       // newly retargeted branch.
934       PN->addIncoming(Selected, PredBB);
935     }
936   } else {
937     for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
938       // Update existing incoming values in PN for this
939       // predecessor of BB.
940       BasicBlock *PredBB = BBPreds[i];
941       Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
942                                                     IncomingValues);
943 
944       // And add a new incoming value for this predecessor for the
945       // newly retargeted branch.
946       PN->addIncoming(Selected, PredBB);
947     }
948   }
949 
950   replaceUndefValuesInPhi(PN, IncomingValues);
951 }
952 
953 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
954                                                    DomTreeUpdater *DTU) {
955   assert(BB != &BB->getParent()->getEntryBlock() &&
956          "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
957 
958   // We can't eliminate infinite loops.
959   BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
960   if (BB == Succ) return false;
961 
962   // Check to see if merging these blocks would cause conflicts for any of the
963   // phi nodes in BB or Succ. If not, we can safely merge.
964   if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
965 
966   // Check for cases where Succ has multiple predecessors and a PHI node in BB
967   // has uses which will not disappear when the PHI nodes are merged.  It is
968   // possible to handle such cases, but difficult: it requires checking whether
969   // BB dominates Succ, which is non-trivial to calculate in the case where
970   // Succ has multiple predecessors.  Also, it requires checking whether
971   // constructing the necessary self-referential PHI node doesn't introduce any
972   // conflicts; this isn't too difficult, but the previous code for doing this
973   // was incorrect.
974   //
975   // Note that if this check finds a live use, BB dominates Succ, so BB is
976   // something like a loop pre-header (or rarely, a part of an irreducible CFG);
977   // folding the branch isn't profitable in that case anyway.
978   if (!Succ->getSinglePredecessor()) {
979     BasicBlock::iterator BBI = BB->begin();
980     while (isa<PHINode>(*BBI)) {
981       for (Use &U : BBI->uses()) {
982         if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
983           if (PN->getIncomingBlock(U) != BB)
984             return false;
985         } else {
986           return false;
987         }
988       }
989       ++BBI;
990     }
991   }
992 
993   // We cannot fold the block if it's a branch to an already present callbr
994   // successor because that creates duplicate successors.
995   for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
996     if (auto *CBI = dyn_cast<CallBrInst>((*I)->getTerminator())) {
997       if (Succ == CBI->getDefaultDest())
998         return false;
999       for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
1000         if (Succ == CBI->getIndirectDest(i))
1001           return false;
1002     }
1003   }
1004 
1005   LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
1006 
1007   SmallVector<DominatorTree::UpdateType, 32> Updates;
1008   if (DTU) {
1009     Updates.push_back({DominatorTree::Delete, BB, Succ});
1010     // All predecessors of BB will be moved to Succ.
1011     for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1012       Updates.push_back({DominatorTree::Delete, *I, BB});
1013       // This predecessor of BB may already have Succ as a successor.
1014       if (llvm::find(successors(*I), Succ) == succ_end(*I))
1015         Updates.push_back({DominatorTree::Insert, *I, Succ});
1016     }
1017   }
1018 
1019   if (isa<PHINode>(Succ->begin())) {
1020     // If there is more than one pred of succ, and there are PHI nodes in
1021     // the successor, then we need to add incoming edges for the PHI nodes
1022     //
1023     const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
1024 
1025     // Loop over all of the PHI nodes in the successor of BB.
1026     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
1027       PHINode *PN = cast<PHINode>(I);
1028 
1029       redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
1030     }
1031   }
1032 
1033   if (Succ->getSinglePredecessor()) {
1034     // BB is the only predecessor of Succ, so Succ will end up with exactly
1035     // the same predecessors BB had.
1036 
1037     // Copy over any phi, debug or lifetime instruction.
1038     BB->getTerminator()->eraseFromParent();
1039     Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
1040                                BB->getInstList());
1041   } else {
1042     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1043       // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
1044       assert(PN->use_empty() && "There shouldn't be any uses here!");
1045       PN->eraseFromParent();
1046     }
1047   }
1048 
1049   // If the unconditional branch we replaced contains llvm.loop metadata, we
1050   // add the metadata to the branch instructions in the predecessors.
1051   unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop");
1052   Instruction *TI = BB->getTerminator();
1053   if (TI)
1054     if (MDNode *LoopMD = TI->getMetadata(LoopMDKind))
1055       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1056         BasicBlock *Pred = *PI;
1057         Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD);
1058       }
1059 
1060   // Everything that jumped to BB now goes to Succ.
1061   BB->replaceAllUsesWith(Succ);
1062   if (!Succ->hasName()) Succ->takeName(BB);
1063 
1064   // Clear the successor list of BB to match updates applying to DTU later.
1065   if (BB->getTerminator())
1066     BB->getInstList().pop_back();
1067   new UnreachableInst(BB->getContext(), BB);
1068   assert(succ_empty(BB) && "The successor list of BB isn't empty before "
1069                            "applying corresponding DTU updates.");
1070 
1071   if (DTU) {
1072     DTU->applyUpdatesPermissive(Updates);
1073     DTU->deleteBB(BB);
1074   } else {
1075     BB->eraseFromParent(); // Delete the old basic block.
1076   }
1077   return true;
1078 }
1079 
1080 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
1081   // This implementation doesn't currently consider undef operands
1082   // specially. Theoretically, two phis which are identical except for
1083   // one having an undef where the other doesn't could be collapsed.
1084 
1085   struct PHIDenseMapInfo {
1086     static PHINode *getEmptyKey() {
1087       return DenseMapInfo<PHINode *>::getEmptyKey();
1088     }
1089 
1090     static PHINode *getTombstoneKey() {
1091       return DenseMapInfo<PHINode *>::getTombstoneKey();
1092     }
1093 
1094     static unsigned getHashValue(PHINode *PN) {
1095       // Compute a hash value on the operands. Instcombine will likely have
1096       // sorted them, which helps expose duplicates, but we have to check all
1097       // the operands to be safe in case instcombine hasn't run.
1098       return static_cast<unsigned>(hash_combine(
1099           hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
1100           hash_combine_range(PN->block_begin(), PN->block_end())));
1101     }
1102 
1103     static bool isEqual(PHINode *LHS, PHINode *RHS) {
1104       if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
1105           RHS == getEmptyKey() || RHS == getTombstoneKey())
1106         return LHS == RHS;
1107       return LHS->isIdenticalTo(RHS);
1108     }
1109   };
1110 
1111   // Set of unique PHINodes.
1112   DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
1113 
1114   // Examine each PHI.
1115   bool Changed = false;
1116   for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
1117     auto Inserted = PHISet.insert(PN);
1118     if (!Inserted.second) {
1119       // A duplicate. Replace this PHI with its duplicate.
1120       PN->replaceAllUsesWith(*Inserted.first);
1121       PN->eraseFromParent();
1122       Changed = true;
1123 
1124       // The RAUW can change PHIs that we already visited. Start over from the
1125       // beginning.
1126       PHISet.clear();
1127       I = BB->begin();
1128     }
1129   }
1130 
1131   return Changed;
1132 }
1133 
1134 /// enforceKnownAlignment - If the specified pointer points to an object that
1135 /// we control, modify the object's alignment to PrefAlign. This isn't
1136 /// often possible though. If alignment is important, a more reliable approach
1137 /// is to simply align all global variables and allocation instructions to
1138 /// their preferred alignment from the beginning.
1139 static unsigned enforceKnownAlignment(Value *V, unsigned Alignment,
1140                                       unsigned PrefAlign,
1141                                       const DataLayout &DL) {
1142   assert(PrefAlign > Alignment);
1143 
1144   V = V->stripPointerCasts();
1145 
1146   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1147     // TODO: ideally, computeKnownBits ought to have used
1148     // AllocaInst::getAlignment() in its computation already, making
1149     // the below max redundant. But, as it turns out,
1150     // stripPointerCasts recurses through infinite layers of bitcasts,
1151     // while computeKnownBits is not allowed to traverse more than 6
1152     // levels.
1153     Alignment = std::max(AI->getAlignment(), Alignment);
1154     if (PrefAlign <= Alignment)
1155       return Alignment;
1156 
1157     // If the preferred alignment is greater than the natural stack alignment
1158     // then don't round up. This avoids dynamic stack realignment.
1159     if (DL.exceedsNaturalStackAlignment(Align(PrefAlign)))
1160       return Alignment;
1161     AI->setAlignment(MaybeAlign(PrefAlign));
1162     return PrefAlign;
1163   }
1164 
1165   if (auto *GO = dyn_cast<GlobalObject>(V)) {
1166     // TODO: as above, this shouldn't be necessary.
1167     Alignment = std::max(GO->getAlignment(), Alignment);
1168     if (PrefAlign <= Alignment)
1169       return Alignment;
1170 
1171     // If there is a large requested alignment and we can, bump up the alignment
1172     // of the global.  If the memory we set aside for the global may not be the
1173     // memory used by the final program then it is impossible for us to reliably
1174     // enforce the preferred alignment.
1175     if (!GO->canIncreaseAlignment())
1176       return Alignment;
1177 
1178     GO->setAlignment(MaybeAlign(PrefAlign));
1179     return PrefAlign;
1180   }
1181 
1182   return Alignment;
1183 }
1184 
1185 unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
1186                                           const DataLayout &DL,
1187                                           const Instruction *CxtI,
1188                                           AssumptionCache *AC,
1189                                           const DominatorTree *DT) {
1190   assert(V->getType()->isPointerTy() &&
1191          "getOrEnforceKnownAlignment expects a pointer!");
1192 
1193   KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);
1194   unsigned TrailZ = Known.countMinTrailingZeros();
1195 
1196   // Avoid trouble with ridiculously large TrailZ values, such as
1197   // those computed from a null pointer.
1198   TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
1199 
1200   unsigned Align = 1u << std::min(Known.getBitWidth() - 1, TrailZ);
1201 
1202   // LLVM doesn't support alignments larger than this currently.
1203   Align = std::min(Align, +Value::MaximumAlignment);
1204 
1205   if (PrefAlign > Align)
1206     Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
1207 
1208   // We don't need to make any adjustment.
1209   return Align;
1210 }
1211 
1212 ///===---------------------------------------------------------------------===//
1213 ///  Dbg Intrinsic utilities
1214 ///
1215 
1216 /// See if there is a dbg.value intrinsic for DIVar before I.
1217 static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr,
1218                               Instruction *I) {
1219   // Since we can't guarantee that the original dbg.declare instrinsic
1220   // is removed by LowerDbgDeclare(), we need to make sure that we are
1221   // not inserting the same dbg.value intrinsic over and over.
1222   BasicBlock::InstListType::iterator PrevI(I);
1223   if (PrevI != I->getParent()->getInstList().begin()) {
1224     --PrevI;
1225     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
1226       if (DVI->getValue() == I->getOperand(0) &&
1227           DVI->getVariable() == DIVar &&
1228           DVI->getExpression() == DIExpr)
1229         return true;
1230   }
1231   return false;
1232 }
1233 
1234 /// See if there is a dbg.value intrinsic for DIVar for the PHI node.
1235 static bool PhiHasDebugValue(DILocalVariable *DIVar,
1236                              DIExpression *DIExpr,
1237                              PHINode *APN) {
1238   // Since we can't guarantee that the original dbg.declare instrinsic
1239   // is removed by LowerDbgDeclare(), we need to make sure that we are
1240   // not inserting the same dbg.value intrinsic over and over.
1241   SmallVector<DbgValueInst *, 1> DbgValues;
1242   findDbgValues(DbgValues, APN);
1243   for (auto *DVI : DbgValues) {
1244     assert(DVI->getValue() == APN);
1245     if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
1246       return true;
1247   }
1248   return false;
1249 }
1250 
1251 /// Check if the alloc size of \p ValTy is large enough to cover the variable
1252 /// (or fragment of the variable) described by \p DII.
1253 ///
1254 /// This is primarily intended as a helper for the different
1255 /// ConvertDebugDeclareToDebugValue functions. The dbg.declare/dbg.addr that is
1256 /// converted describes an alloca'd variable, so we need to use the
1257 /// alloc size of the value when doing the comparison. E.g. an i1 value will be
1258 /// identified as covering an n-bit fragment, if the store size of i1 is at
1259 /// least n bits.
1260 static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {
1261   const DataLayout &DL = DII->getModule()->getDataLayout();
1262   uint64_t ValueSize = DL.getTypeAllocSizeInBits(ValTy);
1263   if (auto FragmentSize = DII->getFragmentSizeInBits())
1264     return ValueSize >= *FragmentSize;
1265   // We can't always calculate the size of the DI variable (e.g. if it is a
1266   // VLA). Try to use the size of the alloca that the dbg intrinsic describes
1267   // intead.
1268   if (DII->isAddressOfVariable())
1269     if (auto *AI = dyn_cast_or_null<AllocaInst>(DII->getVariableLocation()))
1270       if (auto FragmentSize = AI->getAllocationSizeInBits(DL))
1271         return ValueSize >= *FragmentSize;
1272   // Could not determine size of variable. Conservatively return false.
1273   return false;
1274 }
1275 
1276 /// Produce a DebugLoc to use for each dbg.declare/inst pair that are promoted
1277 /// to a dbg.value. Because no machine insts can come from debug intrinsics,
1278 /// only the scope and inlinedAt is significant. Zero line numbers are used in
1279 /// case this DebugLoc leaks into any adjacent instructions.
1280 static DebugLoc getDebugValueLoc(DbgVariableIntrinsic *DII, Instruction *Src) {
1281   // Original dbg.declare must have a location.
1282   DebugLoc DeclareLoc = DII->getDebugLoc();
1283   MDNode *Scope = DeclareLoc.getScope();
1284   DILocation *InlinedAt = DeclareLoc.getInlinedAt();
1285   // Produce an unknown location with the correct scope / inlinedAt fields.
1286   return DebugLoc::get(0, 0, Scope, InlinedAt);
1287 }
1288 
1289 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
1290 /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
1291 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1292                                            StoreInst *SI, DIBuilder &Builder) {
1293   assert(DII->isAddressOfVariable());
1294   auto *DIVar = DII->getVariable();
1295   assert(DIVar && "Missing variable");
1296   auto *DIExpr = DII->getExpression();
1297   Value *DV = SI->getValueOperand();
1298 
1299   DebugLoc NewLoc = getDebugValueLoc(DII, SI);
1300 
1301   if (!valueCoversEntireFragment(DV->getType(), DII)) {
1302     // FIXME: If storing to a part of the variable described by the dbg.declare,
1303     // then we want to insert a dbg.value for the corresponding fragment.
1304     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1305                       << *DII << '\n');
1306     // For now, when there is a store to parts of the variable (but we do not
1307     // know which part) we insert an dbg.value instrinsic to indicate that we
1308     // know nothing about the variable's content.
1309     DV = UndefValue::get(DV->getType());
1310     if (!LdStHasDebugValue(DIVar, DIExpr, SI))
1311       Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
1312     return;
1313   }
1314 
1315   if (!LdStHasDebugValue(DIVar, DIExpr, SI))
1316     Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
1317 }
1318 
1319 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
1320 /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
1321 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1322                                            LoadInst *LI, DIBuilder &Builder) {
1323   auto *DIVar = DII->getVariable();
1324   auto *DIExpr = DII->getExpression();
1325   assert(DIVar && "Missing variable");
1326 
1327   if (LdStHasDebugValue(DIVar, DIExpr, LI))
1328     return;
1329 
1330   if (!valueCoversEntireFragment(LI->getType(), DII)) {
1331     // FIXME: If only referring to a part of the variable described by the
1332     // dbg.declare, then we want to insert a dbg.value for the corresponding
1333     // fragment.
1334     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1335                       << *DII << '\n');
1336     return;
1337   }
1338 
1339   DebugLoc NewLoc = getDebugValueLoc(DII, nullptr);
1340 
1341   // We are now tracking the loaded value instead of the address. In the
1342   // future if multi-location support is added to the IR, it might be
1343   // preferable to keep tracking both the loaded value and the original
1344   // address in case the alloca can not be elided.
1345   Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
1346       LI, DIVar, DIExpr, NewLoc, (Instruction *)nullptr);
1347   DbgValue->insertAfter(LI);
1348 }
1349 
1350 /// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
1351 /// llvm.dbg.declare or llvm.dbg.addr intrinsic.
1352 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1353                                            PHINode *APN, DIBuilder &Builder) {
1354   auto *DIVar = DII->getVariable();
1355   auto *DIExpr = DII->getExpression();
1356   assert(DIVar && "Missing variable");
1357 
1358   if (PhiHasDebugValue(DIVar, DIExpr, APN))
1359     return;
1360 
1361   if (!valueCoversEntireFragment(APN->getType(), DII)) {
1362     // FIXME: If only referring to a part of the variable described by the
1363     // dbg.declare, then we want to insert a dbg.value for the corresponding
1364     // fragment.
1365     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1366                       << *DII << '\n');
1367     return;
1368   }
1369 
1370   BasicBlock *BB = APN->getParent();
1371   auto InsertionPt = BB->getFirstInsertionPt();
1372 
1373   DebugLoc NewLoc = getDebugValueLoc(DII, nullptr);
1374 
1375   // The block may be a catchswitch block, which does not have a valid
1376   // insertion point.
1377   // FIXME: Insert dbg.value markers in the successors when appropriate.
1378   if (InsertionPt != BB->end())
1379     Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, NewLoc, &*InsertionPt);
1380 }
1381 
1382 /// Determine whether this alloca is either a VLA or an array.
1383 static bool isArray(AllocaInst *AI) {
1384   return AI->isArrayAllocation() ||
1385          (AI->getAllocatedType() && AI->getAllocatedType()->isArrayTy());
1386 }
1387 
1388 /// Determine whether this alloca is a structure.
1389 static bool isStructure(AllocaInst *AI) {
1390   return AI->getAllocatedType() && AI->getAllocatedType()->isStructTy();
1391 }
1392 
1393 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1394 /// of llvm.dbg.value intrinsics.
1395 bool llvm::LowerDbgDeclare(Function &F) {
1396   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
1397   SmallVector<DbgDeclareInst *, 4> Dbgs;
1398   for (auto &FI : F)
1399     for (Instruction &BI : FI)
1400       if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1401         Dbgs.push_back(DDI);
1402 
1403   if (Dbgs.empty())
1404     return false;
1405 
1406   for (auto &I : Dbgs) {
1407     DbgDeclareInst *DDI = I;
1408     AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1409     // If this is an alloca for a scalar variable, insert a dbg.value
1410     // at each load and store to the alloca and erase the dbg.declare.
1411     // The dbg.values allow tracking a variable even if it is not
1412     // stored on the stack, while the dbg.declare can only describe
1413     // the stack slot (and at a lexical-scope granularity). Later
1414     // passes will attempt to elide the stack slot.
1415     if (!AI || isArray(AI) || isStructure(AI))
1416       continue;
1417 
1418     // A volatile load/store means that the alloca can't be elided anyway.
1419     if (llvm::any_of(AI->users(), [](User *U) -> bool {
1420           if (LoadInst *LI = dyn_cast<LoadInst>(U))
1421             return LI->isVolatile();
1422           if (StoreInst *SI = dyn_cast<StoreInst>(U))
1423             return SI->isVolatile();
1424           return false;
1425         }))
1426       continue;
1427 
1428     SmallVector<const Value *, 8> WorkList;
1429     WorkList.push_back(AI);
1430     while (!WorkList.empty()) {
1431       const Value *V = WorkList.pop_back_val();
1432       for (auto &AIUse : V->uses()) {
1433         User *U = AIUse.getUser();
1434         if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1435           if (AIUse.getOperandNo() == 1)
1436             ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1437         } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1438           ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1439         } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
1440           // This is a call by-value or some other instruction that takes a
1441           // pointer to the variable. Insert a *value* intrinsic that describes
1442           // the variable by dereferencing the alloca.
1443           if (!CI->isLifetimeStartOrEnd()) {
1444             DebugLoc NewLoc = getDebugValueLoc(DDI, nullptr);
1445             auto *DerefExpr =
1446                 DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
1447             DIB.insertDbgValueIntrinsic(AI, DDI->getVariable(), DerefExpr,
1448                                         NewLoc, CI);
1449           }
1450         } else if (BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
1451           if (BI->getType()->isPointerTy())
1452             WorkList.push_back(BI);
1453         }
1454       }
1455     }
1456     DDI->eraseFromParent();
1457   }
1458   return true;
1459 }
1460 
1461 /// Propagate dbg.value intrinsics through the newly inserted PHIs.
1462 void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
1463                                     SmallVectorImpl<PHINode *> &InsertedPHIs) {
1464   assert(BB && "No BasicBlock to clone dbg.value(s) from.");
1465   if (InsertedPHIs.size() == 0)
1466     return;
1467 
1468   // Map existing PHI nodes to their dbg.values.
1469   ValueToValueMapTy DbgValueMap;
1470   for (auto &I : *BB) {
1471     if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
1472       if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
1473         DbgValueMap.insert({Loc, DbgII});
1474     }
1475   }
1476   if (DbgValueMap.size() == 0)
1477     return;
1478 
1479   // Then iterate through the new PHIs and look to see if they use one of the
1480   // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
1481   // propagate the info through the new PHI.
1482   LLVMContext &C = BB->getContext();
1483   for (auto PHI : InsertedPHIs) {
1484     BasicBlock *Parent = PHI->getParent();
1485     // Avoid inserting an intrinsic into an EH block.
1486     if (Parent->getFirstNonPHI()->isEHPad())
1487       continue;
1488     auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
1489     for (auto VI : PHI->operand_values()) {
1490       auto V = DbgValueMap.find(VI);
1491       if (V != DbgValueMap.end()) {
1492         auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
1493         Instruction *NewDbgII = DbgII->clone();
1494         NewDbgII->setOperand(0, PhiMAV);
1495         auto InsertionPt = Parent->getFirstInsertionPt();
1496         assert(InsertionPt != Parent->end() && "Ill-formed basic block");
1497         NewDbgII->insertBefore(&*InsertionPt);
1498       }
1499     }
1500   }
1501 }
1502 
1503 /// Finds all intrinsics declaring local variables as living in the memory that
1504 /// 'V' points to. This may include a mix of dbg.declare and
1505 /// dbg.addr intrinsics.
1506 TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
1507   // This function is hot. Check whether the value has any metadata to avoid a
1508   // DenseMap lookup.
1509   if (!V->isUsedByMetadata())
1510     return {};
1511   auto *L = LocalAsMetadata::getIfExists(V);
1512   if (!L)
1513     return {};
1514   auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
1515   if (!MDV)
1516     return {};
1517 
1518   TinyPtrVector<DbgVariableIntrinsic *> Declares;
1519   for (User *U : MDV->users()) {
1520     if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
1521       if (DII->isAddressOfVariable())
1522         Declares.push_back(DII);
1523   }
1524 
1525   return Declares;
1526 }
1527 
1528 void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
1529   // This function is hot. Check whether the value has any metadata to avoid a
1530   // DenseMap lookup.
1531   if (!V->isUsedByMetadata())
1532     return;
1533   if (auto *L = LocalAsMetadata::getIfExists(V))
1534     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1535       for (User *U : MDV->users())
1536         if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
1537           DbgValues.push_back(DVI);
1538 }
1539 
1540 void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
1541                         Value *V) {
1542   // This function is hot. Check whether the value has any metadata to avoid a
1543   // DenseMap lookup.
1544   if (!V->isUsedByMetadata())
1545     return;
1546   if (auto *L = LocalAsMetadata::getIfExists(V))
1547     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1548       for (User *U : MDV->users())
1549         if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
1550           DbgUsers.push_back(DII);
1551 }
1552 
1553 bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
1554                              Instruction *InsertBefore, DIBuilder &Builder,
1555                              uint8_t DIExprFlags, int Offset) {
1556   auto DbgAddrs = FindDbgAddrUses(Address);
1557   for (DbgVariableIntrinsic *DII : DbgAddrs) {
1558     DebugLoc Loc = DII->getDebugLoc();
1559     auto *DIVar = DII->getVariable();
1560     auto *DIExpr = DII->getExpression();
1561     assert(DIVar && "Missing variable");
1562     DIExpr = DIExpression::prepend(DIExpr, DIExprFlags, Offset);
1563     // Insert llvm.dbg.declare immediately before InsertBefore, and remove old
1564     // llvm.dbg.declare.
1565     Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
1566     if (DII == InsertBefore)
1567       InsertBefore = InsertBefore->getNextNode();
1568     DII->eraseFromParent();
1569   }
1570   return !DbgAddrs.empty();
1571 }
1572 
1573 bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1574                                       DIBuilder &Builder, uint8_t DIExprFlags,
1575                                       int Offset) {
1576   return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder,
1577                            DIExprFlags, Offset);
1578 }
1579 
1580 static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
1581                                         DIBuilder &Builder, int Offset) {
1582   DebugLoc Loc = DVI->getDebugLoc();
1583   auto *DIVar = DVI->getVariable();
1584   auto *DIExpr = DVI->getExpression();
1585   assert(DIVar && "Missing variable");
1586 
1587   // This is an alloca-based llvm.dbg.value. The first thing it should do with
1588   // the alloca pointer is dereference it. Otherwise we don't know how to handle
1589   // it and give up.
1590   if (!DIExpr || DIExpr->getNumElements() < 1 ||
1591       DIExpr->getElement(0) != dwarf::DW_OP_deref)
1592     return;
1593 
1594   // Insert the offset before the first deref.
1595   // We could just change the offset argument of dbg.value, but it's unsigned...
1596   if (Offset)
1597     DIExpr = DIExpression::prepend(DIExpr, 0, Offset);
1598 
1599   Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI);
1600   DVI->eraseFromParent();
1601 }
1602 
1603 void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1604                                     DIBuilder &Builder, int Offset) {
1605   if (auto *L = LocalAsMetadata::getIfExists(AI))
1606     if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
1607       for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
1608         Use &U = *UI++;
1609         if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
1610           replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
1611       }
1612 }
1613 
1614 /// Wrap \p V in a ValueAsMetadata instance.
1615 static MetadataAsValue *wrapValueInMetadata(LLVMContext &C, Value *V) {
1616   return MetadataAsValue::get(C, ValueAsMetadata::get(V));
1617 }
1618 
1619 bool llvm::salvageDebugInfo(Instruction &I) {
1620   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
1621   findDbgUsers(DbgUsers, &I);
1622   if (DbgUsers.empty())
1623     return false;
1624 
1625   return salvageDebugInfoForDbgValues(I, DbgUsers);
1626 }
1627 
1628 void llvm::salvageDebugInfoOrMarkUndef(Instruction &I) {
1629   if (!salvageDebugInfo(I))
1630     replaceDbgUsesWithUndef(&I);
1631 }
1632 
1633 bool llvm::salvageDebugInfoForDbgValues(
1634     Instruction &I, ArrayRef<DbgVariableIntrinsic *> DbgUsers) {
1635   auto &Ctx = I.getContext();
1636   auto wrapMD = [&](Value *V) { return wrapValueInMetadata(Ctx, V); };
1637 
1638   for (auto *DII : DbgUsers) {
1639     // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
1640     // are implicitly pointing out the value as a DWARF memory location
1641     // description.
1642     bool StackValue = isa<DbgValueInst>(DII);
1643 
1644     DIExpression *DIExpr =
1645         salvageDebugInfoImpl(I, DII->getExpression(), StackValue);
1646 
1647     // salvageDebugInfoImpl should fail on examining the first element of
1648     // DbgUsers, or none of them.
1649     if (!DIExpr)
1650       return false;
1651 
1652     DII->setOperand(0, wrapMD(I.getOperand(0)));
1653     DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr));
1654     LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
1655   }
1656 
1657   return true;
1658 }
1659 
1660 DIExpression *llvm::salvageDebugInfoImpl(Instruction &I,
1661                                          DIExpression *SrcDIExpr,
1662                                          bool WithStackValue) {
1663   auto &M = *I.getModule();
1664   auto &DL = M.getDataLayout();
1665 
1666   // Apply a vector of opcodes to the source DIExpression.
1667   auto doSalvage = [&](SmallVectorImpl<uint64_t> &Ops) -> DIExpression * {
1668     DIExpression *DIExpr = SrcDIExpr;
1669     if (!Ops.empty()) {
1670       DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
1671     }
1672     return DIExpr;
1673   };
1674 
1675   // Apply the given offset to the source DIExpression.
1676   auto applyOffset = [&](uint64_t Offset) -> DIExpression * {
1677     SmallVector<uint64_t, 8> Ops;
1678     DIExpression::appendOffset(Ops, Offset);
1679     return doSalvage(Ops);
1680   };
1681 
1682   // initializer-list helper for applying operators to the source DIExpression.
1683   auto applyOps = [&](ArrayRef<uint64_t> Opcodes) -> DIExpression * {
1684     SmallVector<uint64_t, 8> Ops(Opcodes.begin(), Opcodes.end());
1685     return doSalvage(Ops);
1686   };
1687 
1688   if (auto *CI = dyn_cast<CastInst>(&I)) {
1689     // No-op casts and zexts are irrelevant for debug info.
1690     if (CI->isNoopCast(DL) || isa<ZExtInst>(&I))
1691       return SrcDIExpr;
1692 
1693     Type *Type = CI->getType();
1694     // Casts other than Trunc or SExt to scalar types cannot be salvaged.
1695     if (Type->isVectorTy() || (!isa<TruncInst>(&I) && !isa<SExtInst>(&I)))
1696       return nullptr;
1697 
1698     Value *FromValue = CI->getOperand(0);
1699     unsigned FromTypeBitSize = FromValue->getType()->getScalarSizeInBits();
1700     unsigned ToTypeBitSize = Type->getScalarSizeInBits();
1701 
1702     return applyOps(DIExpression::getExtOps(FromTypeBitSize, ToTypeBitSize,
1703                                             isa<SExtInst>(&I)));
1704   }
1705 
1706   if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1707     unsigned BitWidth =
1708         M.getDataLayout().getIndexSizeInBits(GEP->getPointerAddressSpace());
1709     // Rewrite a constant GEP into a DIExpression.
1710     APInt Offset(BitWidth, 0);
1711     if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset)) {
1712       return applyOffset(Offset.getSExtValue());
1713     } else {
1714       return nullptr;
1715     }
1716   } else if (auto *BI = dyn_cast<BinaryOperator>(&I)) {
1717     // Rewrite binary operations with constant integer operands.
1718     auto *ConstInt = dyn_cast<ConstantInt>(I.getOperand(1));
1719     if (!ConstInt || ConstInt->getBitWidth() > 64)
1720       return nullptr;
1721 
1722     uint64_t Val = ConstInt->getSExtValue();
1723     switch (BI->getOpcode()) {
1724     case Instruction::Add:
1725       return applyOffset(Val);
1726     case Instruction::Sub:
1727       return applyOffset(-int64_t(Val));
1728     case Instruction::Mul:
1729       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mul});
1730     case Instruction::SDiv:
1731       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_div});
1732     case Instruction::SRem:
1733       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mod});
1734     case Instruction::Or:
1735       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_or});
1736     case Instruction::And:
1737       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_and});
1738     case Instruction::Xor:
1739       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_xor});
1740     case Instruction::Shl:
1741       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shl});
1742     case Instruction::LShr:
1743       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shr});
1744     case Instruction::AShr:
1745       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shra});
1746     default:
1747       // TODO: Salvage constants from each kind of binop we know about.
1748       return nullptr;
1749     }
1750     // *Not* to do: we should not attempt to salvage load instructions,
1751     // because the validity and lifetime of a dbg.value containing
1752     // DW_OP_deref becomes difficult to analyze. See PR40628 for examples.
1753   }
1754   return nullptr;
1755 }
1756 
1757 /// A replacement for a dbg.value expression.
1758 using DbgValReplacement = Optional<DIExpression *>;
1759 
1760 /// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
1761 /// possibly moving/undefing users to prevent use-before-def. Returns true if
1762 /// changes are made.
1763 static bool rewriteDebugUsers(
1764     Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
1765     function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr) {
1766   // Find debug users of From.
1767   SmallVector<DbgVariableIntrinsic *, 1> Users;
1768   findDbgUsers(Users, &From);
1769   if (Users.empty())
1770     return false;
1771 
1772   // Prevent use-before-def of To.
1773   bool Changed = false;
1774   SmallPtrSet<DbgVariableIntrinsic *, 1> UndefOrSalvage;
1775   if (isa<Instruction>(&To)) {
1776     bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
1777 
1778     for (auto *DII : Users) {
1779       // It's common to see a debug user between From and DomPoint. Move it
1780       // after DomPoint to preserve the variable update without any reordering.
1781       if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
1782         LLVM_DEBUG(dbgs() << "MOVE:  " << *DII << '\n');
1783         DII->moveAfter(&DomPoint);
1784         Changed = true;
1785 
1786       // Users which otherwise aren't dominated by the replacement value must
1787       // be salvaged or deleted.
1788       } else if (!DT.dominates(&DomPoint, DII)) {
1789         UndefOrSalvage.insert(DII);
1790       }
1791     }
1792   }
1793 
1794   // Update debug users without use-before-def risk.
1795   for (auto *DII : Users) {
1796     if (UndefOrSalvage.count(DII))
1797       continue;
1798 
1799     LLVMContext &Ctx = DII->getContext();
1800     DbgValReplacement DVR = RewriteExpr(*DII);
1801     if (!DVR)
1802       continue;
1803 
1804     DII->setOperand(0, wrapValueInMetadata(Ctx, &To));
1805     DII->setOperand(2, MetadataAsValue::get(Ctx, *DVR));
1806     LLVM_DEBUG(dbgs() << "REWRITE:  " << *DII << '\n');
1807     Changed = true;
1808   }
1809 
1810   if (!UndefOrSalvage.empty()) {
1811     // Try to salvage the remaining debug users.
1812     salvageDebugInfoOrMarkUndef(From);
1813     Changed = true;
1814   }
1815 
1816   return Changed;
1817 }
1818 
1819 /// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
1820 /// losslessly preserve the bits and semantics of the value. This predicate is
1821 /// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
1822 ///
1823 /// Note that Type::canLosslesslyBitCastTo is not suitable here because it
1824 /// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
1825 /// and also does not allow lossless pointer <-> integer conversions.
1826 static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
1827                                          Type *ToTy) {
1828   // Trivially compatible types.
1829   if (FromTy == ToTy)
1830     return true;
1831 
1832   // Handle compatible pointer <-> integer conversions.
1833   if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
1834     bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
1835     bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
1836                               !DL.isNonIntegralPointerType(ToTy);
1837     return SameSize && LosslessConversion;
1838   }
1839 
1840   // TODO: This is not exhaustive.
1841   return false;
1842 }
1843 
1844 bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
1845                                  Instruction &DomPoint, DominatorTree &DT) {
1846   // Exit early if From has no debug users.
1847   if (!From.isUsedByMetadata())
1848     return false;
1849 
1850   assert(&From != &To && "Can't replace something with itself");
1851 
1852   Type *FromTy = From.getType();
1853   Type *ToTy = To.getType();
1854 
1855   auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
1856     return DII.getExpression();
1857   };
1858 
1859   // Handle no-op conversions.
1860   Module &M = *From.getModule();
1861   const DataLayout &DL = M.getDataLayout();
1862   if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
1863     return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
1864 
1865   // Handle integer-to-integer widening and narrowing.
1866   // FIXME: Use DW_OP_convert when it's available everywhere.
1867   if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
1868     uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
1869     uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
1870     assert(FromBits != ToBits && "Unexpected no-op conversion");
1871 
1872     // When the width of the result grows, assume that a debugger will only
1873     // access the low `FromBits` bits when inspecting the source variable.
1874     if (FromBits < ToBits)
1875       return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
1876 
1877     // The width of the result has shrunk. Use sign/zero extension to describe
1878     // the source variable's high bits.
1879     auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
1880       DILocalVariable *Var = DII.getVariable();
1881 
1882       // Without knowing signedness, sign/zero extension isn't possible.
1883       auto Signedness = Var->getSignedness();
1884       if (!Signedness)
1885         return None;
1886 
1887       bool Signed = *Signedness == DIBasicType::Signedness::Signed;
1888       return DIExpression::appendExt(DII.getExpression(), ToBits, FromBits,
1889                                      Signed);
1890     };
1891     return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt);
1892   }
1893 
1894   // TODO: Floating-point conversions, vectors.
1895   return false;
1896 }
1897 
1898 unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
1899   unsigned NumDeadInst = 0;
1900   // Delete the instructions backwards, as it has a reduced likelihood of
1901   // having to update as many def-use and use-def chains.
1902   Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1903   while (EndInst != &BB->front()) {
1904     // Delete the next to last instruction.
1905     Instruction *Inst = &*--EndInst->getIterator();
1906     if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
1907       Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1908     if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
1909       EndInst = Inst;
1910       continue;
1911     }
1912     if (!isa<DbgInfoIntrinsic>(Inst))
1913       ++NumDeadInst;
1914     Inst->eraseFromParent();
1915   }
1916   return NumDeadInst;
1917 }
1918 
1919 unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
1920                                    bool PreserveLCSSA, DomTreeUpdater *DTU,
1921                                    MemorySSAUpdater *MSSAU) {
1922   BasicBlock *BB = I->getParent();
1923   std::vector <DominatorTree::UpdateType> Updates;
1924 
1925   if (MSSAU)
1926     MSSAU->changeToUnreachable(I);
1927 
1928   // Loop over all of the successors, removing BB's entry from any PHI
1929   // nodes.
1930   if (DTU)
1931     Updates.reserve(BB->getTerminator()->getNumSuccessors());
1932   for (BasicBlock *Successor : successors(BB)) {
1933     Successor->removePredecessor(BB, PreserveLCSSA);
1934     if (DTU)
1935       Updates.push_back({DominatorTree::Delete, BB, Successor});
1936   }
1937   // Insert a call to llvm.trap right before this.  This turns the undefined
1938   // behavior into a hard fail instead of falling through into random code.
1939   if (UseLLVMTrap) {
1940     Function *TrapFn =
1941       Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
1942     CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
1943     CallTrap->setDebugLoc(I->getDebugLoc());
1944   }
1945   auto *UI = new UnreachableInst(I->getContext(), I);
1946   UI->setDebugLoc(I->getDebugLoc());
1947 
1948   // All instructions after this are dead.
1949   unsigned NumInstrsRemoved = 0;
1950   BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
1951   while (BBI != BBE) {
1952     if (!BBI->use_empty())
1953       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
1954     BB->getInstList().erase(BBI++);
1955     ++NumInstrsRemoved;
1956   }
1957   if (DTU)
1958     DTU->applyUpdatesPermissive(Updates);
1959   return NumInstrsRemoved;
1960 }
1961 
1962 CallInst *llvm::createCallMatchingInvoke(InvokeInst *II) {
1963   SmallVector<Value *, 8> Args(II->arg_begin(), II->arg_end());
1964   SmallVector<OperandBundleDef, 1> OpBundles;
1965   II->getOperandBundlesAsDefs(OpBundles);
1966   CallInst *NewCall = CallInst::Create(II->getFunctionType(),
1967                                        II->getCalledValue(), Args, OpBundles);
1968   NewCall->setCallingConv(II->getCallingConv());
1969   NewCall->setAttributes(II->getAttributes());
1970   NewCall->setDebugLoc(II->getDebugLoc());
1971   NewCall->copyMetadata(*II);
1972   return NewCall;
1973 }
1974 
1975 /// changeToCall - Convert the specified invoke into a normal call.
1976 void llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) {
1977   CallInst *NewCall = createCallMatchingInvoke(II);
1978   NewCall->takeName(II);
1979   NewCall->insertBefore(II);
1980   II->replaceAllUsesWith(NewCall);
1981 
1982   // Follow the call by a branch to the normal destination.
1983   BasicBlock *NormalDestBB = II->getNormalDest();
1984   BranchInst::Create(NormalDestBB, II);
1985 
1986   // Update PHI nodes in the unwind destination
1987   BasicBlock *BB = II->getParent();
1988   BasicBlock *UnwindDestBB = II->getUnwindDest();
1989   UnwindDestBB->removePredecessor(BB);
1990   II->eraseFromParent();
1991   if (DTU)
1992     DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDestBB}});
1993 }
1994 
1995 BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
1996                                                    BasicBlock *UnwindEdge) {
1997   BasicBlock *BB = CI->getParent();
1998 
1999   // Convert this function call into an invoke instruction.  First, split the
2000   // basic block.
2001   BasicBlock *Split =
2002       BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
2003 
2004   // Delete the unconditional branch inserted by splitBasicBlock
2005   BB->getInstList().pop_back();
2006 
2007   // Create the new invoke instruction.
2008   SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
2009   SmallVector<OperandBundleDef, 1> OpBundles;
2010 
2011   CI->getOperandBundlesAsDefs(OpBundles);
2012 
2013   // Note: we're round tripping operand bundles through memory here, and that
2014   // can potentially be avoided with a cleverer API design that we do not have
2015   // as of this time.
2016 
2017   InvokeInst *II =
2018       InvokeInst::Create(CI->getFunctionType(), CI->getCalledValue(), Split,
2019                          UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);
2020   II->setDebugLoc(CI->getDebugLoc());
2021   II->setCallingConv(CI->getCallingConv());
2022   II->setAttributes(CI->getAttributes());
2023 
2024   // Make sure that anything using the call now uses the invoke!  This also
2025   // updates the CallGraph if present, because it uses a WeakTrackingVH.
2026   CI->replaceAllUsesWith(II);
2027 
2028   // Delete the original call
2029   Split->getInstList().pop_front();
2030   return Split;
2031 }
2032 
2033 static bool markAliveBlocks(Function &F,
2034                             SmallPtrSetImpl<BasicBlock *> &Reachable,
2035                             DomTreeUpdater *DTU = nullptr) {
2036   SmallVector<BasicBlock*, 128> Worklist;
2037   BasicBlock *BB = &F.front();
2038   Worklist.push_back(BB);
2039   Reachable.insert(BB);
2040   bool Changed = false;
2041   do {
2042     BB = Worklist.pop_back_val();
2043 
2044     // Do a quick scan of the basic block, turning any obviously unreachable
2045     // instructions into LLVM unreachable insts.  The instruction combining pass
2046     // canonicalizes unreachable insts into stores to null or undef.
2047     for (Instruction &I : *BB) {
2048       if (auto *CI = dyn_cast<CallInst>(&I)) {
2049         Value *Callee = CI->getCalledValue();
2050         // Handle intrinsic calls.
2051         if (Function *F = dyn_cast<Function>(Callee)) {
2052           auto IntrinsicID = F->getIntrinsicID();
2053           // Assumptions that are known to be false are equivalent to
2054           // unreachable. Also, if the condition is undefined, then we make the
2055           // choice most beneficial to the optimizer, and choose that to also be
2056           // unreachable.
2057           if (IntrinsicID == Intrinsic::assume) {
2058             if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
2059               // Don't insert a call to llvm.trap right before the unreachable.
2060               changeToUnreachable(CI, false, false, DTU);
2061               Changed = true;
2062               break;
2063             }
2064           } else if (IntrinsicID == Intrinsic::experimental_guard) {
2065             // A call to the guard intrinsic bails out of the current
2066             // compilation unit if the predicate passed to it is false. If the
2067             // predicate is a constant false, then we know the guard will bail
2068             // out of the current compile unconditionally, so all code following
2069             // it is dead.
2070             //
2071             // Note: unlike in llvm.assume, it is not "obviously profitable" for
2072             // guards to treat `undef` as `false` since a guard on `undef` can
2073             // still be useful for widening.
2074             if (match(CI->getArgOperand(0), m_Zero()))
2075               if (!isa<UnreachableInst>(CI->getNextNode())) {
2076                 changeToUnreachable(CI->getNextNode(), /*UseLLVMTrap=*/false,
2077                                     false, DTU);
2078                 Changed = true;
2079                 break;
2080               }
2081           }
2082         } else if ((isa<ConstantPointerNull>(Callee) &&
2083                     !NullPointerIsDefined(CI->getFunction())) ||
2084                    isa<UndefValue>(Callee)) {
2085           changeToUnreachable(CI, /*UseLLVMTrap=*/false, false, DTU);
2086           Changed = true;
2087           break;
2088         }
2089         if (CI->doesNotReturn() && !CI->isMustTailCall()) {
2090           // If we found a call to a no-return function, insert an unreachable
2091           // instruction after it.  Make sure there isn't *already* one there
2092           // though.
2093           if (!isa<UnreachableInst>(CI->getNextNode())) {
2094             // Don't insert a call to llvm.trap right before the unreachable.
2095             changeToUnreachable(CI->getNextNode(), false, false, DTU);
2096             Changed = true;
2097           }
2098           break;
2099         }
2100       } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
2101         // Store to undef and store to null are undefined and used to signal
2102         // that they should be changed to unreachable by passes that can't
2103         // modify the CFG.
2104 
2105         // Don't touch volatile stores.
2106         if (SI->isVolatile()) continue;
2107 
2108         Value *Ptr = SI->getOperand(1);
2109 
2110         if (isa<UndefValue>(Ptr) ||
2111             (isa<ConstantPointerNull>(Ptr) &&
2112              !NullPointerIsDefined(SI->getFunction(),
2113                                    SI->getPointerAddressSpace()))) {
2114           changeToUnreachable(SI, true, false, DTU);
2115           Changed = true;
2116           break;
2117         }
2118       }
2119     }
2120 
2121     Instruction *Terminator = BB->getTerminator();
2122     if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
2123       // Turn invokes that call 'nounwind' functions into ordinary calls.
2124       Value *Callee = II->getCalledValue();
2125       if ((isa<ConstantPointerNull>(Callee) &&
2126            !NullPointerIsDefined(BB->getParent())) ||
2127           isa<UndefValue>(Callee)) {
2128         changeToUnreachable(II, true, false, DTU);
2129         Changed = true;
2130       } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
2131         if (II->use_empty() && II->onlyReadsMemory()) {
2132           // jump to the normal destination branch.
2133           BasicBlock *NormalDestBB = II->getNormalDest();
2134           BasicBlock *UnwindDestBB = II->getUnwindDest();
2135           BranchInst::Create(NormalDestBB, II);
2136           UnwindDestBB->removePredecessor(II->getParent());
2137           II->eraseFromParent();
2138           if (DTU)
2139             DTU->applyUpdatesPermissive(
2140                 {{DominatorTree::Delete, BB, UnwindDestBB}});
2141         } else
2142           changeToCall(II, DTU);
2143         Changed = true;
2144       }
2145     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
2146       // Remove catchpads which cannot be reached.
2147       struct CatchPadDenseMapInfo {
2148         static CatchPadInst *getEmptyKey() {
2149           return DenseMapInfo<CatchPadInst *>::getEmptyKey();
2150         }
2151 
2152         static CatchPadInst *getTombstoneKey() {
2153           return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
2154         }
2155 
2156         static unsigned getHashValue(CatchPadInst *CatchPad) {
2157           return static_cast<unsigned>(hash_combine_range(
2158               CatchPad->value_op_begin(), CatchPad->value_op_end()));
2159         }
2160 
2161         static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
2162           if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
2163               RHS == getEmptyKey() || RHS == getTombstoneKey())
2164             return LHS == RHS;
2165           return LHS->isIdenticalTo(RHS);
2166         }
2167       };
2168 
2169       // Set of unique CatchPads.
2170       SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
2171                     CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
2172           HandlerSet;
2173       detail::DenseSetEmpty Empty;
2174       for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
2175                                              E = CatchSwitch->handler_end();
2176            I != E; ++I) {
2177         BasicBlock *HandlerBB = *I;
2178         auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
2179         if (!HandlerSet.insert({CatchPad, Empty}).second) {
2180           CatchSwitch->removeHandler(I);
2181           --I;
2182           --E;
2183           Changed = true;
2184         }
2185       }
2186     }
2187 
2188     Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
2189     for (BasicBlock *Successor : successors(BB))
2190       if (Reachable.insert(Successor).second)
2191         Worklist.push_back(Successor);
2192   } while (!Worklist.empty());
2193   return Changed;
2194 }
2195 
2196 void llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
2197   Instruction *TI = BB->getTerminator();
2198 
2199   if (auto *II = dyn_cast<InvokeInst>(TI)) {
2200     changeToCall(II, DTU);
2201     return;
2202   }
2203 
2204   Instruction *NewTI;
2205   BasicBlock *UnwindDest;
2206 
2207   if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
2208     NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
2209     UnwindDest = CRI->getUnwindDest();
2210   } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
2211     auto *NewCatchSwitch = CatchSwitchInst::Create(
2212         CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
2213         CatchSwitch->getName(), CatchSwitch);
2214     for (BasicBlock *PadBB : CatchSwitch->handlers())
2215       NewCatchSwitch->addHandler(PadBB);
2216 
2217     NewTI = NewCatchSwitch;
2218     UnwindDest = CatchSwitch->getUnwindDest();
2219   } else {
2220     llvm_unreachable("Could not find unwind successor");
2221   }
2222 
2223   NewTI->takeName(TI);
2224   NewTI->setDebugLoc(TI->getDebugLoc());
2225   UnwindDest->removePredecessor(BB);
2226   TI->replaceAllUsesWith(NewTI);
2227   TI->eraseFromParent();
2228   if (DTU)
2229     DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDest}});
2230 }
2231 
2232 /// removeUnreachableBlocks - Remove blocks that are not reachable, even
2233 /// if they are in a dead cycle.  Return true if a change was made, false
2234 /// otherwise.
2235 bool llvm::removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
2236                                    MemorySSAUpdater *MSSAU) {
2237   SmallPtrSet<BasicBlock *, 16> Reachable;
2238   bool Changed = markAliveBlocks(F, Reachable, DTU);
2239 
2240   // If there are unreachable blocks in the CFG...
2241   if (Reachable.size() == F.size())
2242     return Changed;
2243 
2244   assert(Reachable.size() < F.size());
2245   NumRemoved += F.size() - Reachable.size();
2246 
2247   SmallSetVector<BasicBlock *, 8> DeadBlockSet;
2248   for (BasicBlock &BB : F) {
2249     // Skip reachable basic blocks
2250     if (Reachable.find(&BB) != Reachable.end())
2251       continue;
2252     DeadBlockSet.insert(&BB);
2253   }
2254 
2255   if (MSSAU)
2256     MSSAU->removeBlocks(DeadBlockSet);
2257 
2258   // Loop over all of the basic blocks that are not reachable, dropping all of
2259   // their internal references. Update DTU if available.
2260   std::vector<DominatorTree::UpdateType> Updates;
2261   for (auto *BB : DeadBlockSet) {
2262     for (BasicBlock *Successor : successors(BB)) {
2263       if (!DeadBlockSet.count(Successor))
2264         Successor->removePredecessor(BB);
2265       if (DTU)
2266         Updates.push_back({DominatorTree::Delete, BB, Successor});
2267     }
2268     BB->dropAllReferences();
2269     if (DTU) {
2270       Instruction *TI = BB->getTerminator();
2271       assert(TI && "Basic block should have a terminator");
2272       // Terminators like invoke can have users. We have to replace their users,
2273       // before removing them.
2274       if (!TI->use_empty())
2275         TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
2276       TI->eraseFromParent();
2277       new UnreachableInst(BB->getContext(), BB);
2278       assert(succ_empty(BB) && "The successor list of BB isn't empty before "
2279                                "applying corresponding DTU updates.");
2280     }
2281   }
2282 
2283   if (DTU) {
2284     DTU->applyUpdatesPermissive(Updates);
2285     bool Deleted = false;
2286     for (auto *BB : DeadBlockSet) {
2287       if (DTU->isBBPendingDeletion(BB))
2288         --NumRemoved;
2289       else
2290         Deleted = true;
2291       DTU->deleteBB(BB);
2292     }
2293     if (!Deleted)
2294       return false;
2295   } else {
2296     for (auto *BB : DeadBlockSet)
2297       BB->eraseFromParent();
2298   }
2299 
2300   return true;
2301 }
2302 
2303 void llvm::combineMetadata(Instruction *K, const Instruction *J,
2304                            ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
2305   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
2306   K->dropUnknownNonDebugMetadata(KnownIDs);
2307   K->getAllMetadataOtherThanDebugLoc(Metadata);
2308   for (const auto &MD : Metadata) {
2309     unsigned Kind = MD.first;
2310     MDNode *JMD = J->getMetadata(Kind);
2311     MDNode *KMD = MD.second;
2312 
2313     switch (Kind) {
2314       default:
2315         K->setMetadata(Kind, nullptr); // Remove unknown metadata
2316         break;
2317       case LLVMContext::MD_dbg:
2318         llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
2319       case LLVMContext::MD_tbaa:
2320         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2321         break;
2322       case LLVMContext::MD_alias_scope:
2323         K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
2324         break;
2325       case LLVMContext::MD_noalias:
2326       case LLVMContext::MD_mem_parallel_loop_access:
2327         K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
2328         break;
2329       case LLVMContext::MD_access_group:
2330         K->setMetadata(LLVMContext::MD_access_group,
2331                        intersectAccessGroups(K, J));
2332         break;
2333       case LLVMContext::MD_range:
2334 
2335         // If K does move, use most generic range. Otherwise keep the range of
2336         // K.
2337         if (DoesKMove)
2338           // FIXME: If K does move, we should drop the range info and nonnull.
2339           //        Currently this function is used with DoesKMove in passes
2340           //        doing hoisting/sinking and the current behavior of using the
2341           //        most generic range is correct in those cases.
2342           K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
2343         break;
2344       case LLVMContext::MD_fpmath:
2345         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2346         break;
2347       case LLVMContext::MD_invariant_load:
2348         // Only set the !invariant.load if it is present in both instructions.
2349         K->setMetadata(Kind, JMD);
2350         break;
2351       case LLVMContext::MD_nonnull:
2352         // If K does move, keep nonull if it is present in both instructions.
2353         if (DoesKMove)
2354           K->setMetadata(Kind, JMD);
2355         break;
2356       case LLVMContext::MD_invariant_group:
2357         // Preserve !invariant.group in K.
2358         break;
2359       case LLVMContext::MD_align:
2360         K->setMetadata(Kind,
2361           MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2362         break;
2363       case LLVMContext::MD_dereferenceable:
2364       case LLVMContext::MD_dereferenceable_or_null:
2365         K->setMetadata(Kind,
2366           MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2367         break;
2368       case LLVMContext::MD_preserve_access_index:
2369         // Preserve !preserve.access.index in K.
2370         break;
2371     }
2372   }
2373   // Set !invariant.group from J if J has it. If both instructions have it
2374   // then we will just pick it from J - even when they are different.
2375   // Also make sure that K is load or store - f.e. combining bitcast with load
2376   // could produce bitcast with invariant.group metadata, which is invalid.
2377   // FIXME: we should try to preserve both invariant.group md if they are
2378   // different, but right now instruction can only have one invariant.group.
2379   if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
2380     if (isa<LoadInst>(K) || isa<StoreInst>(K))
2381       K->setMetadata(LLVMContext::MD_invariant_group, JMD);
2382 }
2383 
2384 void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
2385                                  bool KDominatesJ) {
2386   unsigned KnownIDs[] = {
2387       LLVMContext::MD_tbaa,            LLVMContext::MD_alias_scope,
2388       LLVMContext::MD_noalias,         LLVMContext::MD_range,
2389       LLVMContext::MD_invariant_load,  LLVMContext::MD_nonnull,
2390       LLVMContext::MD_invariant_group, LLVMContext::MD_align,
2391       LLVMContext::MD_dereferenceable,
2392       LLVMContext::MD_dereferenceable_or_null,
2393       LLVMContext::MD_access_group,    LLVMContext::MD_preserve_access_index};
2394   combineMetadata(K, J, KnownIDs, KDominatesJ);
2395 }
2396 
2397 void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) {
2398   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
2399   Source.getAllMetadata(MD);
2400   MDBuilder MDB(Dest.getContext());
2401   Type *NewType = Dest.getType();
2402   const DataLayout &DL = Source.getModule()->getDataLayout();
2403   for (const auto &MDPair : MD) {
2404     unsigned ID = MDPair.first;
2405     MDNode *N = MDPair.second;
2406     // Note, essentially every kind of metadata should be preserved here! This
2407     // routine is supposed to clone a load instruction changing *only its type*.
2408     // The only metadata it makes sense to drop is metadata which is invalidated
2409     // when the pointer type changes. This should essentially never be the case
2410     // in LLVM, but we explicitly switch over only known metadata to be
2411     // conservatively correct. If you are adding metadata to LLVM which pertains
2412     // to loads, you almost certainly want to add it here.
2413     switch (ID) {
2414     case LLVMContext::MD_dbg:
2415     case LLVMContext::MD_tbaa:
2416     case LLVMContext::MD_prof:
2417     case LLVMContext::MD_fpmath:
2418     case LLVMContext::MD_tbaa_struct:
2419     case LLVMContext::MD_invariant_load:
2420     case LLVMContext::MD_alias_scope:
2421     case LLVMContext::MD_noalias:
2422     case LLVMContext::MD_nontemporal:
2423     case LLVMContext::MD_mem_parallel_loop_access:
2424     case LLVMContext::MD_access_group:
2425       // All of these directly apply.
2426       Dest.setMetadata(ID, N);
2427       break;
2428 
2429     case LLVMContext::MD_nonnull:
2430       copyNonnullMetadata(Source, N, Dest);
2431       break;
2432 
2433     case LLVMContext::MD_align:
2434     case LLVMContext::MD_dereferenceable:
2435     case LLVMContext::MD_dereferenceable_or_null:
2436       // These only directly apply if the new type is also a pointer.
2437       if (NewType->isPointerTy())
2438         Dest.setMetadata(ID, N);
2439       break;
2440 
2441     case LLVMContext::MD_range:
2442       copyRangeMetadata(DL, Source, N, Dest);
2443       break;
2444     }
2445   }
2446 }
2447 
2448 void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
2449   auto *ReplInst = dyn_cast<Instruction>(Repl);
2450   if (!ReplInst)
2451     return;
2452 
2453   // Patch the replacement so that it is not more restrictive than the value
2454   // being replaced.
2455   // Note that if 'I' is a load being replaced by some operation,
2456   // for example, by an arithmetic operation, then andIRFlags()
2457   // would just erase all math flags from the original arithmetic
2458   // operation, which is clearly not wanted and not needed.
2459   if (!isa<LoadInst>(I))
2460     ReplInst->andIRFlags(I);
2461 
2462   // FIXME: If both the original and replacement value are part of the
2463   // same control-flow region (meaning that the execution of one
2464   // guarantees the execution of the other), then we can combine the
2465   // noalias scopes here and do better than the general conservative
2466   // answer used in combineMetadata().
2467 
2468   // In general, GVN unifies expressions over different control-flow
2469   // regions, and so we need a conservative combination of the noalias
2470   // scopes.
2471   static const unsigned KnownIDs[] = {
2472       LLVMContext::MD_tbaa,            LLVMContext::MD_alias_scope,
2473       LLVMContext::MD_noalias,         LLVMContext::MD_range,
2474       LLVMContext::MD_fpmath,          LLVMContext::MD_invariant_load,
2475       LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull,
2476       LLVMContext::MD_access_group,    LLVMContext::MD_preserve_access_index};
2477   combineMetadata(ReplInst, I, KnownIDs, false);
2478 }
2479 
2480 template <typename RootType, typename DominatesFn>
2481 static unsigned replaceDominatedUsesWith(Value *From, Value *To,
2482                                          const RootType &Root,
2483                                          const DominatesFn &Dominates) {
2484   assert(From->getType() == To->getType());
2485 
2486   unsigned Count = 0;
2487   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2488        UI != UE;) {
2489     Use &U = *UI++;
2490     if (!Dominates(Root, U))
2491       continue;
2492     U.set(To);
2493     LLVM_DEBUG(dbgs() << "Replace dominated use of '" << From->getName()
2494                       << "' as " << *To << " in " << *U << "\n");
2495     ++Count;
2496   }
2497   return Count;
2498 }
2499 
2500 unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
2501    assert(From->getType() == To->getType());
2502    auto *BB = From->getParent();
2503    unsigned Count = 0;
2504 
2505   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2506        UI != UE;) {
2507     Use &U = *UI++;
2508     auto *I = cast<Instruction>(U.getUser());
2509     if (I->getParent() == BB)
2510       continue;
2511     U.set(To);
2512     ++Count;
2513   }
2514   return Count;
2515 }
2516 
2517 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2518                                         DominatorTree &DT,
2519                                         const BasicBlockEdge &Root) {
2520   auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
2521     return DT.dominates(Root, U);
2522   };
2523   return ::replaceDominatedUsesWith(From, To, Root, Dominates);
2524 }
2525 
2526 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2527                                         DominatorTree &DT,
2528                                         const BasicBlock *BB) {
2529   auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) {
2530     auto *I = cast<Instruction>(U.getUser())->getParent();
2531     return DT.properlyDominates(BB, I);
2532   };
2533   return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates);
2534 }
2535 
2536 bool llvm::callsGCLeafFunction(const CallBase *Call,
2537                                const TargetLibraryInfo &TLI) {
2538   // Check if the function is specifically marked as a gc leaf function.
2539   if (Call->hasFnAttr("gc-leaf-function"))
2540     return true;
2541   if (const Function *F = Call->getCalledFunction()) {
2542     if (F->hasFnAttribute("gc-leaf-function"))
2543       return true;
2544 
2545     if (auto IID = F->getIntrinsicID())
2546       // Most LLVM intrinsics do not take safepoints.
2547       return IID != Intrinsic::experimental_gc_statepoint &&
2548              IID != Intrinsic::experimental_deoptimize;
2549   }
2550 
2551   // Lib calls can be materialized by some passes, and won't be
2552   // marked as 'gc-leaf-function.' All available Libcalls are
2553   // GC-leaf.
2554   LibFunc LF;
2555   if (TLI.getLibFunc(ImmutableCallSite(Call), LF)) {
2556     return TLI.has(LF);
2557   }
2558 
2559   return false;
2560 }
2561 
2562 void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
2563                                LoadInst &NewLI) {
2564   auto *NewTy = NewLI.getType();
2565 
2566   // This only directly applies if the new type is also a pointer.
2567   if (NewTy->isPointerTy()) {
2568     NewLI.setMetadata(LLVMContext::MD_nonnull, N);
2569     return;
2570   }
2571 
2572   // The only other translation we can do is to integral loads with !range
2573   // metadata.
2574   if (!NewTy->isIntegerTy())
2575     return;
2576 
2577   MDBuilder MDB(NewLI.getContext());
2578   const Value *Ptr = OldLI.getPointerOperand();
2579   auto *ITy = cast<IntegerType>(NewTy);
2580   auto *NullInt = ConstantExpr::getPtrToInt(
2581       ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
2582   auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
2583   NewLI.setMetadata(LLVMContext::MD_range,
2584                     MDB.createRange(NonNullInt, NullInt));
2585 }
2586 
2587 void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
2588                              MDNode *N, LoadInst &NewLI) {
2589   auto *NewTy = NewLI.getType();
2590 
2591   // Give up unless it is converted to a pointer where there is a single very
2592   // valuable mapping we can do reliably.
2593   // FIXME: It would be nice to propagate this in more ways, but the type
2594   // conversions make it hard.
2595   if (!NewTy->isPointerTy())
2596     return;
2597 
2598   unsigned BitWidth = DL.getPointerTypeSizeInBits(NewTy);
2599   if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
2600     MDNode *NN = MDNode::get(OldLI.getContext(), None);
2601     NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
2602   }
2603 }
2604 
2605 void llvm::dropDebugUsers(Instruction &I) {
2606   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
2607   findDbgUsers(DbgUsers, &I);
2608   for (auto *DII : DbgUsers)
2609     DII->eraseFromParent();
2610 }
2611 
2612 void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
2613                                     BasicBlock *BB) {
2614   // Since we are moving the instructions out of its basic block, we do not
2615   // retain their original debug locations (DILocations) and debug intrinsic
2616   // instructions.
2617   //
2618   // Doing so would degrade the debugging experience and adversely affect the
2619   // accuracy of profiling information.
2620   //
2621   // Currently, when hoisting the instructions, we take the following actions:
2622   // - Remove their debug intrinsic instructions.
2623   // - Set their debug locations to the values from the insertion point.
2624   //
2625   // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
2626   // need to be deleted, is because there will not be any instructions with a
2627   // DILocation in either branch left after performing the transformation. We
2628   // can only insert a dbg.value after the two branches are joined again.
2629   //
2630   // See PR38762, PR39243 for more details.
2631   //
2632   // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
2633   // encode predicated DIExpressions that yield different results on different
2634   // code paths.
2635   for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
2636     Instruction *I = &*II;
2637     I->dropUnknownNonDebugMetadata();
2638     if (I->isUsedByMetadata())
2639       dropDebugUsers(*I);
2640     if (isa<DbgInfoIntrinsic>(I)) {
2641       // Remove DbgInfo Intrinsics.
2642       II = I->eraseFromParent();
2643       continue;
2644     }
2645     I->setDebugLoc(InsertPt->getDebugLoc());
2646     ++II;
2647   }
2648   DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(),
2649                                  BB->begin(),
2650                                  BB->getTerminator()->getIterator());
2651 }
2652 
2653 namespace {
2654 
2655 /// A potential constituent of a bitreverse or bswap expression. See
2656 /// collectBitParts for a fuller explanation.
2657 struct BitPart {
2658   BitPart(Value *P, unsigned BW) : Provider(P) {
2659     Provenance.resize(BW);
2660   }
2661 
2662   /// The Value that this is a bitreverse/bswap of.
2663   Value *Provider;
2664 
2665   /// The "provenance" of each bit. Provenance[A] = B means that bit A
2666   /// in Provider becomes bit B in the result of this expression.
2667   SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
2668 
2669   enum { Unset = -1 };
2670 };
2671 
2672 } // end anonymous namespace
2673 
2674 /// Analyze the specified subexpression and see if it is capable of providing
2675 /// pieces of a bswap or bitreverse. The subexpression provides a potential
2676 /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
2677 /// the output of the expression came from a corresponding bit in some other
2678 /// value. This function is recursive, and the end result is a mapping of
2679 /// bitnumber to bitnumber. It is the caller's responsibility to validate that
2680 /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
2681 ///
2682 /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
2683 /// that the expression deposits the low byte of %X into the high byte of the
2684 /// result and that all other bits are zero. This expression is accepted and a
2685 /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
2686 /// [0-7].
2687 ///
2688 /// To avoid revisiting values, the BitPart results are memoized into the
2689 /// provided map. To avoid unnecessary copying of BitParts, BitParts are
2690 /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
2691 /// store BitParts objects, not pointers. As we need the concept of a nullptr
2692 /// BitParts (Value has been analyzed and the analysis failed), we an Optional
2693 /// type instead to provide the same functionality.
2694 ///
2695 /// Because we pass around references into \c BPS, we must use a container that
2696 /// does not invalidate internal references (std::map instead of DenseMap).
2697 static const Optional<BitPart> &
2698 collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
2699                 std::map<Value *, Optional<BitPart>> &BPS, int Depth) {
2700   auto I = BPS.find(V);
2701   if (I != BPS.end())
2702     return I->second;
2703 
2704   auto &Result = BPS[V] = None;
2705   auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2706 
2707   // Prevent stack overflow by limiting the recursion depth
2708   if (Depth == BitPartRecursionMaxDepth) {
2709     LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n");
2710     return Result;
2711   }
2712 
2713   if (Instruction *I = dyn_cast<Instruction>(V)) {
2714     // If this is an or instruction, it may be an inner node of the bswap.
2715     if (I->getOpcode() == Instruction::Or) {
2716       auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
2717                                 MatchBitReversals, BPS, Depth + 1);
2718       auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
2719                                 MatchBitReversals, BPS, Depth + 1);
2720       if (!A || !B)
2721         return Result;
2722 
2723       // Try and merge the two together.
2724       if (!A->Provider || A->Provider != B->Provider)
2725         return Result;
2726 
2727       Result = BitPart(A->Provider, BitWidth);
2728       for (unsigned i = 0; i < A->Provenance.size(); ++i) {
2729         if (A->Provenance[i] != BitPart::Unset &&
2730             B->Provenance[i] != BitPart::Unset &&
2731             A->Provenance[i] != B->Provenance[i])
2732           return Result = None;
2733 
2734         if (A->Provenance[i] == BitPart::Unset)
2735           Result->Provenance[i] = B->Provenance[i];
2736         else
2737           Result->Provenance[i] = A->Provenance[i];
2738       }
2739 
2740       return Result;
2741     }
2742 
2743     // If this is a logical shift by a constant, recurse then shift the result.
2744     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
2745       unsigned BitShift =
2746           cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
2747       // Ensure the shift amount is defined.
2748       if (BitShift > BitWidth)
2749         return Result;
2750 
2751       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
2752                                   MatchBitReversals, BPS, Depth + 1);
2753       if (!Res)
2754         return Result;
2755       Result = Res;
2756 
2757       // Perform the "shift" on BitProvenance.
2758       auto &P = Result->Provenance;
2759       if (I->getOpcode() == Instruction::Shl) {
2760         P.erase(std::prev(P.end(), BitShift), P.end());
2761         P.insert(P.begin(), BitShift, BitPart::Unset);
2762       } else {
2763         P.erase(P.begin(), std::next(P.begin(), BitShift));
2764         P.insert(P.end(), BitShift, BitPart::Unset);
2765       }
2766 
2767       return Result;
2768     }
2769 
2770     // If this is a logical 'and' with a mask that clears bits, recurse then
2771     // unset the appropriate bits.
2772     if (I->getOpcode() == Instruction::And &&
2773         isa<ConstantInt>(I->getOperand(1))) {
2774       APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
2775       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
2776 
2777       // Check that the mask allows a multiple of 8 bits for a bswap, for an
2778       // early exit.
2779       unsigned NumMaskedBits = AndMask.countPopulation();
2780       if (!MatchBitReversals && NumMaskedBits % 8 != 0)
2781         return Result;
2782 
2783       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
2784                                   MatchBitReversals, BPS, Depth + 1);
2785       if (!Res)
2786         return Result;
2787       Result = Res;
2788 
2789       for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
2790         // If the AndMask is zero for this bit, clear the bit.
2791         if ((AndMask & Bit) == 0)
2792           Result->Provenance[i] = BitPart::Unset;
2793       return Result;
2794     }
2795 
2796     // If this is a zext instruction zero extend the result.
2797     if (I->getOpcode() == Instruction::ZExt) {
2798       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
2799                                   MatchBitReversals, BPS, Depth + 1);
2800       if (!Res)
2801         return Result;
2802 
2803       Result = BitPart(Res->Provider, BitWidth);
2804       auto NarrowBitWidth =
2805           cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
2806       for (unsigned i = 0; i < NarrowBitWidth; ++i)
2807         Result->Provenance[i] = Res->Provenance[i];
2808       for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
2809         Result->Provenance[i] = BitPart::Unset;
2810       return Result;
2811     }
2812   }
2813 
2814   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
2815   // the input value to the bswap/bitreverse.
2816   Result = BitPart(V, BitWidth);
2817   for (unsigned i = 0; i < BitWidth; ++i)
2818     Result->Provenance[i] = i;
2819   return Result;
2820 }
2821 
2822 static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
2823                                           unsigned BitWidth) {
2824   if (From % 8 != To % 8)
2825     return false;
2826   // Convert from bit indices to byte indices and check for a byte reversal.
2827   From >>= 3;
2828   To >>= 3;
2829   BitWidth >>= 3;
2830   return From == BitWidth - To - 1;
2831 }
2832 
2833 static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
2834                                                unsigned BitWidth) {
2835   return From == BitWidth - To - 1;
2836 }
2837 
2838 bool llvm::recognizeBSwapOrBitReverseIdiom(
2839     Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
2840     SmallVectorImpl<Instruction *> &InsertedInsts) {
2841   if (Operator::getOpcode(I) != Instruction::Or)
2842     return false;
2843   if (!MatchBSwaps && !MatchBitReversals)
2844     return false;
2845   IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
2846   if (!ITy || ITy->getBitWidth() > 128)
2847     return false;   // Can't do vectors or integers > 128 bits.
2848   unsigned BW = ITy->getBitWidth();
2849 
2850   unsigned DemandedBW = BW;
2851   IntegerType *DemandedTy = ITy;
2852   if (I->hasOneUse()) {
2853     if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
2854       DemandedTy = cast<IntegerType>(Trunc->getType());
2855       DemandedBW = DemandedTy->getBitWidth();
2856     }
2857   }
2858 
2859   // Try to find all the pieces corresponding to the bswap.
2860   std::map<Value *, Optional<BitPart>> BPS;
2861   auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0);
2862   if (!Res)
2863     return false;
2864   auto &BitProvenance = Res->Provenance;
2865 
2866   // Now, is the bit permutation correct for a bswap or a bitreverse? We can
2867   // only byteswap values with an even number of bytes.
2868   bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
2869   for (unsigned i = 0; i < DemandedBW; ++i) {
2870     OKForBSwap &=
2871         bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
2872     OKForBitReverse &=
2873         bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
2874   }
2875 
2876   Intrinsic::ID Intrin;
2877   if (OKForBSwap && MatchBSwaps)
2878     Intrin = Intrinsic::bswap;
2879   else if (OKForBitReverse && MatchBitReversals)
2880     Intrin = Intrinsic::bitreverse;
2881   else
2882     return false;
2883 
2884   if (ITy != DemandedTy) {
2885     Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
2886     Value *Provider = Res->Provider;
2887     IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
2888     // We may need to truncate the provider.
2889     if (DemandedTy != ProviderTy) {
2890       auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
2891                                      "trunc", I);
2892       InsertedInsts.push_back(Trunc);
2893       Provider = Trunc;
2894     }
2895     auto *CI = CallInst::Create(F, Provider, "rev", I);
2896     InsertedInsts.push_back(CI);
2897     auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
2898     InsertedInsts.push_back(ExtInst);
2899     return true;
2900   }
2901 
2902   Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
2903   InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
2904   return true;
2905 }
2906 
2907 // CodeGen has special handling for some string functions that may replace
2908 // them with target-specific intrinsics.  Since that'd skip our interceptors
2909 // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
2910 // we mark affected calls as NoBuiltin, which will disable optimization
2911 // in CodeGen.
2912 void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
2913     CallInst *CI, const TargetLibraryInfo *TLI) {
2914   Function *F = CI->getCalledFunction();
2915   LibFunc Func;
2916   if (F && !F->hasLocalLinkage() && F->hasName() &&
2917       TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
2918       !F->doesNotAccessMemory())
2919     CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
2920 }
2921 
2922 bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
2923   // We can't have a PHI with a metadata type.
2924   if (I->getOperand(OpIdx)->getType()->isMetadataTy())
2925     return false;
2926 
2927   // Early exit.
2928   if (!isa<Constant>(I->getOperand(OpIdx)))
2929     return true;
2930 
2931   switch (I->getOpcode()) {
2932   default:
2933     return true;
2934   case Instruction::Call:
2935   case Instruction::Invoke:
2936     // Can't handle inline asm. Skip it.
2937     if (isa<InlineAsm>(ImmutableCallSite(I).getCalledValue()))
2938       return false;
2939     // Many arithmetic intrinsics have no issue taking a
2940     // variable, however it's hard to distingish these from
2941     // specials such as @llvm.frameaddress that require a constant.
2942     if (isa<IntrinsicInst>(I))
2943       return false;
2944 
2945     // Constant bundle operands may need to retain their constant-ness for
2946     // correctness.
2947     if (ImmutableCallSite(I).isBundleOperand(OpIdx))
2948       return false;
2949     return true;
2950   case Instruction::ShuffleVector:
2951     // Shufflevector masks are constant.
2952     return OpIdx != 2;
2953   case Instruction::Switch:
2954   case Instruction::ExtractValue:
2955     // All operands apart from the first are constant.
2956     return OpIdx == 0;
2957   case Instruction::InsertValue:
2958     // All operands apart from the first and the second are constant.
2959     return OpIdx < 2;
2960   case Instruction::Alloca:
2961     // Static allocas (constant size in the entry block) are handled by
2962     // prologue/epilogue insertion so they're free anyway. We definitely don't
2963     // want to make them non-constant.
2964     return !cast<AllocaInst>(I)->isStaticAlloca();
2965   case Instruction::GetElementPtr:
2966     if (OpIdx == 0)
2967       return true;
2968     gep_type_iterator It = gep_type_begin(I);
2969     for (auto E = std::next(It, OpIdx); It != E; ++It)
2970       if (It.isStruct())
2971         return false;
2972     return true;
2973   }
2974 }
2975 
2976 using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
2977 AllocaInst *llvm::findAllocaForValue(Value *V,
2978                                      AllocaForValueMapTy &AllocaForValue) {
2979   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2980     return AI;
2981   // See if we've already calculated (or started to calculate) alloca for a
2982   // given value.
2983   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
2984   if (I != AllocaForValue.end())
2985     return I->second;
2986   // Store 0 while we're calculating alloca for value V to avoid
2987   // infinite recursion if the value references itself.
2988   AllocaForValue[V] = nullptr;
2989   AllocaInst *Res = nullptr;
2990   if (CastInst *CI = dyn_cast<CastInst>(V))
2991     Res = findAllocaForValue(CI->getOperand(0), AllocaForValue);
2992   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
2993     for (Value *IncValue : PN->incoming_values()) {
2994       // Allow self-referencing phi-nodes.
2995       if (IncValue == PN)
2996         continue;
2997       AllocaInst *IncValueAI = findAllocaForValue(IncValue, AllocaForValue);
2998       // AI for incoming values should exist and should all be equal.
2999       if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
3000         return nullptr;
3001       Res = IncValueAI;
3002     }
3003   } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
3004     Res = findAllocaForValue(EP->getPointerOperand(), AllocaForValue);
3005   } else {
3006     LLVM_DEBUG(dbgs() << "Alloca search cancelled on unknown instruction: "
3007                       << *V << "\n");
3008   }
3009   if (Res)
3010     AllocaForValue[V] = Res;
3011   return Res;
3012 }
3013