12cab237bSDimitry Andric //===- Local.cpp - Functions to perform local transformations -------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This family of functions perform various local transformations to the
11f22ef01cSRoman Divacky // program.
12f22ef01cSRoman Divacky //
13f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
14f22ef01cSRoman Divacky 
15f22ef01cSRoman Divacky #include "llvm/Transforms/Utils/Local.h"
162cab237bSDimitry Andric #include "llvm/ADT/APInt.h"
17f22ef01cSRoman Divacky #include "llvm/ADT/DenseMap.h"
182cab237bSDimitry Andric #include "llvm/ADT/DenseMapInfo.h"
198f0fd8f6SDimitry Andric #include "llvm/ADT/DenseSet.h"
208f0fd8f6SDimitry Andric #include "llvm/ADT/Hashing.h"
212cab237bSDimitry Andric #include "llvm/ADT/None.h"
222cab237bSDimitry Andric #include "llvm/ADT/Optional.h"
23139f7f9bSDimitry Andric #include "llvm/ADT/STLExtras.h"
247d523365SDimitry Andric #include "llvm/ADT/SetVector.h"
25f22ef01cSRoman Divacky #include "llvm/ADT/SmallPtrSet.h"
262cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
27f785676fSDimitry Andric #include "llvm/ADT/Statistic.h"
282cab237bSDimitry Andric #include "llvm/ADT/TinyPtrVector.h"
292cab237bSDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
307d523365SDimitry Andric #include "llvm/Analysis/EHPersonalities.h"
31f22ef01cSRoman Divacky #include "llvm/Analysis/InstructionSimplify.h"
32444ed5c5SDimitry Andric #include "llvm/Analysis/LazyValueInfo.h"
33db17bf38SDimitry Andric #include "llvm/Analysis/MemoryBuiltins.h"
34*b5893f02SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
352cab237bSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
362754fe60SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
37*b5893f02SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
382cab237bSDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
392cab237bSDimitry Andric #include "llvm/IR/Argument.h"
402cab237bSDimitry Andric #include "llvm/IR/Attributes.h"
412cab237bSDimitry Andric #include "llvm/IR/BasicBlock.h"
4291bc56edSDimitry Andric #include "llvm/IR/CFG.h"
432cab237bSDimitry Andric #include "llvm/IR/CallSite.h"
442cab237bSDimitry Andric #include "llvm/IR/Constant.h"
45edd7eaddSDimitry Andric #include "llvm/IR/ConstantRange.h"
46139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
4791bc56edSDimitry Andric #include "llvm/IR/DIBuilder.h"
48139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
492cab237bSDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
502cab237bSDimitry Andric #include "llvm/IR/DebugLoc.h"
51139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
52*b5893f02SDimitry Andric #include "llvm/IR/DomTreeUpdater.h"
5391bc56edSDimitry Andric #include "llvm/IR/Dominators.h"
542cab237bSDimitry Andric #include "llvm/IR/Function.h"
5591bc56edSDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
562cab237bSDimitry Andric #include "llvm/IR/GlobalObject.h"
57139f7f9bSDimitry Andric #include "llvm/IR/IRBuilder.h"
582cab237bSDimitry Andric #include "llvm/IR/InstrTypes.h"
592cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
60139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
61139f7f9bSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
62139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
632cab237bSDimitry Andric #include "llvm/IR/LLVMContext.h"
64139f7f9bSDimitry Andric #include "llvm/IR/MDBuilder.h"
65139f7f9bSDimitry Andric #include "llvm/IR/Metadata.h"
662cab237bSDimitry Andric #include "llvm/IR/Module.h"
67139f7f9bSDimitry Andric #include "llvm/IR/Operator.h"
683ca95b02SDimitry Andric #include "llvm/IR/PatternMatch.h"
692cab237bSDimitry Andric #include "llvm/IR/Type.h"
702cab237bSDimitry Andric #include "llvm/IR/Use.h"
712cab237bSDimitry Andric #include "llvm/IR/User.h"
722cab237bSDimitry Andric #include "llvm/IR/Value.h"
7391bc56edSDimitry Andric #include "llvm/IR/ValueHandle.h"
742cab237bSDimitry Andric #include "llvm/Support/Casting.h"
75f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
762cab237bSDimitry Andric #include "llvm/Support/ErrorHandling.h"
7751690af2SDimitry Andric #include "llvm/Support/KnownBits.h"
78f22ef01cSRoman Divacky #include "llvm/Support/raw_ostream.h"
794ba319b5SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
802cab237bSDimitry Andric #include <algorithm>
812cab237bSDimitry Andric #include <cassert>
822cab237bSDimitry Andric #include <climits>
832cab237bSDimitry Andric #include <cstdint>
842cab237bSDimitry Andric #include <iterator>
852cab237bSDimitry Andric #include <map>
862cab237bSDimitry Andric #include <utility>
872cab237bSDimitry Andric 
88f22ef01cSRoman Divacky using namespace llvm;
893ca95b02SDimitry Andric using namespace llvm::PatternMatch;
90f22ef01cSRoman Divacky 
9191bc56edSDimitry Andric #define DEBUG_TYPE "local"
9291bc56edSDimitry Andric 
93f785676fSDimitry Andric STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
94f785676fSDimitry Andric 
95f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
96f22ef01cSRoman Divacky //  Local constant propagation.
97f22ef01cSRoman Divacky //
98f22ef01cSRoman Divacky 
99bd5abe19SDimitry Andric /// ConstantFoldTerminator - If a terminator instruction is predicated on a
100bd5abe19SDimitry Andric /// constant value, convert it into an unconditional branch to the constant
101bd5abe19SDimitry Andric /// destination.  This is a nontrivial operation because the successors of this
102bd5abe19SDimitry Andric /// basic block must have their PHI nodes updated.
103bd5abe19SDimitry Andric /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
104bd5abe19SDimitry Andric /// conditions and indirectbr addresses this might make dead if
105bd5abe19SDimitry Andric /// DeleteDeadConditions is true.
ConstantFoldTerminator(BasicBlock * BB,bool DeleteDeadConditions,const TargetLibraryInfo * TLI,DomTreeUpdater * DTU)1063861d79fSDimitry Andric bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
1074ba319b5SDimitry Andric                                   const TargetLibraryInfo *TLI,
108*b5893f02SDimitry Andric                                   DomTreeUpdater *DTU) {
109*b5893f02SDimitry Andric   Instruction *T = BB->getTerminator();
110bd5abe19SDimitry Andric   IRBuilder<> Builder(T);
111f22ef01cSRoman Divacky 
112f22ef01cSRoman Divacky   // Branch - See if we are conditional jumping on constant
11330785c0eSDimitry Andric   if (auto *BI = dyn_cast<BranchInst>(T)) {
114f22ef01cSRoman Divacky     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
115f22ef01cSRoman Divacky     BasicBlock *Dest1 = BI->getSuccessor(0);
116f22ef01cSRoman Divacky     BasicBlock *Dest2 = BI->getSuccessor(1);
117f22ef01cSRoman Divacky 
11830785c0eSDimitry Andric     if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
119f22ef01cSRoman Divacky       // Are we branching on constant?
120f22ef01cSRoman Divacky       // YES.  Change to unconditional branch...
121f22ef01cSRoman Divacky       BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
122f22ef01cSRoman Divacky       BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
123f22ef01cSRoman Divacky 
124f22ef01cSRoman Divacky       // Let the basic block know that we are letting go of it.  Based on this,
125f22ef01cSRoman Divacky       // it will adjust it's PHI nodes.
1263b0f4066SDimitry Andric       OldDest->removePredecessor(BB);
127f22ef01cSRoman Divacky 
1282754fe60SDimitry Andric       // Replace the conditional branch with an unconditional one.
129bd5abe19SDimitry Andric       Builder.CreateBr(Destination);
1302754fe60SDimitry Andric       BI->eraseFromParent();
131*b5893f02SDimitry Andric       if (DTU)
132*b5893f02SDimitry Andric         DTU->deleteEdgeRelaxed(BB, OldDest);
133f22ef01cSRoman Divacky       return true;
134f22ef01cSRoman Divacky     }
135f22ef01cSRoman Divacky 
136f22ef01cSRoman Divacky     if (Dest2 == Dest1) {       // Conditional branch to same location?
137f22ef01cSRoman Divacky       // This branch matches something like this:
138f22ef01cSRoman Divacky       //     br bool %cond, label %Dest, label %Dest
139f22ef01cSRoman Divacky       // and changes it into:  br label %Dest
140f22ef01cSRoman Divacky 
141f22ef01cSRoman Divacky       // Let the basic block know that we are letting go of one copy of it.
142f22ef01cSRoman Divacky       assert(BI->getParent() && "Terminator not inserted in block!");
143f22ef01cSRoman Divacky       Dest1->removePredecessor(BI->getParent());
144f22ef01cSRoman Divacky 
1452754fe60SDimitry Andric       // Replace the conditional branch with an unconditional one.
146bd5abe19SDimitry Andric       Builder.CreateBr(Dest1);
147bd5abe19SDimitry Andric       Value *Cond = BI->getCondition();
1482754fe60SDimitry Andric       BI->eraseFromParent();
149bd5abe19SDimitry Andric       if (DeleteDeadConditions)
1503861d79fSDimitry Andric         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
151f22ef01cSRoman Divacky       return true;
152f22ef01cSRoman Divacky     }
153f22ef01cSRoman Divacky     return false;
154f22ef01cSRoman Divacky   }
155f22ef01cSRoman Divacky 
15630785c0eSDimitry Andric   if (auto *SI = dyn_cast<SwitchInst>(T)) {
157ff0cc061SDimitry Andric     // If we are switching on a constant, we can convert the switch to an
158ff0cc061SDimitry Andric     // unconditional branch.
15930785c0eSDimitry Andric     auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
160ff0cc061SDimitry Andric     BasicBlock *DefaultDest = SI->getDefaultDest();
161ff0cc061SDimitry Andric     BasicBlock *TheOnlyDest = DefaultDest;
162ff0cc061SDimitry Andric 
163ff0cc061SDimitry Andric     // If the default is unreachable, ignore it when searching for TheOnlyDest.
164ff0cc061SDimitry Andric     if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
165ff0cc061SDimitry Andric         SI->getNumCases() > 0) {
1667a7e6055SDimitry Andric       TheOnlyDest = SI->case_begin()->getCaseSuccessor();
167ff0cc061SDimitry Andric     }
168f22ef01cSRoman Divacky 
169f22ef01cSRoman Divacky     // Figure out which case it goes to.
1707a7e6055SDimitry Andric     for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
171f22ef01cSRoman Divacky       // Found case matching a constant operand?
1727a7e6055SDimitry Andric       if (i->getCaseValue() == CI) {
1737a7e6055SDimitry Andric         TheOnlyDest = i->getCaseSuccessor();
174f22ef01cSRoman Divacky         break;
175f22ef01cSRoman Divacky       }
176f22ef01cSRoman Divacky 
177f22ef01cSRoman Divacky       // Check to see if this branch is going to the same place as the default
178f22ef01cSRoman Divacky       // dest.  If so, eliminate it as an explicit compare.
1797a7e6055SDimitry Andric       if (i->getCaseSuccessor() == DefaultDest) {
1803861d79fSDimitry Andric         MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
18191bc56edSDimitry Andric         unsigned NCases = SI->getNumCases();
18291bc56edSDimitry Andric         // Fold the case metadata into the default if there will be any branches
18391bc56edSDimitry Andric         // left, unless the metadata doesn't match the switch.
18491bc56edSDimitry Andric         if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
1853861d79fSDimitry Andric           // Collect branch weights into a vector.
1863861d79fSDimitry Andric           SmallVector<uint32_t, 8> Weights;
1873861d79fSDimitry Andric           for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
1883861d79fSDimitry Andric                ++MD_i) {
1893ca95b02SDimitry Andric             auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
1903861d79fSDimitry Andric             Weights.push_back(CI->getValue().getZExtValue());
1913861d79fSDimitry Andric           }
1923861d79fSDimitry Andric           // Merge weight of this case to the default weight.
1937a7e6055SDimitry Andric           unsigned idx = i->getCaseIndex();
1943861d79fSDimitry Andric           Weights[0] += Weights[idx+1];
1953861d79fSDimitry Andric           // Remove weight for this case.
1963861d79fSDimitry Andric           std::swap(Weights[idx+1], Weights.back());
1973861d79fSDimitry Andric           Weights.pop_back();
1983861d79fSDimitry Andric           SI->setMetadata(LLVMContext::MD_prof,
1993861d79fSDimitry Andric                           MDBuilder(BB->getContext()).
2003861d79fSDimitry Andric                           createBranchWeights(Weights));
2013861d79fSDimitry Andric         }
202f22ef01cSRoman Divacky         // Remove this entry.
2034ba319b5SDimitry Andric         BasicBlock *ParentBB = SI->getParent();
2044ba319b5SDimitry Andric         DefaultDest->removePredecessor(ParentBB);
2057a7e6055SDimitry Andric         i = SI->removeCase(i);
2067a7e6055SDimitry Andric         e = SI->case_end();
207*b5893f02SDimitry Andric         if (DTU)
208*b5893f02SDimitry Andric           DTU->deleteEdgeRelaxed(ParentBB, DefaultDest);
209f22ef01cSRoman Divacky         continue;
210f22ef01cSRoman Divacky       }
211f22ef01cSRoman Divacky 
212f22ef01cSRoman Divacky       // Otherwise, check to see if the switch only branches to one destination.
213f22ef01cSRoman Divacky       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
214f22ef01cSRoman Divacky       // destinations.
2157a7e6055SDimitry Andric       if (i->getCaseSuccessor() != TheOnlyDest)
2167a7e6055SDimitry Andric         TheOnlyDest = nullptr;
2177a7e6055SDimitry Andric 
2187a7e6055SDimitry Andric       // Increment this iterator as we haven't removed the case.
2197a7e6055SDimitry Andric       ++i;
220f22ef01cSRoman Divacky     }
221f22ef01cSRoman Divacky 
222f22ef01cSRoman Divacky     if (CI && !TheOnlyDest) {
223f22ef01cSRoman Divacky       // Branching on a constant, but not any of the cases, go to the default
224f22ef01cSRoman Divacky       // successor.
225f22ef01cSRoman Divacky       TheOnlyDest = SI->getDefaultDest();
226f22ef01cSRoman Divacky     }
227f22ef01cSRoman Divacky 
228f22ef01cSRoman Divacky     // If we found a single destination that we can fold the switch into, do so
229f22ef01cSRoman Divacky     // now.
230f22ef01cSRoman Divacky     if (TheOnlyDest) {
231f22ef01cSRoman Divacky       // Insert the new branch.
232bd5abe19SDimitry Andric       Builder.CreateBr(TheOnlyDest);
233f22ef01cSRoman Divacky       BasicBlock *BB = SI->getParent();
2344ba319b5SDimitry Andric       std::vector <DominatorTree::UpdateType> Updates;
235*b5893f02SDimitry Andric       if (DTU)
2364ba319b5SDimitry Andric         Updates.reserve(SI->getNumSuccessors() - 1);
237f22ef01cSRoman Divacky 
238f22ef01cSRoman Divacky       // Remove entries from PHI nodes which we no longer branch to...
239*b5893f02SDimitry Andric       for (BasicBlock *Succ : successors(SI)) {
240f22ef01cSRoman Divacky         // Found case matching a constant operand?
2414ba319b5SDimitry Andric         if (Succ == TheOnlyDest) {
24291bc56edSDimitry Andric           TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
2434ba319b5SDimitry Andric         } else {
244f22ef01cSRoman Divacky           Succ->removePredecessor(BB);
245*b5893f02SDimitry Andric           if (DTU)
2464ba319b5SDimitry Andric             Updates.push_back({DominatorTree::Delete, BB, Succ});
2474ba319b5SDimitry Andric         }
248f22ef01cSRoman Divacky       }
249f22ef01cSRoman Divacky 
250f22ef01cSRoman Divacky       // Delete the old switch.
251bd5abe19SDimitry Andric       Value *Cond = SI->getCondition();
252bd5abe19SDimitry Andric       SI->eraseFromParent();
253bd5abe19SDimitry Andric       if (DeleteDeadConditions)
2543861d79fSDimitry Andric         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
255*b5893f02SDimitry Andric       if (DTU)
256*b5893f02SDimitry Andric         DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
257f22ef01cSRoman Divacky       return true;
258f22ef01cSRoman Divacky     }
259f22ef01cSRoman Divacky 
260dff0c46cSDimitry Andric     if (SI->getNumCases() == 1) {
261f22ef01cSRoman Divacky       // Otherwise, we can fold this switch into a conditional branch
262f22ef01cSRoman Divacky       // instruction if it has only one non-default destination.
2637a7e6055SDimitry Andric       auto FirstCase = *SI->case_begin();
264bd5abe19SDimitry Andric       Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
265f785676fSDimitry Andric           FirstCase.getCaseValue(), "cond");
266bd5abe19SDimitry Andric 
267f22ef01cSRoman Divacky       // Insert the new branch.
2683861d79fSDimitry Andric       BranchInst *NewBr = Builder.CreateCondBr(Cond,
2693861d79fSDimitry Andric                                                FirstCase.getCaseSuccessor(),
270dff0c46cSDimitry Andric                                                SI->getDefaultDest());
2713861d79fSDimitry Andric       MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
2723861d79fSDimitry Andric       if (MD && MD->getNumOperands() == 3) {
27339d628a0SDimitry Andric         ConstantInt *SICase =
27439d628a0SDimitry Andric             mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
27539d628a0SDimitry Andric         ConstantInt *SIDef =
27639d628a0SDimitry Andric             mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
2773861d79fSDimitry Andric         assert(SICase && SIDef);
2783861d79fSDimitry Andric         // The TrueWeight should be the weight for the single case of SI.
2793861d79fSDimitry Andric         NewBr->setMetadata(LLVMContext::MD_prof,
2803861d79fSDimitry Andric                         MDBuilder(BB->getContext()).
2813861d79fSDimitry Andric                         createBranchWeights(SICase->getValue().getZExtValue(),
2823861d79fSDimitry Andric                                             SIDef->getValue().getZExtValue()));
2833861d79fSDimitry Andric       }
284f22ef01cSRoman Divacky 
2857d523365SDimitry Andric       // Update make.implicit metadata to the newly-created conditional branch.
2867d523365SDimitry Andric       MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
2877d523365SDimitry Andric       if (MakeImplicitMD)
2887d523365SDimitry Andric         NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
2897d523365SDimitry Andric 
290f22ef01cSRoman Divacky       // Delete the old switch.
291f22ef01cSRoman Divacky       SI->eraseFromParent();
292f22ef01cSRoman Divacky       return true;
293f22ef01cSRoman Divacky     }
294f22ef01cSRoman Divacky     return false;
295f22ef01cSRoman Divacky   }
296f22ef01cSRoman Divacky 
29730785c0eSDimitry Andric   if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {
298f22ef01cSRoman Divacky     // indirectbr blockaddress(@F, @BB) -> br label @BB
29930785c0eSDimitry Andric     if (auto *BA =
300f22ef01cSRoman Divacky           dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
301f22ef01cSRoman Divacky       BasicBlock *TheOnlyDest = BA->getBasicBlock();
3024ba319b5SDimitry Andric       std::vector <DominatorTree::UpdateType> Updates;
303*b5893f02SDimitry Andric       if (DTU)
3044ba319b5SDimitry Andric         Updates.reserve(IBI->getNumDestinations() - 1);
3054ba319b5SDimitry Andric 
306f22ef01cSRoman Divacky       // Insert the new branch.
307bd5abe19SDimitry Andric       Builder.CreateBr(TheOnlyDest);
308f22ef01cSRoman Divacky 
309f22ef01cSRoman Divacky       for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
3104ba319b5SDimitry Andric         if (IBI->getDestination(i) == TheOnlyDest) {
31191bc56edSDimitry Andric           TheOnlyDest = nullptr;
3124ba319b5SDimitry Andric         } else {
3134ba319b5SDimitry Andric           BasicBlock *ParentBB = IBI->getParent();
3144ba319b5SDimitry Andric           BasicBlock *DestBB = IBI->getDestination(i);
3154ba319b5SDimitry Andric           DestBB->removePredecessor(ParentBB);
316*b5893f02SDimitry Andric           if (DTU)
3174ba319b5SDimitry Andric             Updates.push_back({DominatorTree::Delete, ParentBB, DestBB});
3184ba319b5SDimitry Andric         }
319f22ef01cSRoman Divacky       }
320bd5abe19SDimitry Andric       Value *Address = IBI->getAddress();
321f22ef01cSRoman Divacky       IBI->eraseFromParent();
322bd5abe19SDimitry Andric       if (DeleteDeadConditions)
3233861d79fSDimitry Andric         RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
324f22ef01cSRoman Divacky 
325f22ef01cSRoman Divacky       // If we didn't find our destination in the IBI successor list, then we
326f22ef01cSRoman Divacky       // have undefined behavior.  Replace the unconditional branch with an
327f22ef01cSRoman Divacky       // 'unreachable' instruction.
328f22ef01cSRoman Divacky       if (TheOnlyDest) {
329f22ef01cSRoman Divacky         BB->getTerminator()->eraseFromParent();
330f22ef01cSRoman Divacky         new UnreachableInst(BB->getContext(), BB);
331f22ef01cSRoman Divacky       }
332f22ef01cSRoman Divacky 
333*b5893f02SDimitry Andric       if (DTU)
334*b5893f02SDimitry Andric         DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
335f22ef01cSRoman Divacky       return true;
336f22ef01cSRoman Divacky     }
337f22ef01cSRoman Divacky   }
338f22ef01cSRoman Divacky 
339f22ef01cSRoman Divacky   return false;
340f22ef01cSRoman Divacky }
341f22ef01cSRoman Divacky 
342f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
343f22ef01cSRoman Divacky //  Local dead code elimination.
344f22ef01cSRoman Divacky //
345f22ef01cSRoman Divacky 
346f22ef01cSRoman Divacky /// isInstructionTriviallyDead - Return true if the result produced by the
347f22ef01cSRoman Divacky /// instruction is not used, and the instruction has no side effects.
348f22ef01cSRoman Divacky ///
isInstructionTriviallyDead(Instruction * I,const TargetLibraryInfo * TLI)3493861d79fSDimitry Andric bool llvm::isInstructionTriviallyDead(Instruction *I,
3503861d79fSDimitry Andric                                       const TargetLibraryInfo *TLI) {
3517a7e6055SDimitry Andric   if (!I->use_empty())
3527a7e6055SDimitry Andric     return false;
3537a7e6055SDimitry Andric   return wouldInstructionBeTriviallyDead(I, TLI);
3547a7e6055SDimitry Andric }
3557a7e6055SDimitry Andric 
wouldInstructionBeTriviallyDead(Instruction * I,const TargetLibraryInfo * TLI)3567a7e6055SDimitry Andric bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
3577a7e6055SDimitry Andric                                            const TargetLibraryInfo *TLI) {
358*b5893f02SDimitry Andric   if (I->isTerminator())
3597a7e6055SDimitry Andric     return false;
360f22ef01cSRoman Divacky 
3617d523365SDimitry Andric   // We don't want the landingpad-like instructions removed by anything this
3627d523365SDimitry Andric   // general.
3637d523365SDimitry Andric   if (I->isEHPad())
3646122f3e6SDimitry Andric     return false;
3656122f3e6SDimitry Andric 
3663b0f4066SDimitry Andric   // We don't want debug info removed by anything this general, unless
3673b0f4066SDimitry Andric   // debug info is empty.
3683b0f4066SDimitry Andric   if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
3693b0f4066SDimitry Andric     if (DDI->getAddress())
3703b0f4066SDimitry Andric       return false;
3713b0f4066SDimitry Andric     return true;
3723b0f4066SDimitry Andric   }
3733b0f4066SDimitry Andric   if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
3743b0f4066SDimitry Andric     if (DVI->getValue())
3753b0f4066SDimitry Andric       return false;
3763b0f4066SDimitry Andric     return true;
3773b0f4066SDimitry Andric   }
3784ba319b5SDimitry Andric   if (DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
3794ba319b5SDimitry Andric     if (DLI->getLabel())
3804ba319b5SDimitry Andric       return false;
3814ba319b5SDimitry Andric     return true;
3824ba319b5SDimitry Andric   }
383f22ef01cSRoman Divacky 
3847a7e6055SDimitry Andric   if (!I->mayHaveSideEffects())
3857a7e6055SDimitry Andric     return true;
386f22ef01cSRoman Divacky 
387f22ef01cSRoman Divacky   // Special case intrinsics that "may have side effects" but can be deleted
388f22ef01cSRoman Divacky   // when dead.
3896122f3e6SDimitry Andric   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3904ba319b5SDimitry Andric     // Safe to delete llvm.stacksave and launder.invariant.group if dead.
3914ba319b5SDimitry Andric     if (II->getIntrinsicID() == Intrinsic::stacksave ||
3924ba319b5SDimitry Andric         II->getIntrinsicID() == Intrinsic::launder_invariant_group)
393f22ef01cSRoman Divacky       return true;
3946122f3e6SDimitry Andric 
3956122f3e6SDimitry Andric     // Lifetime intrinsics are dead when their right-hand is undef.
396*b5893f02SDimitry Andric     if (II->isLifetimeStartOrEnd())
3976122f3e6SDimitry Andric       return isa<UndefValue>(II->getArgOperand(1));
39839d628a0SDimitry Andric 
3993ca95b02SDimitry Andric     // Assumptions are dead if their condition is trivially true.  Guards on
4003ca95b02SDimitry Andric     // true are operationally no-ops.  In the future we can consider more
4013ca95b02SDimitry Andric     // sophisticated tradeoffs for guards considering potential for check
4023ca95b02SDimitry Andric     // widening, but for now we keep things simple.
4033ca95b02SDimitry Andric     if (II->getIntrinsicID() == Intrinsic::assume ||
4043ca95b02SDimitry Andric         II->getIntrinsicID() == Intrinsic::experimental_guard) {
40539d628a0SDimitry Andric       if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
40639d628a0SDimitry Andric         return !Cond->isZero();
40739d628a0SDimitry Andric 
40839d628a0SDimitry Andric       return false;
40939d628a0SDimitry Andric     }
4106122f3e6SDimitry Andric   }
411dff0c46cSDimitry Andric 
4127a7e6055SDimitry Andric   if (isAllocLikeFn(I, TLI))
4137a7e6055SDimitry Andric     return true;
414dff0c46cSDimitry Andric 
4153861d79fSDimitry Andric   if (CallInst *CI = isFreeCall(I, TLI))
416dff0c46cSDimitry Andric     if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
417dff0c46cSDimitry Andric       return C->isNullValue() || isa<UndefValue>(C);
418dff0c46cSDimitry Andric 
419d88c1a5aSDimitry Andric   if (CallSite CS = CallSite(I))
420d88c1a5aSDimitry Andric     if (isMathLibCallNoop(CS, TLI))
421d88c1a5aSDimitry Andric       return true;
422d88c1a5aSDimitry Andric 
423f22ef01cSRoman Divacky   return false;
424f22ef01cSRoman Divacky }
425f22ef01cSRoman Divacky 
426f22ef01cSRoman Divacky /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
427f22ef01cSRoman Divacky /// trivially dead instruction, delete it.  If that makes any of its operands
428f22ef01cSRoman Divacky /// trivially dead, delete them too, recursively.  Return true if any
429f22ef01cSRoman Divacky /// instructions were deleted.
RecursivelyDeleteTriviallyDeadInstructions(Value * V,const TargetLibraryInfo * TLI,MemorySSAUpdater * MSSAU)430*b5893f02SDimitry Andric bool llvm::RecursivelyDeleteTriviallyDeadInstructions(
431*b5893f02SDimitry Andric     Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU) {
432f22ef01cSRoman Divacky   Instruction *I = dyn_cast<Instruction>(V);
4333861d79fSDimitry Andric   if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
434f22ef01cSRoman Divacky     return false;
435f22ef01cSRoman Divacky 
436f22ef01cSRoman Divacky   SmallVector<Instruction*, 16> DeadInsts;
437f22ef01cSRoman Divacky   DeadInsts.push_back(I);
438*b5893f02SDimitry Andric   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU);
439f22ef01cSRoman Divacky 
4404ba319b5SDimitry Andric   return true;
4414ba319b5SDimitry Andric }
4424ba319b5SDimitry Andric 
RecursivelyDeleteTriviallyDeadInstructions(SmallVectorImpl<Instruction * > & DeadInsts,const TargetLibraryInfo * TLI,MemorySSAUpdater * MSSAU)4434ba319b5SDimitry Andric void llvm::RecursivelyDeleteTriviallyDeadInstructions(
444*b5893f02SDimitry Andric     SmallVectorImpl<Instruction *> &DeadInsts, const TargetLibraryInfo *TLI,
445*b5893f02SDimitry Andric     MemorySSAUpdater *MSSAU) {
4464ba319b5SDimitry Andric   // Process the dead instruction list until empty.
4474ba319b5SDimitry Andric   while (!DeadInsts.empty()) {
4484ba319b5SDimitry Andric     Instruction &I = *DeadInsts.pop_back_val();
4494ba319b5SDimitry Andric     assert(I.use_empty() && "Instructions with uses are not dead.");
4504ba319b5SDimitry Andric     assert(isInstructionTriviallyDead(&I, TLI) &&
4514ba319b5SDimitry Andric            "Live instruction found in dead worklist!");
4524ba319b5SDimitry Andric 
4534ba319b5SDimitry Andric     // Don't lose the debug info while deleting the instructions.
4544ba319b5SDimitry Andric     salvageDebugInfo(I);
455f22ef01cSRoman Divacky 
456f22ef01cSRoman Divacky     // Null out all of the instruction's operands to see if any operand becomes
457f22ef01cSRoman Divacky     // dead as we go.
4584ba319b5SDimitry Andric     for (Use &OpU : I.operands()) {
4594ba319b5SDimitry Andric       Value *OpV = OpU.get();
4604ba319b5SDimitry Andric       OpU.set(nullptr);
461f22ef01cSRoman Divacky 
4624ba319b5SDimitry Andric       if (!OpV->use_empty())
4634ba319b5SDimitry Andric         continue;
464f22ef01cSRoman Divacky 
465f22ef01cSRoman Divacky       // If the operand is an instruction that became dead as we nulled out the
466f22ef01cSRoman Divacky       // operand, and if it is 'trivially' dead, delete it in a future loop
467f22ef01cSRoman Divacky       // iteration.
468f22ef01cSRoman Divacky       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
4693861d79fSDimitry Andric         if (isInstructionTriviallyDead(OpI, TLI))
470f22ef01cSRoman Divacky           DeadInsts.push_back(OpI);
471f22ef01cSRoman Divacky     }
472*b5893f02SDimitry Andric     if (MSSAU)
473*b5893f02SDimitry Andric       MSSAU->removeMemoryAccess(&I);
474f22ef01cSRoman Divacky 
4754ba319b5SDimitry Andric     I.eraseFromParent();
4764ba319b5SDimitry Andric   }
477f22ef01cSRoman Divacky }
478f22ef01cSRoman Divacky 
replaceDbgUsesWithUndef(Instruction * I)479*b5893f02SDimitry Andric bool llvm::replaceDbgUsesWithUndef(Instruction *I) {
480*b5893f02SDimitry Andric   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
481*b5893f02SDimitry Andric   findDbgUsers(DbgUsers, I);
482*b5893f02SDimitry Andric   for (auto *DII : DbgUsers) {
483*b5893f02SDimitry Andric     Value *Undef = UndefValue::get(I->getType());
484*b5893f02SDimitry Andric     DII->setOperand(0, MetadataAsValue::get(DII->getContext(),
485*b5893f02SDimitry Andric                                             ValueAsMetadata::get(Undef)));
486*b5893f02SDimitry Andric   }
487*b5893f02SDimitry Andric   return !DbgUsers.empty();
488*b5893f02SDimitry Andric }
489*b5893f02SDimitry Andric 
4902754fe60SDimitry Andric /// areAllUsesEqual - Check whether the uses of a value are all the same.
4912754fe60SDimitry Andric /// This is similar to Instruction::hasOneUse() except this will also return
492dd6029ffSDimitry Andric /// true when there are no uses or multiple uses that all refer to the same
493dd6029ffSDimitry Andric /// value.
areAllUsesEqual(Instruction * I)4942754fe60SDimitry Andric static bool areAllUsesEqual(Instruction *I) {
49591bc56edSDimitry Andric   Value::user_iterator UI = I->user_begin();
49691bc56edSDimitry Andric   Value::user_iterator UE = I->user_end();
4972754fe60SDimitry Andric   if (UI == UE)
498dd6029ffSDimitry Andric     return true;
4992754fe60SDimitry Andric 
5002754fe60SDimitry Andric   User *TheUse = *UI;
5012754fe60SDimitry Andric   for (++UI; UI != UE; ++UI) {
5022754fe60SDimitry Andric     if (*UI != TheUse)
5032754fe60SDimitry Andric       return false;
5042754fe60SDimitry Andric   }
5052754fe60SDimitry Andric   return true;
5062754fe60SDimitry Andric }
5072754fe60SDimitry Andric 
508f22ef01cSRoman Divacky /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
509f22ef01cSRoman Divacky /// dead PHI node, due to being a def-use chain of single-use nodes that
510f22ef01cSRoman Divacky /// either forms a cycle or is terminated by a trivially dead instruction,
511f22ef01cSRoman Divacky /// delete it.  If that makes any of its operands trivially dead, delete them
512dd6029ffSDimitry Andric /// too, recursively.  Return true if a change was made.
RecursivelyDeleteDeadPHINode(PHINode * PN,const TargetLibraryInfo * TLI)5133861d79fSDimitry Andric bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
5143861d79fSDimitry Andric                                         const TargetLibraryInfo *TLI) {
515dd6029ffSDimitry Andric   SmallPtrSet<Instruction*, 4> Visited;
516dd6029ffSDimitry Andric   for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
51791bc56edSDimitry Andric        I = cast<Instruction>(*I->user_begin())) {
518dd6029ffSDimitry Andric     if (I->use_empty())
5193861d79fSDimitry Andric       return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
520f22ef01cSRoman Divacky 
521dd6029ffSDimitry Andric     // If we find an instruction more than once, we're on a cycle that
522f22ef01cSRoman Divacky     // won't prove fruitful.
52339d628a0SDimitry Andric     if (!Visited.insert(I).second) {
524dd6029ffSDimitry Andric       // Break the cycle and delete the instruction and its operands.
525dd6029ffSDimitry Andric       I->replaceAllUsesWith(UndefValue::get(I->getType()));
5263861d79fSDimitry Andric       (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
527dd6029ffSDimitry Andric       return true;
528f22ef01cSRoman Divacky     }
529dd6029ffSDimitry Andric   }
530dd6029ffSDimitry Andric   return false;
531f22ef01cSRoman Divacky }
532f22ef01cSRoman Divacky 
5337d523365SDimitry Andric static bool
simplifyAndDCEInstruction(Instruction * I,SmallSetVector<Instruction *,16> & WorkList,const DataLayout & DL,const TargetLibraryInfo * TLI)5347d523365SDimitry Andric simplifyAndDCEInstruction(Instruction *I,
5357d523365SDimitry Andric                           SmallSetVector<Instruction *, 16> &WorkList,
5367d523365SDimitry Andric                           const DataLayout &DL,
5377d523365SDimitry Andric                           const TargetLibraryInfo *TLI) {
5387d523365SDimitry Andric   if (isInstructionTriviallyDead(I, TLI)) {
5394ba319b5SDimitry Andric     salvageDebugInfo(*I);
5404ba319b5SDimitry Andric 
5417d523365SDimitry Andric     // Null out all of the instruction's operands to see if any operand becomes
5427d523365SDimitry Andric     // dead as we go.
5437d523365SDimitry Andric     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
5447d523365SDimitry Andric       Value *OpV = I->getOperand(i);
5457d523365SDimitry Andric       I->setOperand(i, nullptr);
5467d523365SDimitry Andric 
5477d523365SDimitry Andric       if (!OpV->use_empty() || I == OpV)
5487d523365SDimitry Andric         continue;
5497d523365SDimitry Andric 
5507d523365SDimitry Andric       // If the operand is an instruction that became dead as we nulled out the
5517d523365SDimitry Andric       // operand, and if it is 'trivially' dead, delete it in a future loop
5527d523365SDimitry Andric       // iteration.
5537d523365SDimitry Andric       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
5547d523365SDimitry Andric         if (isInstructionTriviallyDead(OpI, TLI))
5557d523365SDimitry Andric           WorkList.insert(OpI);
5567d523365SDimitry Andric     }
5577d523365SDimitry Andric 
5587d523365SDimitry Andric     I->eraseFromParent();
5597d523365SDimitry Andric 
5607d523365SDimitry Andric     return true;
5617d523365SDimitry Andric   }
5627d523365SDimitry Andric 
5637d523365SDimitry Andric   if (Value *SimpleV = SimplifyInstruction(I, DL)) {
5647d523365SDimitry Andric     // Add the users to the worklist. CAREFUL: an instruction can use itself,
5657d523365SDimitry Andric     // in the case of a phi node.
5663ca95b02SDimitry Andric     for (User *U : I->users()) {
5673ca95b02SDimitry Andric       if (U != I) {
5687d523365SDimitry Andric         WorkList.insert(cast<Instruction>(U));
5693ca95b02SDimitry Andric       }
5703ca95b02SDimitry Andric     }
5717d523365SDimitry Andric 
5727d523365SDimitry Andric     // Replace the instruction with its simplified value.
5733ca95b02SDimitry Andric     bool Changed = false;
5743ca95b02SDimitry Andric     if (!I->use_empty()) {
5757d523365SDimitry Andric       I->replaceAllUsesWith(SimpleV);
5763ca95b02SDimitry Andric       Changed = true;
5773ca95b02SDimitry Andric     }
5783ca95b02SDimitry Andric     if (isInstructionTriviallyDead(I, TLI)) {
5797d523365SDimitry Andric       I->eraseFromParent();
5803ca95b02SDimitry Andric       Changed = true;
5813ca95b02SDimitry Andric     }
5823ca95b02SDimitry Andric     return Changed;
5837d523365SDimitry Andric   }
5847d523365SDimitry Andric   return false;
5857d523365SDimitry Andric }
5867d523365SDimitry Andric 
587f22ef01cSRoman Divacky /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
588f22ef01cSRoman Divacky /// simplify any instructions in it and recursively delete dead instructions.
589f22ef01cSRoman Divacky ///
590f22ef01cSRoman Divacky /// This returns true if it changed the code, note that it can delete
591f22ef01cSRoman Divacky /// instructions in other blocks as well in this block.
SimplifyInstructionsInBlock(BasicBlock * BB,const TargetLibraryInfo * TLI)592ff0cc061SDimitry Andric bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
5933861d79fSDimitry Andric                                        const TargetLibraryInfo *TLI) {
594f22ef01cSRoman Divacky   bool MadeChange = false;
5957d523365SDimitry Andric   const DataLayout &DL = BB->getModule()->getDataLayout();
596dff0c46cSDimitry Andric 
597dff0c46cSDimitry Andric #ifndef NDEBUG
598dff0c46cSDimitry Andric   // In debug builds, ensure that the terminator of the block is never replaced
599dff0c46cSDimitry Andric   // or deleted by these simplifications. The idea of simplification is that it
600dff0c46cSDimitry Andric   // cannot introduce new instructions, and there is no way to replace the
601dff0c46cSDimitry Andric   // terminator of a block without introducing a new instruction.
6027d523365SDimitry Andric   AssertingVH<Instruction> TerminatorVH(&BB->back());
603dff0c46cSDimitry Andric #endif
604dff0c46cSDimitry Andric 
6057d523365SDimitry Andric   SmallSetVector<Instruction *, 16> WorkList;
6067d523365SDimitry Andric   // Iterate over the original function, only adding insts to the worklist
6077d523365SDimitry Andric   // if they actually need to be revisited. This avoids having to pre-init
6087d523365SDimitry Andric   // the worklist with the entire function's worth of instructions.
6093ca95b02SDimitry Andric   for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
6103ca95b02SDimitry Andric        BI != E;) {
611dff0c46cSDimitry Andric     assert(!BI->isTerminator());
6127d523365SDimitry Andric     Instruction *I = &*BI;
6137d523365SDimitry Andric     ++BI;
614f22ef01cSRoman Divacky 
6157d523365SDimitry Andric     // We're visiting this instruction now, so make sure it's not in the
6167d523365SDimitry Andric     // worklist from an earlier visit.
6177d523365SDimitry Andric     if (!WorkList.count(I))
6187d523365SDimitry Andric       MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
619f22ef01cSRoman Divacky   }
620f22ef01cSRoman Divacky 
6217d523365SDimitry Andric   while (!WorkList.empty()) {
6227d523365SDimitry Andric     Instruction *I = WorkList.pop_back_val();
6237d523365SDimitry Andric     MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
624f22ef01cSRoman Divacky   }
625f22ef01cSRoman Divacky   return MadeChange;
626f22ef01cSRoman Divacky }
627f22ef01cSRoman Divacky 
628f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
629f22ef01cSRoman Divacky //  Control Flow Graph Restructuring.
630f22ef01cSRoman Divacky //
631f22ef01cSRoman Divacky 
632f22ef01cSRoman Divacky /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
633f22ef01cSRoman Divacky /// method is called when we're about to delete Pred as a predecessor of BB.  If
634f22ef01cSRoman Divacky /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
635f22ef01cSRoman Divacky ///
636f22ef01cSRoman Divacky /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
637f22ef01cSRoman Divacky /// nodes that collapse into identity values.  For example, if we have:
638f22ef01cSRoman Divacky ///   x = phi(1, 0, 0, 0)
639f22ef01cSRoman Divacky ///   y = and x, z
640f22ef01cSRoman Divacky ///
641f22ef01cSRoman Divacky /// .. and delete the predecessor corresponding to the '1', this will attempt to
642f22ef01cSRoman Divacky /// recursively fold the and to 0.
RemovePredecessorAndSimplify(BasicBlock * BB,BasicBlock * Pred,DomTreeUpdater * DTU)6434ba319b5SDimitry Andric void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
644*b5893f02SDimitry Andric                                         DomTreeUpdater *DTU) {
645f22ef01cSRoman Divacky   // This only adjusts blocks with PHI nodes.
646f22ef01cSRoman Divacky   if (!isa<PHINode>(BB->begin()))
647f22ef01cSRoman Divacky     return;
648f22ef01cSRoman Divacky 
649f22ef01cSRoman Divacky   // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
650f22ef01cSRoman Divacky   // them down.  This will leave us with single entry phi nodes and other phis
651f22ef01cSRoman Divacky   // that can be removed.
652f22ef01cSRoman Divacky   BB->removePredecessor(Pred, true);
653f22ef01cSRoman Divacky 
654f37b6182SDimitry Andric   WeakTrackingVH PhiIt = &BB->front();
655f22ef01cSRoman Divacky   while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
656f22ef01cSRoman Divacky     PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
657ffd1746dSEd Schouten     Value *OldPhiIt = PhiIt;
658dff0c46cSDimitry Andric 
659ff0cc061SDimitry Andric     if (!recursivelySimplifyInstruction(PN))
660dff0c46cSDimitry Andric       continue;
661f22ef01cSRoman Divacky 
662f22ef01cSRoman Divacky     // If recursive simplification ended up deleting the next PHI node we would
663f22ef01cSRoman Divacky     // iterate to, then our iterator is invalid, restart scanning from the top
664f22ef01cSRoman Divacky     // of the block.
665ffd1746dSEd Schouten     if (PhiIt != OldPhiIt) PhiIt = &BB->front();
666f22ef01cSRoman Divacky   }
667*b5893f02SDimitry Andric   if (DTU)
668*b5893f02SDimitry Andric     DTU->deleteEdgeRelaxed(Pred, BB);
669f22ef01cSRoman Divacky }
670f22ef01cSRoman Divacky 
671f22ef01cSRoman Divacky /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
672f22ef01cSRoman Divacky /// predecessor is known to have one successor (DestBB!). Eliminate the edge
673f22ef01cSRoman Divacky /// between them, moving the instructions in the predecessor into DestBB and
674f22ef01cSRoman Divacky /// deleting the predecessor block.
MergeBasicBlockIntoOnlyPred(BasicBlock * DestBB,DomTreeUpdater * DTU)675*b5893f02SDimitry Andric void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
676*b5893f02SDimitry Andric                                        DomTreeUpdater *DTU) {
6774ba319b5SDimitry Andric 
678f22ef01cSRoman Divacky   // If BB has single-entry PHI nodes, fold them.
679f22ef01cSRoman Divacky   while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
680f22ef01cSRoman Divacky     Value *NewVal = PN->getIncomingValue(0);
681f22ef01cSRoman Divacky     // Replace self referencing PHI with undef, it must be dead.
682f22ef01cSRoman Divacky     if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
683f22ef01cSRoman Divacky     PN->replaceAllUsesWith(NewVal);
684f22ef01cSRoman Divacky     PN->eraseFromParent();
685f22ef01cSRoman Divacky   }
686f22ef01cSRoman Divacky 
687f22ef01cSRoman Divacky   BasicBlock *PredBB = DestBB->getSinglePredecessor();
688f22ef01cSRoman Divacky   assert(PredBB && "Block doesn't have a single predecessor!");
689f22ef01cSRoman Divacky 
6904ba319b5SDimitry Andric   bool ReplaceEntryBB = false;
6914ba319b5SDimitry Andric   if (PredBB == &DestBB->getParent()->getEntryBlock())
6924ba319b5SDimitry Andric     ReplaceEntryBB = true;
6934ba319b5SDimitry Andric 
694*b5893f02SDimitry Andric   // DTU updates: Collect all the edges that enter
695*b5893f02SDimitry Andric   // PredBB. These dominator edges will be redirected to DestBB.
696*b5893f02SDimitry Andric   SmallVector<DominatorTree::UpdateType, 32> Updates;
697*b5893f02SDimitry Andric 
698*b5893f02SDimitry Andric   if (DTU) {
6994ba319b5SDimitry Andric     Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
7004ba319b5SDimitry Andric     for (auto I = pred_begin(PredBB), E = pred_end(PredBB); I != E; ++I) {
7014ba319b5SDimitry Andric       Updates.push_back({DominatorTree::Delete, *I, PredBB});
7024ba319b5SDimitry Andric       // This predecessor of PredBB may already have DestBB as a successor.
7034ba319b5SDimitry Andric       if (llvm::find(successors(*I), DestBB) == succ_end(*I))
7044ba319b5SDimitry Andric         Updates.push_back({DominatorTree::Insert, *I, DestBB});
7054ba319b5SDimitry Andric     }
7064ba319b5SDimitry Andric   }
7074ba319b5SDimitry Andric 
708f22ef01cSRoman Divacky   // Zap anything that took the address of DestBB.  Not doing this will give the
709f22ef01cSRoman Divacky   // address an invalid value.
710f22ef01cSRoman Divacky   if (DestBB->hasAddressTaken()) {
711f22ef01cSRoman Divacky     BlockAddress *BA = BlockAddress::get(DestBB);
712f22ef01cSRoman Divacky     Constant *Replacement =
7132cab237bSDimitry Andric       ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
714f22ef01cSRoman Divacky     BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
715f22ef01cSRoman Divacky                                                      BA->getType()));
716f22ef01cSRoman Divacky     BA->destroyConstant();
717f22ef01cSRoman Divacky   }
718f22ef01cSRoman Divacky 
719f22ef01cSRoman Divacky   // Anything that branched to PredBB now branches to DestBB.
720f22ef01cSRoman Divacky   PredBB->replaceAllUsesWith(DestBB);
721f22ef01cSRoman Divacky 
72217a519f9SDimitry Andric   // Splice all the instructions from PredBB to DestBB.
72317a519f9SDimitry Andric   PredBB->getTerminator()->eraseFromParent();
72417a519f9SDimitry Andric   DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
725*b5893f02SDimitry Andric   new UnreachableInst(PredBB->getContext(), PredBB);
72617a519f9SDimitry Andric 
72791bc56edSDimitry Andric   // If the PredBB is the entry block of the function, move DestBB up to
72891bc56edSDimitry Andric   // become the entry block after we erase PredBB.
7294ba319b5SDimitry Andric   if (ReplaceEntryBB)
73091bc56edSDimitry Andric     DestBB->moveAfter(PredBB);
73191bc56edSDimitry Andric 
732*b5893f02SDimitry Andric   if (DTU) {
733*b5893f02SDimitry Andric     assert(PredBB->getInstList().size() == 1 &&
734*b5893f02SDimitry Andric            isa<UnreachableInst>(PredBB->getTerminator()) &&
735*b5893f02SDimitry Andric            "The successor list of PredBB isn't empty before "
736*b5893f02SDimitry Andric            "applying corresponding DTU updates.");
737*b5893f02SDimitry Andric     DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
738*b5893f02SDimitry Andric     DTU->deleteBB(PredBB);
739*b5893f02SDimitry Andric     // Recalculation of DomTree is needed when updating a forward DomTree and
740*b5893f02SDimitry Andric     // the Entry BB is replaced.
741*b5893f02SDimitry Andric     if (ReplaceEntryBB && DTU->hasDomTree()) {
742*b5893f02SDimitry Andric       // The entry block was removed and there is no external interface for
743*b5893f02SDimitry Andric       // the dominator tree to be notified of this change. In this corner-case
744*b5893f02SDimitry Andric       // we recalculate the entire tree.
745*b5893f02SDimitry Andric       DTU->recalculate(*(DestBB->getParent()));
746f22ef01cSRoman Divacky     }
7472cab237bSDimitry Andric   }
7484ba319b5SDimitry Andric 
749*b5893f02SDimitry Andric   else {
750*b5893f02SDimitry Andric     PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.
7514ba319b5SDimitry Andric   }
752f22ef01cSRoman Divacky }
753f22ef01cSRoman Divacky 
754f785676fSDimitry Andric /// CanMergeValues - Return true if we can choose one of these values to use
755f785676fSDimitry Andric /// in place of the other. Note that we will always choose the non-undef
756f785676fSDimitry Andric /// value to keep.
CanMergeValues(Value * First,Value * Second)757f785676fSDimitry Andric static bool CanMergeValues(Value *First, Value *Second) {
758f785676fSDimitry Andric   return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
759f785676fSDimitry Andric }
760f785676fSDimitry Andric 
761f22ef01cSRoman Divacky /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
762f785676fSDimitry Andric /// almost-empty BB ending in an unconditional branch to Succ, into Succ.
763f22ef01cSRoman Divacky ///
764f22ef01cSRoman Divacky /// Assumption: Succ is the single successor for BB.
CanPropagatePredecessorsForPHIs(BasicBlock * BB,BasicBlock * Succ)765f22ef01cSRoman Divacky static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
766f22ef01cSRoman Divacky   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
767f22ef01cSRoman Divacky 
7684ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
769f22ef01cSRoman Divacky                     << Succ->getName() << "\n");
770f22ef01cSRoman Divacky   // Shortcut, if there is only a single predecessor it must be BB and merging
771f22ef01cSRoman Divacky   // is always safe
772f22ef01cSRoman Divacky   if (Succ->getSinglePredecessor()) return true;
773f22ef01cSRoman Divacky 
774f22ef01cSRoman Divacky   // Make a list of the predecessors of BB
775dff0c46cSDimitry Andric   SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
776f22ef01cSRoman Divacky 
777f22ef01cSRoman Divacky   // Look at all the phi nodes in Succ, to see if they present a conflict when
778f22ef01cSRoman Divacky   // merging these blocks
779f22ef01cSRoman Divacky   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
780f22ef01cSRoman Divacky     PHINode *PN = cast<PHINode>(I);
781f22ef01cSRoman Divacky 
782f22ef01cSRoman Divacky     // If the incoming value from BB is again a PHINode in
783f22ef01cSRoman Divacky     // BB which has the same incoming value for *PI as PN does, we can
784f22ef01cSRoman Divacky     // merge the phi nodes and then the blocks can still be merged
785f22ef01cSRoman Divacky     PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
786f22ef01cSRoman Divacky     if (BBPN && BBPN->getParent() == BB) {
787dff0c46cSDimitry Andric       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
788dff0c46cSDimitry Andric         BasicBlock *IBB = PN->getIncomingBlock(PI);
789dff0c46cSDimitry Andric         if (BBPreds.count(IBB) &&
790f785676fSDimitry Andric             !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
791f785676fSDimitry Andric                             PN->getIncomingValue(PI))) {
7924ba319b5SDimitry Andric           LLVM_DEBUG(dbgs()
7934ba319b5SDimitry Andric                      << "Can't fold, phi node " << PN->getName() << " in "
794f22ef01cSRoman Divacky                      << Succ->getName() << " is conflicting with "
795f22ef01cSRoman Divacky                      << BBPN->getName() << " with regard to common predecessor "
796dff0c46cSDimitry Andric                      << IBB->getName() << "\n");
797f22ef01cSRoman Divacky           return false;
798f22ef01cSRoman Divacky         }
799f22ef01cSRoman Divacky       }
800f22ef01cSRoman Divacky     } else {
801f22ef01cSRoman Divacky       Value* Val = PN->getIncomingValueForBlock(BB);
802dff0c46cSDimitry Andric       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
803f22ef01cSRoman Divacky         // See if the incoming value for the common predecessor is equal to the
804f22ef01cSRoman Divacky         // one for BB, in which case this phi node will not prevent the merging
805f22ef01cSRoman Divacky         // of the block.
806dff0c46cSDimitry Andric         BasicBlock *IBB = PN->getIncomingBlock(PI);
807f785676fSDimitry Andric         if (BBPreds.count(IBB) &&
808f785676fSDimitry Andric             !CanMergeValues(Val, PN->getIncomingValue(PI))) {
8094ba319b5SDimitry Andric           LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()
8104ba319b5SDimitry Andric                             << " in " << Succ->getName()
8114ba319b5SDimitry Andric                             << " is conflicting with regard to common "
812dff0c46cSDimitry Andric                             << "predecessor " << IBB->getName() << "\n");
813f22ef01cSRoman Divacky           return false;
814f22ef01cSRoman Divacky         }
815f22ef01cSRoman Divacky       }
816f22ef01cSRoman Divacky     }
817f22ef01cSRoman Divacky   }
818f22ef01cSRoman Divacky 
819f22ef01cSRoman Divacky   return true;
820f22ef01cSRoman Divacky }
821f22ef01cSRoman Divacky 
8222cab237bSDimitry Andric using PredBlockVector = SmallVector<BasicBlock *, 16>;
8232cab237bSDimitry Andric using IncomingValueMap = DenseMap<BasicBlock *, Value *>;
824f785676fSDimitry Andric 
8254ba319b5SDimitry Andric /// Determines the value to use as the phi node input for a block.
826f785676fSDimitry Andric ///
827f785676fSDimitry Andric /// Select between \p OldVal any value that we know flows from \p BB
828f785676fSDimitry Andric /// to a particular phi on the basis of which one (if either) is not
829f785676fSDimitry Andric /// undef. Update IncomingValues based on the selected value.
830f785676fSDimitry Andric ///
831f785676fSDimitry Andric /// \param OldVal The value we are considering selecting.
832f785676fSDimitry Andric /// \param BB The block that the value flows in from.
833f785676fSDimitry Andric /// \param IncomingValues A map from block-to-value for other phi inputs
834f785676fSDimitry Andric /// that we have examined.
835f785676fSDimitry Andric ///
836f785676fSDimitry Andric /// \returns the selected value.
selectIncomingValueForBlock(Value * OldVal,BasicBlock * BB,IncomingValueMap & IncomingValues)837f785676fSDimitry Andric static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
838f785676fSDimitry Andric                                           IncomingValueMap &IncomingValues) {
839f785676fSDimitry Andric   if (!isa<UndefValue>(OldVal)) {
840f785676fSDimitry Andric     assert((!IncomingValues.count(BB) ||
841f785676fSDimitry Andric             IncomingValues.find(BB)->second == OldVal) &&
842f785676fSDimitry Andric            "Expected OldVal to match incoming value from BB!");
843f785676fSDimitry Andric 
844f785676fSDimitry Andric     IncomingValues.insert(std::make_pair(BB, OldVal));
845f785676fSDimitry Andric     return OldVal;
846f785676fSDimitry Andric   }
847f785676fSDimitry Andric 
848f785676fSDimitry Andric   IncomingValueMap::const_iterator It = IncomingValues.find(BB);
849f785676fSDimitry Andric   if (It != IncomingValues.end()) return It->second;
850f785676fSDimitry Andric 
851f785676fSDimitry Andric   return OldVal;
852f785676fSDimitry Andric }
853f785676fSDimitry Andric 
8544ba319b5SDimitry Andric /// Create a map from block to value for the operands of a
855f785676fSDimitry Andric /// given phi.
856f785676fSDimitry Andric ///
857f785676fSDimitry Andric /// Create a map from block to value for each non-undef value flowing
858f785676fSDimitry Andric /// into \p PN.
859f785676fSDimitry Andric ///
860f785676fSDimitry Andric /// \param PN The phi we are collecting the map for.
861f785676fSDimitry Andric /// \param IncomingValues [out] The map from block to value for this phi.
gatherIncomingValuesToPhi(PHINode * PN,IncomingValueMap & IncomingValues)862f785676fSDimitry Andric static void gatherIncomingValuesToPhi(PHINode *PN,
863f785676fSDimitry Andric                                       IncomingValueMap &IncomingValues) {
864f785676fSDimitry Andric   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
865f785676fSDimitry Andric     BasicBlock *BB = PN->getIncomingBlock(i);
866f785676fSDimitry Andric     Value *V = PN->getIncomingValue(i);
867f785676fSDimitry Andric 
868f785676fSDimitry Andric     if (!isa<UndefValue>(V))
869f785676fSDimitry Andric       IncomingValues.insert(std::make_pair(BB, V));
870f785676fSDimitry Andric   }
871f785676fSDimitry Andric }
872f785676fSDimitry Andric 
8734ba319b5SDimitry Andric /// Replace the incoming undef values to a phi with the values
874f785676fSDimitry Andric /// from a block-to-value map.
875f785676fSDimitry Andric ///
876f785676fSDimitry Andric /// \param PN The phi we are replacing the undefs in.
877f785676fSDimitry Andric /// \param IncomingValues A map from block to value.
replaceUndefValuesInPhi(PHINode * PN,const IncomingValueMap & IncomingValues)878f785676fSDimitry Andric static void replaceUndefValuesInPhi(PHINode *PN,
879f785676fSDimitry Andric                                     const IncomingValueMap &IncomingValues) {
880f785676fSDimitry Andric   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
881f785676fSDimitry Andric     Value *V = PN->getIncomingValue(i);
882f785676fSDimitry Andric 
883f785676fSDimitry Andric     if (!isa<UndefValue>(V)) continue;
884f785676fSDimitry Andric 
885f785676fSDimitry Andric     BasicBlock *BB = PN->getIncomingBlock(i);
886f785676fSDimitry Andric     IncomingValueMap::const_iterator It = IncomingValues.find(BB);
887f785676fSDimitry Andric     if (It == IncomingValues.end()) continue;
888f785676fSDimitry Andric 
889f785676fSDimitry Andric     PN->setIncomingValue(i, It->second);
890f785676fSDimitry Andric   }
891f785676fSDimitry Andric }
892f785676fSDimitry Andric 
8934ba319b5SDimitry Andric /// Replace a value flowing from a block to a phi with
894f785676fSDimitry Andric /// potentially multiple instances of that value flowing from the
895f785676fSDimitry Andric /// block's predecessors to the phi.
896f785676fSDimitry Andric ///
897f785676fSDimitry Andric /// \param BB The block with the value flowing into the phi.
898f785676fSDimitry Andric /// \param BBPreds The predecessors of BB.
899f785676fSDimitry Andric /// \param PN The phi that we are updating.
redirectValuesFromPredecessorsToPhi(BasicBlock * BB,const PredBlockVector & BBPreds,PHINode * PN)900f785676fSDimitry Andric static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
901f785676fSDimitry Andric                                                 const PredBlockVector &BBPreds,
902f785676fSDimitry Andric                                                 PHINode *PN) {
903f785676fSDimitry Andric   Value *OldVal = PN->removeIncomingValue(BB, false);
904f785676fSDimitry Andric   assert(OldVal && "No entry in PHI for Pred BB!");
905f785676fSDimitry Andric 
906f785676fSDimitry Andric   IncomingValueMap IncomingValues;
907f785676fSDimitry Andric 
908f785676fSDimitry Andric   // We are merging two blocks - BB, and the block containing PN - and
909f785676fSDimitry Andric   // as a result we need to redirect edges from the predecessors of BB
910f785676fSDimitry Andric   // to go to the block containing PN, and update PN
911f785676fSDimitry Andric   // accordingly. Since we allow merging blocks in the case where the
912f785676fSDimitry Andric   // predecessor and successor blocks both share some predecessors,
913f785676fSDimitry Andric   // and where some of those common predecessors might have undef
914f785676fSDimitry Andric   // values flowing into PN, we want to rewrite those values to be
915f785676fSDimitry Andric   // consistent with the non-undef values.
916f785676fSDimitry Andric 
917f785676fSDimitry Andric   gatherIncomingValuesToPhi(PN, IncomingValues);
918f785676fSDimitry Andric 
919f785676fSDimitry Andric   // If this incoming value is one of the PHI nodes in BB, the new entries
920f785676fSDimitry Andric   // in the PHI node are the entries from the old PHI.
921f785676fSDimitry Andric   if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
922f785676fSDimitry Andric     PHINode *OldValPN = cast<PHINode>(OldVal);
923f785676fSDimitry Andric     for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
924f785676fSDimitry Andric       // Note that, since we are merging phi nodes and BB and Succ might
925f785676fSDimitry Andric       // have common predecessors, we could end up with a phi node with
926f785676fSDimitry Andric       // identical incoming branches. This will be cleaned up later (and
927f785676fSDimitry Andric       // will trigger asserts if we try to clean it up now, without also
928f785676fSDimitry Andric       // simplifying the corresponding conditional branch).
929f785676fSDimitry Andric       BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
930f785676fSDimitry Andric       Value *PredVal = OldValPN->getIncomingValue(i);
931f785676fSDimitry Andric       Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
932f785676fSDimitry Andric                                                     IncomingValues);
933f785676fSDimitry Andric 
934f785676fSDimitry Andric       // And add a new incoming value for this predecessor for the
935f785676fSDimitry Andric       // newly retargeted branch.
936f785676fSDimitry Andric       PN->addIncoming(Selected, PredBB);
937f785676fSDimitry Andric     }
938f785676fSDimitry Andric   } else {
939f785676fSDimitry Andric     for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
940f785676fSDimitry Andric       // Update existing incoming values in PN for this
941f785676fSDimitry Andric       // predecessor of BB.
942f785676fSDimitry Andric       BasicBlock *PredBB = BBPreds[i];
943f785676fSDimitry Andric       Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
944f785676fSDimitry Andric                                                     IncomingValues);
945f785676fSDimitry Andric 
946f785676fSDimitry Andric       // And add a new incoming value for this predecessor for the
947f785676fSDimitry Andric       // newly retargeted branch.
948f785676fSDimitry Andric       PN->addIncoming(Selected, PredBB);
949f785676fSDimitry Andric     }
950f785676fSDimitry Andric   }
951f785676fSDimitry Andric 
952f785676fSDimitry Andric   replaceUndefValuesInPhi(PN, IncomingValues);
953f785676fSDimitry Andric }
954f785676fSDimitry Andric 
955f22ef01cSRoman Divacky /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
956f22ef01cSRoman Divacky /// unconditional branch, and contains no instructions other than PHI nodes,
95717a519f9SDimitry Andric /// potential side-effect free intrinsics and the branch.  If possible,
95817a519f9SDimitry Andric /// eliminate BB by rewriting all the predecessors to branch to the successor
95917a519f9SDimitry Andric /// block and return true.  If we can't transform, return false.
TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock * BB,DomTreeUpdater * DTU)9604ba319b5SDimitry Andric bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
961*b5893f02SDimitry Andric                                                    DomTreeUpdater *DTU) {
962e580952dSDimitry Andric   assert(BB != &BB->getParent()->getEntryBlock() &&
963e580952dSDimitry Andric          "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
964e580952dSDimitry Andric 
965f22ef01cSRoman Divacky   // We can't eliminate infinite loops.
966f22ef01cSRoman Divacky   BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
967f22ef01cSRoman Divacky   if (BB == Succ) return false;
968f22ef01cSRoman Divacky 
969f22ef01cSRoman Divacky   // Check to see if merging these blocks would cause conflicts for any of the
970f22ef01cSRoman Divacky   // phi nodes in BB or Succ. If not, we can safely merge.
971f22ef01cSRoman Divacky   if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
972f22ef01cSRoman Divacky 
973f22ef01cSRoman Divacky   // Check for cases where Succ has multiple predecessors and a PHI node in BB
974f22ef01cSRoman Divacky   // has uses which will not disappear when the PHI nodes are merged.  It is
975f22ef01cSRoman Divacky   // possible to handle such cases, but difficult: it requires checking whether
976f22ef01cSRoman Divacky   // BB dominates Succ, which is non-trivial to calculate in the case where
977f22ef01cSRoman Divacky   // Succ has multiple predecessors.  Also, it requires checking whether
978139f7f9bSDimitry Andric   // constructing the necessary self-referential PHI node doesn't introduce any
979f22ef01cSRoman Divacky   // conflicts; this isn't too difficult, but the previous code for doing this
980f22ef01cSRoman Divacky   // was incorrect.
981f22ef01cSRoman Divacky   //
982f22ef01cSRoman Divacky   // Note that if this check finds a live use, BB dominates Succ, so BB is
983f22ef01cSRoman Divacky   // something like a loop pre-header (or rarely, a part of an irreducible CFG);
984f22ef01cSRoman Divacky   // folding the branch isn't profitable in that case anyway.
985f22ef01cSRoman Divacky   if (!Succ->getSinglePredecessor()) {
986f22ef01cSRoman Divacky     BasicBlock::iterator BBI = BB->begin();
987f22ef01cSRoman Divacky     while (isa<PHINode>(*BBI)) {
98891bc56edSDimitry Andric       for (Use &U : BBI->uses()) {
98991bc56edSDimitry Andric         if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
99091bc56edSDimitry Andric           if (PN->getIncomingBlock(U) != BB)
991f22ef01cSRoman Divacky             return false;
992f22ef01cSRoman Divacky         } else {
993f22ef01cSRoman Divacky           return false;
994f22ef01cSRoman Divacky         }
995f22ef01cSRoman Divacky       }
996f22ef01cSRoman Divacky       ++BBI;
997f22ef01cSRoman Divacky     }
998f22ef01cSRoman Divacky   }
999f22ef01cSRoman Divacky 
10004ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
10014ba319b5SDimitry Andric 
1002*b5893f02SDimitry Andric   SmallVector<DominatorTree::UpdateType, 32> Updates;
1003*b5893f02SDimitry Andric   if (DTU) {
10044ba319b5SDimitry Andric     Updates.push_back({DominatorTree::Delete, BB, Succ});
10054ba319b5SDimitry Andric     // All predecessors of BB will be moved to Succ.
10064ba319b5SDimitry Andric     for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
10074ba319b5SDimitry Andric       Updates.push_back({DominatorTree::Delete, *I, BB});
10084ba319b5SDimitry Andric       // This predecessor of BB may already have Succ as a successor.
10094ba319b5SDimitry Andric       if (llvm::find(successors(*I), Succ) == succ_end(*I))
10104ba319b5SDimitry Andric         Updates.push_back({DominatorTree::Insert, *I, Succ});
10114ba319b5SDimitry Andric     }
10124ba319b5SDimitry Andric   }
1013f22ef01cSRoman Divacky 
1014f22ef01cSRoman Divacky   if (isa<PHINode>(Succ->begin())) {
1015f22ef01cSRoman Divacky     // If there is more than one pred of succ, and there are PHI nodes in
1016f22ef01cSRoman Divacky     // the successor, then we need to add incoming edges for the PHI nodes
1017f22ef01cSRoman Divacky     //
1018f785676fSDimitry Andric     const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
1019f22ef01cSRoman Divacky 
1020f22ef01cSRoman Divacky     // Loop over all of the PHI nodes in the successor of BB.
1021f22ef01cSRoman Divacky     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
1022f22ef01cSRoman Divacky       PHINode *PN = cast<PHINode>(I);
1023f22ef01cSRoman Divacky 
1024f785676fSDimitry Andric       redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
1025f22ef01cSRoman Divacky     }
1026f22ef01cSRoman Divacky   }
1027f22ef01cSRoman Divacky 
1028f22ef01cSRoman Divacky   if (Succ->getSinglePredecessor()) {
1029f22ef01cSRoman Divacky     // BB is the only predecessor of Succ, so Succ will end up with exactly
1030f22ef01cSRoman Divacky     // the same predecessors BB had.
103117a519f9SDimitry Andric 
103217a519f9SDimitry Andric     // Copy over any phi, debug or lifetime instruction.
103317a519f9SDimitry Andric     BB->getTerminator()->eraseFromParent();
10347d523365SDimitry Andric     Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
10357d523365SDimitry Andric                                BB->getInstList());
1036f22ef01cSRoman Divacky   } else {
103717a519f9SDimitry Andric     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1038f22ef01cSRoman Divacky       // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
1039f22ef01cSRoman Divacky       assert(PN->use_empty() && "There shouldn't be any uses here!");
1040f22ef01cSRoman Divacky       PN->eraseFromParent();
1041f22ef01cSRoman Divacky     }
1042f22ef01cSRoman Divacky   }
1043f22ef01cSRoman Divacky 
1044d88c1a5aSDimitry Andric   // If the unconditional branch we replaced contains llvm.loop metadata, we
1045d88c1a5aSDimitry Andric   // add the metadata to the branch instructions in the predecessors.
1046d88c1a5aSDimitry Andric   unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop");
1047d88c1a5aSDimitry Andric   Instruction *TI = BB->getTerminator();
1048d88c1a5aSDimitry Andric   if (TI)
1049d88c1a5aSDimitry Andric     if (MDNode *LoopMD = TI->getMetadata(LoopMDKind))
1050d88c1a5aSDimitry Andric       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1051d88c1a5aSDimitry Andric         BasicBlock *Pred = *PI;
1052d88c1a5aSDimitry Andric         Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD);
1053d88c1a5aSDimitry Andric       }
1054d88c1a5aSDimitry Andric 
1055f22ef01cSRoman Divacky   // Everything that jumped to BB now goes to Succ.
1056f22ef01cSRoman Divacky   BB->replaceAllUsesWith(Succ);
1057f22ef01cSRoman Divacky   if (!Succ->hasName()) Succ->takeName(BB);
10584ba319b5SDimitry Andric 
1059*b5893f02SDimitry Andric   // Clear the successor list of BB to match updates applying to DTU later.
1060*b5893f02SDimitry Andric   if (BB->getTerminator())
1061*b5893f02SDimitry Andric     BB->getInstList().pop_back();
1062*b5893f02SDimitry Andric   new UnreachableInst(BB->getContext(), BB);
1063*b5893f02SDimitry Andric   assert(succ_empty(BB) && "The successor list of BB isn't empty before "
1064*b5893f02SDimitry Andric                            "applying corresponding DTU updates.");
1065*b5893f02SDimitry Andric 
1066*b5893f02SDimitry Andric   if (DTU) {
1067*b5893f02SDimitry Andric     DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
1068*b5893f02SDimitry Andric     DTU->deleteBB(BB);
10694ba319b5SDimitry Andric   } else {
1070f22ef01cSRoman Divacky     BB->eraseFromParent(); // Delete the old basic block.
10714ba319b5SDimitry Andric   }
1072f22ef01cSRoman Divacky   return true;
1073f22ef01cSRoman Divacky }
1074f22ef01cSRoman Divacky 
1075f22ef01cSRoman Divacky /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
1076f22ef01cSRoman Divacky /// nodes in this block. This doesn't try to be clever about PHI nodes
1077f22ef01cSRoman Divacky /// which differ only in the order of the incoming values, but instcombine
1078f22ef01cSRoman Divacky /// orders them so it usually won't matter.
EliminateDuplicatePHINodes(BasicBlock * BB)1079f22ef01cSRoman Divacky bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
1080f22ef01cSRoman Divacky   // This implementation doesn't currently consider undef operands
108117a519f9SDimitry Andric   // specially. Theoretically, two phis which are identical except for
1082f22ef01cSRoman Divacky   // one having an undef where the other doesn't could be collapsed.
1083f22ef01cSRoman Divacky 
10848f0fd8f6SDimitry Andric   struct PHIDenseMapInfo {
10858f0fd8f6SDimitry Andric     static PHINode *getEmptyKey() {
10868f0fd8f6SDimitry Andric       return DenseMapInfo<PHINode *>::getEmptyKey();
10878f0fd8f6SDimitry Andric     }
10882cab237bSDimitry Andric 
10898f0fd8f6SDimitry Andric     static PHINode *getTombstoneKey() {
10908f0fd8f6SDimitry Andric       return DenseMapInfo<PHINode *>::getTombstoneKey();
10918f0fd8f6SDimitry Andric     }
10922cab237bSDimitry Andric 
10938f0fd8f6SDimitry Andric     static unsigned getHashValue(PHINode *PN) {
10948f0fd8f6SDimitry Andric       // Compute a hash value on the operands. Instcombine will likely have
10958f0fd8f6SDimitry Andric       // sorted them, which helps expose duplicates, but we have to check all
10968f0fd8f6SDimitry Andric       // the operands to be safe in case instcombine hasn't run.
10978f0fd8f6SDimitry Andric       return static_cast<unsigned>(hash_combine(
10988f0fd8f6SDimitry Andric           hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
10998f0fd8f6SDimitry Andric           hash_combine_range(PN->block_begin(), PN->block_end())));
11008f0fd8f6SDimitry Andric     }
11012cab237bSDimitry Andric 
11028f0fd8f6SDimitry Andric     static bool isEqual(PHINode *LHS, PHINode *RHS) {
11038f0fd8f6SDimitry Andric       if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
11048f0fd8f6SDimitry Andric           RHS == getEmptyKey() || RHS == getTombstoneKey())
11058f0fd8f6SDimitry Andric         return LHS == RHS;
11068f0fd8f6SDimitry Andric       return LHS->isIdenticalTo(RHS);
11078f0fd8f6SDimitry Andric     }
11088f0fd8f6SDimitry Andric   };
1109f22ef01cSRoman Divacky 
11108f0fd8f6SDimitry Andric   // Set of unique PHINodes.
11118f0fd8f6SDimitry Andric   DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
1112f22ef01cSRoman Divacky 
1113f22ef01cSRoman Divacky   // Examine each PHI.
11148f0fd8f6SDimitry Andric   bool Changed = false;
11158f0fd8f6SDimitry Andric   for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
11168f0fd8f6SDimitry Andric     auto Inserted = PHISet.insert(PN);
11178f0fd8f6SDimitry Andric     if (!Inserted.second) {
1118f22ef01cSRoman Divacky       // A duplicate. Replace this PHI with its duplicate.
11198f0fd8f6SDimitry Andric       PN->replaceAllUsesWith(*Inserted.first);
1120f22ef01cSRoman Divacky       PN->eraseFromParent();
1121f22ef01cSRoman Divacky       Changed = true;
11229a4b3118SDimitry Andric 
11239a4b3118SDimitry Andric       // The RAUW can change PHIs that we already visited. Start over from the
11249a4b3118SDimitry Andric       // beginning.
11259a4b3118SDimitry Andric       PHISet.clear();
11269a4b3118SDimitry Andric       I = BB->begin();
1127f22ef01cSRoman Divacky     }
1128f22ef01cSRoman Divacky   }
1129f22ef01cSRoman Divacky 
1130f22ef01cSRoman Divacky   return Changed;
1131f22ef01cSRoman Divacky }
11322754fe60SDimitry Andric 
11332754fe60SDimitry Andric /// enforceKnownAlignment - If the specified pointer points to an object that
11342754fe60SDimitry Andric /// we control, modify the object's alignment to PrefAlign. This isn't
11352754fe60SDimitry Andric /// often possible though. If alignment is important, a more reliable approach
11362754fe60SDimitry Andric /// is to simply align all global variables and allocation instructions to
11372754fe60SDimitry Andric /// their preferred alignment from the beginning.
enforceKnownAlignment(Value * V,unsigned Align,unsigned PrefAlign,const DataLayout & DL)11382754fe60SDimitry Andric static unsigned enforceKnownAlignment(Value *V, unsigned Align,
1139ff0cc061SDimitry Andric                                       unsigned PrefAlign,
1140ff0cc061SDimitry Andric                                       const DataLayout &DL) {
1141cdd9644cSDimitry Andric   assert(PrefAlign > Align);
1142cdd9644cSDimitry Andric 
114317a519f9SDimitry Andric   V = V->stripPointerCasts();
11442754fe60SDimitry Andric 
114517a519f9SDimitry Andric   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1146cdd9644cSDimitry Andric     // TODO: ideally, computeKnownBits ought to have used
1147cdd9644cSDimitry Andric     // AllocaInst::getAlignment() in its computation already, making
1148cdd9644cSDimitry Andric     // the below max redundant. But, as it turns out,
1149cdd9644cSDimitry Andric     // stripPointerCasts recurses through infinite layers of bitcasts,
1150cdd9644cSDimitry Andric     // while computeKnownBits is not allowed to traverse more than 6
1151cdd9644cSDimitry Andric     // levels.
1152cdd9644cSDimitry Andric     Align = std::max(AI->getAlignment(), Align);
1153cdd9644cSDimitry Andric     if (PrefAlign <= Align)
1154cdd9644cSDimitry Andric       return Align;
1155cdd9644cSDimitry Andric 
11566122f3e6SDimitry Andric     // If the preferred alignment is greater than the natural stack alignment
11576122f3e6SDimitry Andric     // then don't round up. This avoids dynamic stack realignment.
1158ff0cc061SDimitry Andric     if (DL.exceedsNaturalStackAlignment(PrefAlign))
11596122f3e6SDimitry Andric       return Align;
11602754fe60SDimitry Andric     AI->setAlignment(PrefAlign);
11612754fe60SDimitry Andric     return PrefAlign;
11622754fe60SDimitry Andric   }
11632754fe60SDimitry Andric 
116491bc56edSDimitry Andric   if (auto *GO = dyn_cast<GlobalObject>(V)) {
1165cdd9644cSDimitry Andric     // TODO: as above, this shouldn't be necessary.
1166cdd9644cSDimitry Andric     Align = std::max(GO->getAlignment(), Align);
1167cdd9644cSDimitry Andric     if (PrefAlign <= Align)
1168cdd9644cSDimitry Andric       return Align;
1169cdd9644cSDimitry Andric 
11702754fe60SDimitry Andric     // If there is a large requested alignment and we can, bump up the alignment
1171875ed548SDimitry Andric     // of the global.  If the memory we set aside for the global may not be the
1172875ed548SDimitry Andric     // memory used by the final program then it is impossible for us to reliably
1173875ed548SDimitry Andric     // enforce the preferred alignment.
1174cdd9644cSDimitry Andric     if (!GO->canIncreaseAlignment())
117591bc56edSDimitry Andric       return Align;
11762754fe60SDimitry Andric 
117791bc56edSDimitry Andric     GO->setAlignment(PrefAlign);
1178cdd9644cSDimitry Andric     return PrefAlign;
11792754fe60SDimitry Andric   }
11802754fe60SDimitry Andric 
11812754fe60SDimitry Andric   return Align;
11822754fe60SDimitry Andric }
11832754fe60SDimitry Andric 
getOrEnforceKnownAlignment(Value * V,unsigned PrefAlign,const DataLayout & DL,const Instruction * CxtI,AssumptionCache * AC,const DominatorTree * DT)11842754fe60SDimitry Andric unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
1185ff0cc061SDimitry Andric                                           const DataLayout &DL,
118639d628a0SDimitry Andric                                           const Instruction *CxtI,
1187ff0cc061SDimitry Andric                                           AssumptionCache *AC,
118839d628a0SDimitry Andric                                           const DominatorTree *DT) {
11892754fe60SDimitry Andric   assert(V->getType()->isPointerTy() &&
11902754fe60SDimitry Andric          "getOrEnforceKnownAlignment expects a pointer!");
1191f785676fSDimitry Andric 
1192302affcbSDimitry Andric   KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);
11935517e702SDimitry Andric   unsigned TrailZ = Known.countMinTrailingZeros();
11942754fe60SDimitry Andric 
1195f785676fSDimitry Andric   // Avoid trouble with ridiculously large TrailZ values, such as
11962754fe60SDimitry Andric   // those computed from a null pointer.
11972754fe60SDimitry Andric   TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
11982754fe60SDimitry Andric 
1199302affcbSDimitry Andric   unsigned Align = 1u << std::min(Known.getBitWidth() - 1, TrailZ);
12002754fe60SDimitry Andric 
12012754fe60SDimitry Andric   // LLVM doesn't support alignments larger than this currently.
12022754fe60SDimitry Andric   Align = std::min(Align, +Value::MaximumAlignment);
12032754fe60SDimitry Andric 
12042754fe60SDimitry Andric   if (PrefAlign > Align)
1205f785676fSDimitry Andric     Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
12062754fe60SDimitry Andric 
12072754fe60SDimitry Andric   // We don't need to make any adjustment.
12082754fe60SDimitry Andric   return Align;
12092754fe60SDimitry Andric }
12102754fe60SDimitry Andric 
12113b0f4066SDimitry Andric ///===---------------------------------------------------------------------===//
12123b0f4066SDimitry Andric ///  Dbg Intrinsic utilities
12133b0f4066SDimitry Andric ///
12143b0f4066SDimitry Andric 
1215284c1978SDimitry Andric /// See if there is a dbg.value intrinsic for DIVar before I.
LdStHasDebugValue(DILocalVariable * DIVar,DIExpression * DIExpr,Instruction * I)12163ca95b02SDimitry Andric static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr,
12173ca95b02SDimitry Andric                               Instruction *I) {
1218284c1978SDimitry Andric   // Since we can't guarantee that the original dbg.declare instrinsic
1219284c1978SDimitry Andric   // is removed by LowerDbgDeclare(), we need to make sure that we are
1220284c1978SDimitry Andric   // not inserting the same dbg.value intrinsic over and over.
12212cab237bSDimitry Andric   BasicBlock::InstListType::iterator PrevI(I);
1222284c1978SDimitry Andric   if (PrevI != I->getParent()->getInstList().begin()) {
1223284c1978SDimitry Andric     --PrevI;
1224284c1978SDimitry Andric     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
1225284c1978SDimitry Andric       if (DVI->getValue() == I->getOperand(0) &&
12263ca95b02SDimitry Andric           DVI->getVariable() == DIVar &&
12273ca95b02SDimitry Andric           DVI->getExpression() == DIExpr)
1228284c1978SDimitry Andric         return true;
1229284c1978SDimitry Andric   }
1230284c1978SDimitry Andric   return false;
1231284c1978SDimitry Andric }
1232284c1978SDimitry Andric 
1233d88c1a5aSDimitry Andric /// See if there is a dbg.value intrinsic for DIVar for the PHI node.
PhiHasDebugValue(DILocalVariable * DIVar,DIExpression * DIExpr,PHINode * APN)1234d88c1a5aSDimitry Andric static bool PhiHasDebugValue(DILocalVariable *DIVar,
1235d88c1a5aSDimitry Andric                              DIExpression *DIExpr,
1236d88c1a5aSDimitry Andric                              PHINode *APN) {
1237d88c1a5aSDimitry Andric   // Since we can't guarantee that the original dbg.declare instrinsic
1238d88c1a5aSDimitry Andric   // is removed by LowerDbgDeclare(), we need to make sure that we are
1239d88c1a5aSDimitry Andric   // not inserting the same dbg.value intrinsic over and over.
12407a7e6055SDimitry Andric   SmallVector<DbgValueInst *, 1> DbgValues;
12417a7e6055SDimitry Andric   findDbgValues(DbgValues, APN);
12427a7e6055SDimitry Andric   for (auto *DVI : DbgValues) {
1243d88c1a5aSDimitry Andric     assert(DVI->getValue() == APN);
1244d88c1a5aSDimitry Andric     if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
1245d88c1a5aSDimitry Andric       return true;
1246d88c1a5aSDimitry Andric   }
1247d88c1a5aSDimitry Andric   return false;
1248d88c1a5aSDimitry Andric }
1249d88c1a5aSDimitry Andric 
12504ba319b5SDimitry Andric /// Check if the alloc size of \p ValTy is large enough to cover the variable
12514ba319b5SDimitry Andric /// (or fragment of the variable) described by \p DII.
12524ba319b5SDimitry Andric ///
12534ba319b5SDimitry Andric /// This is primarily intended as a helper for the different
12544ba319b5SDimitry Andric /// ConvertDebugDeclareToDebugValue functions. The dbg.declare/dbg.addr that is
12554ba319b5SDimitry Andric /// converted describes an alloca'd variable, so we need to use the
12564ba319b5SDimitry Andric /// alloc size of the value when doing the comparison. E.g. an i1 value will be
12574ba319b5SDimitry Andric /// identified as covering an n-bit fragment, if the store size of i1 is at
12584ba319b5SDimitry Andric /// least n bits.
valueCoversEntireFragment(Type * ValTy,DbgVariableIntrinsic * DII)1259*b5893f02SDimitry Andric static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {
12604ba319b5SDimitry Andric   const DataLayout &DL = DII->getModule()->getDataLayout();
12614ba319b5SDimitry Andric   uint64_t ValueSize = DL.getTypeAllocSizeInBits(ValTy);
12624ba319b5SDimitry Andric   if (auto FragmentSize = DII->getFragmentSizeInBits())
12634ba319b5SDimitry Andric     return ValueSize >= *FragmentSize;
12644ba319b5SDimitry Andric   // We can't always calculate the size of the DI variable (e.g. if it is a
12654ba319b5SDimitry Andric   // VLA). Try to use the size of the alloca that the dbg intrinsic describes
12664ba319b5SDimitry Andric   // intead.
12674ba319b5SDimitry Andric   if (DII->isAddressOfVariable())
12684ba319b5SDimitry Andric     if (auto *AI = dyn_cast_or_null<AllocaInst>(DII->getVariableLocation()))
12694ba319b5SDimitry Andric       if (auto FragmentSize = AI->getAllocationSizeInBits(DL))
12704ba319b5SDimitry Andric         return ValueSize >= *FragmentSize;
12714ba319b5SDimitry Andric   // Could not determine size of variable. Conservatively return false.
12724ba319b5SDimitry Andric   return false;
12734ba319b5SDimitry Andric }
12744ba319b5SDimitry Andric 
1275284c1978SDimitry Andric /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
12762cab237bSDimitry Andric /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic * DII,StoreInst * SI,DIBuilder & Builder)1277*b5893f02SDimitry Andric void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
12783b0f4066SDimitry Andric                                            StoreInst *SI, DIBuilder &Builder) {
12792cab237bSDimitry Andric   assert(DII->isAddressOfVariable());
12802cab237bSDimitry Andric   auto *DIVar = DII->getVariable();
1281ff0cc061SDimitry Andric   assert(DIVar && "Missing variable");
12822cab237bSDimitry Andric   auto *DIExpr = DII->getExpression();
12835517e702SDimitry Andric   Value *DV = SI->getOperand(0);
12843b0f4066SDimitry Andric 
12854ba319b5SDimitry Andric   if (!valueCoversEntireFragment(SI->getValueOperand()->getType(), DII)) {
12864ba319b5SDimitry Andric     // FIXME: If storing to a part of the variable described by the dbg.declare,
12874ba319b5SDimitry Andric     // then we want to insert a dbg.value for the corresponding fragment.
12884ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
12894ba319b5SDimitry Andric                       << *DII << '\n');
12904ba319b5SDimitry Andric     // For now, when there is a store to parts of the variable (but we do not
12914ba319b5SDimitry Andric     // know which part) we insert an dbg.value instrinsic to indicate that we
12924ba319b5SDimitry Andric     // know nothing about the variable's content.
12934ba319b5SDimitry Andric     DV = UndefValue::get(DV->getType());
12944ba319b5SDimitry Andric     if (!LdStHasDebugValue(DIVar, DIExpr, SI))
12954ba319b5SDimitry Andric       Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, DII->getDebugLoc(),
12964ba319b5SDimitry Andric                                       SI);
12974ba319b5SDimitry Andric     return;
12984ba319b5SDimitry Andric   }
12994ba319b5SDimitry Andric 
13005517e702SDimitry Andric   if (!LdStHasDebugValue(DIVar, DIExpr, SI))
13012cab237bSDimitry Andric     Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, DII->getDebugLoc(),
13025517e702SDimitry Andric                                     SI);
13033b0f4066SDimitry Andric }
13043b0f4066SDimitry Andric 
1305284c1978SDimitry Andric /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
13062cab237bSDimitry Andric /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic * DII,LoadInst * LI,DIBuilder & Builder)1307*b5893f02SDimitry Andric void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
13083b0f4066SDimitry Andric                                            LoadInst *LI, DIBuilder &Builder) {
13092cab237bSDimitry Andric   auto *DIVar = DII->getVariable();
13102cab237bSDimitry Andric   auto *DIExpr = DII->getExpression();
1311ff0cc061SDimitry Andric   assert(DIVar && "Missing variable");
13123b0f4066SDimitry Andric 
13133ca95b02SDimitry Andric   if (LdStHasDebugValue(DIVar, DIExpr, LI))
1314d88c1a5aSDimitry Andric     return;
1315284c1978SDimitry Andric 
13164ba319b5SDimitry Andric   if (!valueCoversEntireFragment(LI->getType(), DII)) {
13174ba319b5SDimitry Andric     // FIXME: If only referring to a part of the variable described by the
13184ba319b5SDimitry Andric     // dbg.declare, then we want to insert a dbg.value for the corresponding
13194ba319b5SDimitry Andric     // fragment.
13204ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
13214ba319b5SDimitry Andric                       << *DII << '\n');
13224ba319b5SDimitry Andric     return;
13234ba319b5SDimitry Andric   }
13244ba319b5SDimitry Andric 
13257d523365SDimitry Andric   // We are now tracking the loaded value instead of the address. In the
13267d523365SDimitry Andric   // future if multi-location support is added to the IR, it might be
13277d523365SDimitry Andric   // preferable to keep tracking both the loaded value and the original
13287d523365SDimitry Andric   // address in case the alloca can not be elided.
13297d523365SDimitry Andric   Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
13302cab237bSDimitry Andric       LI, DIVar, DIExpr, DII->getDebugLoc(), (Instruction *)nullptr);
13317d523365SDimitry Andric   DbgValue->insertAfter(LI);
1332d88c1a5aSDimitry Andric }
1333d88c1a5aSDimitry Andric 
13342cab237bSDimitry Andric /// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
13352cab237bSDimitry Andric /// llvm.dbg.declare or llvm.dbg.addr intrinsic.
ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic * DII,PHINode * APN,DIBuilder & Builder)1336*b5893f02SDimitry Andric void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1337d88c1a5aSDimitry Andric                                            PHINode *APN, DIBuilder &Builder) {
13382cab237bSDimitry Andric   auto *DIVar = DII->getVariable();
13392cab237bSDimitry Andric   auto *DIExpr = DII->getExpression();
1340d88c1a5aSDimitry Andric   assert(DIVar && "Missing variable");
1341d88c1a5aSDimitry Andric 
1342d88c1a5aSDimitry Andric   if (PhiHasDebugValue(DIVar, DIExpr, APN))
1343d88c1a5aSDimitry Andric     return;
1344d88c1a5aSDimitry Andric 
13454ba319b5SDimitry Andric   if (!valueCoversEntireFragment(APN->getType(), DII)) {
13464ba319b5SDimitry Andric     // FIXME: If only referring to a part of the variable described by the
13474ba319b5SDimitry Andric     // dbg.declare, then we want to insert a dbg.value for the corresponding
13484ba319b5SDimitry Andric     // fragment.
13494ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
13504ba319b5SDimitry Andric                       << *DII << '\n');
13514ba319b5SDimitry Andric     return;
13524ba319b5SDimitry Andric   }
13534ba319b5SDimitry Andric 
1354d88c1a5aSDimitry Andric   BasicBlock *BB = APN->getParent();
1355d88c1a5aSDimitry Andric   auto InsertionPt = BB->getFirstInsertionPt();
1356d88c1a5aSDimitry Andric 
1357d88c1a5aSDimitry Andric   // The block may be a catchswitch block, which does not have a valid
1358d88c1a5aSDimitry Andric   // insertion point.
1359d88c1a5aSDimitry Andric   // FIXME: Insert dbg.value markers in the successors when appropriate.
1360d88c1a5aSDimitry Andric   if (InsertionPt != BB->end())
13612cab237bSDimitry Andric     Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, DII->getDebugLoc(),
1362d88c1a5aSDimitry Andric                                     &*InsertionPt);
13633b0f4066SDimitry Andric }
13643b0f4066SDimitry Andric 
136591bc56edSDimitry Andric /// Determine whether this alloca is either a VLA or an array.
isArray(AllocaInst * AI)136691bc56edSDimitry Andric static bool isArray(AllocaInst *AI) {
136791bc56edSDimitry Andric   return AI->isArrayAllocation() ||
136891bc56edSDimitry Andric     AI->getType()->getElementType()->isArrayTy();
136991bc56edSDimitry Andric }
137091bc56edSDimitry Andric 
13713b0f4066SDimitry Andric /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
13723b0f4066SDimitry Andric /// of llvm.dbg.value intrinsics.
LowerDbgDeclare(Function & F)13733b0f4066SDimitry Andric bool llvm::LowerDbgDeclare(Function &F) {
137439d628a0SDimitry Andric   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
13753b0f4066SDimitry Andric   SmallVector<DbgDeclareInst *, 4> Dbgs;
137691bc56edSDimitry Andric   for (auto &FI : F)
13777d523365SDimitry Andric     for (Instruction &BI : FI)
13787d523365SDimitry Andric       if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
13793b0f4066SDimitry Andric         Dbgs.push_back(DDI);
138091bc56edSDimitry Andric 
13813b0f4066SDimitry Andric   if (Dbgs.empty())
13823b0f4066SDimitry Andric     return false;
13833b0f4066SDimitry Andric 
138491bc56edSDimitry Andric   for (auto &I : Dbgs) {
138591bc56edSDimitry Andric     DbgDeclareInst *DDI = I;
1386f785676fSDimitry Andric     AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1387f785676fSDimitry Andric     // If this is an alloca for a scalar variable, insert a dbg.value
1388f785676fSDimitry Andric     // at each load and store to the alloca and erase the dbg.declare.
138991bc56edSDimitry Andric     // The dbg.values allow tracking a variable even if it is not
139091bc56edSDimitry Andric     // stored on the stack, while the dbg.declare can only describe
139191bc56edSDimitry Andric     // the stack slot (and at a lexical-scope granularity). Later
139291bc56edSDimitry Andric     // passes will attempt to elide the stack slot.
13934ba319b5SDimitry Andric     if (!AI || isArray(AI))
13944ba319b5SDimitry Andric       continue;
13954ba319b5SDimitry Andric 
13964ba319b5SDimitry Andric     // A volatile load/store means that the alloca can't be elided anyway.
13974ba319b5SDimitry Andric     if (llvm::any_of(AI->users(), [](User *U) -> bool {
13984ba319b5SDimitry Andric           if (LoadInst *LI = dyn_cast<LoadInst>(U))
13994ba319b5SDimitry Andric             return LI->isVolatile();
14004ba319b5SDimitry Andric           if (StoreInst *SI = dyn_cast<StoreInst>(U))
14014ba319b5SDimitry Andric             return SI->isVolatile();
14024ba319b5SDimitry Andric           return false;
14034ba319b5SDimitry Andric         }))
14044ba319b5SDimitry Andric       continue;
14054ba319b5SDimitry Andric 
14063ca95b02SDimitry Andric     for (auto &AIUse : AI->uses()) {
14073ca95b02SDimitry Andric       User *U = AIUse.getUser();
14083ca95b02SDimitry Andric       if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
14093ca95b02SDimitry Andric         if (AIUse.getOperandNo() == 1)
14103b0f4066SDimitry Andric           ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
14113ca95b02SDimitry Andric       } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
14123b0f4066SDimitry Andric         ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
14133ca95b02SDimitry Andric       } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
14144ba319b5SDimitry Andric         // This is a call by-value or some other instruction that takes a
14154ba319b5SDimitry Andric         // pointer to the variable. Insert a *value* intrinsic that describes
14164ba319b5SDimitry Andric         // the variable by dereferencing the alloca.
14174ba319b5SDimitry Andric         auto *DerefExpr =
14184ba319b5SDimitry Andric             DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
14194ba319b5SDimitry Andric         DIB.insertDbgValueIntrinsic(AI, DDI->getVariable(), DerefExpr,
14204ba319b5SDimitry Andric                                     DDI->getDebugLoc(), CI);
142191bc56edSDimitry Andric       }
14223ca95b02SDimitry Andric     }
14233b0f4066SDimitry Andric     DDI->eraseFromParent();
14243b0f4066SDimitry Andric   }
14253b0f4066SDimitry Andric   return true;
14263b0f4066SDimitry Andric }
1427bd5abe19SDimitry Andric 
14284ba319b5SDimitry Andric /// Propagate dbg.value intrinsics through the newly inserted PHIs.
insertDebugValuesForPHIs(BasicBlock * BB,SmallVectorImpl<PHINode * > & InsertedPHIs)14294ba319b5SDimitry Andric void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
14304ba319b5SDimitry Andric                                     SmallVectorImpl<PHINode *> &InsertedPHIs) {
14314ba319b5SDimitry Andric   assert(BB && "No BasicBlock to clone dbg.value(s) from.");
14324ba319b5SDimitry Andric   if (InsertedPHIs.size() == 0)
14334ba319b5SDimitry Andric     return;
14344ba319b5SDimitry Andric 
14354ba319b5SDimitry Andric   // Map existing PHI nodes to their dbg.values.
14364ba319b5SDimitry Andric   ValueToValueMapTy DbgValueMap;
14374ba319b5SDimitry Andric   for (auto &I : *BB) {
1438*b5893f02SDimitry Andric     if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
14394ba319b5SDimitry Andric       if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
14404ba319b5SDimitry Andric         DbgValueMap.insert({Loc, DbgII});
14414ba319b5SDimitry Andric     }
14424ba319b5SDimitry Andric   }
14434ba319b5SDimitry Andric   if (DbgValueMap.size() == 0)
14444ba319b5SDimitry Andric     return;
14454ba319b5SDimitry Andric 
14464ba319b5SDimitry Andric   // Then iterate through the new PHIs and look to see if they use one of the
14474ba319b5SDimitry Andric   // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
14484ba319b5SDimitry Andric   // propagate the info through the new PHI.
14494ba319b5SDimitry Andric   LLVMContext &C = BB->getContext();
14504ba319b5SDimitry Andric   for (auto PHI : InsertedPHIs) {
14514ba319b5SDimitry Andric     BasicBlock *Parent = PHI->getParent();
14524ba319b5SDimitry Andric     // Avoid inserting an intrinsic into an EH block.
14534ba319b5SDimitry Andric     if (Parent->getFirstNonPHI()->isEHPad())
14544ba319b5SDimitry Andric       continue;
14554ba319b5SDimitry Andric     auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
14564ba319b5SDimitry Andric     for (auto VI : PHI->operand_values()) {
14574ba319b5SDimitry Andric       auto V = DbgValueMap.find(VI);
14584ba319b5SDimitry Andric       if (V != DbgValueMap.end()) {
1459*b5893f02SDimitry Andric         auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
14604ba319b5SDimitry Andric         Instruction *NewDbgII = DbgII->clone();
14614ba319b5SDimitry Andric         NewDbgII->setOperand(0, PhiMAV);
14624ba319b5SDimitry Andric         auto InsertionPt = Parent->getFirstInsertionPt();
14634ba319b5SDimitry Andric         assert(InsertionPt != Parent->end() && "Ill-formed basic block");
14644ba319b5SDimitry Andric         NewDbgII->insertBefore(&*InsertionPt);
14654ba319b5SDimitry Andric       }
14664ba319b5SDimitry Andric     }
14674ba319b5SDimitry Andric   }
14684ba319b5SDimitry Andric }
14694ba319b5SDimitry Andric 
14702cab237bSDimitry Andric /// Finds all intrinsics declaring local variables as living in the memory that
14712cab237bSDimitry Andric /// 'V' points to. This may include a mix of dbg.declare and
14722cab237bSDimitry Andric /// dbg.addr intrinsics.
FindDbgAddrUses(Value * V)1473*b5893f02SDimitry Andric TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
14744ba319b5SDimitry Andric   // This function is hot. Check whether the value has any metadata to avoid a
14754ba319b5SDimitry Andric   // DenseMap lookup.
14764ba319b5SDimitry Andric   if (!V->isUsedByMetadata())
14774ba319b5SDimitry Andric     return {};
14782cab237bSDimitry Andric   auto *L = LocalAsMetadata::getIfExists(V);
14792cab237bSDimitry Andric   if (!L)
14802cab237bSDimitry Andric     return {};
14812cab237bSDimitry Andric   auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
14822cab237bSDimitry Andric   if (!MDV)
14832cab237bSDimitry Andric     return {};
1484bd5abe19SDimitry Andric 
1485*b5893f02SDimitry Andric   TinyPtrVector<DbgVariableIntrinsic *> Declares;
14862cab237bSDimitry Andric   for (User *U : MDV->users()) {
1487*b5893f02SDimitry Andric     if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
14882cab237bSDimitry Andric       if (DII->isAddressOfVariable())
14892cab237bSDimitry Andric         Declares.push_back(DII);
14902cab237bSDimitry Andric   }
14912cab237bSDimitry Andric 
14922cab237bSDimitry Andric   return Declares;
1493bd5abe19SDimitry Andric }
1494139f7f9bSDimitry Andric 
findDbgValues(SmallVectorImpl<DbgValueInst * > & DbgValues,Value * V)14957a7e6055SDimitry Andric void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
14964ba319b5SDimitry Andric   // This function is hot. Check whether the value has any metadata to avoid a
14974ba319b5SDimitry Andric   // DenseMap lookup.
14984ba319b5SDimitry Andric   if (!V->isUsedByMetadata())
14994ba319b5SDimitry Andric     return;
1500d88c1a5aSDimitry Andric   if (auto *L = LocalAsMetadata::getIfExists(V))
1501d88c1a5aSDimitry Andric     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1502d88c1a5aSDimitry Andric       for (User *U : MDV->users())
1503d88c1a5aSDimitry Andric         if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
1504d88c1a5aSDimitry Andric           DbgValues.push_back(DVI);
1505d88c1a5aSDimitry Andric }
1506d88c1a5aSDimitry Andric 
findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic * > & DbgUsers,Value * V)1507*b5893f02SDimitry Andric void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
15082cab237bSDimitry Andric                         Value *V) {
15094ba319b5SDimitry Andric   // This function is hot. Check whether the value has any metadata to avoid a
15104ba319b5SDimitry Andric   // DenseMap lookup.
15114ba319b5SDimitry Andric   if (!V->isUsedByMetadata())
15124ba319b5SDimitry Andric     return;
15132cab237bSDimitry Andric   if (auto *L = LocalAsMetadata::getIfExists(V))
15142cab237bSDimitry Andric     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
15152cab237bSDimitry Andric       for (User *U : MDV->users())
1516*b5893f02SDimitry Andric         if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
15172cab237bSDimitry Andric           DbgUsers.push_back(DII);
15182cab237bSDimitry Andric }
15193ca95b02SDimitry Andric 
replaceDbgDeclare(Value * Address,Value * NewAddress,Instruction * InsertBefore,DIBuilder & Builder,bool DerefBefore,int Offset,bool DerefAfter)15207d523365SDimitry Andric bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
15217d523365SDimitry Andric                              Instruction *InsertBefore, DIBuilder &Builder,
15222cab237bSDimitry Andric                              bool DerefBefore, int Offset, bool DerefAfter) {
15232cab237bSDimitry Andric   auto DbgAddrs = FindDbgAddrUses(Address);
1524*b5893f02SDimitry Andric   for (DbgVariableIntrinsic *DII : DbgAddrs) {
15252cab237bSDimitry Andric     DebugLoc Loc = DII->getDebugLoc();
15262cab237bSDimitry Andric     auto *DIVar = DII->getVariable();
15272cab237bSDimitry Andric     auto *DIExpr = DII->getExpression();
1528ff0cc061SDimitry Andric     assert(DIVar && "Missing variable");
15292cab237bSDimitry Andric     DIExpr = DIExpression::prepend(DIExpr, DerefBefore, Offset, DerefAfter);
15304ba319b5SDimitry Andric     // Insert llvm.dbg.declare immediately before InsertBefore, and remove old
15312cab237bSDimitry Andric     // llvm.dbg.declare.
15327d523365SDimitry Andric     Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
15332cab237bSDimitry Andric     if (DII == InsertBefore)
15344ba319b5SDimitry Andric       InsertBefore = InsertBefore->getNextNode();
15352cab237bSDimitry Andric     DII->eraseFromParent();
15362cab237bSDimitry Andric   }
15372cab237bSDimitry Andric   return !DbgAddrs.empty();
1538139f7f9bSDimitry Andric }
1539139f7f9bSDimitry Andric 
replaceDbgDeclareForAlloca(AllocaInst * AI,Value * NewAllocaAddress,DIBuilder & Builder,bool DerefBefore,int Offset,bool DerefAfter)15407d523365SDimitry Andric bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
15412cab237bSDimitry Andric                                       DIBuilder &Builder, bool DerefBefore,
15422cab237bSDimitry Andric                                       int Offset, bool DerefAfter) {
15437d523365SDimitry Andric   return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder,
15442cab237bSDimitry Andric                            DerefBefore, Offset, DerefAfter);
15457d523365SDimitry Andric }
15467d523365SDimitry Andric 
replaceOneDbgValueForAlloca(DbgValueInst * DVI,Value * NewAddress,DIBuilder & Builder,int Offset)15473ca95b02SDimitry Andric static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
15483ca95b02SDimitry Andric                                         DIBuilder &Builder, int Offset) {
15493ca95b02SDimitry Andric   DebugLoc Loc = DVI->getDebugLoc();
15503ca95b02SDimitry Andric   auto *DIVar = DVI->getVariable();
15513ca95b02SDimitry Andric   auto *DIExpr = DVI->getExpression();
15523ca95b02SDimitry Andric   assert(DIVar && "Missing variable");
15533ca95b02SDimitry Andric 
15543ca95b02SDimitry Andric   // This is an alloca-based llvm.dbg.value. The first thing it should do with
15553ca95b02SDimitry Andric   // the alloca pointer is dereference it. Otherwise we don't know how to handle
15563ca95b02SDimitry Andric   // it and give up.
15573ca95b02SDimitry Andric   if (!DIExpr || DIExpr->getNumElements() < 1 ||
15583ca95b02SDimitry Andric       DIExpr->getElement(0) != dwarf::DW_OP_deref)
15593ca95b02SDimitry Andric     return;
15603ca95b02SDimitry Andric 
15613ca95b02SDimitry Andric   // Insert the offset immediately after the first deref.
15623ca95b02SDimitry Andric   // We could just change the offset argument of dbg.value, but it's unsigned...
15633ca95b02SDimitry Andric   if (Offset) {
15647a7e6055SDimitry Andric     SmallVector<uint64_t, 4> Ops;
15657a7e6055SDimitry Andric     Ops.push_back(dwarf::DW_OP_deref);
1566f37b6182SDimitry Andric     DIExpression::appendOffset(Ops, Offset);
15677a7e6055SDimitry Andric     Ops.append(DIExpr->elements_begin() + 1, DIExpr->elements_end());
15687a7e6055SDimitry Andric     DIExpr = Builder.createExpression(Ops);
15693ca95b02SDimitry Andric   }
15703ca95b02SDimitry Andric 
15712cab237bSDimitry Andric   Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI);
15723ca95b02SDimitry Andric   DVI->eraseFromParent();
15733ca95b02SDimitry Andric }
15743ca95b02SDimitry Andric 
replaceDbgValueForAlloca(AllocaInst * AI,Value * NewAllocaAddress,DIBuilder & Builder,int Offset)15753ca95b02SDimitry Andric void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
15763ca95b02SDimitry Andric                                     DIBuilder &Builder, int Offset) {
15773ca95b02SDimitry Andric   if (auto *L = LocalAsMetadata::getIfExists(AI))
15783ca95b02SDimitry Andric     if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
15793ca95b02SDimitry Andric       for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
15803ca95b02SDimitry Andric         Use &U = *UI++;
15813ca95b02SDimitry Andric         if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
15823ca95b02SDimitry Andric           replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
15833ca95b02SDimitry Andric       }
15843ca95b02SDimitry Andric }
15853ca95b02SDimitry Andric 
15864ba319b5SDimitry Andric /// Wrap \p V in a ValueAsMetadata instance.
wrapValueInMetadata(LLVMContext & C,Value * V)15874ba319b5SDimitry Andric static MetadataAsValue *wrapValueInMetadata(LLVMContext &C, Value *V) {
15884ba319b5SDimitry Andric   return MetadataAsValue::get(C, ValueAsMetadata::get(V));
15894ba319b5SDimitry Andric }
15907a7e6055SDimitry Andric 
salvageDebugInfo(Instruction & I)15914ba319b5SDimitry Andric bool llvm::salvageDebugInfo(Instruction &I) {
1592*b5893f02SDimitry Andric   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
15932cab237bSDimitry Andric   findDbgUsers(DbgUsers, &I);
15944ba319b5SDimitry Andric   if (DbgUsers.empty())
15954ba319b5SDimitry Andric     return false;
15964ba319b5SDimitry Andric 
15974ba319b5SDimitry Andric   auto &M = *I.getModule();
15984ba319b5SDimitry Andric   auto &DL = M.getDataLayout();
15994ba319b5SDimitry Andric   auto &Ctx = I.getContext();
16004ba319b5SDimitry Andric   auto wrapMD = [&](Value *V) { return wrapValueInMetadata(Ctx, V); };
16014ba319b5SDimitry Andric 
1602*b5893f02SDimitry Andric   auto doSalvage = [&](DbgVariableIntrinsic *DII, SmallVectorImpl<uint64_t> &Ops) {
16034ba319b5SDimitry Andric     auto *DIExpr = DII->getExpression();
16044ba319b5SDimitry Andric     if (!Ops.empty()) {
16054ba319b5SDimitry Andric       // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
16064ba319b5SDimitry Andric       // are implicitly pointing out the value as a DWARF memory location
16074ba319b5SDimitry Andric       // description.
16084ba319b5SDimitry Andric       bool WithStackValue = isa<DbgValueInst>(DII);
16094ba319b5SDimitry Andric       DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
16107a7e6055SDimitry Andric     }
16114ba319b5SDimitry Andric     DII->setOperand(0, wrapMD(I.getOperand(0)));
16124ba319b5SDimitry Andric     DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr));
16134ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
16144ba319b5SDimitry Andric   };
16154ba319b5SDimitry Andric 
1616*b5893f02SDimitry Andric   auto applyOffset = [&](DbgVariableIntrinsic *DII, uint64_t Offset) {
16174ba319b5SDimitry Andric     SmallVector<uint64_t, 8> Ops;
16184ba319b5SDimitry Andric     DIExpression::appendOffset(Ops, Offset);
16194ba319b5SDimitry Andric     doSalvage(DII, Ops);
16204ba319b5SDimitry Andric   };
16214ba319b5SDimitry Andric 
1622*b5893f02SDimitry Andric   auto applyOps = [&](DbgVariableIntrinsic *DII,
16234ba319b5SDimitry Andric                       std::initializer_list<uint64_t> Opcodes) {
16244ba319b5SDimitry Andric     SmallVector<uint64_t, 8> Ops(Opcodes);
16254ba319b5SDimitry Andric     doSalvage(DII, Ops);
16264ba319b5SDimitry Andric   };
16274ba319b5SDimitry Andric 
16284ba319b5SDimitry Andric   if (auto *CI = dyn_cast<CastInst>(&I)) {
16294ba319b5SDimitry Andric     if (!CI->isNoopCast(DL))
16304ba319b5SDimitry Andric       return false;
16314ba319b5SDimitry Andric 
16324ba319b5SDimitry Andric     // No-op casts are irrelevant for debug info.
16334ba319b5SDimitry Andric     MetadataAsValue *CastSrc = wrapMD(I.getOperand(0));
16344ba319b5SDimitry Andric     for (auto *DII : DbgUsers) {
16354ba319b5SDimitry Andric       DII->setOperand(0, CastSrc);
16364ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
16374ba319b5SDimitry Andric     }
16384ba319b5SDimitry Andric     return true;
16397a7e6055SDimitry Andric   } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
16407a7e6055SDimitry Andric     unsigned BitWidth =
16414ba319b5SDimitry Andric         M.getDataLayout().getIndexSizeInBits(GEP->getPointerAddressSpace());
164251690af2SDimitry Andric     // Rewrite a constant GEP into a DIExpression.  Since we are performing
164351690af2SDimitry Andric     // arithmetic to compute the variable's *value* in the DIExpression, we
164451690af2SDimitry Andric     // need to mark the expression with a DW_OP_stack_value.
16454ba319b5SDimitry Andric     APInt Offset(BitWidth, 0);
16462cab237bSDimitry Andric     if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset))
16474ba319b5SDimitry Andric       for (auto *DII : DbgUsers)
16484ba319b5SDimitry Andric         applyOffset(DII, Offset.getSExtValue());
16494ba319b5SDimitry Andric     return true;
16502cab237bSDimitry Andric   } else if (auto *BI = dyn_cast<BinaryOperator>(&I)) {
16514ba319b5SDimitry Andric     // Rewrite binary operations with constant integer operands.
16524ba319b5SDimitry Andric     auto *ConstInt = dyn_cast<ConstantInt>(I.getOperand(1));
16534ba319b5SDimitry Andric     if (!ConstInt || ConstInt->getBitWidth() > 64)
16544ba319b5SDimitry Andric       return false;
16554ba319b5SDimitry Andric 
16564ba319b5SDimitry Andric     uint64_t Val = ConstInt->getSExtValue();
16574ba319b5SDimitry Andric     for (auto *DII : DbgUsers) {
16584ba319b5SDimitry Andric       switch (BI->getOpcode()) {
16594ba319b5SDimitry Andric       case Instruction::Add:
16604ba319b5SDimitry Andric         applyOffset(DII, Val);
16614ba319b5SDimitry Andric         break;
16624ba319b5SDimitry Andric       case Instruction::Sub:
16634ba319b5SDimitry Andric         applyOffset(DII, -int64_t(Val));
16644ba319b5SDimitry Andric         break;
16654ba319b5SDimitry Andric       case Instruction::Mul:
16664ba319b5SDimitry Andric         applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_mul});
16674ba319b5SDimitry Andric         break;
16684ba319b5SDimitry Andric       case Instruction::SDiv:
16694ba319b5SDimitry Andric         applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_div});
16704ba319b5SDimitry Andric         break;
16714ba319b5SDimitry Andric       case Instruction::SRem:
16724ba319b5SDimitry Andric         applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_mod});
16734ba319b5SDimitry Andric         break;
16744ba319b5SDimitry Andric       case Instruction::Or:
16754ba319b5SDimitry Andric         applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_or});
16764ba319b5SDimitry Andric         break;
16774ba319b5SDimitry Andric       case Instruction::And:
16784ba319b5SDimitry Andric         applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_and});
16794ba319b5SDimitry Andric         break;
16804ba319b5SDimitry Andric       case Instruction::Xor:
16814ba319b5SDimitry Andric         applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_xor});
16824ba319b5SDimitry Andric         break;
16834ba319b5SDimitry Andric       case Instruction::Shl:
16844ba319b5SDimitry Andric         applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_shl});
16854ba319b5SDimitry Andric         break;
16864ba319b5SDimitry Andric       case Instruction::LShr:
16874ba319b5SDimitry Andric         applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_shr});
16884ba319b5SDimitry Andric         break;
16894ba319b5SDimitry Andric       case Instruction::AShr:
16904ba319b5SDimitry Andric         applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_shra});
16914ba319b5SDimitry Andric         break;
16924ba319b5SDimitry Andric       default:
16934ba319b5SDimitry Andric         // TODO: Salvage constants from each kind of binop we know about.
16944ba319b5SDimitry Andric         return false;
16957a7e6055SDimitry Andric       }
16964ba319b5SDimitry Andric     }
16974ba319b5SDimitry Andric     return true;
16987a7e6055SDimitry Andric   } else if (isa<LoadInst>(&I)) {
16994ba319b5SDimitry Andric     MetadataAsValue *AddrMD = wrapMD(I.getOperand(0));
17004ba319b5SDimitry Andric     for (auto *DII : DbgUsers) {
17017a7e6055SDimitry Andric       // Rewrite the load into DW_OP_deref.
17024ba319b5SDimitry Andric       auto *DIExpr = DII->getExpression();
1703f37b6182SDimitry Andric       DIExpr = DIExpression::prepend(DIExpr, DIExpression::WithDeref);
17044ba319b5SDimitry Andric       DII->setOperand(0, AddrMD);
17054ba319b5SDimitry Andric       DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr));
17064ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "SALVAGE:  " << *DII << '\n');
17074ba319b5SDimitry Andric     }
17084ba319b5SDimitry Andric     return true;
17094ba319b5SDimitry Andric   }
17104ba319b5SDimitry Andric   return false;
17114ba319b5SDimitry Andric }
17124ba319b5SDimitry Andric 
17134ba319b5SDimitry Andric /// A replacement for a dbg.value expression.
17144ba319b5SDimitry Andric using DbgValReplacement = Optional<DIExpression *>;
17154ba319b5SDimitry Andric 
17164ba319b5SDimitry Andric /// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
17174ba319b5SDimitry Andric /// possibly moving/deleting users to prevent use-before-def. Returns true if
17184ba319b5SDimitry Andric /// changes are made.
rewriteDebugUsers(Instruction & From,Value & To,Instruction & DomPoint,DominatorTree & DT,function_ref<DbgValReplacement (DbgVariableIntrinsic & DII)> RewriteExpr)17194ba319b5SDimitry Andric static bool rewriteDebugUsers(
17204ba319b5SDimitry Andric     Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
1721*b5893f02SDimitry Andric     function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr) {
17224ba319b5SDimitry Andric   // Find debug users of From.
1723*b5893f02SDimitry Andric   SmallVector<DbgVariableIntrinsic *, 1> Users;
17244ba319b5SDimitry Andric   findDbgUsers(Users, &From);
17254ba319b5SDimitry Andric   if (Users.empty())
17264ba319b5SDimitry Andric     return false;
17274ba319b5SDimitry Andric 
17284ba319b5SDimitry Andric   // Prevent use-before-def of To.
17294ba319b5SDimitry Andric   bool Changed = false;
1730*b5893f02SDimitry Andric   SmallPtrSet<DbgVariableIntrinsic *, 1> DeleteOrSalvage;
17314ba319b5SDimitry Andric   if (isa<Instruction>(&To)) {
17324ba319b5SDimitry Andric     bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
17334ba319b5SDimitry Andric 
17344ba319b5SDimitry Andric     for (auto *DII : Users) {
17354ba319b5SDimitry Andric       // It's common to see a debug user between From and DomPoint. Move it
17364ba319b5SDimitry Andric       // after DomPoint to preserve the variable update without any reordering.
17374ba319b5SDimitry Andric       if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
17384ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "MOVE:  " << *DII << '\n');
17394ba319b5SDimitry Andric         DII->moveAfter(&DomPoint);
17404ba319b5SDimitry Andric         Changed = true;
17414ba319b5SDimitry Andric 
17424ba319b5SDimitry Andric       // Users which otherwise aren't dominated by the replacement value must
17434ba319b5SDimitry Andric       // be salvaged or deleted.
17444ba319b5SDimitry Andric       } else if (!DT.dominates(&DomPoint, DII)) {
17454ba319b5SDimitry Andric         DeleteOrSalvage.insert(DII);
17467a7e6055SDimitry Andric       }
17477a7e6055SDimitry Andric     }
17487a7e6055SDimitry Andric   }
17497a7e6055SDimitry Andric 
17504ba319b5SDimitry Andric   // Update debug users without use-before-def risk.
17514ba319b5SDimitry Andric   for (auto *DII : Users) {
17524ba319b5SDimitry Andric     if (DeleteOrSalvage.count(DII))
17534ba319b5SDimitry Andric       continue;
17544ba319b5SDimitry Andric 
17554ba319b5SDimitry Andric     LLVMContext &Ctx = DII->getContext();
17564ba319b5SDimitry Andric     DbgValReplacement DVR = RewriteExpr(*DII);
17574ba319b5SDimitry Andric     if (!DVR)
17584ba319b5SDimitry Andric       continue;
17594ba319b5SDimitry Andric 
17604ba319b5SDimitry Andric     DII->setOperand(0, wrapValueInMetadata(Ctx, &To));
17614ba319b5SDimitry Andric     DII->setOperand(2, MetadataAsValue::get(Ctx, *DVR));
17624ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "REWRITE:  " << *DII << '\n');
17634ba319b5SDimitry Andric     Changed = true;
17644ba319b5SDimitry Andric   }
17654ba319b5SDimitry Andric 
17664ba319b5SDimitry Andric   if (!DeleteOrSalvage.empty()) {
17674ba319b5SDimitry Andric     // Try to salvage the remaining debug users.
17684ba319b5SDimitry Andric     Changed |= salvageDebugInfo(From);
17694ba319b5SDimitry Andric 
17704ba319b5SDimitry Andric     // Delete the debug users which weren't salvaged.
17714ba319b5SDimitry Andric     for (auto *DII : DeleteOrSalvage) {
17724ba319b5SDimitry Andric       if (DII->getVariableLocation() == &From) {
17734ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "Erased UseBeforeDef:  " << *DII << '\n');
17744ba319b5SDimitry Andric         DII->eraseFromParent();
17754ba319b5SDimitry Andric         Changed = true;
17764ba319b5SDimitry Andric       }
17774ba319b5SDimitry Andric     }
17784ba319b5SDimitry Andric   }
17794ba319b5SDimitry Andric 
17804ba319b5SDimitry Andric   return Changed;
17814ba319b5SDimitry Andric }
17824ba319b5SDimitry Andric 
17834ba319b5SDimitry Andric /// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
17844ba319b5SDimitry Andric /// losslessly preserve the bits and semantics of the value. This predicate is
17854ba319b5SDimitry Andric /// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
17864ba319b5SDimitry Andric ///
17874ba319b5SDimitry Andric /// Note that Type::canLosslesslyBitCastTo is not suitable here because it
17884ba319b5SDimitry Andric /// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
17894ba319b5SDimitry Andric /// and also does not allow lossless pointer <-> integer conversions.
isBitCastSemanticsPreserving(const DataLayout & DL,Type * FromTy,Type * ToTy)17904ba319b5SDimitry Andric static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
17914ba319b5SDimitry Andric                                          Type *ToTy) {
17924ba319b5SDimitry Andric   // Trivially compatible types.
17934ba319b5SDimitry Andric   if (FromTy == ToTy)
17944ba319b5SDimitry Andric     return true;
17954ba319b5SDimitry Andric 
17964ba319b5SDimitry Andric   // Handle compatible pointer <-> integer conversions.
17974ba319b5SDimitry Andric   if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
17984ba319b5SDimitry Andric     bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
17994ba319b5SDimitry Andric     bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
18004ba319b5SDimitry Andric                               !DL.isNonIntegralPointerType(ToTy);
18014ba319b5SDimitry Andric     return SameSize && LosslessConversion;
18024ba319b5SDimitry Andric   }
18034ba319b5SDimitry Andric 
18044ba319b5SDimitry Andric   // TODO: This is not exhaustive.
18054ba319b5SDimitry Andric   return false;
18064ba319b5SDimitry Andric }
18074ba319b5SDimitry Andric 
replaceAllDbgUsesWith(Instruction & From,Value & To,Instruction & DomPoint,DominatorTree & DT)18084ba319b5SDimitry Andric bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
18094ba319b5SDimitry Andric                                  Instruction &DomPoint, DominatorTree &DT) {
18104ba319b5SDimitry Andric   // Exit early if From has no debug users.
18114ba319b5SDimitry Andric   if (!From.isUsedByMetadata())
18124ba319b5SDimitry Andric     return false;
18134ba319b5SDimitry Andric 
18144ba319b5SDimitry Andric   assert(&From != &To && "Can't replace something with itself");
18154ba319b5SDimitry Andric 
18164ba319b5SDimitry Andric   Type *FromTy = From.getType();
18174ba319b5SDimitry Andric   Type *ToTy = To.getType();
18184ba319b5SDimitry Andric 
1819*b5893f02SDimitry Andric   auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
18204ba319b5SDimitry Andric     return DII.getExpression();
18214ba319b5SDimitry Andric   };
18224ba319b5SDimitry Andric 
18234ba319b5SDimitry Andric   // Handle no-op conversions.
18244ba319b5SDimitry Andric   Module &M = *From.getModule();
18254ba319b5SDimitry Andric   const DataLayout &DL = M.getDataLayout();
18264ba319b5SDimitry Andric   if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
18274ba319b5SDimitry Andric     return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
18284ba319b5SDimitry Andric 
18294ba319b5SDimitry Andric   // Handle integer-to-integer widening and narrowing.
18304ba319b5SDimitry Andric   // FIXME: Use DW_OP_convert when it's available everywhere.
18314ba319b5SDimitry Andric   if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
18324ba319b5SDimitry Andric     uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
18334ba319b5SDimitry Andric     uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
18344ba319b5SDimitry Andric     assert(FromBits != ToBits && "Unexpected no-op conversion");
18354ba319b5SDimitry Andric 
18364ba319b5SDimitry Andric     // When the width of the result grows, assume that a debugger will only
18374ba319b5SDimitry Andric     // access the low `FromBits` bits when inspecting the source variable.
18384ba319b5SDimitry Andric     if (FromBits < ToBits)
18394ba319b5SDimitry Andric       return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
18404ba319b5SDimitry Andric 
18414ba319b5SDimitry Andric     // The width of the result has shrunk. Use sign/zero extension to describe
18424ba319b5SDimitry Andric     // the source variable's high bits.
1843*b5893f02SDimitry Andric     auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
18444ba319b5SDimitry Andric       DILocalVariable *Var = DII.getVariable();
18454ba319b5SDimitry Andric 
18464ba319b5SDimitry Andric       // Without knowing signedness, sign/zero extension isn't possible.
18474ba319b5SDimitry Andric       auto Signedness = Var->getSignedness();
18484ba319b5SDimitry Andric       if (!Signedness)
18494ba319b5SDimitry Andric         return None;
18504ba319b5SDimitry Andric 
18514ba319b5SDimitry Andric       bool Signed = *Signedness == DIBasicType::Signedness::Signed;
18524ba319b5SDimitry Andric 
18534ba319b5SDimitry Andric       if (!Signed) {
18544ba319b5SDimitry Andric         // In the unsigned case, assume that a debugger will initialize the
18554ba319b5SDimitry Andric         // high bits to 0 and do a no-op conversion.
18564ba319b5SDimitry Andric         return Identity(DII);
18574ba319b5SDimitry Andric       } else {
18584ba319b5SDimitry Andric         // In the signed case, the high bits are given by sign extension, i.e:
18594ba319b5SDimitry Andric         //   (To >> (ToBits - 1)) * ((2 ^ FromBits) - 1)
18604ba319b5SDimitry Andric         // Calculate the high bits and OR them together with the low bits.
18614ba319b5SDimitry Andric         SmallVector<uint64_t, 8> Ops({dwarf::DW_OP_dup, dwarf::DW_OP_constu,
18624ba319b5SDimitry Andric                                       (ToBits - 1), dwarf::DW_OP_shr,
18634ba319b5SDimitry Andric                                       dwarf::DW_OP_lit0, dwarf::DW_OP_not,
18644ba319b5SDimitry Andric                                       dwarf::DW_OP_mul, dwarf::DW_OP_or});
18654ba319b5SDimitry Andric         return DIExpression::appendToStack(DII.getExpression(), Ops);
18664ba319b5SDimitry Andric       }
18674ba319b5SDimitry Andric     };
18684ba319b5SDimitry Andric     return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt);
18694ba319b5SDimitry Andric   }
18704ba319b5SDimitry Andric 
18714ba319b5SDimitry Andric   // TODO: Floating-point conversions, vectors.
18724ba319b5SDimitry Andric   return false;
18734ba319b5SDimitry Andric }
18744ba319b5SDimitry Andric 
removeAllNonTerminatorAndEHPadInstructions(BasicBlock * BB)18753ca95b02SDimitry Andric unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
18763ca95b02SDimitry Andric   unsigned NumDeadInst = 0;
18773ca95b02SDimitry Andric   // Delete the instructions backwards, as it has a reduced likelihood of
18783ca95b02SDimitry Andric   // having to update as many def-use and use-def chains.
18793ca95b02SDimitry Andric   Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
18803ca95b02SDimitry Andric   while (EndInst != &BB->front()) {
18813ca95b02SDimitry Andric     // Delete the next to last instruction.
18823ca95b02SDimitry Andric     Instruction *Inst = &*--EndInst->getIterator();
18833ca95b02SDimitry Andric     if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
18843ca95b02SDimitry Andric       Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
18853ca95b02SDimitry Andric     if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
18863ca95b02SDimitry Andric       EndInst = Inst;
18873ca95b02SDimitry Andric       continue;
18883ca95b02SDimitry Andric     }
18893ca95b02SDimitry Andric     if (!isa<DbgInfoIntrinsic>(Inst))
18903ca95b02SDimitry Andric       ++NumDeadInst;
18913ca95b02SDimitry Andric     Inst->eraseFromParent();
18923ca95b02SDimitry Andric   }
18933ca95b02SDimitry Andric   return NumDeadInst;
18943ca95b02SDimitry Andric }
18953ca95b02SDimitry Andric 
changeToUnreachable(Instruction * I,bool UseLLVMTrap,bool PreserveLCSSA,DomTreeUpdater * DTU)1896d88c1a5aSDimitry Andric unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
1897*b5893f02SDimitry Andric                                    bool PreserveLCSSA, DomTreeUpdater *DTU) {
1898f785676fSDimitry Andric   BasicBlock *BB = I->getParent();
18994ba319b5SDimitry Andric   std::vector <DominatorTree::UpdateType> Updates;
19004ba319b5SDimitry Andric 
1901f785676fSDimitry Andric   // Loop over all of the successors, removing BB's entry from any PHI
1902f785676fSDimitry Andric   // nodes.
1903*b5893f02SDimitry Andric   if (DTU)
19044ba319b5SDimitry Andric     Updates.reserve(BB->getTerminator()->getNumSuccessors());
19054ba319b5SDimitry Andric   for (BasicBlock *Successor : successors(BB)) {
1906d88c1a5aSDimitry Andric     Successor->removePredecessor(BB, PreserveLCSSA);
1907*b5893f02SDimitry Andric     if (DTU)
19084ba319b5SDimitry Andric       Updates.push_back({DominatorTree::Delete, BB, Successor});
19094ba319b5SDimitry Andric   }
1910f785676fSDimitry Andric   // Insert a call to llvm.trap right before this.  This turns the undefined
1911f785676fSDimitry Andric   // behavior into a hard fail instead of falling through into random code.
1912f785676fSDimitry Andric   if (UseLLVMTrap) {
1913f785676fSDimitry Andric     Function *TrapFn =
1914f785676fSDimitry Andric       Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
1915f785676fSDimitry Andric     CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
1916f785676fSDimitry Andric     CallTrap->setDebugLoc(I->getDebugLoc());
1917f785676fSDimitry Andric   }
1918*b5893f02SDimitry Andric   auto *UI = new UnreachableInst(I->getContext(), I);
1919*b5893f02SDimitry Andric   UI->setDebugLoc(I->getDebugLoc());
1920f785676fSDimitry Andric 
1921f785676fSDimitry Andric   // All instructions after this are dead.
19223ca95b02SDimitry Andric   unsigned NumInstrsRemoved = 0;
19237d523365SDimitry Andric   BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
1924f785676fSDimitry Andric   while (BBI != BBE) {
1925f785676fSDimitry Andric     if (!BBI->use_empty())
1926f785676fSDimitry Andric       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
1927f785676fSDimitry Andric     BB->getInstList().erase(BBI++);
19283ca95b02SDimitry Andric     ++NumInstrsRemoved;
1929f785676fSDimitry Andric   }
1930*b5893f02SDimitry Andric   if (DTU)
1931*b5893f02SDimitry Andric     DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
19323ca95b02SDimitry Andric   return NumInstrsRemoved;
1933f785676fSDimitry Andric }
1934f785676fSDimitry Andric 
1935f785676fSDimitry Andric /// changeToCall - Convert the specified invoke into a normal call.
changeToCall(InvokeInst * II,DomTreeUpdater * DTU=nullptr)1936*b5893f02SDimitry Andric static void changeToCall(InvokeInst *II, DomTreeUpdater *DTU = nullptr) {
19377d523365SDimitry Andric   SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end());
19387d523365SDimitry Andric   SmallVector<OperandBundleDef, 1> OpBundles;
19397d523365SDimitry Andric   II->getOperandBundlesAsDefs(OpBundles);
19407d523365SDimitry Andric   CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, OpBundles,
19417d523365SDimitry Andric                                        "", II);
1942f785676fSDimitry Andric   NewCall->takeName(II);
1943f785676fSDimitry Andric   NewCall->setCallingConv(II->getCallingConv());
1944f785676fSDimitry Andric   NewCall->setAttributes(II->getAttributes());
1945f785676fSDimitry Andric   NewCall->setDebugLoc(II->getDebugLoc());
1946*b5893f02SDimitry Andric   NewCall->copyMetadata(*II);
1947f785676fSDimitry Andric   II->replaceAllUsesWith(NewCall);
1948f785676fSDimitry Andric 
1949f785676fSDimitry Andric   // Follow the call by a branch to the normal destination.
19504ba319b5SDimitry Andric   BasicBlock *NormalDestBB = II->getNormalDest();
19514ba319b5SDimitry Andric   BranchInst::Create(NormalDestBB, II);
1952f785676fSDimitry Andric 
1953f785676fSDimitry Andric   // Update PHI nodes in the unwind destination
19544ba319b5SDimitry Andric   BasicBlock *BB = II->getParent();
19554ba319b5SDimitry Andric   BasicBlock *UnwindDestBB = II->getUnwindDest();
19564ba319b5SDimitry Andric   UnwindDestBB->removePredecessor(BB);
1957f785676fSDimitry Andric   II->eraseFromParent();
1958*b5893f02SDimitry Andric   if (DTU)
1959*b5893f02SDimitry Andric     DTU->deleteEdgeRelaxed(BB, UnwindDestBB);
1960f785676fSDimitry Andric }
1961f785676fSDimitry Andric 
changeToInvokeAndSplitBasicBlock(CallInst * CI,BasicBlock * UnwindEdge)1962d88c1a5aSDimitry Andric BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
1963d88c1a5aSDimitry Andric                                                    BasicBlock *UnwindEdge) {
1964d88c1a5aSDimitry Andric   BasicBlock *BB = CI->getParent();
1965d88c1a5aSDimitry Andric 
1966d88c1a5aSDimitry Andric   // Convert this function call into an invoke instruction.  First, split the
1967d88c1a5aSDimitry Andric   // basic block.
1968d88c1a5aSDimitry Andric   BasicBlock *Split =
1969d88c1a5aSDimitry Andric       BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
1970d88c1a5aSDimitry Andric 
1971d88c1a5aSDimitry Andric   // Delete the unconditional branch inserted by splitBasicBlock
1972d88c1a5aSDimitry Andric   BB->getInstList().pop_back();
1973d88c1a5aSDimitry Andric 
1974d88c1a5aSDimitry Andric   // Create the new invoke instruction.
1975d88c1a5aSDimitry Andric   SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
1976d88c1a5aSDimitry Andric   SmallVector<OperandBundleDef, 1> OpBundles;
1977d88c1a5aSDimitry Andric 
1978d88c1a5aSDimitry Andric   CI->getOperandBundlesAsDefs(OpBundles);
1979d88c1a5aSDimitry Andric 
1980d88c1a5aSDimitry Andric   // Note: we're round tripping operand bundles through memory here, and that
1981d88c1a5aSDimitry Andric   // can potentially be avoided with a cleverer API design that we do not have
1982d88c1a5aSDimitry Andric   // as of this time.
1983d88c1a5aSDimitry Andric 
1984d88c1a5aSDimitry Andric   InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split, UnwindEdge,
1985d88c1a5aSDimitry Andric                                       InvokeArgs, OpBundles, CI->getName(), BB);
1986d88c1a5aSDimitry Andric   II->setDebugLoc(CI->getDebugLoc());
1987d88c1a5aSDimitry Andric   II->setCallingConv(CI->getCallingConv());
1988d88c1a5aSDimitry Andric   II->setAttributes(CI->getAttributes());
1989d88c1a5aSDimitry Andric 
1990d88c1a5aSDimitry Andric   // Make sure that anything using the call now uses the invoke!  This also
1991f37b6182SDimitry Andric   // updates the CallGraph if present, because it uses a WeakTrackingVH.
1992d88c1a5aSDimitry Andric   CI->replaceAllUsesWith(II);
1993d88c1a5aSDimitry Andric 
1994d88c1a5aSDimitry Andric   // Delete the original call
1995d88c1a5aSDimitry Andric   Split->getInstList().pop_front();
1996d88c1a5aSDimitry Andric   return Split;
1997d88c1a5aSDimitry Andric }
1998d88c1a5aSDimitry Andric 
markAliveBlocks(Function & F,SmallPtrSetImpl<BasicBlock * > & Reachable,DomTreeUpdater * DTU=nullptr)19998f0fd8f6SDimitry Andric static bool markAliveBlocks(Function &F,
20004ba319b5SDimitry Andric                             SmallPtrSetImpl<BasicBlock *> &Reachable,
2001*b5893f02SDimitry Andric                             DomTreeUpdater *DTU = nullptr) {
2002139f7f9bSDimitry Andric   SmallVector<BasicBlock*, 128> Worklist;
20037d523365SDimitry Andric   BasicBlock *BB = &F.front();
2004f785676fSDimitry Andric   Worklist.push_back(BB);
2005f785676fSDimitry Andric   Reachable.insert(BB);
2006f785676fSDimitry Andric   bool Changed = false;
2007139f7f9bSDimitry Andric   do {
2008f785676fSDimitry Andric     BB = Worklist.pop_back_val();
2009f785676fSDimitry Andric 
2010f785676fSDimitry Andric     // Do a quick scan of the basic block, turning any obviously unreachable
2011f785676fSDimitry Andric     // instructions into LLVM unreachable insts.  The instruction combining pass
2012f785676fSDimitry Andric     // canonicalizes unreachable insts into stores to null or undef.
20133ca95b02SDimitry Andric     for (Instruction &I : *BB) {
20144ba319b5SDimitry Andric       if (auto *CI = dyn_cast<CallInst>(&I)) {
20154ba319b5SDimitry Andric         Value *Callee = CI->getCalledValue();
20164ba319b5SDimitry Andric         // Handle intrinsic calls.
20174ba319b5SDimitry Andric         if (Function *F = dyn_cast<Function>(Callee)) {
20184ba319b5SDimitry Andric           auto IntrinsicID = F->getIntrinsicID();
20194ba319b5SDimitry Andric           // Assumptions that are known to be false are equivalent to
20204ba319b5SDimitry Andric           // unreachable. Also, if the condition is undefined, then we make the
20214ba319b5SDimitry Andric           // choice most beneficial to the optimizer, and choose that to also be
20224ba319b5SDimitry Andric           // unreachable.
20234ba319b5SDimitry Andric           if (IntrinsicID == Intrinsic::assume) {
20244ba319b5SDimitry Andric             if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
202539d628a0SDimitry Andric               // Don't insert a call to llvm.trap right before the unreachable.
2026*b5893f02SDimitry Andric               changeToUnreachable(CI, false, false, DTU);
202739d628a0SDimitry Andric               Changed = true;
202839d628a0SDimitry Andric               break;
202939d628a0SDimitry Andric             }
20304ba319b5SDimitry Andric           } else if (IntrinsicID == Intrinsic::experimental_guard) {
20314ba319b5SDimitry Andric             // A call to the guard intrinsic bails out of the current
20324ba319b5SDimitry Andric             // compilation unit if the predicate passed to it is false. If the
20334ba319b5SDimitry Andric             // predicate is a constant false, then we know the guard will bail
20344ba319b5SDimitry Andric             // out of the current compile unconditionally, so all code following
20354ba319b5SDimitry Andric             // it is dead.
20363ca95b02SDimitry Andric             //
20373ca95b02SDimitry Andric             // Note: unlike in llvm.assume, it is not "obviously profitable" for
20383ca95b02SDimitry Andric             // guards to treat `undef` as `false` since a guard on `undef` can
20393ca95b02SDimitry Andric             // still be useful for widening.
20404ba319b5SDimitry Andric             if (match(CI->getArgOperand(0), m_Zero()))
20414ba319b5SDimitry Andric               if (!isa<UnreachableInst>(CI->getNextNode())) {
20424ba319b5SDimitry Andric                 changeToUnreachable(CI->getNextNode(), /*UseLLVMTrap=*/false,
2043*b5893f02SDimitry Andric                                     false, DTU);
20443ca95b02SDimitry Andric                 Changed = true;
20453ca95b02SDimitry Andric                 break;
20463ca95b02SDimitry Andric               }
20473ca95b02SDimitry Andric           }
20484ba319b5SDimitry Andric         } else if ((isa<ConstantPointerNull>(Callee) &&
20494ba319b5SDimitry Andric                     !NullPointerIsDefined(CI->getFunction())) ||
20504ba319b5SDimitry Andric                    isa<UndefValue>(Callee)) {
2051*b5893f02SDimitry Andric           changeToUnreachable(CI, /*UseLLVMTrap=*/false, false, DTU);
20523ca95b02SDimitry Andric           Changed = true;
20533ca95b02SDimitry Andric           break;
20543ca95b02SDimitry Andric         }
2055f785676fSDimitry Andric         if (CI->doesNotReturn()) {
2056f785676fSDimitry Andric           // If we found a call to a no-return function, insert an unreachable
2057f785676fSDimitry Andric           // instruction after it.  Make sure there isn't *already* one there
2058f785676fSDimitry Andric           // though.
20593ca95b02SDimitry Andric           if (!isa<UnreachableInst>(CI->getNextNode())) {
2060f785676fSDimitry Andric             // Don't insert a call to llvm.trap right before the unreachable.
2061*b5893f02SDimitry Andric             changeToUnreachable(CI->getNextNode(), false, false, DTU);
2062f785676fSDimitry Andric             Changed = true;
2063f785676fSDimitry Andric           }
2064f785676fSDimitry Andric           break;
2065f785676fSDimitry Andric         }
20664ba319b5SDimitry Andric       } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
20674ba319b5SDimitry Andric         // Store to undef and store to null are undefined and used to signal
20684ba319b5SDimitry Andric         // that they should be changed to unreachable by passes that can't
20694ba319b5SDimitry Andric         // modify the CFG.
2070f785676fSDimitry Andric 
2071f785676fSDimitry Andric         // Don't touch volatile stores.
2072f785676fSDimitry Andric         if (SI->isVolatile()) continue;
2073f785676fSDimitry Andric 
2074f785676fSDimitry Andric         Value *Ptr = SI->getOperand(1);
2075f785676fSDimitry Andric 
2076f785676fSDimitry Andric         if (isa<UndefValue>(Ptr) ||
2077f785676fSDimitry Andric             (isa<ConstantPointerNull>(Ptr) &&
20784ba319b5SDimitry Andric              !NullPointerIsDefined(SI->getFunction(),
20794ba319b5SDimitry Andric                                    SI->getPointerAddressSpace()))) {
2080*b5893f02SDimitry Andric           changeToUnreachable(SI, true, false, DTU);
2081f785676fSDimitry Andric           Changed = true;
2082f785676fSDimitry Andric           break;
2083f785676fSDimitry Andric         }
2084f785676fSDimitry Andric       }
2085f785676fSDimitry Andric     }
2086f785676fSDimitry Andric 
2087*b5893f02SDimitry Andric     Instruction *Terminator = BB->getTerminator();
20884d0b32cdSDimitry Andric     if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
2089f785676fSDimitry Andric       // Turn invokes that call 'nounwind' functions into ordinary calls.
2090f785676fSDimitry Andric       Value *Callee = II->getCalledValue();
20914ba319b5SDimitry Andric       if ((isa<ConstantPointerNull>(Callee) &&
20924ba319b5SDimitry Andric            !NullPointerIsDefined(BB->getParent())) ||
20934ba319b5SDimitry Andric           isa<UndefValue>(Callee)) {
2094*b5893f02SDimitry Andric         changeToUnreachable(II, true, false, DTU);
2095f785676fSDimitry Andric         Changed = true;
20968f0fd8f6SDimitry Andric       } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
2097f785676fSDimitry Andric         if (II->use_empty() && II->onlyReadsMemory()) {
2098f785676fSDimitry Andric           // jump to the normal destination branch.
20994ba319b5SDimitry Andric           BasicBlock *NormalDestBB = II->getNormalDest();
21004ba319b5SDimitry Andric           BasicBlock *UnwindDestBB = II->getUnwindDest();
21014ba319b5SDimitry Andric           BranchInst::Create(NormalDestBB, II);
21024ba319b5SDimitry Andric           UnwindDestBB->removePredecessor(II->getParent());
2103f785676fSDimitry Andric           II->eraseFromParent();
2104*b5893f02SDimitry Andric           if (DTU)
2105*b5893f02SDimitry Andric             DTU->deleteEdgeRelaxed(BB, UnwindDestBB);
2106f785676fSDimitry Andric         } else
2107*b5893f02SDimitry Andric           changeToCall(II, DTU);
2108f785676fSDimitry Andric         Changed = true;
2109f785676fSDimitry Andric       }
21104d0b32cdSDimitry Andric     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
21114d0b32cdSDimitry Andric       // Remove catchpads which cannot be reached.
21124d0b32cdSDimitry Andric       struct CatchPadDenseMapInfo {
21134d0b32cdSDimitry Andric         static CatchPadInst *getEmptyKey() {
21144d0b32cdSDimitry Andric           return DenseMapInfo<CatchPadInst *>::getEmptyKey();
21154d0b32cdSDimitry Andric         }
21162cab237bSDimitry Andric 
21174d0b32cdSDimitry Andric         static CatchPadInst *getTombstoneKey() {
21184d0b32cdSDimitry Andric           return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
21194d0b32cdSDimitry Andric         }
21202cab237bSDimitry Andric 
21214d0b32cdSDimitry Andric         static unsigned getHashValue(CatchPadInst *CatchPad) {
21224d0b32cdSDimitry Andric           return static_cast<unsigned>(hash_combine_range(
21234d0b32cdSDimitry Andric               CatchPad->value_op_begin(), CatchPad->value_op_end()));
21244d0b32cdSDimitry Andric         }
21252cab237bSDimitry Andric 
21264d0b32cdSDimitry Andric         static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
21274d0b32cdSDimitry Andric           if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
21284d0b32cdSDimitry Andric               RHS == getEmptyKey() || RHS == getTombstoneKey())
21294d0b32cdSDimitry Andric             return LHS == RHS;
21304d0b32cdSDimitry Andric           return LHS->isIdenticalTo(RHS);
21314d0b32cdSDimitry Andric         }
21324d0b32cdSDimitry Andric       };
21334d0b32cdSDimitry Andric 
21344d0b32cdSDimitry Andric       // Set of unique CatchPads.
21354d0b32cdSDimitry Andric       SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
21364d0b32cdSDimitry Andric                     CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
21374d0b32cdSDimitry Andric           HandlerSet;
21384d0b32cdSDimitry Andric       detail::DenseSetEmpty Empty;
21394d0b32cdSDimitry Andric       for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
21404d0b32cdSDimitry Andric                                              E = CatchSwitch->handler_end();
21414d0b32cdSDimitry Andric            I != E; ++I) {
21424d0b32cdSDimitry Andric         BasicBlock *HandlerBB = *I;
21434d0b32cdSDimitry Andric         auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
21444d0b32cdSDimitry Andric         if (!HandlerSet.insert({CatchPad, Empty}).second) {
21454d0b32cdSDimitry Andric           CatchSwitch->removeHandler(I);
21464d0b32cdSDimitry Andric           --I;
21474d0b32cdSDimitry Andric           --E;
21484d0b32cdSDimitry Andric           Changed = true;
21494d0b32cdSDimitry Andric         }
21504d0b32cdSDimitry Andric       }
2151f785676fSDimitry Andric     }
2152f785676fSDimitry Andric 
2153*b5893f02SDimitry Andric     Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
21543ca95b02SDimitry Andric     for (BasicBlock *Successor : successors(BB))
21553ca95b02SDimitry Andric       if (Reachable.insert(Successor).second)
21563ca95b02SDimitry Andric         Worklist.push_back(Successor);
2157139f7f9bSDimitry Andric   } while (!Worklist.empty());
2158f785676fSDimitry Andric   return Changed;
2159139f7f9bSDimitry Andric }
2160139f7f9bSDimitry Andric 
removeUnwindEdge(BasicBlock * BB,DomTreeUpdater * DTU)2161*b5893f02SDimitry Andric void llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
2162*b5893f02SDimitry Andric   Instruction *TI = BB->getTerminator();
21637d523365SDimitry Andric 
21647d523365SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(TI)) {
2165*b5893f02SDimitry Andric     changeToCall(II, DTU);
21667d523365SDimitry Andric     return;
21677d523365SDimitry Andric   }
21687d523365SDimitry Andric 
2169*b5893f02SDimitry Andric   Instruction *NewTI;
21707d523365SDimitry Andric   BasicBlock *UnwindDest;
21717d523365SDimitry Andric 
21727d523365SDimitry Andric   if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
21737d523365SDimitry Andric     NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
21747d523365SDimitry Andric     UnwindDest = CRI->getUnwindDest();
21757d523365SDimitry Andric   } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
21767d523365SDimitry Andric     auto *NewCatchSwitch = CatchSwitchInst::Create(
21777d523365SDimitry Andric         CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
21787d523365SDimitry Andric         CatchSwitch->getName(), CatchSwitch);
21797d523365SDimitry Andric     for (BasicBlock *PadBB : CatchSwitch->handlers())
21807d523365SDimitry Andric       NewCatchSwitch->addHandler(PadBB);
21817d523365SDimitry Andric 
21827d523365SDimitry Andric     NewTI = NewCatchSwitch;
21837d523365SDimitry Andric     UnwindDest = CatchSwitch->getUnwindDest();
21847d523365SDimitry Andric   } else {
21857d523365SDimitry Andric     llvm_unreachable("Could not find unwind successor");
21867d523365SDimitry Andric   }
21877d523365SDimitry Andric 
21887d523365SDimitry Andric   NewTI->takeName(TI);
21897d523365SDimitry Andric   NewTI->setDebugLoc(TI->getDebugLoc());
21907d523365SDimitry Andric   UnwindDest->removePredecessor(BB);
21917d523365SDimitry Andric   TI->replaceAllUsesWith(NewTI);
21927d523365SDimitry Andric   TI->eraseFromParent();
2193*b5893f02SDimitry Andric   if (DTU)
2194*b5893f02SDimitry Andric     DTU->deleteEdgeRelaxed(BB, UnwindDest);
21957d523365SDimitry Andric }
21967d523365SDimitry Andric 
2197c4394386SDimitry Andric /// removeUnreachableBlocks - Remove blocks that are not reachable, even
2198f785676fSDimitry Andric /// if they are in a dead cycle.  Return true if a change was made, false
2199c4394386SDimitry Andric /// otherwise. If `LVI` is passed, this function preserves LazyValueInfo
2200c4394386SDimitry Andric /// after modifying the CFG.
removeUnreachableBlocks(Function & F,LazyValueInfo * LVI,DomTreeUpdater * DTU,MemorySSAUpdater * MSSAU)22014ba319b5SDimitry Andric bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI,
2202*b5893f02SDimitry Andric                                    DomTreeUpdater *DTU,
2203*b5893f02SDimitry Andric                                    MemorySSAUpdater *MSSAU) {
22043ca95b02SDimitry Andric   SmallPtrSet<BasicBlock*, 16> Reachable;
2205*b5893f02SDimitry Andric   bool Changed = markAliveBlocks(F, Reachable, DTU);
2206f785676fSDimitry Andric 
2207f785676fSDimitry Andric   // If there are unreachable blocks in the CFG...
2208f785676fSDimitry Andric   if (Reachable.size() == F.size())
2209f785676fSDimitry Andric     return Changed;
2210f785676fSDimitry Andric 
2211f785676fSDimitry Andric   assert(Reachable.size() < F.size());
2212f785676fSDimitry Andric   NumRemoved += F.size()-Reachable.size();
2213f785676fSDimitry Andric 
2214*b5893f02SDimitry Andric   SmallPtrSet<BasicBlock *, 16> DeadBlockSet;
22154ba319b5SDimitry Andric   for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ++I) {
22164ba319b5SDimitry Andric     auto *BB = &*I;
22174ba319b5SDimitry Andric     if (Reachable.count(BB))
2218f785676fSDimitry Andric       continue;
2219*b5893f02SDimitry Andric     DeadBlockSet.insert(BB);
2220*b5893f02SDimitry Andric   }
2221*b5893f02SDimitry Andric 
2222*b5893f02SDimitry Andric   if (MSSAU)
2223*b5893f02SDimitry Andric     MSSAU->removeBlocks(DeadBlockSet);
2224*b5893f02SDimitry Andric 
2225*b5893f02SDimitry Andric   // Loop over all of the basic blocks that are not reachable, dropping all of
2226*b5893f02SDimitry Andric   // their internal references. Update DTU and LVI if available.
2227*b5893f02SDimitry Andric   std::vector<DominatorTree::UpdateType> Updates;
2228*b5893f02SDimitry Andric   for (auto *BB : DeadBlockSet) {
22294ba319b5SDimitry Andric     for (BasicBlock *Successor : successors(BB)) {
2230*b5893f02SDimitry Andric       if (!DeadBlockSet.count(Successor))
22314ba319b5SDimitry Andric         Successor->removePredecessor(BB);
2232*b5893f02SDimitry Andric       if (DTU)
22334ba319b5SDimitry Andric         Updates.push_back({DominatorTree::Delete, BB, Successor});
22344ba319b5SDimitry Andric     }
2235444ed5c5SDimitry Andric     if (LVI)
22364ba319b5SDimitry Andric       LVI->eraseBlock(BB);
2237f785676fSDimitry Andric     BB->dropAllReferences();
2238f785676fSDimitry Andric   }
22394ba319b5SDimitry Andric   for (Function::iterator I = ++F.begin(); I != F.end();) {
22404ba319b5SDimitry Andric     auto *BB = &*I;
22414ba319b5SDimitry Andric     if (Reachable.count(BB)) {
2242139f7f9bSDimitry Andric       ++I;
22434ba319b5SDimitry Andric       continue;
22444ba319b5SDimitry Andric     }
2245*b5893f02SDimitry Andric     if (DTU) {
2246*b5893f02SDimitry Andric       // Remove the terminator of BB to clear the successor list of BB.
2247*b5893f02SDimitry Andric       if (BB->getTerminator())
2248*b5893f02SDimitry Andric         BB->getInstList().pop_back();
2249*b5893f02SDimitry Andric       new UnreachableInst(BB->getContext(), BB);
2250*b5893f02SDimitry Andric       assert(succ_empty(BB) && "The successor list of BB isn't empty before "
2251*b5893f02SDimitry Andric                                "applying corresponding DTU updates.");
22524ba319b5SDimitry Andric       ++I;
22534ba319b5SDimitry Andric     } else {
22544ba319b5SDimitry Andric       I = F.getBasicBlockList().erase(I);
22554ba319b5SDimitry Andric     }
22564ba319b5SDimitry Andric   }
2257139f7f9bSDimitry Andric 
2258*b5893f02SDimitry Andric   if (DTU) {
2259*b5893f02SDimitry Andric     DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
2260*b5893f02SDimitry Andric     bool Deleted = false;
2261*b5893f02SDimitry Andric     for (auto *BB : DeadBlockSet) {
2262*b5893f02SDimitry Andric       if (DTU->isBBPendingDeletion(BB))
2263*b5893f02SDimitry Andric         --NumRemoved;
2264*b5893f02SDimitry Andric       else
2265*b5893f02SDimitry Andric         Deleted = true;
2266*b5893f02SDimitry Andric       DTU->deleteBB(BB);
2267*b5893f02SDimitry Andric     }
2268*b5893f02SDimitry Andric     if (!Deleted)
2269*b5893f02SDimitry Andric       return false;
2270*b5893f02SDimitry Andric   }
2271139f7f9bSDimitry Andric   return true;
2272139f7f9bSDimitry Andric }
227339d628a0SDimitry Andric 
combineMetadata(Instruction * K,const Instruction * J,ArrayRef<unsigned> KnownIDs,bool DoesKMove)22747d523365SDimitry Andric void llvm::combineMetadata(Instruction *K, const Instruction *J,
2275*b5893f02SDimitry Andric                            ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
227639d628a0SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
22777d523365SDimitry Andric   K->dropUnknownNonDebugMetadata(KnownIDs);
227839d628a0SDimitry Andric   K->getAllMetadataOtherThanDebugLoc(Metadata);
2279d88c1a5aSDimitry Andric   for (const auto &MD : Metadata) {
2280d88c1a5aSDimitry Andric     unsigned Kind = MD.first;
228139d628a0SDimitry Andric     MDNode *JMD = J->getMetadata(Kind);
2282d88c1a5aSDimitry Andric     MDNode *KMD = MD.second;
228339d628a0SDimitry Andric 
228439d628a0SDimitry Andric     switch (Kind) {
228539d628a0SDimitry Andric       default:
228639d628a0SDimitry Andric         K->setMetadata(Kind, nullptr); // Remove unknown metadata
228739d628a0SDimitry Andric         break;
228839d628a0SDimitry Andric       case LLVMContext::MD_dbg:
228939d628a0SDimitry Andric         llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
229039d628a0SDimitry Andric       case LLVMContext::MD_tbaa:
229139d628a0SDimitry Andric         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
229239d628a0SDimitry Andric         break;
229339d628a0SDimitry Andric       case LLVMContext::MD_alias_scope:
229444f7b0dcSDimitry Andric         K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
229544f7b0dcSDimitry Andric         break;
229639d628a0SDimitry Andric       case LLVMContext::MD_noalias:
22973ca95b02SDimitry Andric       case LLVMContext::MD_mem_parallel_loop_access:
229839d628a0SDimitry Andric         K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
229939d628a0SDimitry Andric         break;
2300*b5893f02SDimitry Andric       case LLVMContext::MD_access_group:
2301*b5893f02SDimitry Andric         K->setMetadata(LLVMContext::MD_access_group,
2302*b5893f02SDimitry Andric                        intersectAccessGroups(K, J));
2303*b5893f02SDimitry Andric         break;
230439d628a0SDimitry Andric       case LLVMContext::MD_range:
2305*b5893f02SDimitry Andric 
2306*b5893f02SDimitry Andric         // If K does move, use most generic range. Otherwise keep the range of
2307*b5893f02SDimitry Andric         // K.
2308*b5893f02SDimitry Andric         if (DoesKMove)
2309*b5893f02SDimitry Andric           // FIXME: If K does move, we should drop the range info and nonnull.
2310*b5893f02SDimitry Andric           //        Currently this function is used with DoesKMove in passes
2311*b5893f02SDimitry Andric           //        doing hoisting/sinking and the current behavior of using the
2312*b5893f02SDimitry Andric           //        most generic range is correct in those cases.
231339d628a0SDimitry Andric           K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
231439d628a0SDimitry Andric         break;
231539d628a0SDimitry Andric       case LLVMContext::MD_fpmath:
231639d628a0SDimitry Andric         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
231739d628a0SDimitry Andric         break;
231839d628a0SDimitry Andric       case LLVMContext::MD_invariant_load:
231939d628a0SDimitry Andric         // Only set the !invariant.load if it is present in both instructions.
232039d628a0SDimitry Andric         K->setMetadata(Kind, JMD);
232139d628a0SDimitry Andric         break;
232239d628a0SDimitry Andric       case LLVMContext::MD_nonnull:
2323*b5893f02SDimitry Andric         // If K does move, keep nonull if it is present in both instructions.
2324*b5893f02SDimitry Andric         if (DoesKMove)
232539d628a0SDimitry Andric           K->setMetadata(Kind, JMD);
232639d628a0SDimitry Andric         break;
23277d523365SDimitry Andric       case LLVMContext::MD_invariant_group:
23287d523365SDimitry Andric         // Preserve !invariant.group in K.
23297d523365SDimitry Andric         break;
23307d523365SDimitry Andric       case LLVMContext::MD_align:
23317d523365SDimitry Andric         K->setMetadata(Kind,
23327d523365SDimitry Andric           MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
23337d523365SDimitry Andric         break;
23347d523365SDimitry Andric       case LLVMContext::MD_dereferenceable:
23357d523365SDimitry Andric       case LLVMContext::MD_dereferenceable_or_null:
23367d523365SDimitry Andric         K->setMetadata(Kind,
23377d523365SDimitry Andric           MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
23387d523365SDimitry Andric         break;
233939d628a0SDimitry Andric     }
234039d628a0SDimitry Andric   }
23417d523365SDimitry Andric   // Set !invariant.group from J if J has it. If both instructions have it
23427d523365SDimitry Andric   // then we will just pick it from J - even when they are different.
23437d523365SDimitry Andric   // Also make sure that K is load or store - f.e. combining bitcast with load
23447d523365SDimitry Andric   // could produce bitcast with invariant.group metadata, which is invalid.
23457d523365SDimitry Andric   // FIXME: we should try to preserve both invariant.group md if they are
23467d523365SDimitry Andric   // different, but right now instruction can only have one invariant.group.
23477d523365SDimitry Andric   if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
23487d523365SDimitry Andric     if (isa<LoadInst>(K) || isa<StoreInst>(K))
23497d523365SDimitry Andric       K->setMetadata(LLVMContext::MD_invariant_group, JMD);
235039d628a0SDimitry Andric }
2351ff0cc061SDimitry Andric 
combineMetadataForCSE(Instruction * K,const Instruction * J,bool KDominatesJ)2352*b5893f02SDimitry Andric void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
2353*b5893f02SDimitry Andric                                  bool KDominatesJ) {
2354d88c1a5aSDimitry Andric   unsigned KnownIDs[] = {
2355d88c1a5aSDimitry Andric       LLVMContext::MD_tbaa,            LLVMContext::MD_alias_scope,
2356d88c1a5aSDimitry Andric       LLVMContext::MD_noalias,         LLVMContext::MD_range,
2357d88c1a5aSDimitry Andric       LLVMContext::MD_invariant_load,  LLVMContext::MD_nonnull,
2358d88c1a5aSDimitry Andric       LLVMContext::MD_invariant_group, LLVMContext::MD_align,
2359d88c1a5aSDimitry Andric       LLVMContext::MD_dereferenceable,
2360*b5893f02SDimitry Andric       LLVMContext::MD_dereferenceable_or_null,
2361*b5893f02SDimitry Andric       LLVMContext::MD_access_group};
2362*b5893f02SDimitry Andric   combineMetadata(K, J, KnownIDs, KDominatesJ);
2363*b5893f02SDimitry Andric }
2364*b5893f02SDimitry Andric 
patchReplacementInstruction(Instruction * I,Value * Repl)2365*b5893f02SDimitry Andric void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
2366*b5893f02SDimitry Andric   auto *ReplInst = dyn_cast<Instruction>(Repl);
2367*b5893f02SDimitry Andric   if (!ReplInst)
2368*b5893f02SDimitry Andric     return;
2369*b5893f02SDimitry Andric 
2370*b5893f02SDimitry Andric   // Patch the replacement so that it is not more restrictive than the value
2371*b5893f02SDimitry Andric   // being replaced.
2372*b5893f02SDimitry Andric   // Note that if 'I' is a load being replaced by some operation,
2373*b5893f02SDimitry Andric   // for example, by an arithmetic operation, then andIRFlags()
2374*b5893f02SDimitry Andric   // would just erase all math flags from the original arithmetic
2375*b5893f02SDimitry Andric   // operation, which is clearly not wanted and not needed.
2376*b5893f02SDimitry Andric   if (!isa<LoadInst>(I))
2377*b5893f02SDimitry Andric     ReplInst->andIRFlags(I);
2378*b5893f02SDimitry Andric 
2379*b5893f02SDimitry Andric   // FIXME: If both the original and replacement value are part of the
2380*b5893f02SDimitry Andric   // same control-flow region (meaning that the execution of one
2381*b5893f02SDimitry Andric   // guarantees the execution of the other), then we can combine the
2382*b5893f02SDimitry Andric   // noalias scopes here and do better than the general conservative
2383*b5893f02SDimitry Andric   // answer used in combineMetadata().
2384*b5893f02SDimitry Andric 
2385*b5893f02SDimitry Andric   // In general, GVN unifies expressions over different control-flow
2386*b5893f02SDimitry Andric   // regions, and so we need a conservative combination of the noalias
2387*b5893f02SDimitry Andric   // scopes.
2388*b5893f02SDimitry Andric   static const unsigned KnownIDs[] = {
2389*b5893f02SDimitry Andric       LLVMContext::MD_tbaa,            LLVMContext::MD_alias_scope,
2390*b5893f02SDimitry Andric       LLVMContext::MD_noalias,         LLVMContext::MD_range,
2391*b5893f02SDimitry Andric       LLVMContext::MD_fpmath,          LLVMContext::MD_invariant_load,
2392*b5893f02SDimitry Andric       LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull,
2393*b5893f02SDimitry Andric       LLVMContext::MD_access_group};
2394*b5893f02SDimitry Andric   combineMetadata(ReplInst, I, KnownIDs, false);
2395d88c1a5aSDimitry Andric }
2396d88c1a5aSDimitry Andric 
23975517e702SDimitry Andric template <typename RootType, typename DominatesFn>
replaceDominatedUsesWith(Value * From,Value * To,const RootType & Root,const DominatesFn & Dominates)23985517e702SDimitry Andric static unsigned replaceDominatedUsesWith(Value *From, Value *To,
23995517e702SDimitry Andric                                          const RootType &Root,
24005517e702SDimitry Andric                                          const DominatesFn &Dominates) {
2401ff0cc061SDimitry Andric   assert(From->getType() == To->getType());
2402ff0cc061SDimitry Andric 
2403ff0cc061SDimitry Andric   unsigned Count = 0;
2404ff0cc061SDimitry Andric   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2405ff0cc061SDimitry Andric        UI != UE;) {
2406ff0cc061SDimitry Andric     Use &U = *UI++;
24075517e702SDimitry Andric     if (!Dominates(Root, U))
24085517e702SDimitry Andric       continue;
24097d523365SDimitry Andric     U.set(To);
24104ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Replace dominated use of '" << From->getName()
24114ba319b5SDimitry Andric                       << "' as " << *To << " in " << *U << "\n");
24127d523365SDimitry Andric     ++Count;
24137d523365SDimitry Andric   }
24147d523365SDimitry Andric   return Count;
24157d523365SDimitry Andric }
24167d523365SDimitry Andric 
replaceNonLocalUsesWith(Instruction * From,Value * To)2417302affcbSDimitry Andric unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
2418302affcbSDimitry Andric    assert(From->getType() == To->getType());
2419302affcbSDimitry Andric    auto *BB = From->getParent();
2420302affcbSDimitry Andric    unsigned Count = 0;
2421302affcbSDimitry Andric 
2422302affcbSDimitry Andric   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2423302affcbSDimitry Andric        UI != UE;) {
2424302affcbSDimitry Andric     Use &U = *UI++;
2425302affcbSDimitry Andric     auto *I = cast<Instruction>(U.getUser());
2426302affcbSDimitry Andric     if (I->getParent() == BB)
2427302affcbSDimitry Andric       continue;
2428302affcbSDimitry Andric     U.set(To);
2429302affcbSDimitry Andric     ++Count;
2430302affcbSDimitry Andric   }
2431302affcbSDimitry Andric   return Count;
2432302affcbSDimitry Andric }
2433302affcbSDimitry Andric 
replaceDominatedUsesWith(Value * From,Value * To,DominatorTree & DT,const BasicBlockEdge & Root)24345517e702SDimitry Andric unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
24355517e702SDimitry Andric                                         DominatorTree &DT,
24365517e702SDimitry Andric                                         const BasicBlockEdge &Root) {
24375517e702SDimitry Andric   auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
24385517e702SDimitry Andric     return DT.dominates(Root, U);
24395517e702SDimitry Andric   };
24405517e702SDimitry Andric   return ::replaceDominatedUsesWith(From, To, Root, Dominates);
24415517e702SDimitry Andric }
24425517e702SDimitry Andric 
replaceDominatedUsesWith(Value * From,Value * To,DominatorTree & DT,const BasicBlock * BB)24435517e702SDimitry Andric unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
24445517e702SDimitry Andric                                         DominatorTree &DT,
24455517e702SDimitry Andric                                         const BasicBlock *BB) {
24465517e702SDimitry Andric   auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) {
24475517e702SDimitry Andric     auto *I = cast<Instruction>(U.getUser())->getParent();
24485517e702SDimitry Andric     return DT.properlyDominates(BB, I);
24495517e702SDimitry Andric   };
24505517e702SDimitry Andric   return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates);
24515517e702SDimitry Andric }
24525517e702SDimitry Andric 
callsGCLeafFunction(ImmutableCallSite CS,const TargetLibraryInfo & TLI)24532cab237bSDimitry Andric bool llvm::callsGCLeafFunction(ImmutableCallSite CS,
24542cab237bSDimitry Andric                                const TargetLibraryInfo &TLI) {
24557d523365SDimitry Andric   // Check if the function is specifically marked as a gc leaf function.
24564d0b32cdSDimitry Andric   if (CS.hasFnAttr("gc-leaf-function"))
24574d0b32cdSDimitry Andric     return true;
24583ca95b02SDimitry Andric   if (const Function *F = CS.getCalledFunction()) {
24593ca95b02SDimitry Andric     if (F->hasFnAttribute("gc-leaf-function"))
24603ca95b02SDimitry Andric       return true;
24613ca95b02SDimitry Andric 
24623ca95b02SDimitry Andric     if (auto IID = F->getIntrinsicID())
24633ca95b02SDimitry Andric       // Most LLVM intrinsics do not take safepoints.
24643ca95b02SDimitry Andric       return IID != Intrinsic::experimental_gc_statepoint &&
24653ca95b02SDimitry Andric              IID != Intrinsic::experimental_deoptimize;
24663ca95b02SDimitry Andric   }
24677d523365SDimitry Andric 
24682cab237bSDimitry Andric   // Lib calls can be materialized by some passes, and won't be
24692cab237bSDimitry Andric   // marked as 'gc-leaf-function.' All available Libcalls are
24702cab237bSDimitry Andric   // GC-leaf.
24712cab237bSDimitry Andric   LibFunc LF;
24722cab237bSDimitry Andric   if (TLI.getLibFunc(CS, LF)) {
24732cab237bSDimitry Andric     return TLI.has(LF);
24742cab237bSDimitry Andric   }
24752cab237bSDimitry Andric 
24767d523365SDimitry Andric   return false;
24777d523365SDimitry Andric }
24788c24ff90SDimitry Andric 
copyNonnullMetadata(const LoadInst & OldLI,MDNode * N,LoadInst & NewLI)2479edd7eaddSDimitry Andric void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
2480edd7eaddSDimitry Andric                                LoadInst &NewLI) {
2481edd7eaddSDimitry Andric   auto *NewTy = NewLI.getType();
2482edd7eaddSDimitry Andric 
2483edd7eaddSDimitry Andric   // This only directly applies if the new type is also a pointer.
2484edd7eaddSDimitry Andric   if (NewTy->isPointerTy()) {
2485edd7eaddSDimitry Andric     NewLI.setMetadata(LLVMContext::MD_nonnull, N);
2486edd7eaddSDimitry Andric     return;
2487edd7eaddSDimitry Andric   }
2488edd7eaddSDimitry Andric 
2489edd7eaddSDimitry Andric   // The only other translation we can do is to integral loads with !range
2490edd7eaddSDimitry Andric   // metadata.
2491edd7eaddSDimitry Andric   if (!NewTy->isIntegerTy())
2492edd7eaddSDimitry Andric     return;
2493edd7eaddSDimitry Andric 
2494edd7eaddSDimitry Andric   MDBuilder MDB(NewLI.getContext());
2495edd7eaddSDimitry Andric   const Value *Ptr = OldLI.getPointerOperand();
2496edd7eaddSDimitry Andric   auto *ITy = cast<IntegerType>(NewTy);
2497edd7eaddSDimitry Andric   auto *NullInt = ConstantExpr::getPtrToInt(
2498edd7eaddSDimitry Andric       ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
2499edd7eaddSDimitry Andric   auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
2500edd7eaddSDimitry Andric   NewLI.setMetadata(LLVMContext::MD_range,
2501edd7eaddSDimitry Andric                     MDB.createRange(NonNullInt, NullInt));
2502edd7eaddSDimitry Andric }
2503edd7eaddSDimitry Andric 
copyRangeMetadata(const DataLayout & DL,const LoadInst & OldLI,MDNode * N,LoadInst & NewLI)2504edd7eaddSDimitry Andric void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
2505edd7eaddSDimitry Andric                              MDNode *N, LoadInst &NewLI) {
2506edd7eaddSDimitry Andric   auto *NewTy = NewLI.getType();
2507edd7eaddSDimitry Andric 
2508edd7eaddSDimitry Andric   // Give up unless it is converted to a pointer where there is a single very
2509edd7eaddSDimitry Andric   // valuable mapping we can do reliably.
2510edd7eaddSDimitry Andric   // FIXME: It would be nice to propagate this in more ways, but the type
2511edd7eaddSDimitry Andric   // conversions make it hard.
2512edd7eaddSDimitry Andric   if (!NewTy->isPointerTy())
2513edd7eaddSDimitry Andric     return;
2514edd7eaddSDimitry Andric 
25154ba319b5SDimitry Andric   unsigned BitWidth = DL.getIndexTypeSizeInBits(NewTy);
2516edd7eaddSDimitry Andric   if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
2517edd7eaddSDimitry Andric     MDNode *NN = MDNode::get(OldLI.getContext(), None);
2518edd7eaddSDimitry Andric     NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
2519edd7eaddSDimitry Andric   }
2520edd7eaddSDimitry Andric }
2521edd7eaddSDimitry Andric 
dropDebugUsers(Instruction & I)2522*b5893f02SDimitry Andric void llvm::dropDebugUsers(Instruction &I) {
2523*b5893f02SDimitry Andric   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
2524*b5893f02SDimitry Andric   findDbgUsers(DbgUsers, &I);
2525*b5893f02SDimitry Andric   for (auto *DII : DbgUsers)
2526*b5893f02SDimitry Andric     DII->eraseFromParent();
2527*b5893f02SDimitry Andric }
2528*b5893f02SDimitry Andric 
hoistAllInstructionsInto(BasicBlock * DomBlock,Instruction * InsertPt,BasicBlock * BB)2529*b5893f02SDimitry Andric void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
2530*b5893f02SDimitry Andric                                     BasicBlock *BB) {
2531*b5893f02SDimitry Andric   // Since we are moving the instructions out of its basic block, we do not
2532*b5893f02SDimitry Andric   // retain their original debug locations (DILocations) and debug intrinsic
2533*b5893f02SDimitry Andric   // instructions (dbg.values).
2534*b5893f02SDimitry Andric   //
2535*b5893f02SDimitry Andric   // Doing so would degrade the debugging experience and adversely affect the
2536*b5893f02SDimitry Andric   // accuracy of profiling information.
2537*b5893f02SDimitry Andric   //
2538*b5893f02SDimitry Andric   // Currently, when hoisting the instructions, we take the following actions:
2539*b5893f02SDimitry Andric   // - Remove their dbg.values.
2540*b5893f02SDimitry Andric   // - Set their debug locations to the values from the insertion point.
2541*b5893f02SDimitry Andric   //
2542*b5893f02SDimitry Andric   // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
2543*b5893f02SDimitry Andric   // need to be deleted, is because there will not be any instructions with a
2544*b5893f02SDimitry Andric   // DILocation in either branch left after performing the transformation. We
2545*b5893f02SDimitry Andric   // can only insert a dbg.value after the two branches are joined again.
2546*b5893f02SDimitry Andric   //
2547*b5893f02SDimitry Andric   // See PR38762, PR39243 for more details.
2548*b5893f02SDimitry Andric   //
2549*b5893f02SDimitry Andric   // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
2550*b5893f02SDimitry Andric   // encode predicated DIExpressions that yield different results on different
2551*b5893f02SDimitry Andric   // code paths.
2552*b5893f02SDimitry Andric   for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
2553*b5893f02SDimitry Andric     Instruction *I = &*II;
2554*b5893f02SDimitry Andric     I->dropUnknownNonDebugMetadata();
2555*b5893f02SDimitry Andric     if (I->isUsedByMetadata())
2556*b5893f02SDimitry Andric       dropDebugUsers(*I);
2557*b5893f02SDimitry Andric     if (isa<DbgVariableIntrinsic>(I)) {
2558*b5893f02SDimitry Andric       // Remove DbgInfo Intrinsics.
2559*b5893f02SDimitry Andric       II = I->eraseFromParent();
2560*b5893f02SDimitry Andric       continue;
2561*b5893f02SDimitry Andric     }
2562*b5893f02SDimitry Andric     I->setDebugLoc(InsertPt->getDebugLoc());
2563*b5893f02SDimitry Andric     ++II;
2564*b5893f02SDimitry Andric   }
2565*b5893f02SDimitry Andric   DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(),
2566*b5893f02SDimitry Andric                                  BB->begin(),
2567*b5893f02SDimitry Andric                                  BB->getTerminator()->getIterator());
2568*b5893f02SDimitry Andric }
2569*b5893f02SDimitry Andric 
2570d88c1a5aSDimitry Andric namespace {
25712cab237bSDimitry Andric 
25728c24ff90SDimitry Andric /// A potential constituent of a bitreverse or bswap expression. See
25738c24ff90SDimitry Andric /// collectBitParts for a fuller explanation.
25748c24ff90SDimitry Andric struct BitPart {
BitPart__anon799a4a1e0a11::BitPart25758c24ff90SDimitry Andric   BitPart(Value *P, unsigned BW) : Provider(P) {
25768c24ff90SDimitry Andric     Provenance.resize(BW);
25778c24ff90SDimitry Andric   }
25788c24ff90SDimitry Andric 
25798c24ff90SDimitry Andric   /// The Value that this is a bitreverse/bswap of.
25808c24ff90SDimitry Andric   Value *Provider;
25812cab237bSDimitry Andric 
25828c24ff90SDimitry Andric   /// The "provenance" of each bit. Provenance[A] = B means that bit A
25838c24ff90SDimitry Andric   /// in Provider becomes bit B in the result of this expression.
25848c24ff90SDimitry Andric   SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
25858c24ff90SDimitry Andric 
25868c24ff90SDimitry Andric   enum { Unset = -1 };
25878c24ff90SDimitry Andric };
25882cab237bSDimitry Andric 
2589d88c1a5aSDimitry Andric } // end anonymous namespace
25908c24ff90SDimitry Andric 
25918c24ff90SDimitry Andric /// Analyze the specified subexpression and see if it is capable of providing
25928c24ff90SDimitry Andric /// pieces of a bswap or bitreverse. The subexpression provides a potential
25938c24ff90SDimitry Andric /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
25948c24ff90SDimitry Andric /// the output of the expression came from a corresponding bit in some other
25958c24ff90SDimitry Andric /// value. This function is recursive, and the end result is a mapping of
25968c24ff90SDimitry Andric /// bitnumber to bitnumber. It is the caller's responsibility to validate that
25978c24ff90SDimitry Andric /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
25988c24ff90SDimitry Andric ///
25998c24ff90SDimitry Andric /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
26008c24ff90SDimitry Andric /// that the expression deposits the low byte of %X into the high byte of the
26018c24ff90SDimitry Andric /// result and that all other bits are zero. This expression is accepted and a
26028c24ff90SDimitry Andric /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
26038c24ff90SDimitry Andric /// [0-7].
26048c24ff90SDimitry Andric ///
26058c24ff90SDimitry Andric /// To avoid revisiting values, the BitPart results are memoized into the
26068c24ff90SDimitry Andric /// provided map. To avoid unnecessary copying of BitParts, BitParts are
26078c24ff90SDimitry Andric /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
26088c24ff90SDimitry Andric /// store BitParts objects, not pointers. As we need the concept of a nullptr
26098c24ff90SDimitry Andric /// BitParts (Value has been analyzed and the analysis failed), we an Optional
26108c24ff90SDimitry Andric /// type instead to provide the same functionality.
26118c24ff90SDimitry Andric ///
26128c24ff90SDimitry Andric /// Because we pass around references into \c BPS, we must use a container that
26138c24ff90SDimitry Andric /// does not invalidate internal references (std::map instead of DenseMap).
26148c24ff90SDimitry Andric static const Optional<BitPart> &
collectBitParts(Value * V,bool MatchBSwaps,bool MatchBitReversals,std::map<Value *,Optional<BitPart>> & BPS)26158c24ff90SDimitry Andric collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
26168c24ff90SDimitry Andric                 std::map<Value *, Optional<BitPart>> &BPS) {
26178c24ff90SDimitry Andric   auto I = BPS.find(V);
26188c24ff90SDimitry Andric   if (I != BPS.end())
26198c24ff90SDimitry Andric     return I->second;
26208c24ff90SDimitry Andric 
26218c24ff90SDimitry Andric   auto &Result = BPS[V] = None;
26228c24ff90SDimitry Andric   auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
26238c24ff90SDimitry Andric 
26248c24ff90SDimitry Andric   if (Instruction *I = dyn_cast<Instruction>(V)) {
26258c24ff90SDimitry Andric     // If this is an or instruction, it may be an inner node of the bswap.
26268c24ff90SDimitry Andric     if (I->getOpcode() == Instruction::Or) {
26278c24ff90SDimitry Andric       auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
26288c24ff90SDimitry Andric                                 MatchBitReversals, BPS);
26298c24ff90SDimitry Andric       auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
26308c24ff90SDimitry Andric                                 MatchBitReversals, BPS);
26318c24ff90SDimitry Andric       if (!A || !B)
26328c24ff90SDimitry Andric         return Result;
26338c24ff90SDimitry Andric 
26348c24ff90SDimitry Andric       // Try and merge the two together.
26358c24ff90SDimitry Andric       if (!A->Provider || A->Provider != B->Provider)
26368c24ff90SDimitry Andric         return Result;
26378c24ff90SDimitry Andric 
26388c24ff90SDimitry Andric       Result = BitPart(A->Provider, BitWidth);
26398c24ff90SDimitry Andric       for (unsigned i = 0; i < A->Provenance.size(); ++i) {
26408c24ff90SDimitry Andric         if (A->Provenance[i] != BitPart::Unset &&
26418c24ff90SDimitry Andric             B->Provenance[i] != BitPart::Unset &&
26428c24ff90SDimitry Andric             A->Provenance[i] != B->Provenance[i])
26438c24ff90SDimitry Andric           return Result = None;
26448c24ff90SDimitry Andric 
26458c24ff90SDimitry Andric         if (A->Provenance[i] == BitPart::Unset)
26468c24ff90SDimitry Andric           Result->Provenance[i] = B->Provenance[i];
26478c24ff90SDimitry Andric         else
26488c24ff90SDimitry Andric           Result->Provenance[i] = A->Provenance[i];
26498c24ff90SDimitry Andric       }
26508c24ff90SDimitry Andric 
26518c24ff90SDimitry Andric       return Result;
26528c24ff90SDimitry Andric     }
26538c24ff90SDimitry Andric 
26548c24ff90SDimitry Andric     // If this is a logical shift by a constant, recurse then shift the result.
26558c24ff90SDimitry Andric     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
26568c24ff90SDimitry Andric       unsigned BitShift =
26578c24ff90SDimitry Andric           cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
26588c24ff90SDimitry Andric       // Ensure the shift amount is defined.
26598c24ff90SDimitry Andric       if (BitShift > BitWidth)
26608c24ff90SDimitry Andric         return Result;
26618c24ff90SDimitry Andric 
26628c24ff90SDimitry Andric       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
26638c24ff90SDimitry Andric                                   MatchBitReversals, BPS);
26648c24ff90SDimitry Andric       if (!Res)
26658c24ff90SDimitry Andric         return Result;
26668c24ff90SDimitry Andric       Result = Res;
26678c24ff90SDimitry Andric 
26688c24ff90SDimitry Andric       // Perform the "shift" on BitProvenance.
26698c24ff90SDimitry Andric       auto &P = Result->Provenance;
26708c24ff90SDimitry Andric       if (I->getOpcode() == Instruction::Shl) {
26718c24ff90SDimitry Andric         P.erase(std::prev(P.end(), BitShift), P.end());
26728c24ff90SDimitry Andric         P.insert(P.begin(), BitShift, BitPart::Unset);
26738c24ff90SDimitry Andric       } else {
26748c24ff90SDimitry Andric         P.erase(P.begin(), std::next(P.begin(), BitShift));
26758c24ff90SDimitry Andric         P.insert(P.end(), BitShift, BitPart::Unset);
26768c24ff90SDimitry Andric       }
26778c24ff90SDimitry Andric 
26788c24ff90SDimitry Andric       return Result;
26798c24ff90SDimitry Andric     }
26808c24ff90SDimitry Andric 
26818c24ff90SDimitry Andric     // If this is a logical 'and' with a mask that clears bits, recurse then
26828c24ff90SDimitry Andric     // unset the appropriate bits.
26838c24ff90SDimitry Andric     if (I->getOpcode() == Instruction::And &&
26848c24ff90SDimitry Andric         isa<ConstantInt>(I->getOperand(1))) {
26858c24ff90SDimitry Andric       APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
26868c24ff90SDimitry Andric       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
26878c24ff90SDimitry Andric 
26888c24ff90SDimitry Andric       // Check that the mask allows a multiple of 8 bits for a bswap, for an
26898c24ff90SDimitry Andric       // early exit.
26908c24ff90SDimitry Andric       unsigned NumMaskedBits = AndMask.countPopulation();
26918c24ff90SDimitry Andric       if (!MatchBitReversals && NumMaskedBits % 8 != 0)
26928c24ff90SDimitry Andric         return Result;
26938c24ff90SDimitry Andric 
26948c24ff90SDimitry Andric       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
26958c24ff90SDimitry Andric                                   MatchBitReversals, BPS);
26968c24ff90SDimitry Andric       if (!Res)
26978c24ff90SDimitry Andric         return Result;
26988c24ff90SDimitry Andric       Result = Res;
26998c24ff90SDimitry Andric 
27008c24ff90SDimitry Andric       for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
27018c24ff90SDimitry Andric         // If the AndMask is zero for this bit, clear the bit.
27028c24ff90SDimitry Andric         if ((AndMask & Bit) == 0)
27038c24ff90SDimitry Andric           Result->Provenance[i] = BitPart::Unset;
27043ca95b02SDimitry Andric       return Result;
27053ca95b02SDimitry Andric     }
27068c24ff90SDimitry Andric 
27073ca95b02SDimitry Andric     // If this is a zext instruction zero extend the result.
27083ca95b02SDimitry Andric     if (I->getOpcode() == Instruction::ZExt) {
27093ca95b02SDimitry Andric       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
27103ca95b02SDimitry Andric                                   MatchBitReversals, BPS);
27113ca95b02SDimitry Andric       if (!Res)
27123ca95b02SDimitry Andric         return Result;
27133ca95b02SDimitry Andric 
27143ca95b02SDimitry Andric       Result = BitPart(Res->Provider, BitWidth);
27153ca95b02SDimitry Andric       auto NarrowBitWidth =
27163ca95b02SDimitry Andric           cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
27173ca95b02SDimitry Andric       for (unsigned i = 0; i < NarrowBitWidth; ++i)
27183ca95b02SDimitry Andric         Result->Provenance[i] = Res->Provenance[i];
27193ca95b02SDimitry Andric       for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
27203ca95b02SDimitry Andric         Result->Provenance[i] = BitPart::Unset;
27218c24ff90SDimitry Andric       return Result;
27228c24ff90SDimitry Andric     }
27238c24ff90SDimitry Andric   }
27248c24ff90SDimitry Andric 
27258c24ff90SDimitry Andric   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
27268c24ff90SDimitry Andric   // the input value to the bswap/bitreverse.
27278c24ff90SDimitry Andric   Result = BitPart(V, BitWidth);
27288c24ff90SDimitry Andric   for (unsigned i = 0; i < BitWidth; ++i)
27298c24ff90SDimitry Andric     Result->Provenance[i] = i;
27308c24ff90SDimitry Andric   return Result;
27318c24ff90SDimitry Andric }
27328c24ff90SDimitry Andric 
bitTransformIsCorrectForBSwap(unsigned From,unsigned To,unsigned BitWidth)27338c24ff90SDimitry Andric static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
27348c24ff90SDimitry Andric                                           unsigned BitWidth) {
27358c24ff90SDimitry Andric   if (From % 8 != To % 8)
27368c24ff90SDimitry Andric     return false;
27378c24ff90SDimitry Andric   // Convert from bit indices to byte indices and check for a byte reversal.
27388c24ff90SDimitry Andric   From >>= 3;
27398c24ff90SDimitry Andric   To >>= 3;
27408c24ff90SDimitry Andric   BitWidth >>= 3;
27418c24ff90SDimitry Andric   return From == BitWidth - To - 1;
27428c24ff90SDimitry Andric }
27438c24ff90SDimitry Andric 
bitTransformIsCorrectForBitReverse(unsigned From,unsigned To,unsigned BitWidth)27448c24ff90SDimitry Andric static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
27458c24ff90SDimitry Andric                                                unsigned BitWidth) {
27468c24ff90SDimitry Andric   return From == BitWidth - To - 1;
27478c24ff90SDimitry Andric }
27488c24ff90SDimitry Andric 
recognizeBSwapOrBitReverseIdiom(Instruction * I,bool MatchBSwaps,bool MatchBitReversals,SmallVectorImpl<Instruction * > & InsertedInsts)27493ca95b02SDimitry Andric bool llvm::recognizeBSwapOrBitReverseIdiom(
27508c24ff90SDimitry Andric     Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
27518c24ff90SDimitry Andric     SmallVectorImpl<Instruction *> &InsertedInsts) {
27528c24ff90SDimitry Andric   if (Operator::getOpcode(I) != Instruction::Or)
27538c24ff90SDimitry Andric     return false;
27548c24ff90SDimitry Andric   if (!MatchBSwaps && !MatchBitReversals)
27558c24ff90SDimitry Andric     return false;
27568c24ff90SDimitry Andric   IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
27578c24ff90SDimitry Andric   if (!ITy || ITy->getBitWidth() > 128)
27588c24ff90SDimitry Andric     return false;   // Can't do vectors or integers > 128 bits.
27598c24ff90SDimitry Andric   unsigned BW = ITy->getBitWidth();
27608c24ff90SDimitry Andric 
27613ca95b02SDimitry Andric   unsigned DemandedBW = BW;
27623ca95b02SDimitry Andric   IntegerType *DemandedTy = ITy;
27633ca95b02SDimitry Andric   if (I->hasOneUse()) {
27643ca95b02SDimitry Andric     if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
27653ca95b02SDimitry Andric       DemandedTy = cast<IntegerType>(Trunc->getType());
27663ca95b02SDimitry Andric       DemandedBW = DemandedTy->getBitWidth();
27673ca95b02SDimitry Andric     }
27683ca95b02SDimitry Andric   }
27693ca95b02SDimitry Andric 
27708c24ff90SDimitry Andric   // Try to find all the pieces corresponding to the bswap.
27718c24ff90SDimitry Andric   std::map<Value *, Optional<BitPart>> BPS;
27728c24ff90SDimitry Andric   auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS);
27738c24ff90SDimitry Andric   if (!Res)
27748c24ff90SDimitry Andric     return false;
27758c24ff90SDimitry Andric   auto &BitProvenance = Res->Provenance;
27768c24ff90SDimitry Andric 
27778c24ff90SDimitry Andric   // Now, is the bit permutation correct for a bswap or a bitreverse? We can
27788c24ff90SDimitry Andric   // only byteswap values with an even number of bytes.
27793ca95b02SDimitry Andric   bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
27803ca95b02SDimitry Andric   for (unsigned i = 0; i < DemandedBW; ++i) {
27813ca95b02SDimitry Andric     OKForBSwap &=
27823ca95b02SDimitry Andric         bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
27838c24ff90SDimitry Andric     OKForBitReverse &=
27843ca95b02SDimitry Andric         bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
27858c24ff90SDimitry Andric   }
27868c24ff90SDimitry Andric 
27878c24ff90SDimitry Andric   Intrinsic::ID Intrin;
27888c24ff90SDimitry Andric   if (OKForBSwap && MatchBSwaps)
27898c24ff90SDimitry Andric     Intrin = Intrinsic::bswap;
27908c24ff90SDimitry Andric   else if (OKForBitReverse && MatchBitReversals)
27918c24ff90SDimitry Andric     Intrin = Intrinsic::bitreverse;
27928c24ff90SDimitry Andric   else
27938c24ff90SDimitry Andric     return false;
27948c24ff90SDimitry Andric 
27953ca95b02SDimitry Andric   if (ITy != DemandedTy) {
27963ca95b02SDimitry Andric     Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
27973ca95b02SDimitry Andric     Value *Provider = Res->Provider;
27983ca95b02SDimitry Andric     IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
27993ca95b02SDimitry Andric     // We may need to truncate the provider.
28003ca95b02SDimitry Andric     if (DemandedTy != ProviderTy) {
28013ca95b02SDimitry Andric       auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
28023ca95b02SDimitry Andric                                      "trunc", I);
28033ca95b02SDimitry Andric       InsertedInsts.push_back(Trunc);
28043ca95b02SDimitry Andric       Provider = Trunc;
28053ca95b02SDimitry Andric     }
28063ca95b02SDimitry Andric     auto *CI = CallInst::Create(F, Provider, "rev", I);
28073ca95b02SDimitry Andric     InsertedInsts.push_back(CI);
28083ca95b02SDimitry Andric     auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
28093ca95b02SDimitry Andric     InsertedInsts.push_back(ExtInst);
28103ca95b02SDimitry Andric     return true;
28113ca95b02SDimitry Andric   }
28123ca95b02SDimitry Andric 
28138c24ff90SDimitry Andric   Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
28148c24ff90SDimitry Andric   InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
28158c24ff90SDimitry Andric   return true;
28168c24ff90SDimitry Andric }
28173ca95b02SDimitry Andric 
28183ca95b02SDimitry Andric // CodeGen has special handling for some string functions that may replace
28193ca95b02SDimitry Andric // them with target-specific intrinsics.  Since that'd skip our interceptors
28203ca95b02SDimitry Andric // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
28213ca95b02SDimitry Andric // we mark affected calls as NoBuiltin, which will disable optimization
28223ca95b02SDimitry Andric // in CodeGen.
maybeMarkSanitizerLibraryCallNoBuiltin(CallInst * CI,const TargetLibraryInfo * TLI)2823d88c1a5aSDimitry Andric void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
2824d88c1a5aSDimitry Andric     CallInst *CI, const TargetLibraryInfo *TLI) {
28253ca95b02SDimitry Andric   Function *F = CI->getCalledFunction();
28267a7e6055SDimitry Andric   LibFunc Func;
2827d88c1a5aSDimitry Andric   if (F && !F->hasLocalLinkage() && F->hasName() &&
2828d88c1a5aSDimitry Andric       TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
2829d88c1a5aSDimitry Andric       !F->doesNotAccessMemory())
28307a7e6055SDimitry Andric     CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
28313ca95b02SDimitry Andric }
2832302affcbSDimitry Andric 
canReplaceOperandWithVariable(const Instruction * I,unsigned OpIdx)2833302affcbSDimitry Andric bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
2834302affcbSDimitry Andric   // We can't have a PHI with a metadata type.
2835302affcbSDimitry Andric   if (I->getOperand(OpIdx)->getType()->isMetadataTy())
2836302affcbSDimitry Andric     return false;
2837302affcbSDimitry Andric 
2838302affcbSDimitry Andric   // Early exit.
2839302affcbSDimitry Andric   if (!isa<Constant>(I->getOperand(OpIdx)))
2840302affcbSDimitry Andric     return true;
2841302affcbSDimitry Andric 
2842302affcbSDimitry Andric   switch (I->getOpcode()) {
2843302affcbSDimitry Andric   default:
2844302affcbSDimitry Andric     return true;
2845302affcbSDimitry Andric   case Instruction::Call:
2846302affcbSDimitry Andric   case Instruction::Invoke:
2847c4394386SDimitry Andric     // Can't handle inline asm. Skip it.
2848c4394386SDimitry Andric     if (isa<InlineAsm>(ImmutableCallSite(I).getCalledValue()))
2849c4394386SDimitry Andric       return false;
2850302affcbSDimitry Andric     // Many arithmetic intrinsics have no issue taking a
2851302affcbSDimitry Andric     // variable, however it's hard to distingish these from
2852302affcbSDimitry Andric     // specials such as @llvm.frameaddress that require a constant.
2853302affcbSDimitry Andric     if (isa<IntrinsicInst>(I))
2854302affcbSDimitry Andric       return false;
2855302affcbSDimitry Andric 
2856302affcbSDimitry Andric     // Constant bundle operands may need to retain their constant-ness for
2857302affcbSDimitry Andric     // correctness.
2858302affcbSDimitry Andric     if (ImmutableCallSite(I).isBundleOperand(OpIdx))
2859302affcbSDimitry Andric       return false;
2860302affcbSDimitry Andric     return true;
2861302affcbSDimitry Andric   case Instruction::ShuffleVector:
2862302affcbSDimitry Andric     // Shufflevector masks are constant.
2863302affcbSDimitry Andric     return OpIdx != 2;
2864c4394386SDimitry Andric   case Instruction::Switch:
2865302affcbSDimitry Andric   case Instruction::ExtractValue:
2866302affcbSDimitry Andric     // All operands apart from the first are constant.
2867302affcbSDimitry Andric     return OpIdx == 0;
2868c4394386SDimitry Andric   case Instruction::InsertValue:
2869c4394386SDimitry Andric     // All operands apart from the first and the second are constant.
2870c4394386SDimitry Andric     return OpIdx < 2;
2871302affcbSDimitry Andric   case Instruction::Alloca:
2872c4394386SDimitry Andric     // Static allocas (constant size in the entry block) are handled by
2873c4394386SDimitry Andric     // prologue/epilogue insertion so they're free anyway. We definitely don't
2874c4394386SDimitry Andric     // want to make them non-constant.
28754ba319b5SDimitry Andric     return !cast<AllocaInst>(I)->isStaticAlloca();
2876302affcbSDimitry Andric   case Instruction::GetElementPtr:
2877302affcbSDimitry Andric     if (OpIdx == 0)
2878302affcbSDimitry Andric       return true;
2879302affcbSDimitry Andric     gep_type_iterator It = gep_type_begin(I);
2880302affcbSDimitry Andric     for (auto E = std::next(It, OpIdx); It != E; ++It)
2881302affcbSDimitry Andric       if (It.isStruct())
2882302affcbSDimitry Andric         return false;
2883302affcbSDimitry Andric     return true;
2884302affcbSDimitry Andric   }
2885302affcbSDimitry Andric }
2886