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