1*09467b48Spatrick //===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===// 2*09467b48Spatrick // 3*09467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4*09467b48Spatrick // See https://llvm.org/LICENSE.txt for license information. 5*09467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6*09467b48Spatrick // 7*09467b48Spatrick //===----------------------------------------------------------------------===// 8*09467b48Spatrick // 9*09467b48Spatrick // This file defines several CodeGen-specific LLVM IR analysis utilities. 10*09467b48Spatrick // 11*09467b48Spatrick //===----------------------------------------------------------------------===// 12*09467b48Spatrick 13*09467b48Spatrick #include "llvm/CodeGen/Analysis.h" 14*09467b48Spatrick #include "llvm/Analysis/ValueTracking.h" 15*09467b48Spatrick #include "llvm/CodeGen/MachineFunction.h" 16*09467b48Spatrick #include "llvm/CodeGen/TargetInstrInfo.h" 17*09467b48Spatrick #include "llvm/CodeGen/TargetLowering.h" 18*09467b48Spatrick #include "llvm/CodeGen/TargetSubtargetInfo.h" 19*09467b48Spatrick #include "llvm/IR/DataLayout.h" 20*09467b48Spatrick #include "llvm/IR/DerivedTypes.h" 21*09467b48Spatrick #include "llvm/IR/Function.h" 22*09467b48Spatrick #include "llvm/IR/Instructions.h" 23*09467b48Spatrick #include "llvm/IR/IntrinsicInst.h" 24*09467b48Spatrick #include "llvm/IR/LLVMContext.h" 25*09467b48Spatrick #include "llvm/IR/Module.h" 26*09467b48Spatrick #include "llvm/Support/ErrorHandling.h" 27*09467b48Spatrick #include "llvm/Support/MathExtras.h" 28*09467b48Spatrick #include "llvm/Transforms/Utils/GlobalStatus.h" 29*09467b48Spatrick 30*09467b48Spatrick using namespace llvm; 31*09467b48Spatrick 32*09467b48Spatrick /// Compute the linearized index of a member in a nested aggregate/struct/array 33*09467b48Spatrick /// by recursing and accumulating CurIndex as long as there are indices in the 34*09467b48Spatrick /// index list. 35*09467b48Spatrick unsigned llvm::ComputeLinearIndex(Type *Ty, 36*09467b48Spatrick const unsigned *Indices, 37*09467b48Spatrick const unsigned *IndicesEnd, 38*09467b48Spatrick unsigned CurIndex) { 39*09467b48Spatrick // Base case: We're done. 40*09467b48Spatrick if (Indices && Indices == IndicesEnd) 41*09467b48Spatrick return CurIndex; 42*09467b48Spatrick 43*09467b48Spatrick // Given a struct type, recursively traverse the elements. 44*09467b48Spatrick if (StructType *STy = dyn_cast<StructType>(Ty)) { 45*09467b48Spatrick for (StructType::element_iterator EB = STy->element_begin(), 46*09467b48Spatrick EI = EB, 47*09467b48Spatrick EE = STy->element_end(); 48*09467b48Spatrick EI != EE; ++EI) { 49*09467b48Spatrick if (Indices && *Indices == unsigned(EI - EB)) 50*09467b48Spatrick return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex); 51*09467b48Spatrick CurIndex = ComputeLinearIndex(*EI, nullptr, nullptr, CurIndex); 52*09467b48Spatrick } 53*09467b48Spatrick assert(!Indices && "Unexpected out of bound"); 54*09467b48Spatrick return CurIndex; 55*09467b48Spatrick } 56*09467b48Spatrick // Given an array type, recursively traverse the elements. 57*09467b48Spatrick else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 58*09467b48Spatrick Type *EltTy = ATy->getElementType(); 59*09467b48Spatrick unsigned NumElts = ATy->getNumElements(); 60*09467b48Spatrick // Compute the Linear offset when jumping one element of the array 61*09467b48Spatrick unsigned EltLinearOffset = ComputeLinearIndex(EltTy, nullptr, nullptr, 0); 62*09467b48Spatrick if (Indices) { 63*09467b48Spatrick assert(*Indices < NumElts && "Unexpected out of bound"); 64*09467b48Spatrick // If the indice is inside the array, compute the index to the requested 65*09467b48Spatrick // elt and recurse inside the element with the end of the indices list 66*09467b48Spatrick CurIndex += EltLinearOffset* *Indices; 67*09467b48Spatrick return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex); 68*09467b48Spatrick } 69*09467b48Spatrick CurIndex += EltLinearOffset*NumElts; 70*09467b48Spatrick return CurIndex; 71*09467b48Spatrick } 72*09467b48Spatrick // We haven't found the type we're looking for, so keep searching. 73*09467b48Spatrick return CurIndex + 1; 74*09467b48Spatrick } 75*09467b48Spatrick 76*09467b48Spatrick /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of 77*09467b48Spatrick /// EVTs that represent all the individual underlying 78*09467b48Spatrick /// non-aggregate types that comprise it. 79*09467b48Spatrick /// 80*09467b48Spatrick /// If Offsets is non-null, it points to a vector to be filled in 81*09467b48Spatrick /// with the in-memory offsets of each of the individual values. 82*09467b48Spatrick /// 83*09467b48Spatrick void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL, 84*09467b48Spatrick Type *Ty, SmallVectorImpl<EVT> &ValueVTs, 85*09467b48Spatrick SmallVectorImpl<EVT> *MemVTs, 86*09467b48Spatrick SmallVectorImpl<uint64_t> *Offsets, 87*09467b48Spatrick uint64_t StartingOffset) { 88*09467b48Spatrick // Given a struct type, recursively traverse the elements. 89*09467b48Spatrick if (StructType *STy = dyn_cast<StructType>(Ty)) { 90*09467b48Spatrick const StructLayout *SL = DL.getStructLayout(STy); 91*09467b48Spatrick for (StructType::element_iterator EB = STy->element_begin(), 92*09467b48Spatrick EI = EB, 93*09467b48Spatrick EE = STy->element_end(); 94*09467b48Spatrick EI != EE; ++EI) 95*09467b48Spatrick ComputeValueVTs(TLI, DL, *EI, ValueVTs, MemVTs, Offsets, 96*09467b48Spatrick StartingOffset + SL->getElementOffset(EI - EB)); 97*09467b48Spatrick return; 98*09467b48Spatrick } 99*09467b48Spatrick // Given an array type, recursively traverse the elements. 100*09467b48Spatrick if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 101*09467b48Spatrick Type *EltTy = ATy->getElementType(); 102*09467b48Spatrick uint64_t EltSize = DL.getTypeAllocSize(EltTy); 103*09467b48Spatrick for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) 104*09467b48Spatrick ComputeValueVTs(TLI, DL, EltTy, ValueVTs, MemVTs, Offsets, 105*09467b48Spatrick StartingOffset + i * EltSize); 106*09467b48Spatrick return; 107*09467b48Spatrick } 108*09467b48Spatrick // Interpret void as zero return values. 109*09467b48Spatrick if (Ty->isVoidTy()) 110*09467b48Spatrick return; 111*09467b48Spatrick // Base case: we can get an EVT for this LLVM IR type. 112*09467b48Spatrick ValueVTs.push_back(TLI.getValueType(DL, Ty)); 113*09467b48Spatrick if (MemVTs) 114*09467b48Spatrick MemVTs->push_back(TLI.getMemValueType(DL, Ty)); 115*09467b48Spatrick if (Offsets) 116*09467b48Spatrick Offsets->push_back(StartingOffset); 117*09467b48Spatrick } 118*09467b48Spatrick 119*09467b48Spatrick void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL, 120*09467b48Spatrick Type *Ty, SmallVectorImpl<EVT> &ValueVTs, 121*09467b48Spatrick SmallVectorImpl<uint64_t> *Offsets, 122*09467b48Spatrick uint64_t StartingOffset) { 123*09467b48Spatrick return ComputeValueVTs(TLI, DL, Ty, ValueVTs, /*MemVTs=*/nullptr, Offsets, 124*09467b48Spatrick StartingOffset); 125*09467b48Spatrick } 126*09467b48Spatrick 127*09467b48Spatrick void llvm::computeValueLLTs(const DataLayout &DL, Type &Ty, 128*09467b48Spatrick SmallVectorImpl<LLT> &ValueTys, 129*09467b48Spatrick SmallVectorImpl<uint64_t> *Offsets, 130*09467b48Spatrick uint64_t StartingOffset) { 131*09467b48Spatrick // Given a struct type, recursively traverse the elements. 132*09467b48Spatrick if (StructType *STy = dyn_cast<StructType>(&Ty)) { 133*09467b48Spatrick const StructLayout *SL = DL.getStructLayout(STy); 134*09467b48Spatrick for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) 135*09467b48Spatrick computeValueLLTs(DL, *STy->getElementType(I), ValueTys, Offsets, 136*09467b48Spatrick StartingOffset + SL->getElementOffset(I)); 137*09467b48Spatrick return; 138*09467b48Spatrick } 139*09467b48Spatrick // Given an array type, recursively traverse the elements. 140*09467b48Spatrick if (ArrayType *ATy = dyn_cast<ArrayType>(&Ty)) { 141*09467b48Spatrick Type *EltTy = ATy->getElementType(); 142*09467b48Spatrick uint64_t EltSize = DL.getTypeAllocSize(EltTy); 143*09467b48Spatrick for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) 144*09467b48Spatrick computeValueLLTs(DL, *EltTy, ValueTys, Offsets, 145*09467b48Spatrick StartingOffset + i * EltSize); 146*09467b48Spatrick return; 147*09467b48Spatrick } 148*09467b48Spatrick // Interpret void as zero return values. 149*09467b48Spatrick if (Ty.isVoidTy()) 150*09467b48Spatrick return; 151*09467b48Spatrick // Base case: we can get an LLT for this LLVM IR type. 152*09467b48Spatrick ValueTys.push_back(getLLTForType(Ty, DL)); 153*09467b48Spatrick if (Offsets != nullptr) 154*09467b48Spatrick Offsets->push_back(StartingOffset * 8); 155*09467b48Spatrick } 156*09467b48Spatrick 157*09467b48Spatrick /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V. 158*09467b48Spatrick GlobalValue *llvm::ExtractTypeInfo(Value *V) { 159*09467b48Spatrick V = V->stripPointerCasts(); 160*09467b48Spatrick GlobalValue *GV = dyn_cast<GlobalValue>(V); 161*09467b48Spatrick GlobalVariable *Var = dyn_cast<GlobalVariable>(V); 162*09467b48Spatrick 163*09467b48Spatrick if (Var && Var->getName() == "llvm.eh.catch.all.value") { 164*09467b48Spatrick assert(Var->hasInitializer() && 165*09467b48Spatrick "The EH catch-all value must have an initializer"); 166*09467b48Spatrick Value *Init = Var->getInitializer(); 167*09467b48Spatrick GV = dyn_cast<GlobalValue>(Init); 168*09467b48Spatrick if (!GV) V = cast<ConstantPointerNull>(Init); 169*09467b48Spatrick } 170*09467b48Spatrick 171*09467b48Spatrick assert((GV || isa<ConstantPointerNull>(V)) && 172*09467b48Spatrick "TypeInfo must be a global variable or NULL"); 173*09467b48Spatrick return GV; 174*09467b48Spatrick } 175*09467b48Spatrick 176*09467b48Spatrick /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being 177*09467b48Spatrick /// processed uses a memory 'm' constraint. 178*09467b48Spatrick bool 179*09467b48Spatrick llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos, 180*09467b48Spatrick const TargetLowering &TLI) { 181*09467b48Spatrick for (unsigned i = 0, e = CInfos.size(); i != e; ++i) { 182*09467b48Spatrick InlineAsm::ConstraintInfo &CI = CInfos[i]; 183*09467b48Spatrick for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) { 184*09467b48Spatrick TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]); 185*09467b48Spatrick if (CType == TargetLowering::C_Memory) 186*09467b48Spatrick return true; 187*09467b48Spatrick } 188*09467b48Spatrick 189*09467b48Spatrick // Indirect operand accesses access memory. 190*09467b48Spatrick if (CI.isIndirect) 191*09467b48Spatrick return true; 192*09467b48Spatrick } 193*09467b48Spatrick 194*09467b48Spatrick return false; 195*09467b48Spatrick } 196*09467b48Spatrick 197*09467b48Spatrick /// getFCmpCondCode - Return the ISD condition code corresponding to 198*09467b48Spatrick /// the given LLVM IR floating-point condition code. This includes 199*09467b48Spatrick /// consideration of global floating-point math flags. 200*09467b48Spatrick /// 201*09467b48Spatrick ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) { 202*09467b48Spatrick switch (Pred) { 203*09467b48Spatrick case FCmpInst::FCMP_FALSE: return ISD::SETFALSE; 204*09467b48Spatrick case FCmpInst::FCMP_OEQ: return ISD::SETOEQ; 205*09467b48Spatrick case FCmpInst::FCMP_OGT: return ISD::SETOGT; 206*09467b48Spatrick case FCmpInst::FCMP_OGE: return ISD::SETOGE; 207*09467b48Spatrick case FCmpInst::FCMP_OLT: return ISD::SETOLT; 208*09467b48Spatrick case FCmpInst::FCMP_OLE: return ISD::SETOLE; 209*09467b48Spatrick case FCmpInst::FCMP_ONE: return ISD::SETONE; 210*09467b48Spatrick case FCmpInst::FCMP_ORD: return ISD::SETO; 211*09467b48Spatrick case FCmpInst::FCMP_UNO: return ISD::SETUO; 212*09467b48Spatrick case FCmpInst::FCMP_UEQ: return ISD::SETUEQ; 213*09467b48Spatrick case FCmpInst::FCMP_UGT: return ISD::SETUGT; 214*09467b48Spatrick case FCmpInst::FCMP_UGE: return ISD::SETUGE; 215*09467b48Spatrick case FCmpInst::FCMP_ULT: return ISD::SETULT; 216*09467b48Spatrick case FCmpInst::FCMP_ULE: return ISD::SETULE; 217*09467b48Spatrick case FCmpInst::FCMP_UNE: return ISD::SETUNE; 218*09467b48Spatrick case FCmpInst::FCMP_TRUE: return ISD::SETTRUE; 219*09467b48Spatrick default: llvm_unreachable("Invalid FCmp predicate opcode!"); 220*09467b48Spatrick } 221*09467b48Spatrick } 222*09467b48Spatrick 223*09467b48Spatrick ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) { 224*09467b48Spatrick switch (CC) { 225*09467b48Spatrick case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ; 226*09467b48Spatrick case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE; 227*09467b48Spatrick case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT; 228*09467b48Spatrick case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE; 229*09467b48Spatrick case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT; 230*09467b48Spatrick case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE; 231*09467b48Spatrick default: return CC; 232*09467b48Spatrick } 233*09467b48Spatrick } 234*09467b48Spatrick 235*09467b48Spatrick /// getICmpCondCode - Return the ISD condition code corresponding to 236*09467b48Spatrick /// the given LLVM IR integer condition code. 237*09467b48Spatrick /// 238*09467b48Spatrick ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) { 239*09467b48Spatrick switch (Pred) { 240*09467b48Spatrick case ICmpInst::ICMP_EQ: return ISD::SETEQ; 241*09467b48Spatrick case ICmpInst::ICMP_NE: return ISD::SETNE; 242*09467b48Spatrick case ICmpInst::ICMP_SLE: return ISD::SETLE; 243*09467b48Spatrick case ICmpInst::ICMP_ULE: return ISD::SETULE; 244*09467b48Spatrick case ICmpInst::ICMP_SGE: return ISD::SETGE; 245*09467b48Spatrick case ICmpInst::ICMP_UGE: return ISD::SETUGE; 246*09467b48Spatrick case ICmpInst::ICMP_SLT: return ISD::SETLT; 247*09467b48Spatrick case ICmpInst::ICMP_ULT: return ISD::SETULT; 248*09467b48Spatrick case ICmpInst::ICMP_SGT: return ISD::SETGT; 249*09467b48Spatrick case ICmpInst::ICMP_UGT: return ISD::SETUGT; 250*09467b48Spatrick default: 251*09467b48Spatrick llvm_unreachable("Invalid ICmp predicate opcode!"); 252*09467b48Spatrick } 253*09467b48Spatrick } 254*09467b48Spatrick 255*09467b48Spatrick static bool isNoopBitcast(Type *T1, Type *T2, 256*09467b48Spatrick const TargetLoweringBase& TLI) { 257*09467b48Spatrick return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) || 258*09467b48Spatrick (isa<VectorType>(T1) && isa<VectorType>(T2) && 259*09467b48Spatrick TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2))); 260*09467b48Spatrick } 261*09467b48Spatrick 262*09467b48Spatrick /// Look through operations that will be free to find the earliest source of 263*09467b48Spatrick /// this value. 264*09467b48Spatrick /// 265*09467b48Spatrick /// @param ValLoc If V has aggregate type, we will be interested in a particular 266*09467b48Spatrick /// scalar component. This records its address; the reverse of this list gives a 267*09467b48Spatrick /// sequence of indices appropriate for an extractvalue to locate the important 268*09467b48Spatrick /// value. This value is updated during the function and on exit will indicate 269*09467b48Spatrick /// similar information for the Value returned. 270*09467b48Spatrick /// 271*09467b48Spatrick /// @param DataBits If this function looks through truncate instructions, this 272*09467b48Spatrick /// will record the smallest size attained. 273*09467b48Spatrick static const Value *getNoopInput(const Value *V, 274*09467b48Spatrick SmallVectorImpl<unsigned> &ValLoc, 275*09467b48Spatrick unsigned &DataBits, 276*09467b48Spatrick const TargetLoweringBase &TLI, 277*09467b48Spatrick const DataLayout &DL) { 278*09467b48Spatrick while (true) { 279*09467b48Spatrick // Try to look through V1; if V1 is not an instruction, it can't be looked 280*09467b48Spatrick // through. 281*09467b48Spatrick const Instruction *I = dyn_cast<Instruction>(V); 282*09467b48Spatrick if (!I || I->getNumOperands() == 0) return V; 283*09467b48Spatrick const Value *NoopInput = nullptr; 284*09467b48Spatrick 285*09467b48Spatrick Value *Op = I->getOperand(0); 286*09467b48Spatrick if (isa<BitCastInst>(I)) { 287*09467b48Spatrick // Look through truly no-op bitcasts. 288*09467b48Spatrick if (isNoopBitcast(Op->getType(), I->getType(), TLI)) 289*09467b48Spatrick NoopInput = Op; 290*09467b48Spatrick } else if (isa<GetElementPtrInst>(I)) { 291*09467b48Spatrick // Look through getelementptr 292*09467b48Spatrick if (cast<GetElementPtrInst>(I)->hasAllZeroIndices()) 293*09467b48Spatrick NoopInput = Op; 294*09467b48Spatrick } else if (isa<IntToPtrInst>(I)) { 295*09467b48Spatrick // Look through inttoptr. 296*09467b48Spatrick // Make sure this isn't a truncating or extending cast. We could 297*09467b48Spatrick // support this eventually, but don't bother for now. 298*09467b48Spatrick if (!isa<VectorType>(I->getType()) && 299*09467b48Spatrick DL.getPointerSizeInBits() == 300*09467b48Spatrick cast<IntegerType>(Op->getType())->getBitWidth()) 301*09467b48Spatrick NoopInput = Op; 302*09467b48Spatrick } else if (isa<PtrToIntInst>(I)) { 303*09467b48Spatrick // Look through ptrtoint. 304*09467b48Spatrick // Make sure this isn't a truncating or extending cast. We could 305*09467b48Spatrick // support this eventually, but don't bother for now. 306*09467b48Spatrick if (!isa<VectorType>(I->getType()) && 307*09467b48Spatrick DL.getPointerSizeInBits() == 308*09467b48Spatrick cast<IntegerType>(I->getType())->getBitWidth()) 309*09467b48Spatrick NoopInput = Op; 310*09467b48Spatrick } else if (isa<TruncInst>(I) && 311*09467b48Spatrick TLI.allowTruncateForTailCall(Op->getType(), I->getType())) { 312*09467b48Spatrick DataBits = std::min((uint64_t)DataBits, 313*09467b48Spatrick I->getType()->getPrimitiveSizeInBits().getFixedSize()); 314*09467b48Spatrick NoopInput = Op; 315*09467b48Spatrick } else if (auto CS = ImmutableCallSite(I)) { 316*09467b48Spatrick const Value *ReturnedOp = CS.getReturnedArgOperand(); 317*09467b48Spatrick if (ReturnedOp && isNoopBitcast(ReturnedOp->getType(), I->getType(), TLI)) 318*09467b48Spatrick NoopInput = ReturnedOp; 319*09467b48Spatrick } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(V)) { 320*09467b48Spatrick // Value may come from either the aggregate or the scalar 321*09467b48Spatrick ArrayRef<unsigned> InsertLoc = IVI->getIndices(); 322*09467b48Spatrick if (ValLoc.size() >= InsertLoc.size() && 323*09467b48Spatrick std::equal(InsertLoc.begin(), InsertLoc.end(), ValLoc.rbegin())) { 324*09467b48Spatrick // The type being inserted is a nested sub-type of the aggregate; we 325*09467b48Spatrick // have to remove those initial indices to get the location we're 326*09467b48Spatrick // interested in for the operand. 327*09467b48Spatrick ValLoc.resize(ValLoc.size() - InsertLoc.size()); 328*09467b48Spatrick NoopInput = IVI->getInsertedValueOperand(); 329*09467b48Spatrick } else { 330*09467b48Spatrick // The struct we're inserting into has the value we're interested in, no 331*09467b48Spatrick // change of address. 332*09467b48Spatrick NoopInput = Op; 333*09467b48Spatrick } 334*09467b48Spatrick } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) { 335*09467b48Spatrick // The part we're interested in will inevitably be some sub-section of the 336*09467b48Spatrick // previous aggregate. Combine the two paths to obtain the true address of 337*09467b48Spatrick // our element. 338*09467b48Spatrick ArrayRef<unsigned> ExtractLoc = EVI->getIndices(); 339*09467b48Spatrick ValLoc.append(ExtractLoc.rbegin(), ExtractLoc.rend()); 340*09467b48Spatrick NoopInput = Op; 341*09467b48Spatrick } 342*09467b48Spatrick // Terminate if we couldn't find anything to look through. 343*09467b48Spatrick if (!NoopInput) 344*09467b48Spatrick return V; 345*09467b48Spatrick 346*09467b48Spatrick V = NoopInput; 347*09467b48Spatrick } 348*09467b48Spatrick } 349*09467b48Spatrick 350*09467b48Spatrick /// Return true if this scalar return value only has bits discarded on its path 351*09467b48Spatrick /// from the "tail call" to the "ret". This includes the obvious noop 352*09467b48Spatrick /// instructions handled by getNoopInput above as well as free truncations (or 353*09467b48Spatrick /// extensions prior to the call). 354*09467b48Spatrick static bool slotOnlyDiscardsData(const Value *RetVal, const Value *CallVal, 355*09467b48Spatrick SmallVectorImpl<unsigned> &RetIndices, 356*09467b48Spatrick SmallVectorImpl<unsigned> &CallIndices, 357*09467b48Spatrick bool AllowDifferingSizes, 358*09467b48Spatrick const TargetLoweringBase &TLI, 359*09467b48Spatrick const DataLayout &DL) { 360*09467b48Spatrick 361*09467b48Spatrick // Trace the sub-value needed by the return value as far back up the graph as 362*09467b48Spatrick // possible, in the hope that it will intersect with the value produced by the 363*09467b48Spatrick // call. In the simple case with no "returned" attribute, the hope is actually 364*09467b48Spatrick // that we end up back at the tail call instruction itself. 365*09467b48Spatrick unsigned BitsRequired = UINT_MAX; 366*09467b48Spatrick RetVal = getNoopInput(RetVal, RetIndices, BitsRequired, TLI, DL); 367*09467b48Spatrick 368*09467b48Spatrick // If this slot in the value returned is undef, it doesn't matter what the 369*09467b48Spatrick // call puts there, it'll be fine. 370*09467b48Spatrick if (isa<UndefValue>(RetVal)) 371*09467b48Spatrick return true; 372*09467b48Spatrick 373*09467b48Spatrick // Now do a similar search up through the graph to find where the value 374*09467b48Spatrick // actually returned by the "tail call" comes from. In the simple case without 375*09467b48Spatrick // a "returned" attribute, the search will be blocked immediately and the loop 376*09467b48Spatrick // a Noop. 377*09467b48Spatrick unsigned BitsProvided = UINT_MAX; 378*09467b48Spatrick CallVal = getNoopInput(CallVal, CallIndices, BitsProvided, TLI, DL); 379*09467b48Spatrick 380*09467b48Spatrick // There's no hope if we can't actually trace them to (the same part of!) the 381*09467b48Spatrick // same value. 382*09467b48Spatrick if (CallVal != RetVal || CallIndices != RetIndices) 383*09467b48Spatrick return false; 384*09467b48Spatrick 385*09467b48Spatrick // However, intervening truncates may have made the call non-tail. Make sure 386*09467b48Spatrick // all the bits that are needed by the "ret" have been provided by the "tail 387*09467b48Spatrick // call". FIXME: with sufficiently cunning bit-tracking, we could look through 388*09467b48Spatrick // extensions too. 389*09467b48Spatrick if (BitsProvided < BitsRequired || 390*09467b48Spatrick (!AllowDifferingSizes && BitsProvided != BitsRequired)) 391*09467b48Spatrick return false; 392*09467b48Spatrick 393*09467b48Spatrick return true; 394*09467b48Spatrick } 395*09467b48Spatrick 396*09467b48Spatrick /// For an aggregate type, determine whether a given index is within bounds or 397*09467b48Spatrick /// not. 398*09467b48Spatrick static bool indexReallyValid(CompositeType *T, unsigned Idx) { 399*09467b48Spatrick if (ArrayType *AT = dyn_cast<ArrayType>(T)) 400*09467b48Spatrick return Idx < AT->getNumElements(); 401*09467b48Spatrick 402*09467b48Spatrick return Idx < cast<StructType>(T)->getNumElements(); 403*09467b48Spatrick } 404*09467b48Spatrick 405*09467b48Spatrick /// Move the given iterators to the next leaf type in depth first traversal. 406*09467b48Spatrick /// 407*09467b48Spatrick /// Performs a depth-first traversal of the type as specified by its arguments, 408*09467b48Spatrick /// stopping at the next leaf node (which may be a legitimate scalar type or an 409*09467b48Spatrick /// empty struct or array). 410*09467b48Spatrick /// 411*09467b48Spatrick /// @param SubTypes List of the partial components making up the type from 412*09467b48Spatrick /// outermost to innermost non-empty aggregate. The element currently 413*09467b48Spatrick /// represented is SubTypes.back()->getTypeAtIndex(Path.back() - 1). 414*09467b48Spatrick /// 415*09467b48Spatrick /// @param Path Set of extractvalue indices leading from the outermost type 416*09467b48Spatrick /// (SubTypes[0]) to the leaf node currently represented. 417*09467b48Spatrick /// 418*09467b48Spatrick /// @returns true if a new type was found, false otherwise. Calling this 419*09467b48Spatrick /// function again on a finished iterator will repeatedly return 420*09467b48Spatrick /// false. SubTypes.back()->getTypeAtIndex(Path.back()) is either an empty 421*09467b48Spatrick /// aggregate or a non-aggregate 422*09467b48Spatrick static bool advanceToNextLeafType(SmallVectorImpl<CompositeType *> &SubTypes, 423*09467b48Spatrick SmallVectorImpl<unsigned> &Path) { 424*09467b48Spatrick // First march back up the tree until we can successfully increment one of the 425*09467b48Spatrick // coordinates in Path. 426*09467b48Spatrick while (!Path.empty() && !indexReallyValid(SubTypes.back(), Path.back() + 1)) { 427*09467b48Spatrick Path.pop_back(); 428*09467b48Spatrick SubTypes.pop_back(); 429*09467b48Spatrick } 430*09467b48Spatrick 431*09467b48Spatrick // If we reached the top, then the iterator is done. 432*09467b48Spatrick if (Path.empty()) 433*09467b48Spatrick return false; 434*09467b48Spatrick 435*09467b48Spatrick // We know there's *some* valid leaf now, so march back down the tree picking 436*09467b48Spatrick // out the left-most element at each node. 437*09467b48Spatrick ++Path.back(); 438*09467b48Spatrick Type *DeeperType = SubTypes.back()->getTypeAtIndex(Path.back()); 439*09467b48Spatrick while (DeeperType->isAggregateType()) { 440*09467b48Spatrick CompositeType *CT = cast<CompositeType>(DeeperType); 441*09467b48Spatrick if (!indexReallyValid(CT, 0)) 442*09467b48Spatrick return true; 443*09467b48Spatrick 444*09467b48Spatrick SubTypes.push_back(CT); 445*09467b48Spatrick Path.push_back(0); 446*09467b48Spatrick 447*09467b48Spatrick DeeperType = CT->getTypeAtIndex(0U); 448*09467b48Spatrick } 449*09467b48Spatrick 450*09467b48Spatrick return true; 451*09467b48Spatrick } 452*09467b48Spatrick 453*09467b48Spatrick /// Find the first non-empty, scalar-like type in Next and setup the iterator 454*09467b48Spatrick /// components. 455*09467b48Spatrick /// 456*09467b48Spatrick /// Assuming Next is an aggregate of some kind, this function will traverse the 457*09467b48Spatrick /// tree from left to right (i.e. depth-first) looking for the first 458*09467b48Spatrick /// non-aggregate type which will play a role in function return. 459*09467b48Spatrick /// 460*09467b48Spatrick /// For example, if Next was {[0 x i64], {{}, i32, {}}, i32} then we would setup 461*09467b48Spatrick /// Path as [1, 1] and SubTypes as [Next, {{}, i32, {}}] to represent the first 462*09467b48Spatrick /// i32 in that type. 463*09467b48Spatrick static bool firstRealType(Type *Next, 464*09467b48Spatrick SmallVectorImpl<CompositeType *> &SubTypes, 465*09467b48Spatrick SmallVectorImpl<unsigned> &Path) { 466*09467b48Spatrick // First initialise the iterator components to the first "leaf" node 467*09467b48Spatrick // (i.e. node with no valid sub-type at any index, so {} does count as a leaf 468*09467b48Spatrick // despite nominally being an aggregate). 469*09467b48Spatrick while (Next->isAggregateType() && 470*09467b48Spatrick indexReallyValid(cast<CompositeType>(Next), 0)) { 471*09467b48Spatrick SubTypes.push_back(cast<CompositeType>(Next)); 472*09467b48Spatrick Path.push_back(0); 473*09467b48Spatrick Next = cast<CompositeType>(Next)->getTypeAtIndex(0U); 474*09467b48Spatrick } 475*09467b48Spatrick 476*09467b48Spatrick // If there's no Path now, Next was originally scalar already (or empty 477*09467b48Spatrick // leaf). We're done. 478*09467b48Spatrick if (Path.empty()) 479*09467b48Spatrick return true; 480*09467b48Spatrick 481*09467b48Spatrick // Otherwise, use normal iteration to keep looking through the tree until we 482*09467b48Spatrick // find a non-aggregate type. 483*09467b48Spatrick while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType()) { 484*09467b48Spatrick if (!advanceToNextLeafType(SubTypes, Path)) 485*09467b48Spatrick return false; 486*09467b48Spatrick } 487*09467b48Spatrick 488*09467b48Spatrick return true; 489*09467b48Spatrick } 490*09467b48Spatrick 491*09467b48Spatrick /// Set the iterator data-structures to the next non-empty, non-aggregate 492*09467b48Spatrick /// subtype. 493*09467b48Spatrick static bool nextRealType(SmallVectorImpl<CompositeType *> &SubTypes, 494*09467b48Spatrick SmallVectorImpl<unsigned> &Path) { 495*09467b48Spatrick do { 496*09467b48Spatrick if (!advanceToNextLeafType(SubTypes, Path)) 497*09467b48Spatrick return false; 498*09467b48Spatrick 499*09467b48Spatrick assert(!Path.empty() && "found a leaf but didn't set the path?"); 500*09467b48Spatrick } while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType()); 501*09467b48Spatrick 502*09467b48Spatrick return true; 503*09467b48Spatrick } 504*09467b48Spatrick 505*09467b48Spatrick 506*09467b48Spatrick /// Test if the given instruction is in a position to be optimized 507*09467b48Spatrick /// with a tail-call. This roughly means that it's in a block with 508*09467b48Spatrick /// a return and there's nothing that needs to be scheduled 509*09467b48Spatrick /// between it and the return. 510*09467b48Spatrick /// 511*09467b48Spatrick /// This function only tests target-independent requirements. 512*09467b48Spatrick bool llvm::isInTailCallPosition(ImmutableCallSite CS, const TargetMachine &TM) { 513*09467b48Spatrick const Instruction *I = CS.getInstruction(); 514*09467b48Spatrick const BasicBlock *ExitBB = I->getParent(); 515*09467b48Spatrick const Instruction *Term = ExitBB->getTerminator(); 516*09467b48Spatrick const ReturnInst *Ret = dyn_cast<ReturnInst>(Term); 517*09467b48Spatrick 518*09467b48Spatrick // The block must end in a return statement or unreachable. 519*09467b48Spatrick // 520*09467b48Spatrick // FIXME: Decline tailcall if it's not guaranteed and if the block ends in 521*09467b48Spatrick // an unreachable, for now. The way tailcall optimization is currently 522*09467b48Spatrick // implemented means it will add an epilogue followed by a jump. That is 523*09467b48Spatrick // not profitable. Also, if the callee is a special function (e.g. 524*09467b48Spatrick // longjmp on x86), it can end up causing miscompilation that has not 525*09467b48Spatrick // been fully understood. 526*09467b48Spatrick if (!Ret && 527*09467b48Spatrick ((!TM.Options.GuaranteedTailCallOpt && 528*09467b48Spatrick CS.getCallingConv() != CallingConv::Tail) || !isa<UnreachableInst>(Term))) 529*09467b48Spatrick return false; 530*09467b48Spatrick 531*09467b48Spatrick // If I will have a chain, make sure no other instruction that will have a 532*09467b48Spatrick // chain interposes between I and the return. 533*09467b48Spatrick if (I->mayHaveSideEffects() || I->mayReadFromMemory() || 534*09467b48Spatrick !isSafeToSpeculativelyExecute(I)) 535*09467b48Spatrick for (BasicBlock::const_iterator BBI = std::prev(ExitBB->end(), 2);; --BBI) { 536*09467b48Spatrick if (&*BBI == I) 537*09467b48Spatrick break; 538*09467b48Spatrick // Debug info intrinsics do not get in the way of tail call optimization. 539*09467b48Spatrick if (isa<DbgInfoIntrinsic>(BBI)) 540*09467b48Spatrick continue; 541*09467b48Spatrick // A lifetime end or assume intrinsic should not stop tail call 542*09467b48Spatrick // optimization. 543*09467b48Spatrick if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI)) 544*09467b48Spatrick if (II->getIntrinsicID() == Intrinsic::lifetime_end || 545*09467b48Spatrick II->getIntrinsicID() == Intrinsic::assume) 546*09467b48Spatrick continue; 547*09467b48Spatrick if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() || 548*09467b48Spatrick !isSafeToSpeculativelyExecute(&*BBI)) 549*09467b48Spatrick return false; 550*09467b48Spatrick } 551*09467b48Spatrick 552*09467b48Spatrick const Function *F = ExitBB->getParent(); 553*09467b48Spatrick return returnTypeIsEligibleForTailCall( 554*09467b48Spatrick F, I, Ret, *TM.getSubtargetImpl(*F)->getTargetLowering()); 555*09467b48Spatrick } 556*09467b48Spatrick 557*09467b48Spatrick bool llvm::attributesPermitTailCall(const Function *F, const Instruction *I, 558*09467b48Spatrick const ReturnInst *Ret, 559*09467b48Spatrick const TargetLoweringBase &TLI, 560*09467b48Spatrick bool *AllowDifferingSizes) { 561*09467b48Spatrick // ADS may be null, so don't write to it directly. 562*09467b48Spatrick bool DummyADS; 563*09467b48Spatrick bool &ADS = AllowDifferingSizes ? *AllowDifferingSizes : DummyADS; 564*09467b48Spatrick ADS = true; 565*09467b48Spatrick 566*09467b48Spatrick AttrBuilder CallerAttrs(F->getAttributes(), AttributeList::ReturnIndex); 567*09467b48Spatrick AttrBuilder CalleeAttrs(cast<CallInst>(I)->getAttributes(), 568*09467b48Spatrick AttributeList::ReturnIndex); 569*09467b48Spatrick 570*09467b48Spatrick // Following attributes are completely benign as far as calling convention 571*09467b48Spatrick // goes, they shouldn't affect whether the call is a tail call. 572*09467b48Spatrick CallerAttrs.removeAttribute(Attribute::NoAlias); 573*09467b48Spatrick CalleeAttrs.removeAttribute(Attribute::NoAlias); 574*09467b48Spatrick CallerAttrs.removeAttribute(Attribute::NonNull); 575*09467b48Spatrick CalleeAttrs.removeAttribute(Attribute::NonNull); 576*09467b48Spatrick CallerAttrs.removeAttribute(Attribute::Dereferenceable); 577*09467b48Spatrick CalleeAttrs.removeAttribute(Attribute::Dereferenceable); 578*09467b48Spatrick CallerAttrs.removeAttribute(Attribute::DereferenceableOrNull); 579*09467b48Spatrick CalleeAttrs.removeAttribute(Attribute::DereferenceableOrNull); 580*09467b48Spatrick 581*09467b48Spatrick if (CallerAttrs.contains(Attribute::ZExt)) { 582*09467b48Spatrick if (!CalleeAttrs.contains(Attribute::ZExt)) 583*09467b48Spatrick return false; 584*09467b48Spatrick 585*09467b48Spatrick ADS = false; 586*09467b48Spatrick CallerAttrs.removeAttribute(Attribute::ZExt); 587*09467b48Spatrick CalleeAttrs.removeAttribute(Attribute::ZExt); 588*09467b48Spatrick } else if (CallerAttrs.contains(Attribute::SExt)) { 589*09467b48Spatrick if (!CalleeAttrs.contains(Attribute::SExt)) 590*09467b48Spatrick return false; 591*09467b48Spatrick 592*09467b48Spatrick ADS = false; 593*09467b48Spatrick CallerAttrs.removeAttribute(Attribute::SExt); 594*09467b48Spatrick CalleeAttrs.removeAttribute(Attribute::SExt); 595*09467b48Spatrick } 596*09467b48Spatrick 597*09467b48Spatrick // Drop sext and zext return attributes if the result is not used. 598*09467b48Spatrick // This enables tail calls for code like: 599*09467b48Spatrick // 600*09467b48Spatrick // define void @caller() { 601*09467b48Spatrick // entry: 602*09467b48Spatrick // %unused_result = tail call zeroext i1 @callee() 603*09467b48Spatrick // br label %retlabel 604*09467b48Spatrick // retlabel: 605*09467b48Spatrick // ret void 606*09467b48Spatrick // } 607*09467b48Spatrick if (I->use_empty()) { 608*09467b48Spatrick CalleeAttrs.removeAttribute(Attribute::SExt); 609*09467b48Spatrick CalleeAttrs.removeAttribute(Attribute::ZExt); 610*09467b48Spatrick } 611*09467b48Spatrick 612*09467b48Spatrick // If they're still different, there's some facet we don't understand 613*09467b48Spatrick // (currently only "inreg", but in future who knows). It may be OK but the 614*09467b48Spatrick // only safe option is to reject the tail call. 615*09467b48Spatrick return CallerAttrs == CalleeAttrs; 616*09467b48Spatrick } 617*09467b48Spatrick 618*09467b48Spatrick /// Check whether B is a bitcast of a pointer type to another pointer type, 619*09467b48Spatrick /// which is equal to A. 620*09467b48Spatrick static bool isPointerBitcastEqualTo(const Value *A, const Value *B) { 621*09467b48Spatrick assert(A && B && "Expected non-null inputs!"); 622*09467b48Spatrick 623*09467b48Spatrick auto *BitCastIn = dyn_cast<BitCastInst>(B); 624*09467b48Spatrick 625*09467b48Spatrick if (!BitCastIn) 626*09467b48Spatrick return false; 627*09467b48Spatrick 628*09467b48Spatrick if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy()) 629*09467b48Spatrick return false; 630*09467b48Spatrick 631*09467b48Spatrick return A == BitCastIn->getOperand(0); 632*09467b48Spatrick } 633*09467b48Spatrick 634*09467b48Spatrick bool llvm::returnTypeIsEligibleForTailCall(const Function *F, 635*09467b48Spatrick const Instruction *I, 636*09467b48Spatrick const ReturnInst *Ret, 637*09467b48Spatrick const TargetLoweringBase &TLI) { 638*09467b48Spatrick // If the block ends with a void return or unreachable, it doesn't matter 639*09467b48Spatrick // what the call's return type is. 640*09467b48Spatrick if (!Ret || Ret->getNumOperands() == 0) return true; 641*09467b48Spatrick 642*09467b48Spatrick // If the return value is undef, it doesn't matter what the call's 643*09467b48Spatrick // return type is. 644*09467b48Spatrick if (isa<UndefValue>(Ret->getOperand(0))) return true; 645*09467b48Spatrick 646*09467b48Spatrick // Make sure the attributes attached to each return are compatible. 647*09467b48Spatrick bool AllowDifferingSizes; 648*09467b48Spatrick if (!attributesPermitTailCall(F, I, Ret, TLI, &AllowDifferingSizes)) 649*09467b48Spatrick return false; 650*09467b48Spatrick 651*09467b48Spatrick const Value *RetVal = Ret->getOperand(0), *CallVal = I; 652*09467b48Spatrick // Intrinsic like llvm.memcpy has no return value, but the expanded 653*09467b48Spatrick // libcall may or may not have return value. On most platforms, it 654*09467b48Spatrick // will be expanded as memcpy in libc, which returns the first 655*09467b48Spatrick // argument. On other platforms like arm-none-eabi, memcpy may be 656*09467b48Spatrick // expanded as library call without return value, like __aeabi_memcpy. 657*09467b48Spatrick const CallInst *Call = cast<CallInst>(I); 658*09467b48Spatrick if (Function *F = Call->getCalledFunction()) { 659*09467b48Spatrick Intrinsic::ID IID = F->getIntrinsicID(); 660*09467b48Spatrick if (((IID == Intrinsic::memcpy && 661*09467b48Spatrick TLI.getLibcallName(RTLIB::MEMCPY) == StringRef("memcpy")) || 662*09467b48Spatrick (IID == Intrinsic::memmove && 663*09467b48Spatrick TLI.getLibcallName(RTLIB::MEMMOVE) == StringRef("memmove")) || 664*09467b48Spatrick (IID == Intrinsic::memset && 665*09467b48Spatrick TLI.getLibcallName(RTLIB::MEMSET) == StringRef("memset"))) && 666*09467b48Spatrick (RetVal == Call->getArgOperand(0) || 667*09467b48Spatrick isPointerBitcastEqualTo(RetVal, Call->getArgOperand(0)))) 668*09467b48Spatrick return true; 669*09467b48Spatrick } 670*09467b48Spatrick 671*09467b48Spatrick SmallVector<unsigned, 4> RetPath, CallPath; 672*09467b48Spatrick SmallVector<CompositeType *, 4> RetSubTypes, CallSubTypes; 673*09467b48Spatrick 674*09467b48Spatrick bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath); 675*09467b48Spatrick bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath); 676*09467b48Spatrick 677*09467b48Spatrick // Nothing's actually returned, it doesn't matter what the callee put there 678*09467b48Spatrick // it's a valid tail call. 679*09467b48Spatrick if (RetEmpty) 680*09467b48Spatrick return true; 681*09467b48Spatrick 682*09467b48Spatrick // Iterate pairwise through each of the value types making up the tail call 683*09467b48Spatrick // and the corresponding return. For each one we want to know whether it's 684*09467b48Spatrick // essentially going directly from the tail call to the ret, via operations 685*09467b48Spatrick // that end up not generating any code. 686*09467b48Spatrick // 687*09467b48Spatrick // We allow a certain amount of covariance here. For example it's permitted 688*09467b48Spatrick // for the tail call to define more bits than the ret actually cares about 689*09467b48Spatrick // (e.g. via a truncate). 690*09467b48Spatrick do { 691*09467b48Spatrick if (CallEmpty) { 692*09467b48Spatrick // We've exhausted the values produced by the tail call instruction, the 693*09467b48Spatrick // rest are essentially undef. The type doesn't really matter, but we need 694*09467b48Spatrick // *something*. 695*09467b48Spatrick Type *SlotType = RetSubTypes.back()->getTypeAtIndex(RetPath.back()); 696*09467b48Spatrick CallVal = UndefValue::get(SlotType); 697*09467b48Spatrick } 698*09467b48Spatrick 699*09467b48Spatrick // The manipulations performed when we're looking through an insertvalue or 700*09467b48Spatrick // an extractvalue would happen at the front of the RetPath list, so since 701*09467b48Spatrick // we have to copy it anyway it's more efficient to create a reversed copy. 702*09467b48Spatrick SmallVector<unsigned, 4> TmpRetPath(RetPath.rbegin(), RetPath.rend()); 703*09467b48Spatrick SmallVector<unsigned, 4> TmpCallPath(CallPath.rbegin(), CallPath.rend()); 704*09467b48Spatrick 705*09467b48Spatrick // Finally, we can check whether the value produced by the tail call at this 706*09467b48Spatrick // index is compatible with the value we return. 707*09467b48Spatrick if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath, 708*09467b48Spatrick AllowDifferingSizes, TLI, 709*09467b48Spatrick F->getParent()->getDataLayout())) 710*09467b48Spatrick return false; 711*09467b48Spatrick 712*09467b48Spatrick CallEmpty = !nextRealType(CallSubTypes, CallPath); 713*09467b48Spatrick } while(nextRealType(RetSubTypes, RetPath)); 714*09467b48Spatrick 715*09467b48Spatrick return true; 716*09467b48Spatrick } 717*09467b48Spatrick 718*09467b48Spatrick static void collectEHScopeMembers( 719*09467b48Spatrick DenseMap<const MachineBasicBlock *, int> &EHScopeMembership, int EHScope, 720*09467b48Spatrick const MachineBasicBlock *MBB) { 721*09467b48Spatrick SmallVector<const MachineBasicBlock *, 16> Worklist = {MBB}; 722*09467b48Spatrick while (!Worklist.empty()) { 723*09467b48Spatrick const MachineBasicBlock *Visiting = Worklist.pop_back_val(); 724*09467b48Spatrick // Don't follow blocks which start new scopes. 725*09467b48Spatrick if (Visiting->isEHPad() && Visiting != MBB) 726*09467b48Spatrick continue; 727*09467b48Spatrick 728*09467b48Spatrick // Add this MBB to our scope. 729*09467b48Spatrick auto P = EHScopeMembership.insert(std::make_pair(Visiting, EHScope)); 730*09467b48Spatrick 731*09467b48Spatrick // Don't revisit blocks. 732*09467b48Spatrick if (!P.second) { 733*09467b48Spatrick assert(P.first->second == EHScope && "MBB is part of two scopes!"); 734*09467b48Spatrick continue; 735*09467b48Spatrick } 736*09467b48Spatrick 737*09467b48Spatrick // Returns are boundaries where scope transfer can occur, don't follow 738*09467b48Spatrick // successors. 739*09467b48Spatrick if (Visiting->isEHScopeReturnBlock()) 740*09467b48Spatrick continue; 741*09467b48Spatrick 742*09467b48Spatrick for (const MachineBasicBlock *Succ : Visiting->successors()) 743*09467b48Spatrick Worklist.push_back(Succ); 744*09467b48Spatrick } 745*09467b48Spatrick } 746*09467b48Spatrick 747*09467b48Spatrick DenseMap<const MachineBasicBlock *, int> 748*09467b48Spatrick llvm::getEHScopeMembership(const MachineFunction &MF) { 749*09467b48Spatrick DenseMap<const MachineBasicBlock *, int> EHScopeMembership; 750*09467b48Spatrick 751*09467b48Spatrick // We don't have anything to do if there aren't any EH pads. 752*09467b48Spatrick if (!MF.hasEHScopes()) 753*09467b48Spatrick return EHScopeMembership; 754*09467b48Spatrick 755*09467b48Spatrick int EntryBBNumber = MF.front().getNumber(); 756*09467b48Spatrick bool IsSEH = isAsynchronousEHPersonality( 757*09467b48Spatrick classifyEHPersonality(MF.getFunction().getPersonalityFn())); 758*09467b48Spatrick 759*09467b48Spatrick const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 760*09467b48Spatrick SmallVector<const MachineBasicBlock *, 16> EHScopeBlocks; 761*09467b48Spatrick SmallVector<const MachineBasicBlock *, 16> UnreachableBlocks; 762*09467b48Spatrick SmallVector<const MachineBasicBlock *, 16> SEHCatchPads; 763*09467b48Spatrick SmallVector<std::pair<const MachineBasicBlock *, int>, 16> CatchRetSuccessors; 764*09467b48Spatrick for (const MachineBasicBlock &MBB : MF) { 765*09467b48Spatrick if (MBB.isEHScopeEntry()) { 766*09467b48Spatrick EHScopeBlocks.push_back(&MBB); 767*09467b48Spatrick } else if (IsSEH && MBB.isEHPad()) { 768*09467b48Spatrick SEHCatchPads.push_back(&MBB); 769*09467b48Spatrick } else if (MBB.pred_empty()) { 770*09467b48Spatrick UnreachableBlocks.push_back(&MBB); 771*09467b48Spatrick } 772*09467b48Spatrick 773*09467b48Spatrick MachineBasicBlock::const_iterator MBBI = MBB.getFirstTerminator(); 774*09467b48Spatrick 775*09467b48Spatrick // CatchPads are not scopes for SEH so do not consider CatchRet to 776*09467b48Spatrick // transfer control to another scope. 777*09467b48Spatrick if (MBBI == MBB.end() || MBBI->getOpcode() != TII->getCatchReturnOpcode()) 778*09467b48Spatrick continue; 779*09467b48Spatrick 780*09467b48Spatrick // FIXME: SEH CatchPads are not necessarily in the parent function: 781*09467b48Spatrick // they could be inside a finally block. 782*09467b48Spatrick const MachineBasicBlock *Successor = MBBI->getOperand(0).getMBB(); 783*09467b48Spatrick const MachineBasicBlock *SuccessorColor = MBBI->getOperand(1).getMBB(); 784*09467b48Spatrick CatchRetSuccessors.push_back( 785*09467b48Spatrick {Successor, IsSEH ? EntryBBNumber : SuccessorColor->getNumber()}); 786*09467b48Spatrick } 787*09467b48Spatrick 788*09467b48Spatrick // We don't have anything to do if there aren't any EH pads. 789*09467b48Spatrick if (EHScopeBlocks.empty()) 790*09467b48Spatrick return EHScopeMembership; 791*09467b48Spatrick 792*09467b48Spatrick // Identify all the basic blocks reachable from the function entry. 793*09467b48Spatrick collectEHScopeMembers(EHScopeMembership, EntryBBNumber, &MF.front()); 794*09467b48Spatrick // All blocks not part of a scope are in the parent function. 795*09467b48Spatrick for (const MachineBasicBlock *MBB : UnreachableBlocks) 796*09467b48Spatrick collectEHScopeMembers(EHScopeMembership, EntryBBNumber, MBB); 797*09467b48Spatrick // Next, identify all the blocks inside the scopes. 798*09467b48Spatrick for (const MachineBasicBlock *MBB : EHScopeBlocks) 799*09467b48Spatrick collectEHScopeMembers(EHScopeMembership, MBB->getNumber(), MBB); 800*09467b48Spatrick // SEH CatchPads aren't really scopes, handle them separately. 801*09467b48Spatrick for (const MachineBasicBlock *MBB : SEHCatchPads) 802*09467b48Spatrick collectEHScopeMembers(EHScopeMembership, EntryBBNumber, MBB); 803*09467b48Spatrick // Finally, identify all the targets of a catchret. 804*09467b48Spatrick for (std::pair<const MachineBasicBlock *, int> CatchRetPair : 805*09467b48Spatrick CatchRetSuccessors) 806*09467b48Spatrick collectEHScopeMembers(EHScopeMembership, CatchRetPair.second, 807*09467b48Spatrick CatchRetPair.first); 808*09467b48Spatrick return EHScopeMembership; 809*09467b48Spatrick } 810