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