150f02cb2SNick Lewycky //===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===//
2450aa64fSDan Gohman //
3450aa64fSDan Gohman //                     The LLVM Compiler Infrastructure
4450aa64fSDan Gohman //
5450aa64fSDan Gohman // This file is distributed under the University of Illinois Open Source
6450aa64fSDan Gohman // License. See LICENSE.TXT for details.
7450aa64fSDan Gohman //
8450aa64fSDan Gohman //===----------------------------------------------------------------------===//
9450aa64fSDan Gohman //
10db5028bdSEric Christopher // This file defines several CodeGen-specific LLVM IR analysis utilities.
11450aa64fSDan Gohman //
12450aa64fSDan Gohman //===----------------------------------------------------------------------===//
13450aa64fSDan Gohman 
1409fc276dSEric Christopher #include "llvm/CodeGen/Analysis.h"
15dda00098SEric Christopher #include "llvm/Analysis/ValueTracking.h"
16ed0881b2SChandler Carruth #include "llvm/CodeGen/MachineFunction.h"
173f833edcSDavid Blaikie #include "llvm/CodeGen/TargetInstrInfo.h"
18b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetLowering.h"
19b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h"
209fb823bbSChandler Carruth #include "llvm/IR/DataLayout.h"
219fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
229fb823bbSChandler Carruth #include "llvm/IR/Function.h"
239fb823bbSChandler Carruth #include "llvm/IR/Instructions.h"
249fb823bbSChandler Carruth #include "llvm/IR/IntrinsicInst.h"
259fb823bbSChandler Carruth #include "llvm/IR/LLVMContext.h"
269fb823bbSChandler Carruth #include "llvm/IR/Module.h"
27450aa64fSDan Gohman #include "llvm/Support/ErrorHandling.h"
28450aa64fSDan Gohman #include "llvm/Support/MathExtras.h"
29f21434ccSRafael Espindola #include "llvm/Transforms/Utils/GlobalStatus.h"
30d913448bSEric Christopher 
31450aa64fSDan Gohman using namespace llvm;
32450aa64fSDan Gohman 
338923cc54SMehdi Amini /// Compute the linearized index of a member in a nested aggregate/struct/array
348923cc54SMehdi Amini /// by recursing and accumulating CurIndex as long as there are indices in the
358923cc54SMehdi Amini /// index list.
36229907cdSChris Lattner unsigned llvm::ComputeLinearIndex(Type *Ty,
37450aa64fSDan Gohman                                   const unsigned *Indices,
38450aa64fSDan Gohman                                   const unsigned *IndicesEnd,
39450aa64fSDan Gohman                                   unsigned CurIndex) {
40450aa64fSDan Gohman   // Base case: We're done.
41450aa64fSDan Gohman   if (Indices && Indices == IndicesEnd)
42450aa64fSDan Gohman     return CurIndex;
43450aa64fSDan Gohman 
44450aa64fSDan Gohman   // Given a struct type, recursively traverse the elements.
45229907cdSChris Lattner   if (StructType *STy = dyn_cast<StructType>(Ty)) {
46450aa64fSDan Gohman     for (StructType::element_iterator EB = STy->element_begin(),
47450aa64fSDan Gohman                                       EI = EB,
48450aa64fSDan Gohman                                       EE = STy->element_end();
49450aa64fSDan Gohman         EI != EE; ++EI) {
50450aa64fSDan Gohman       if (Indices && *Indices == unsigned(EI - EB))
51aadc5596SDan Gohman         return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex);
52c0196b1bSCraig Topper       CurIndex = ComputeLinearIndex(*EI, nullptr, nullptr, CurIndex);
53450aa64fSDan Gohman     }
547b068f6bSMehdi Amini     assert(!Indices && "Unexpected out of bound");
55450aa64fSDan Gohman     return CurIndex;
56450aa64fSDan Gohman   }
57450aa64fSDan Gohman   // Given an array type, recursively traverse the elements.
58229907cdSChris Lattner   else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
59229907cdSChris Lattner     Type *EltTy = ATy->getElementType();
608923cc54SMehdi Amini     unsigned NumElts = ATy->getNumElements();
618923cc54SMehdi Amini     // Compute the Linear offset when jumping one element of the array
628923cc54SMehdi Amini     unsigned EltLinearOffset = ComputeLinearIndex(EltTy, nullptr, nullptr, 0);
637b068f6bSMehdi Amini     if (Indices) {
647b068f6bSMehdi Amini       assert(*Indices < NumElts && "Unexpected out of bound");
658923cc54SMehdi Amini       // If the indice is inside the array, compute the index to the requested
668923cc54SMehdi Amini       // elt and recurse inside the element with the end of the indices list
678923cc54SMehdi Amini       CurIndex += EltLinearOffset* *Indices;
68aadc5596SDan Gohman       return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex);
69450aa64fSDan Gohman     }
708923cc54SMehdi Amini     CurIndex += EltLinearOffset*NumElts;
71450aa64fSDan Gohman     return CurIndex;
72450aa64fSDan Gohman   }
73450aa64fSDan Gohman   // We haven't found the type we're looking for, so keep searching.
74450aa64fSDan Gohman   return CurIndex + 1;
75450aa64fSDan Gohman }
76450aa64fSDan Gohman 
77450aa64fSDan Gohman /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
78450aa64fSDan Gohman /// EVTs that represent all the individual underlying
79450aa64fSDan Gohman /// non-aggregate types that comprise it.
80450aa64fSDan Gohman ///
81450aa64fSDan Gohman /// If Offsets is non-null, it points to a vector to be filled in
82450aa64fSDan Gohman /// with the in-memory offsets of each of the individual values.
83450aa64fSDan Gohman ///
8456228dabSMehdi Amini void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL,
8556228dabSMehdi Amini                            Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
86450aa64fSDan Gohman                            SmallVectorImpl<uint64_t> *Offsets,
87450aa64fSDan Gohman                            uint64_t StartingOffset) {
88450aa64fSDan Gohman   // Given a struct type, recursively traverse the elements.
89229907cdSChris Lattner   if (StructType *STy = dyn_cast<StructType>(Ty)) {
9056228dabSMehdi Amini     const StructLayout *SL = DL.getStructLayout(STy);
91450aa64fSDan Gohman     for (StructType::element_iterator EB = STy->element_begin(),
92450aa64fSDan Gohman                                       EI = EB,
93450aa64fSDan Gohman                                       EE = STy->element_end();
94450aa64fSDan Gohman          EI != EE; ++EI)
9556228dabSMehdi Amini       ComputeValueVTs(TLI, DL, *EI, ValueVTs, Offsets,
96450aa64fSDan Gohman                       StartingOffset + SL->getElementOffset(EI - EB));
97450aa64fSDan Gohman     return;
98450aa64fSDan Gohman   }
99450aa64fSDan Gohman   // Given an array type, recursively traverse the elements.
100229907cdSChris Lattner   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
101229907cdSChris Lattner     Type *EltTy = ATy->getElementType();
10256228dabSMehdi Amini     uint64_t EltSize = DL.getTypeAllocSize(EltTy);
103450aa64fSDan Gohman     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
10456228dabSMehdi Amini       ComputeValueVTs(TLI, DL, EltTy, ValueVTs, Offsets,
105450aa64fSDan Gohman                       StartingOffset + i * EltSize);
106450aa64fSDan Gohman     return;
107450aa64fSDan Gohman   }
108450aa64fSDan Gohman   // Interpret void as zero return values.
109450aa64fSDan Gohman   if (Ty->isVoidTy())
110450aa64fSDan Gohman     return;
111450aa64fSDan Gohman   // Base case: we can get an EVT for this LLVM IR type.
11244ede33aSMehdi Amini   ValueVTs.push_back(TLI.getValueType(DL, Ty));
113450aa64fSDan Gohman   if (Offsets)
114450aa64fSDan Gohman     Offsets->push_back(StartingOffset);
115450aa64fSDan Gohman }
116450aa64fSDan Gohman 
117450aa64fSDan Gohman /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
118283bc2edSReid Kleckner GlobalValue *llvm::ExtractTypeInfo(Value *V) {
119450aa64fSDan Gohman   V = V->stripPointerCasts();
120283bc2edSReid Kleckner   GlobalValue *GV = dyn_cast<GlobalValue>(V);
121283bc2edSReid Kleckner   GlobalVariable *Var = dyn_cast<GlobalVariable>(V);
122450aa64fSDan Gohman 
123283bc2edSReid Kleckner   if (Var && Var->getName() == "llvm.eh.catch.all.value") {
124283bc2edSReid Kleckner     assert(Var->hasInitializer() &&
125450aa64fSDan Gohman            "The EH catch-all value must have an initializer");
126283bc2edSReid Kleckner     Value *Init = Var->getInitializer();
127283bc2edSReid Kleckner     GV = dyn_cast<GlobalValue>(Init);
128450aa64fSDan Gohman     if (!GV) V = cast<ConstantPointerNull>(Init);
129450aa64fSDan Gohman   }
130450aa64fSDan Gohman 
131450aa64fSDan Gohman   assert((GV || isa<ConstantPointerNull>(V)) &&
132450aa64fSDan Gohman          "TypeInfo must be a global variable or NULL");
133450aa64fSDan Gohman   return GV;
134450aa64fSDan Gohman }
135450aa64fSDan Gohman 
136450aa64fSDan Gohman /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
137450aa64fSDan Gohman /// processed uses a memory 'm' constraint.
138450aa64fSDan Gohman bool
139e8360b71SJohn Thompson llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos,
140450aa64fSDan Gohman                                 const TargetLowering &TLI) {
141450aa64fSDan Gohman   for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
142450aa64fSDan Gohman     InlineAsm::ConstraintInfo &CI = CInfos[i];
143450aa64fSDan Gohman     for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
144450aa64fSDan Gohman       TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
145450aa64fSDan Gohman       if (CType == TargetLowering::C_Memory)
146450aa64fSDan Gohman         return true;
147450aa64fSDan Gohman     }
148450aa64fSDan Gohman 
149450aa64fSDan Gohman     // Indirect operand accesses access memory.
150450aa64fSDan Gohman     if (CI.isIndirect)
151450aa64fSDan Gohman       return true;
152450aa64fSDan Gohman   }
153450aa64fSDan Gohman 
154450aa64fSDan Gohman   return false;
155450aa64fSDan Gohman }
156450aa64fSDan Gohman 
157450aa64fSDan Gohman /// getFCmpCondCode - Return the ISD condition code corresponding to
158450aa64fSDan Gohman /// the given LLVM IR floating-point condition code.  This includes
159450aa64fSDan Gohman /// consideration of global floating-point math flags.
160450aa64fSDan Gohman ///
161450aa64fSDan Gohman ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
162450aa64fSDan Gohman   switch (Pred) {
16350f02cb2SNick Lewycky   case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
16450f02cb2SNick Lewycky   case FCmpInst::FCMP_OEQ:   return ISD::SETOEQ;
16550f02cb2SNick Lewycky   case FCmpInst::FCMP_OGT:   return ISD::SETOGT;
16650f02cb2SNick Lewycky   case FCmpInst::FCMP_OGE:   return ISD::SETOGE;
16750f02cb2SNick Lewycky   case FCmpInst::FCMP_OLT:   return ISD::SETOLT;
16850f02cb2SNick Lewycky   case FCmpInst::FCMP_OLE:   return ISD::SETOLE;
16950f02cb2SNick Lewycky   case FCmpInst::FCMP_ONE:   return ISD::SETONE;
17050f02cb2SNick Lewycky   case FCmpInst::FCMP_ORD:   return ISD::SETO;
17150f02cb2SNick Lewycky   case FCmpInst::FCMP_UNO:   return ISD::SETUO;
17250f02cb2SNick Lewycky   case FCmpInst::FCMP_UEQ:   return ISD::SETUEQ;
17350f02cb2SNick Lewycky   case FCmpInst::FCMP_UGT:   return ISD::SETUGT;
17450f02cb2SNick Lewycky   case FCmpInst::FCMP_UGE:   return ISD::SETUGE;
17550f02cb2SNick Lewycky   case FCmpInst::FCMP_ULT:   return ISD::SETULT;
17650f02cb2SNick Lewycky   case FCmpInst::FCMP_ULE:   return ISD::SETULE;
17750f02cb2SNick Lewycky   case FCmpInst::FCMP_UNE:   return ISD::SETUNE;
17850f02cb2SNick Lewycky   case FCmpInst::FCMP_TRUE:  return ISD::SETTRUE;
17946a9f016SDavid Blaikie   default: llvm_unreachable("Invalid FCmp predicate opcode!");
180450aa64fSDan Gohman   }
18150f02cb2SNick Lewycky }
18250f02cb2SNick Lewycky 
18350f02cb2SNick Lewycky ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
18450f02cb2SNick Lewycky   switch (CC) {
18550f02cb2SNick Lewycky     case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
18650f02cb2SNick Lewycky     case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
18750f02cb2SNick Lewycky     case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
18850f02cb2SNick Lewycky     case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
18950f02cb2SNick Lewycky     case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
19050f02cb2SNick Lewycky     case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
19146a9f016SDavid Blaikie     default: return CC;
19250f02cb2SNick Lewycky   }
193450aa64fSDan Gohman }
194450aa64fSDan Gohman 
195450aa64fSDan Gohman /// getICmpCondCode - Return the ISD condition code corresponding to
196450aa64fSDan Gohman /// the given LLVM IR integer condition code.
197450aa64fSDan Gohman ///
198450aa64fSDan Gohman ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
199450aa64fSDan Gohman   switch (Pred) {
200450aa64fSDan Gohman   case ICmpInst::ICMP_EQ:  return ISD::SETEQ;
201450aa64fSDan Gohman   case ICmpInst::ICMP_NE:  return ISD::SETNE;
202450aa64fSDan Gohman   case ICmpInst::ICMP_SLE: return ISD::SETLE;
203450aa64fSDan Gohman   case ICmpInst::ICMP_ULE: return ISD::SETULE;
204450aa64fSDan Gohman   case ICmpInst::ICMP_SGE: return ISD::SETGE;
205450aa64fSDan Gohman   case ICmpInst::ICMP_UGE: return ISD::SETUGE;
206450aa64fSDan Gohman   case ICmpInst::ICMP_SLT: return ISD::SETLT;
207450aa64fSDan Gohman   case ICmpInst::ICMP_ULT: return ISD::SETULT;
208450aa64fSDan Gohman   case ICmpInst::ICMP_SGT: return ISD::SETGT;
209450aa64fSDan Gohman   case ICmpInst::ICMP_UGT: return ISD::SETUGT;
210450aa64fSDan Gohman   default:
211450aa64fSDan Gohman     llvm_unreachable("Invalid ICmp predicate opcode!");
212450aa64fSDan Gohman   }
213450aa64fSDan Gohman }
214450aa64fSDan Gohman 
215ffc44549SStephen Lin static bool isNoopBitcast(Type *T1, Type *T2,
216c0659fadSMichael Gottesman                           const TargetLoweringBase& TLI) {
217ffc44549SStephen Lin   return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) ||
218ffc44549SStephen Lin          (isa<VectorType>(T1) && isa<VectorType>(T2) &&
219ffc44549SStephen Lin           TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2)));
220ffc44549SStephen Lin }
2214f3615deSChris Lattner 
222a4415854STim Northover /// Look through operations that will be free to find the earliest source of
223a4415854STim Northover /// this value.
224a4415854STim Northover ///
225a4415854STim Northover /// @param ValLoc If V has aggegate type, we will be interested in a particular
226a4415854STim Northover /// scalar component. This records its address; the reverse of this list gives a
227a4415854STim Northover /// sequence of indices appropriate for an extractvalue to locate the important
228a4415854STim Northover /// value. This value is updated during the function and on exit will indicate
229a4415854STim Northover /// similar information for the Value returned.
230a4415854STim Northover ///
231a4415854STim Northover /// @param DataBits If this function looks through truncate instructions, this
232a4415854STim Northover /// will record the smallest size attained.
233a4415854STim Northover static const Value *getNoopInput(const Value *V,
234a4415854STim Northover                                  SmallVectorImpl<unsigned> &ValLoc,
235a4415854STim Northover                                  unsigned &DataBits,
23644ede33aSMehdi Amini                                  const TargetLoweringBase &TLI,
23744ede33aSMehdi Amini                                  const DataLayout &DL) {
238ffc44549SStephen Lin   while (true) {
239ffc44549SStephen Lin     // Try to look through V1; if V1 is not an instruction, it can't be looked
240ffc44549SStephen Lin     // through.
241a4415854STim Northover     const Instruction *I = dyn_cast<Instruction>(V);
242a4415854STim Northover     if (!I || I->getNumOperands() == 0) return V;
243c0196b1bSCraig Topper     const Value *NoopInput = nullptr;
244a4415854STim Northover 
245182fe3eeSChris Lattner     Value *Op = I->getOperand(0);
246a4415854STim Northover     if (isa<BitCastInst>(I)) {
2474f3615deSChris Lattner       // Look through truly no-op bitcasts.
248ffc44549SStephen Lin       if (isNoopBitcast(Op->getType(), I->getType(), TLI))
249ffc44549SStephen Lin         NoopInput = Op;
250ffc44549SStephen Lin     } else if (isa<GetElementPtrInst>(I)) {
251ffc44549SStephen Lin       // Look through getelementptr
252ffc44549SStephen Lin       if (cast<GetElementPtrInst>(I)->hasAllZeroIndices())
253ffc44549SStephen Lin         NoopInput = Op;
254ffc44549SStephen Lin     } else if (isa<IntToPtrInst>(I)) {
255182fe3eeSChris Lattner       // Look through inttoptr.
256ffc44549SStephen Lin       // Make sure this isn't a truncating or extending cast.  We could
257ffc44549SStephen Lin       // support this eventually, but don't bother for now.
258ffc44549SStephen Lin       if (!isa<VectorType>(I->getType()) &&
25944ede33aSMehdi Amini           DL.getPointerSizeInBits() ==
260182fe3eeSChris Lattner               cast<IntegerType>(Op->getType())->getBitWidth())
261ffc44549SStephen Lin         NoopInput = Op;
262ffc44549SStephen Lin     } else if (isa<PtrToIntInst>(I)) {
263182fe3eeSChris Lattner       // Look through ptrtoint.
264ffc44549SStephen Lin       // Make sure this isn't a truncating or extending cast.  We could
265ffc44549SStephen Lin       // support this eventually, but don't bother for now.
266ffc44549SStephen Lin       if (!isa<VectorType>(I->getType()) &&
26744ede33aSMehdi Amini           DL.getPointerSizeInBits() ==
268182fe3eeSChris Lattner               cast<IntegerType>(I->getType())->getBitWidth())
269ffc44549SStephen Lin         NoopInput = Op;
270a4415854STim Northover     } else if (isa<TruncInst>(I) &&
271a4415854STim Northover                TLI.allowTruncateForTailCall(Op->getType(), I->getType())) {
272a4415854STim Northover       DataBits = std::min(DataBits, I->getType()->getPrimitiveSizeInBits());
273a4415854STim Northover       NoopInput = Op;
2748a41319dSAhmed Bougacha     } else if (auto CS = ImmutableCallSite(I)) {
2758a41319dSAhmed Bougacha       const Value *ReturnedOp = CS.getReturnedArgOperand();
2766aff744eSAhmed Bougacha       if (ReturnedOp && isNoopBitcast(ReturnedOp->getType(), I->getType(), TLI))
2776aff744eSAhmed Bougacha         NoopInput = ReturnedOp;
278a4415854STim Northover     } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(V)) {
279a4415854STim Northover       // Value may come from either the aggregate or the scalar
280a4415854STim Northover       ArrayRef<unsigned> InsertLoc = IVI->getIndices();
281e4310fe9STim Northover       if (ValLoc.size() >= InsertLoc.size() &&
282e4310fe9STim Northover           std::equal(InsertLoc.begin(), InsertLoc.end(), ValLoc.rbegin())) {
283a4415854STim Northover         // The type being inserted is a nested sub-type of the aggregate; we
284a4415854STim Northover         // have to remove those initial indices to get the location we're
285a4415854STim Northover         // interested in for the operand.
286a4415854STim Northover         ValLoc.resize(ValLoc.size() - InsertLoc.size());
287a4415854STim Northover         NoopInput = IVI->getInsertedValueOperand();
288a4415854STim Northover       } else {
289a4415854STim Northover         // The struct we're inserting into has the value we're interested in, no
290a4415854STim Northover         // change of address.
291a4415854STim Northover         NoopInput = Op;
292a4415854STim Northover       }
293a4415854STim Northover     } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
294a4415854STim Northover       // The part we're interested in will inevitably be some sub-section of the
295a4415854STim Northover       // previous aggregate. Combine the two paths to obtain the true address of
296a4415854STim Northover       // our element.
297a4415854STim Northover       ArrayRef<unsigned> ExtractLoc = EVI->getIndices();
2984f6ac162SBenjamin Kramer       ValLoc.append(ExtractLoc.rbegin(), ExtractLoc.rend());
299a4415854STim Northover       NoopInput = Op;
300a4415854STim Northover     }
301a4415854STim Northover     // Terminate if we couldn't find anything to look through.
302a4415854STim Northover     if (!NoopInput)
303a4415854STim Northover       return V;
304a4415854STim Northover 
305a4415854STim Northover     V = NoopInput;
306ffc44549SStephen Lin   }
307182fe3eeSChris Lattner }
308182fe3eeSChris Lattner 
309a4415854STim Northover /// Return true if this scalar return value only has bits discarded on its path
310a4415854STim Northover /// from the "tail call" to the "ret". This includes the obvious noop
311a4415854STim Northover /// instructions handled by getNoopInput above as well as free truncations (or
312a4415854STim Northover /// extensions prior to the call).
313a4415854STim Northover static bool slotOnlyDiscardsData(const Value *RetVal, const Value *CallVal,
314a4415854STim Northover                                  SmallVectorImpl<unsigned> &RetIndices,
315a4415854STim Northover                                  SmallVectorImpl<unsigned> &CallIndices,
316707d68f0STim Northover                                  bool AllowDifferingSizes,
31744ede33aSMehdi Amini                                  const TargetLoweringBase &TLI,
31844ede33aSMehdi Amini                                  const DataLayout &DL) {
3194f3615deSChris Lattner 
320a4415854STim Northover   // Trace the sub-value needed by the return value as far back up the graph as
321a4415854STim Northover   // possible, in the hope that it will intersect with the value produced by the
322a4415854STim Northover   // call. In the simple case with no "returned" attribute, the hope is actually
323a4415854STim Northover   // that we end up back at the tail call instruction itself.
324a4415854STim Northover   unsigned BitsRequired = UINT_MAX;
32544ede33aSMehdi Amini   RetVal = getNoopInput(RetVal, RetIndices, BitsRequired, TLI, DL);
326ffc44549SStephen Lin 
327a4415854STim Northover   // If this slot in the value returned is undef, it doesn't matter what the
328a4415854STim Northover   // call puts there, it'll be fine.
329a4415854STim Northover   if (isa<UndefValue>(RetVal))
330a4415854STim Northover     return true;
331ffc44549SStephen Lin 
332a4415854STim Northover   // Now do a similar search up through the graph to find where the value
333a4415854STim Northover   // actually returned by the "tail call" comes from. In the simple case without
334a4415854STim Northover   // a "returned" attribute, the search will be blocked immediately and the loop
335a4415854STim Northover   // a Noop.
336a4415854STim Northover   unsigned BitsProvided = UINT_MAX;
33744ede33aSMehdi Amini   CallVal = getNoopInput(CallVal, CallIndices, BitsProvided, TLI, DL);
338a4415854STim Northover 
339a4415854STim Northover   // There's no hope if we can't actually trace them to (the same part of!) the
340a4415854STim Northover   // same value.
341a4415854STim Northover   if (CallVal != RetVal || CallIndices != RetIndices)
342a4415854STim Northover     return false;
343a4415854STim Northover 
344a4415854STim Northover   // However, intervening truncates may have made the call non-tail. Make sure
345a4415854STim Northover   // all the bits that are needed by the "ret" have been provided by the "tail
346a4415854STim Northover   // call". FIXME: with sufficiently cunning bit-tracking, we could look through
347a4415854STim Northover   // extensions too.
348707d68f0STim Northover   if (BitsProvided < BitsRequired ||
349707d68f0STim Northover       (!AllowDifferingSizes && BitsProvided != BitsRequired))
350a4415854STim Northover     return false;
351a4415854STim Northover 
352ffc44549SStephen Lin   return true;
353ffc44549SStephen Lin }
354a4415854STim Northover 
355a4415854STim Northover /// For an aggregate type, determine whether a given index is within bounds or
356a4415854STim Northover /// not.
357a4415854STim Northover static bool indexReallyValid(CompositeType *T, unsigned Idx) {
358a4415854STim Northover   if (ArrayType *AT = dyn_cast<ArrayType>(T))
359a4415854STim Northover     return Idx < AT->getNumElements();
360a4415854STim Northover 
361a4415854STim Northover   return Idx < cast<StructType>(T)->getNumElements();
362ffc44549SStephen Lin }
363a4415854STim Northover 
364a4415854STim Northover /// Move the given iterators to the next leaf type in depth first traversal.
365a4415854STim Northover ///
366a4415854STim Northover /// Performs a depth-first traversal of the type as specified by its arguments,
367a4415854STim Northover /// stopping at the next leaf node (which may be a legitimate scalar type or an
368a4415854STim Northover /// empty struct or array).
369a4415854STim Northover ///
370a4415854STim Northover /// @param SubTypes List of the partial components making up the type from
371a4415854STim Northover /// outermost to innermost non-empty aggregate. The element currently
372a4415854STim Northover /// represented is SubTypes.back()->getTypeAtIndex(Path.back() - 1).
373a4415854STim Northover ///
374a4415854STim Northover /// @param Path Set of extractvalue indices leading from the outermost type
375a4415854STim Northover /// (SubTypes[0]) to the leaf node currently represented.
376a4415854STim Northover ///
377a4415854STim Northover /// @returns true if a new type was found, false otherwise. Calling this
378a4415854STim Northover /// function again on a finished iterator will repeatedly return
379a4415854STim Northover /// false. SubTypes.back()->getTypeAtIndex(Path.back()) is either an empty
380a4415854STim Northover /// aggregate or a non-aggregate
381df03449aSBenjamin Kramer static bool advanceToNextLeafType(SmallVectorImpl<CompositeType *> &SubTypes,
382a4415854STim Northover                                   SmallVectorImpl<unsigned> &Path) {
383a4415854STim Northover   // First march back up the tree until we can successfully increment one of the
384a4415854STim Northover   // coordinates in Path.
385a4415854STim Northover   while (!Path.empty() && !indexReallyValid(SubTypes.back(), Path.back() + 1)) {
386a4415854STim Northover     Path.pop_back();
387a4415854STim Northover     SubTypes.pop_back();
388a4415854STim Northover   }
389a4415854STim Northover 
390a4415854STim Northover   // If we reached the top, then the iterator is done.
391a4415854STim Northover   if (Path.empty())
392a4415854STim Northover     return false;
393a4415854STim Northover 
394a4415854STim Northover   // We know there's *some* valid leaf now, so march back down the tree picking
395a4415854STim Northover   // out the left-most element at each node.
396a4415854STim Northover   ++Path.back();
397a4415854STim Northover   Type *DeeperType = SubTypes.back()->getTypeAtIndex(Path.back());
398a4415854STim Northover   while (DeeperType->isAggregateType()) {
399a4415854STim Northover     CompositeType *CT = cast<CompositeType>(DeeperType);
400a4415854STim Northover     if (!indexReallyValid(CT, 0))
401a4415854STim Northover       return true;
402a4415854STim Northover 
403a4415854STim Northover     SubTypes.push_back(CT);
404a4415854STim Northover     Path.push_back(0);
405a4415854STim Northover 
406a4415854STim Northover     DeeperType = CT->getTypeAtIndex(0U);
407a4415854STim Northover   }
408a4415854STim Northover 
409ffc44549SStephen Lin   return true;
410ffc44549SStephen Lin }
411a4415854STim Northover 
412a4415854STim Northover /// Find the first non-empty, scalar-like type in Next and setup the iterator
413a4415854STim Northover /// components.
414a4415854STim Northover ///
415a4415854STim Northover /// Assuming Next is an aggregate of some kind, this function will traverse the
416a4415854STim Northover /// tree from left to right (i.e. depth-first) looking for the first
417a4415854STim Northover /// non-aggregate type which will play a role in function return.
418a4415854STim Northover ///
419a4415854STim Northover /// For example, if Next was {[0 x i64], {{}, i32, {}}, i32} then we would setup
420a4415854STim Northover /// Path as [1, 1] and SubTypes as [Next, {{}, i32, {}}] to represent the first
421a4415854STim Northover /// i32 in that type.
422a4415854STim Northover static bool firstRealType(Type *Next,
423a4415854STim Northover                           SmallVectorImpl<CompositeType *> &SubTypes,
424a4415854STim Northover                           SmallVectorImpl<unsigned> &Path) {
425a4415854STim Northover   // First initialise the iterator components to the first "leaf" node
426a4415854STim Northover   // (i.e. node with no valid sub-type at any index, so {} does count as a leaf
427a4415854STim Northover   // despite nominally being an aggregate).
428a4415854STim Northover   while (Next->isAggregateType() &&
429a4415854STim Northover          indexReallyValid(cast<CompositeType>(Next), 0)) {
430a4415854STim Northover     SubTypes.push_back(cast<CompositeType>(Next));
431a4415854STim Northover     Path.push_back(0);
432a4415854STim Northover     Next = cast<CompositeType>(Next)->getTypeAtIndex(0U);
433ffc44549SStephen Lin   }
434ffc44549SStephen Lin 
435a4415854STim Northover   // If there's no Path now, Next was originally scalar already (or empty
436a4415854STim Northover   // leaf). We're done.
437a4415854STim Northover   if (Path.empty())
438a4415854STim Northover     return true;
439ffc44549SStephen Lin 
440a4415854STim Northover   // Otherwise, use normal iteration to keep looking through the tree until we
441a4415854STim Northover   // find a non-aggregate type.
442a4415854STim Northover   while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType()) {
443a4415854STim Northover     if (!advanceToNextLeafType(SubTypes, Path))
444ffc44549SStephen Lin       return false;
445ffc44549SStephen Lin   }
4464f3615deSChris Lattner 
447a4415854STim Northover   return true;
448a4415854STim Northover }
449a4415854STim Northover 
450a4415854STim Northover /// Set the iterator data-structures to the next non-empty, non-aggregate
451a4415854STim Northover /// subtype.
452df03449aSBenjamin Kramer static bool nextRealType(SmallVectorImpl<CompositeType *> &SubTypes,
453a4415854STim Northover                          SmallVectorImpl<unsigned> &Path) {
454a4415854STim Northover   do {
455a4415854STim Northover     if (!advanceToNextLeafType(SubTypes, Path))
456a4415854STim Northover       return false;
457a4415854STim Northover 
458a4415854STim Northover     assert(!Path.empty() && "found a leaf but didn't set the path?");
459a4415854STim Northover   } while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType());
460a4415854STim Northover 
461a4415854STim Northover   return true;
462a4415854STim Northover }
463a4415854STim Northover 
464a4415854STim Northover 
465450aa64fSDan Gohman /// Test if the given instruction is in a position to be optimized
466450aa64fSDan Gohman /// with a tail-call. This roughly means that it's in a block with
467450aa64fSDan Gohman /// a return and there's nothing that needs to be scheduled
468450aa64fSDan Gohman /// between it and the return.
469450aa64fSDan Gohman ///
470450aa64fSDan Gohman /// This function only tests target-independent requirements.
471480872b4SJuergen Ributzka bool llvm::isInTailCallPosition(ImmutableCallSite CS, const TargetMachine &TM) {
472450aa64fSDan Gohman   const Instruction *I = CS.getInstruction();
473450aa64fSDan Gohman   const BasicBlock *ExitBB = I->getParent();
474450aa64fSDan Gohman   const TerminatorInst *Term = ExitBB->getTerminator();
475450aa64fSDan Gohman   const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
476450aa64fSDan Gohman 
477450aa64fSDan Gohman   // The block must end in a return statement or unreachable.
478450aa64fSDan Gohman   //
479450aa64fSDan Gohman   // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
480450aa64fSDan Gohman   // an unreachable, for now. The way tailcall optimization is currently
481450aa64fSDan Gohman   // implemented means it will add an epilogue followed by a jump. That is
482450aa64fSDan Gohman   // not profitable. Also, if the callee is a special function (e.g.
483450aa64fSDan Gohman   // longjmp on x86), it can end up causing miscompilation that has not
484450aa64fSDan Gohman   // been fully understood.
485450aa64fSDan Gohman   if (!Ret &&
4864ce9863dSJuergen Ributzka       (!TM.Options.GuaranteedTailCallOpt || !isa<UnreachableInst>(Term)))
4874f3615deSChris Lattner     return false;
488450aa64fSDan Gohman 
489450aa64fSDan Gohman   // If I will have a chain, make sure no other instruction that will have a
490450aa64fSDan Gohman   // chain interposes between I and the return.
4910a92f86fSDavid Majnemer   if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4920a92f86fSDavid Majnemer       !isSafeToSpeculativelyExecute(I))
493b6d0bd48SBenjamin Kramer     for (BasicBlock::const_iterator BBI = std::prev(ExitBB->end(), 2);; --BBI) {
494450aa64fSDan Gohman       if (&*BBI == I)
495450aa64fSDan Gohman         break;
496450aa64fSDan Gohman       // Debug info intrinsics do not get in the way of tail call optimization.
497450aa64fSDan Gohman       if (isa<DbgInfoIntrinsic>(BBI))
498450aa64fSDan Gohman         continue;
499450aa64fSDan Gohman       if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
500980f8f26SDuncan P. N. Exon Smith           !isSafeToSpeculativelyExecute(&*BBI))
501450aa64fSDan Gohman         return false;
502450aa64fSDan Gohman     }
503450aa64fSDan Gohman 
504f734a8baSEric Christopher   const Function *F = ExitBB->getParent();
505d913448bSEric Christopher   return returnTypeIsEligibleForTailCall(
506f734a8baSEric Christopher       F, I, Ret, *TM.getSubtargetImpl(*F)->getTargetLowering());
507ce0e4c26SMichael Gottesman }
508ce0e4c26SMichael Gottesman 
509f79af6f8SMichael Kuperstein bool llvm::attributesPermitTailCall(const Function *F, const Instruction *I,
510f79af6f8SMichael Kuperstein                                     const ReturnInst *Ret,
511f79af6f8SMichael Kuperstein                                     const TargetLoweringBase &TLI,
512f79af6f8SMichael Kuperstein                                     bool *AllowDifferingSizes) {
513f79af6f8SMichael Kuperstein   // ADS may be null, so don't write to it directly.
514f79af6f8SMichael Kuperstein   bool DummyADS;
515f79af6f8SMichael Kuperstein   bool &ADS = AllowDifferingSizes ? *AllowDifferingSizes : DummyADS;
516f79af6f8SMichael Kuperstein   ADS = true;
517f79af6f8SMichael Kuperstein 
518b518054bSReid Kleckner   AttrBuilder CallerAttrs(F->getAttributes(), AttributeList::ReturnIndex);
519f79af6f8SMichael Kuperstein   AttrBuilder CalleeAttrs(cast<CallInst>(I)->getAttributes(),
520b518054bSReid Kleckner                           AttributeList::ReturnIndex);
521f79af6f8SMichael Kuperstein 
522f79af6f8SMichael Kuperstein   // Noalias is completely benign as far as calling convention goes, it
523f79af6f8SMichael Kuperstein   // shouldn't affect whether the call is a tail call.
524807f732cSBjorn Pettersson   CallerAttrs.removeAttribute(Attribute::NoAlias);
525807f732cSBjorn Pettersson   CalleeAttrs.removeAttribute(Attribute::NoAlias);
526f79af6f8SMichael Kuperstein 
527f79af6f8SMichael Kuperstein   if (CallerAttrs.contains(Attribute::ZExt)) {
528f79af6f8SMichael Kuperstein     if (!CalleeAttrs.contains(Attribute::ZExt))
529f79af6f8SMichael Kuperstein       return false;
530f79af6f8SMichael Kuperstein 
531f79af6f8SMichael Kuperstein     ADS = false;
532f79af6f8SMichael Kuperstein     CallerAttrs.removeAttribute(Attribute::ZExt);
533f79af6f8SMichael Kuperstein     CalleeAttrs.removeAttribute(Attribute::ZExt);
534f79af6f8SMichael Kuperstein   } else if (CallerAttrs.contains(Attribute::SExt)) {
535f79af6f8SMichael Kuperstein     if (!CalleeAttrs.contains(Attribute::SExt))
536f79af6f8SMichael Kuperstein       return false;
537f79af6f8SMichael Kuperstein 
538f79af6f8SMichael Kuperstein     ADS = false;
539f79af6f8SMichael Kuperstein     CallerAttrs.removeAttribute(Attribute::SExt);
540f79af6f8SMichael Kuperstein     CalleeAttrs.removeAttribute(Attribute::SExt);
541f79af6f8SMichael Kuperstein   }
542f79af6f8SMichael Kuperstein 
543f79af6f8SMichael Kuperstein   // If they're still different, there's some facet we don't understand
544f79af6f8SMichael Kuperstein   // (currently only "inreg", but in future who knows). It may be OK but the
545f79af6f8SMichael Kuperstein   // only safe option is to reject the tail call.
546f79af6f8SMichael Kuperstein   return CallerAttrs == CalleeAttrs;
547f79af6f8SMichael Kuperstein }
548f79af6f8SMichael Kuperstein 
549ce0e4c26SMichael Gottesman bool llvm::returnTypeIsEligibleForTailCall(const Function *F,
550ce0e4c26SMichael Gottesman                                            const Instruction *I,
551ce0e4c26SMichael Gottesman                                            const ReturnInst *Ret,
552ce0e4c26SMichael Gottesman                                            const TargetLoweringBase &TLI) {
553450aa64fSDan Gohman   // If the block ends with a void return or unreachable, it doesn't matter
554450aa64fSDan Gohman   // what the call's return type is.
555450aa64fSDan Gohman   if (!Ret || Ret->getNumOperands() == 0) return true;
556450aa64fSDan Gohman 
557450aa64fSDan Gohman   // If the return value is undef, it doesn't matter what the call's
558450aa64fSDan Gohman   // return type is.
559450aa64fSDan Gohman   if (isa<UndefValue>(Ret->getOperand(0))) return true;
560450aa64fSDan Gohman 
561707d68f0STim Northover   // Make sure the attributes attached to each return are compatible.
562f79af6f8SMichael Kuperstein   bool AllowDifferingSizes;
563f79af6f8SMichael Kuperstein   if (!attributesPermitTailCall(F, I, Ret, TLI, &AllowDifferingSizes))
564450aa64fSDan Gohman     return false;
565450aa64fSDan Gohman 
566a4415854STim Northover   const Value *RetVal = Ret->getOperand(0), *CallVal = I;
5675d84d9b3SWei Mi   // Intrinsic like llvm.memcpy has no return value, but the expanded
5685d84d9b3SWei Mi   // libcall may or may not have return value. On most platforms, it
5695d84d9b3SWei Mi   // will be expanded as memcpy in libc, which returns the first
5705d84d9b3SWei Mi   // argument. On other platforms like arm-none-eabi, memcpy may be
5715d84d9b3SWei Mi   // expanded as library call without return value, like __aeabi_memcpy.
572818d50a9SWei Mi   const CallInst *Call = cast<CallInst>(I);
573818d50a9SWei Mi   if (Function *F = Call->getCalledFunction()) {
574818d50a9SWei Mi     Intrinsic::ID IID = F->getIntrinsicID();
5755d84d9b3SWei Mi     if (((IID == Intrinsic::memcpy &&
5765d84d9b3SWei Mi           TLI.getLibcallName(RTLIB::MEMCPY) == StringRef("memcpy")) ||
5775d84d9b3SWei Mi          (IID == Intrinsic::memmove &&
5785d84d9b3SWei Mi           TLI.getLibcallName(RTLIB::MEMMOVE) == StringRef("memmove")) ||
5795d84d9b3SWei Mi          (IID == Intrinsic::memset &&
5805d84d9b3SWei Mi           TLI.getLibcallName(RTLIB::MEMSET) == StringRef("memset"))) &&
581818d50a9SWei Mi         RetVal == Call->getArgOperand(0))
582818d50a9SWei Mi       return true;
583818d50a9SWei Mi   }
584818d50a9SWei Mi 
585a4415854STim Northover   SmallVector<unsigned, 4> RetPath, CallPath;
586a4415854STim Northover   SmallVector<CompositeType *, 4> RetSubTypes, CallSubTypes;
587a4415854STim Northover 
588a4415854STim Northover   bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath);
589a4415854STim Northover   bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath);
590a4415854STim Northover 
591a4415854STim Northover   // Nothing's actually returned, it doesn't matter what the callee put there
592a4415854STim Northover   // it's a valid tail call.
593a4415854STim Northover   if (RetEmpty)
594a4415854STim Northover     return true;
595a4415854STim Northover 
596a4415854STim Northover   // Iterate pairwise through each of the value types making up the tail call
597a4415854STim Northover   // and the corresponding return. For each one we want to know whether it's
598a4415854STim Northover   // essentially going directly from the tail call to the ret, via operations
599a4415854STim Northover   // that end up not generating any code.
600a4415854STim Northover   //
601a4415854STim Northover   // We allow a certain amount of covariance here. For example it's permitted
602a4415854STim Northover   // for the tail call to define more bits than the ret actually cares about
603a4415854STim Northover   // (e.g. via a truncate).
604a4415854STim Northover   do {
605a4415854STim Northover     if (CallEmpty) {
606a4415854STim Northover       // We've exhausted the values produced by the tail call instruction, the
607a4415854STim Northover       // rest are essentially undef. The type doesn't really matter, but we need
608a4415854STim Northover       // *something*.
609a4415854STim Northover       Type *SlotType = RetSubTypes.back()->getTypeAtIndex(RetPath.back());
610a4415854STim Northover       CallVal = UndefValue::get(SlotType);
611a4415854STim Northover     }
612a4415854STim Northover 
613a4415854STim Northover     // The manipulations performed when we're looking through an insertvalue or
614a4415854STim Northover     // an extractvalue would happen at the front of the RetPath list, so since
615a4415854STim Northover     // we have to copy it anyway it's more efficient to create a reversed copy.
6164f6ac162SBenjamin Kramer     SmallVector<unsigned, 4> TmpRetPath(RetPath.rbegin(), RetPath.rend());
6174f6ac162SBenjamin Kramer     SmallVector<unsigned, 4> TmpCallPath(CallPath.rbegin(), CallPath.rend());
618a4415854STim Northover 
619a4415854STim Northover     // Finally, we can check whether the value produced by the tail call at this
620a4415854STim Northover     // index is compatible with the value we return.
621707d68f0STim Northover     if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath,
62244ede33aSMehdi Amini                               AllowDifferingSizes, TLI,
62344ede33aSMehdi Amini                               F->getParent()->getDataLayout()))
624a4415854STim Northover       return false;
625a4415854STim Northover 
626a4415854STim Northover     CallEmpty  = !nextRealType(CallSubTypes, CallPath);
627a4415854STim Northover   } while(nextRealType(RetSubTypes, RetPath));
628a4415854STim Northover 
629a4415854STim Northover   return true;
630450aa64fSDan Gohman }
631f21434ccSRafael Espindola 
63216193552SDavid Majnemer static void collectFuncletMembers(
63316193552SDavid Majnemer     DenseMap<const MachineBasicBlock *, int> &FuncletMembership, int Funclet,
63416193552SDavid Majnemer     const MachineBasicBlock *MBB) {
635734d7c32SDavid Majnemer   SmallVector<const MachineBasicBlock *, 16> Worklist = {MBB};
636734d7c32SDavid Majnemer   while (!Worklist.empty()) {
637734d7c32SDavid Majnemer     const MachineBasicBlock *Visiting = Worklist.pop_back_val();
638734d7c32SDavid Majnemer     // Don't follow blocks which start new funclets.
639734d7c32SDavid Majnemer     if (Visiting->isEHPad() && Visiting != MBB)
640734d7c32SDavid Majnemer       continue;
641734d7c32SDavid Majnemer 
6427b54b525SDavid Blaikie     // Add this MBB to our funclet.
643734d7c32SDavid Majnemer     auto P = FuncletMembership.insert(std::make_pair(Visiting, Funclet));
6447b54b525SDavid Blaikie 
64516193552SDavid Majnemer     // Don't revisit blocks.
6467b54b525SDavid Blaikie     if (!P.second) {
6477b54b525SDavid Blaikie       assert(P.first->second == Funclet && "MBB is part of two funclets!");
648734d7c32SDavid Majnemer       continue;
64916193552SDavid Majnemer     }
65016193552SDavid Majnemer 
65116193552SDavid Majnemer     // Returns are boundaries where funclet transfer can occur, don't follow
65216193552SDavid Majnemer     // successors.
653734d7c32SDavid Majnemer     if (Visiting->isReturnBlock())
654734d7c32SDavid Majnemer       continue;
65516193552SDavid Majnemer 
656734d7c32SDavid Majnemer     for (const MachineBasicBlock *Succ : Visiting->successors())
657734d7c32SDavid Majnemer       Worklist.push_back(Succ);
658734d7c32SDavid Majnemer   }
65916193552SDavid Majnemer }
66016193552SDavid Majnemer 
66116193552SDavid Majnemer DenseMap<const MachineBasicBlock *, int>
66216193552SDavid Majnemer llvm::getFuncletMembership(const MachineFunction &MF) {
66316193552SDavid Majnemer   DenseMap<const MachineBasicBlock *, int> FuncletMembership;
66416193552SDavid Majnemer 
66516193552SDavid Majnemer   // We don't have anything to do if there aren't any EH pads.
666d0ee66c2SMatthias Braun   if (!MF.hasEHFunclets())
66716193552SDavid Majnemer     return FuncletMembership;
66816193552SDavid Majnemer 
669e4f9b09bSDavid Majnemer   int EntryBBNumber = MF.front().getNumber();
67016193552SDavid Majnemer   bool IsSEH = isAsynchronousEHPersonality(
671*f1caa283SMatthias Braun       classifyEHPersonality(MF.getFunction().getPersonalityFn()));
67216193552SDavid Majnemer 
67316193552SDavid Majnemer   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
67416193552SDavid Majnemer   SmallVector<const MachineBasicBlock *, 16> FuncletBlocks;
675e4f9b09bSDavid Majnemer   SmallVector<const MachineBasicBlock *, 16> UnreachableBlocks;
676e4f9b09bSDavid Majnemer   SmallVector<const MachineBasicBlock *, 16> SEHCatchPads;
67716193552SDavid Majnemer   SmallVector<std::pair<const MachineBasicBlock *, int>, 16> CatchRetSuccessors;
67816193552SDavid Majnemer   for (const MachineBasicBlock &MBB : MF) {
679e4f9b09bSDavid Majnemer     if (MBB.isEHFuncletEntry()) {
68016193552SDavid Majnemer       FuncletBlocks.push_back(&MBB);
681e4f9b09bSDavid Majnemer     } else if (IsSEH && MBB.isEHPad()) {
682e4f9b09bSDavid Majnemer       SEHCatchPads.push_back(&MBB);
683e4f9b09bSDavid Majnemer     } else if (MBB.pred_empty()) {
684e4f9b09bSDavid Majnemer       UnreachableBlocks.push_back(&MBB);
685e4f9b09bSDavid Majnemer     }
68616193552SDavid Majnemer 
68716193552SDavid Majnemer     MachineBasicBlock::const_iterator MBBI = MBB.getFirstTerminator();
6882e7af979SDuncan P. N. Exon Smith 
68916193552SDavid Majnemer     // CatchPads are not funclets for SEH so do not consider CatchRet to
69016193552SDavid Majnemer     // transfer control to another funclet.
69126f9e9ebSReid Kleckner     if (MBBI == MBB.end() || MBBI->getOpcode() != TII->getCatchReturnOpcode())
69216193552SDavid Majnemer       continue;
69316193552SDavid Majnemer 
694e4f9b09bSDavid Majnemer     // FIXME: SEH CatchPads are not necessarily in the parent function:
695e4f9b09bSDavid Majnemer     // they could be inside a finally block.
69616193552SDavid Majnemer     const MachineBasicBlock *Successor = MBBI->getOperand(0).getMBB();
69716193552SDavid Majnemer     const MachineBasicBlock *SuccessorColor = MBBI->getOperand(1).getMBB();
698e4f9b09bSDavid Majnemer     CatchRetSuccessors.push_back(
699e4f9b09bSDavid Majnemer         {Successor, IsSEH ? EntryBBNumber : SuccessorColor->getNumber()});
70016193552SDavid Majnemer   }
70116193552SDavid Majnemer 
70216193552SDavid Majnemer   // We don't have anything to do if there aren't any EH pads.
70316193552SDavid Majnemer   if (FuncletBlocks.empty())
70416193552SDavid Majnemer     return FuncletMembership;
70516193552SDavid Majnemer 
70616193552SDavid Majnemer   // Identify all the basic blocks reachable from the function entry.
707980f8f26SDuncan P. N. Exon Smith   collectFuncletMembers(FuncletMembership, EntryBBNumber, &MF.front());
708e4f9b09bSDavid Majnemer   // All blocks not part of a funclet are in the parent function.
709e4f9b09bSDavid Majnemer   for (const MachineBasicBlock *MBB : UnreachableBlocks)
710e4f9b09bSDavid Majnemer     collectFuncletMembers(FuncletMembership, EntryBBNumber, MBB);
71116193552SDavid Majnemer   // Next, identify all the blocks inside the funclets.
71216193552SDavid Majnemer   for (const MachineBasicBlock *MBB : FuncletBlocks)
71316193552SDavid Majnemer     collectFuncletMembers(FuncletMembership, MBB->getNumber(), MBB);
714e4f9b09bSDavid Majnemer   // SEH CatchPads aren't really funclets, handle them separately.
715e4f9b09bSDavid Majnemer   for (const MachineBasicBlock *MBB : SEHCatchPads)
716e4f9b09bSDavid Majnemer     collectFuncletMembers(FuncletMembership, EntryBBNumber, MBB);
71716193552SDavid Majnemer   // Finally, identify all the targets of a catchret.
71816193552SDavid Majnemer   for (std::pair<const MachineBasicBlock *, int> CatchRetPair :
71916193552SDavid Majnemer        CatchRetSuccessors)
72016193552SDavid Majnemer     collectFuncletMembers(FuncletMembership, CatchRetPair.second,
72116193552SDavid Majnemer                           CatchRetPair.first);
72216193552SDavid Majnemer   return FuncletMembership;
72316193552SDavid Majnemer }
724