LLVM  mainline
Analysis.cpp
Go to the documentation of this file.
00001 //===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines several CodeGen-specific LLVM IR analysis utilities.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/CodeGen/Analysis.h"
00015 #include "llvm/Analysis/ValueTracking.h"
00016 #include "llvm/CodeGen/MachineFunction.h"
00017 #include "llvm/CodeGen/MachineModuleInfo.h"
00018 #include "llvm/CodeGen/SelectionDAG.h"
00019 #include "llvm/IR/DataLayout.h"
00020 #include "llvm/IR/DerivedTypes.h"
00021 #include "llvm/IR/Function.h"
00022 #include "llvm/IR/Instructions.h"
00023 #include "llvm/IR/IntrinsicInst.h"
00024 #include "llvm/IR/LLVMContext.h"
00025 #include "llvm/IR/Module.h"
00026 #include "llvm/Support/ErrorHandling.h"
00027 #include "llvm/Support/MathExtras.h"
00028 #include "llvm/Target/TargetLowering.h"
00029 #include "llvm/Target/TargetInstrInfo.h"
00030 #include "llvm/Target/TargetSubtargetInfo.h"
00031 #include "llvm/Transforms/Utils/GlobalStatus.h"
00032 
00033 using namespace llvm;
00034 
00035 /// Compute the linearized index of a member in a nested aggregate/struct/array
00036 /// by recursing and accumulating CurIndex as long as there are indices in the
00037 /// index list.
00038 unsigned llvm::ComputeLinearIndex(Type *Ty,
00039                                   const unsigned *Indices,
00040                                   const unsigned *IndicesEnd,
00041                                   unsigned CurIndex) {
00042   // Base case: We're done.
00043   if (Indices && Indices == IndicesEnd)
00044     return CurIndex;
00045 
00046   // Given a struct type, recursively traverse the elements.
00047   if (StructType *STy = dyn_cast<StructType>(Ty)) {
00048     for (StructType::element_iterator EB = STy->element_begin(),
00049                                       EI = EB,
00050                                       EE = STy->element_end();
00051         EI != EE; ++EI) {
00052       if (Indices && *Indices == unsigned(EI - EB))
00053         return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex);
00054       CurIndex = ComputeLinearIndex(*EI, nullptr, nullptr, CurIndex);
00055     }
00056     assert(!Indices && "Unexpected out of bound");
00057     return CurIndex;
00058   }
00059   // Given an array type, recursively traverse the elements.
00060   else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00061     Type *EltTy = ATy->getElementType();
00062     unsigned NumElts = ATy->getNumElements();
00063     // Compute the Linear offset when jumping one element of the array
00064     unsigned EltLinearOffset = ComputeLinearIndex(EltTy, nullptr, nullptr, 0);
00065     if (Indices) {
00066       assert(*Indices < NumElts && "Unexpected out of bound");
00067       // If the indice is inside the array, compute the index to the requested
00068       // elt and recurse inside the element with the end of the indices list
00069       CurIndex += EltLinearOffset* *Indices;
00070       return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex);
00071     }
00072     CurIndex += EltLinearOffset*NumElts;
00073     return CurIndex;
00074   }
00075   // We haven't found the type we're looking for, so keep searching.
00076   return CurIndex + 1;
00077 }
00078 
00079 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
00080 /// EVTs that represent all the individual underlying
00081 /// non-aggregate types that comprise it.
00082 ///
00083 /// If Offsets is non-null, it points to a vector to be filled in
00084 /// with the in-memory offsets of each of the individual values.
00085 ///
00086 void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL,
00087                            Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
00088                            SmallVectorImpl<uint64_t> *Offsets,
00089                            uint64_t StartingOffset) {
00090   // Given a struct type, recursively traverse the elements.
00091   if (StructType *STy = dyn_cast<StructType>(Ty)) {
00092     const StructLayout *SL = DL.getStructLayout(STy);
00093     for (StructType::element_iterator EB = STy->element_begin(),
00094                                       EI = EB,
00095                                       EE = STy->element_end();
00096          EI != EE; ++EI)
00097       ComputeValueVTs(TLI, DL, *EI, ValueVTs, Offsets,
00098                       StartingOffset + SL->getElementOffset(EI - EB));
00099     return;
00100   }
00101   // Given an array type, recursively traverse the elements.
00102   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00103     Type *EltTy = ATy->getElementType();
00104     uint64_t EltSize = DL.getTypeAllocSize(EltTy);
00105     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
00106       ComputeValueVTs(TLI, DL, EltTy, ValueVTs, Offsets,
00107                       StartingOffset + i * EltSize);
00108     return;
00109   }
00110   // Interpret void as zero return values.
00111   if (Ty->isVoidTy())
00112     return;
00113   // Base case: we can get an EVT for this LLVM IR type.
00114   ValueVTs.push_back(TLI.getValueType(DL, Ty));
00115   if (Offsets)
00116     Offsets->push_back(StartingOffset);
00117 }
00118 
00119 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
00120 GlobalValue *llvm::ExtractTypeInfo(Value *V) {
00121   V = V->stripPointerCasts();
00122   GlobalValue *GV = dyn_cast<GlobalValue>(V);
00123   GlobalVariable *Var = dyn_cast<GlobalVariable>(V);
00124 
00125   if (Var && Var->getName() == "llvm.eh.catch.all.value") {
00126     assert(Var->hasInitializer() &&
00127            "The EH catch-all value must have an initializer");
00128     Value *Init = Var->getInitializer();
00129     GV = dyn_cast<GlobalValue>(Init);
00130     if (!GV) V = cast<ConstantPointerNull>(Init);
00131   }
00132 
00133   assert((GV || isa<ConstantPointerNull>(V)) &&
00134          "TypeInfo must be a global variable or NULL");
00135   return GV;
00136 }
00137 
00138 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
00139 /// processed uses a memory 'm' constraint.
00140 bool
00141 llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos,
00142                                 const TargetLowering &TLI) {
00143   for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
00144     InlineAsm::ConstraintInfo &CI = CInfos[i];
00145     for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
00146       TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
00147       if (CType == TargetLowering::C_Memory)
00148         return true;
00149     }
00150 
00151     // Indirect operand accesses access memory.
00152     if (CI.isIndirect)
00153       return true;
00154   }
00155 
00156   return false;
00157 }
00158 
00159 /// getFCmpCondCode - Return the ISD condition code corresponding to
00160 /// the given LLVM IR floating-point condition code.  This includes
00161 /// consideration of global floating-point math flags.
00162 ///
00163 ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
00164   switch (Pred) {
00165   case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
00166   case FCmpInst::FCMP_OEQ:   return ISD::SETOEQ;
00167   case FCmpInst::FCMP_OGT:   return ISD::SETOGT;
00168   case FCmpInst::FCMP_OGE:   return ISD::SETOGE;
00169   case FCmpInst::FCMP_OLT:   return ISD::SETOLT;
00170   case FCmpInst::FCMP_OLE:   return ISD::SETOLE;
00171   case FCmpInst::FCMP_ONE:   return ISD::SETONE;
00172   case FCmpInst::FCMP_ORD:   return ISD::SETO;
00173   case FCmpInst::FCMP_UNO:   return ISD::SETUO;
00174   case FCmpInst::FCMP_UEQ:   return ISD::SETUEQ;
00175   case FCmpInst::FCMP_UGT:   return ISD::SETUGT;
00176   case FCmpInst::FCMP_UGE:   return ISD::SETUGE;
00177   case FCmpInst::FCMP_ULT:   return ISD::SETULT;
00178   case FCmpInst::FCMP_ULE:   return ISD::SETULE;
00179   case FCmpInst::FCMP_UNE:   return ISD::SETUNE;
00180   case FCmpInst::FCMP_TRUE:  return ISD::SETTRUE;
00181   default: llvm_unreachable("Invalid FCmp predicate opcode!");
00182   }
00183 }
00184 
00185 ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
00186   switch (CC) {
00187     case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
00188     case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
00189     case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
00190     case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
00191     case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
00192     case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
00193     default: return CC;
00194   }
00195 }
00196 
00197 /// getICmpCondCode - Return the ISD condition code corresponding to
00198 /// the given LLVM IR integer condition code.
00199 ///
00200 ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
00201   switch (Pred) {
00202   case ICmpInst::ICMP_EQ:  return ISD::SETEQ;
00203   case ICmpInst::ICMP_NE:  return ISD::SETNE;
00204   case ICmpInst::ICMP_SLE: return ISD::SETLE;
00205   case ICmpInst::ICMP_ULE: return ISD::SETULE;
00206   case ICmpInst::ICMP_SGE: return ISD::SETGE;
00207   case ICmpInst::ICMP_UGE: return ISD::SETUGE;
00208   case ICmpInst::ICMP_SLT: return ISD::SETLT;
00209   case ICmpInst::ICMP_ULT: return ISD::SETULT;
00210   case ICmpInst::ICMP_SGT: return ISD::SETGT;
00211   case ICmpInst::ICMP_UGT: return ISD::SETUGT;
00212   default:
00213     llvm_unreachable("Invalid ICmp predicate opcode!");
00214   }
00215 }
00216 
00217 static bool isNoopBitcast(Type *T1, Type *T2,
00218                           const TargetLoweringBase& TLI) {
00219   return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) ||
00220          (isa<VectorType>(T1) && isa<VectorType>(T2) &&
00221           TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2)));
00222 }
00223 
00224 /// Look through operations that will be free to find the earliest source of
00225 /// this value.
00226 ///
00227 /// @param ValLoc If V has aggegate type, we will be interested in a particular
00228 /// scalar component. This records its address; the reverse of this list gives a
00229 /// sequence of indices appropriate for an extractvalue to locate the important
00230 /// value. This value is updated during the function and on exit will indicate
00231 /// similar information for the Value returned.
00232 ///
00233 /// @param DataBits If this function looks through truncate instructions, this
00234 /// will record the smallest size attained.
00235 static const Value *getNoopInput(const Value *V,
00236                                  SmallVectorImpl<unsigned> &ValLoc,
00237                                  unsigned &DataBits,
00238                                  const TargetLoweringBase &TLI,
00239                                  const DataLayout &DL) {
00240   while (true) {
00241     // Try to look through V1; if V1 is not an instruction, it can't be looked
00242     // through.
00243     const Instruction *I = dyn_cast<Instruction>(V);
00244     if (!I || I->getNumOperands() == 0) return V;
00245     const Value *NoopInput = nullptr;
00246 
00247     Value *Op = I->getOperand(0);
00248     if (isa<BitCastInst>(I)) {
00249       // Look through truly no-op bitcasts.
00250       if (isNoopBitcast(Op->getType(), I->getType(), TLI))
00251         NoopInput = Op;
00252     } else if (isa<GetElementPtrInst>(I)) {
00253       // Look through getelementptr
00254       if (cast<GetElementPtrInst>(I)->hasAllZeroIndices())
00255         NoopInput = Op;
00256     } else if (isa<IntToPtrInst>(I)) {
00257       // Look through inttoptr.
00258       // Make sure this isn't a truncating or extending cast.  We could
00259       // support this eventually, but don't bother for now.
00260       if (!isa<VectorType>(I->getType()) &&
00261           DL.getPointerSizeInBits() ==
00262               cast<IntegerType>(Op->getType())->getBitWidth())
00263         NoopInput = Op;
00264     } else if (isa<PtrToIntInst>(I)) {
00265       // Look through ptrtoint.
00266       // Make sure this isn't a truncating or extending cast.  We could
00267       // support this eventually, but don't bother for now.
00268       if (!isa<VectorType>(I->getType()) &&
00269           DL.getPointerSizeInBits() ==
00270               cast<IntegerType>(I->getType())->getBitWidth())
00271         NoopInput = Op;
00272     } else if (isa<TruncInst>(I) &&
00273                TLI.allowTruncateForTailCall(Op->getType(), I->getType())) {
00274       DataBits = std::min(DataBits, I->getType()->getPrimitiveSizeInBits());
00275       NoopInput = Op;
00276     } else if (isa<CallInst>(I)) {
00277       // Look through call (skipping callee)
00278       for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 1;
00279            i != e; ++i) {
00280         unsigned attrInd = i - I->op_begin() + 1;
00281         if (cast<CallInst>(I)->paramHasAttr(attrInd, Attribute::Returned) &&
00282             isNoopBitcast((*i)->getType(), I->getType(), TLI)) {
00283           NoopInput = *i;
00284           break;
00285         }
00286       }
00287     } else if (isa<InvokeInst>(I)) {
00288       // Look through invoke (skipping BB, BB, Callee)
00289       for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 3;
00290            i != e; ++i) {
00291         unsigned attrInd = i - I->op_begin() + 1;
00292         if (cast<InvokeInst>(I)->paramHasAttr(attrInd, Attribute::Returned) &&
00293             isNoopBitcast((*i)->getType(), I->getType(), TLI)) {
00294           NoopInput = *i;
00295           break;
00296         }
00297       }
00298     } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(V)) {
00299       // Value may come from either the aggregate or the scalar
00300       ArrayRef<unsigned> InsertLoc = IVI->getIndices();
00301       if (ValLoc.size() >= InsertLoc.size() &&
00302           std::equal(InsertLoc.begin(), InsertLoc.end(), ValLoc.rbegin())) {
00303         // The type being inserted is a nested sub-type of the aggregate; we
00304         // have to remove those initial indices to get the location we're
00305         // interested in for the operand.
00306         ValLoc.resize(ValLoc.size() - InsertLoc.size());
00307         NoopInput = IVI->getInsertedValueOperand();
00308       } else {
00309         // The struct we're inserting into has the value we're interested in, no
00310         // change of address.
00311         NoopInput = Op;
00312       }
00313     } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
00314       // The part we're interested in will inevitably be some sub-section of the
00315       // previous aggregate. Combine the two paths to obtain the true address of
00316       // our element.
00317       ArrayRef<unsigned> ExtractLoc = EVI->getIndices();
00318       ValLoc.append(ExtractLoc.rbegin(), ExtractLoc.rend());
00319       NoopInput = Op;
00320     }
00321     // Terminate if we couldn't find anything to look through.
00322     if (!NoopInput)
00323       return V;
00324 
00325     V = NoopInput;
00326   }
00327 }
00328 
00329 /// Return true if this scalar return value only has bits discarded on its path
00330 /// from the "tail call" to the "ret". This includes the obvious noop
00331 /// instructions handled by getNoopInput above as well as free truncations (or
00332 /// extensions prior to the call).
00333 static bool slotOnlyDiscardsData(const Value *RetVal, const Value *CallVal,
00334                                  SmallVectorImpl<unsigned> &RetIndices,
00335                                  SmallVectorImpl<unsigned> &CallIndices,
00336                                  bool AllowDifferingSizes,
00337                                  const TargetLoweringBase &TLI,
00338                                  const DataLayout &DL) {
00339 
00340   // Trace the sub-value needed by the return value as far back up the graph as
00341   // possible, in the hope that it will intersect with the value produced by the
00342   // call. In the simple case with no "returned" attribute, the hope is actually
00343   // that we end up back at the tail call instruction itself.
00344   unsigned BitsRequired = UINT_MAX;
00345   RetVal = getNoopInput(RetVal, RetIndices, BitsRequired, TLI, DL);
00346 
00347   // If this slot in the value returned is undef, it doesn't matter what the
00348   // call puts there, it'll be fine.
00349   if (isa<UndefValue>(RetVal))
00350     return true;
00351 
00352   // Now do a similar search up through the graph to find where the value
00353   // actually returned by the "tail call" comes from. In the simple case without
00354   // a "returned" attribute, the search will be blocked immediately and the loop
00355   // a Noop.
00356   unsigned BitsProvided = UINT_MAX;
00357   CallVal = getNoopInput(CallVal, CallIndices, BitsProvided, TLI, DL);
00358 
00359   // There's no hope if we can't actually trace them to (the same part of!) the
00360   // same value.
00361   if (CallVal != RetVal || CallIndices != RetIndices)
00362     return false;
00363 
00364   // However, intervening truncates may have made the call non-tail. Make sure
00365   // all the bits that are needed by the "ret" have been provided by the "tail
00366   // call". FIXME: with sufficiently cunning bit-tracking, we could look through
00367   // extensions too.
00368   if (BitsProvided < BitsRequired ||
00369       (!AllowDifferingSizes && BitsProvided != BitsRequired))
00370     return false;
00371 
00372   return true;
00373 }
00374 
00375 /// For an aggregate type, determine whether a given index is within bounds or
00376 /// not.
00377 static bool indexReallyValid(CompositeType *T, unsigned Idx) {
00378   if (ArrayType *AT = dyn_cast<ArrayType>(T))
00379     return Idx < AT->getNumElements();
00380 
00381   return Idx < cast<StructType>(T)->getNumElements();
00382 }
00383 
00384 /// Move the given iterators to the next leaf type in depth first traversal.
00385 ///
00386 /// Performs a depth-first traversal of the type as specified by its arguments,
00387 /// stopping at the next leaf node (which may be a legitimate scalar type or an
00388 /// empty struct or array).
00389 ///
00390 /// @param SubTypes List of the partial components making up the type from
00391 /// outermost to innermost non-empty aggregate. The element currently
00392 /// represented is SubTypes.back()->getTypeAtIndex(Path.back() - 1).
00393 ///
00394 /// @param Path Set of extractvalue indices leading from the outermost type
00395 /// (SubTypes[0]) to the leaf node currently represented.
00396 ///
00397 /// @returns true if a new type was found, false otherwise. Calling this
00398 /// function again on a finished iterator will repeatedly return
00399 /// false. SubTypes.back()->getTypeAtIndex(Path.back()) is either an empty
00400 /// aggregate or a non-aggregate
00401 static bool advanceToNextLeafType(SmallVectorImpl<CompositeType *> &SubTypes,
00402                                   SmallVectorImpl<unsigned> &Path) {
00403   // First march back up the tree until we can successfully increment one of the
00404   // coordinates in Path.
00405   while (!Path.empty() && !indexReallyValid(SubTypes.back(), Path.back() + 1)) {
00406     Path.pop_back();
00407     SubTypes.pop_back();
00408   }
00409 
00410   // If we reached the top, then the iterator is done.
00411   if (Path.empty())
00412     return false;
00413 
00414   // We know there's *some* valid leaf now, so march back down the tree picking
00415   // out the left-most element at each node.
00416   ++Path.back();
00417   Type *DeeperType = SubTypes.back()->getTypeAtIndex(Path.back());
00418   while (DeeperType->isAggregateType()) {
00419     CompositeType *CT = cast<CompositeType>(DeeperType);
00420     if (!indexReallyValid(CT, 0))
00421       return true;
00422 
00423     SubTypes.push_back(CT);
00424     Path.push_back(0);
00425 
00426     DeeperType = CT->getTypeAtIndex(0U);
00427   }
00428 
00429   return true;
00430 }
00431 
00432 /// Find the first non-empty, scalar-like type in Next and setup the iterator
00433 /// components.
00434 ///
00435 /// Assuming Next is an aggregate of some kind, this function will traverse the
00436 /// tree from left to right (i.e. depth-first) looking for the first
00437 /// non-aggregate type which will play a role in function return.
00438 ///
00439 /// For example, if Next was {[0 x i64], {{}, i32, {}}, i32} then we would setup
00440 /// Path as [1, 1] and SubTypes as [Next, {{}, i32, {}}] to represent the first
00441 /// i32 in that type.
00442 static bool firstRealType(Type *Next,
00443                           SmallVectorImpl<CompositeType *> &SubTypes,
00444                           SmallVectorImpl<unsigned> &Path) {
00445   // First initialise the iterator components to the first "leaf" node
00446   // (i.e. node with no valid sub-type at any index, so {} does count as a leaf
00447   // despite nominally being an aggregate).
00448   while (Next->isAggregateType() &&
00449          indexReallyValid(cast<CompositeType>(Next), 0)) {
00450     SubTypes.push_back(cast<CompositeType>(Next));
00451     Path.push_back(0);
00452     Next = cast<CompositeType>(Next)->getTypeAtIndex(0U);
00453   }
00454 
00455   // If there's no Path now, Next was originally scalar already (or empty
00456   // leaf). We're done.
00457   if (Path.empty())
00458     return true;
00459 
00460   // Otherwise, use normal iteration to keep looking through the tree until we
00461   // find a non-aggregate type.
00462   while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType()) {
00463     if (!advanceToNextLeafType(SubTypes, Path))
00464       return false;
00465   }
00466 
00467   return true;
00468 }
00469 
00470 /// Set the iterator data-structures to the next non-empty, non-aggregate
00471 /// subtype.
00472 static bool nextRealType(SmallVectorImpl<CompositeType *> &SubTypes,
00473                          SmallVectorImpl<unsigned> &Path) {
00474   do {
00475     if (!advanceToNextLeafType(SubTypes, Path))
00476       return false;
00477 
00478     assert(!Path.empty() && "found a leaf but didn't set the path?");
00479   } while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType());
00480 
00481   return true;
00482 }
00483 
00484 
00485 /// Test if the given instruction is in a position to be optimized
00486 /// with a tail-call. This roughly means that it's in a block with
00487 /// a return and there's nothing that needs to be scheduled
00488 /// between it and the return.
00489 ///
00490 /// This function only tests target-independent requirements.
00491 bool llvm::isInTailCallPosition(ImmutableCallSite CS, const TargetMachine &TM) {
00492   const Instruction *I = CS.getInstruction();
00493   const BasicBlock *ExitBB = I->getParent();
00494   const TerminatorInst *Term = ExitBB->getTerminator();
00495   const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
00496 
00497   // The block must end in a return statement or unreachable.
00498   //
00499   // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
00500   // an unreachable, for now. The way tailcall optimization is currently
00501   // implemented means it will add an epilogue followed by a jump. That is
00502   // not profitable. Also, if the callee is a special function (e.g.
00503   // longjmp on x86), it can end up causing miscompilation that has not
00504   // been fully understood.
00505   if (!Ret &&
00506       (!TM.Options.GuaranteedTailCallOpt || !isa<UnreachableInst>(Term)))
00507     return false;
00508 
00509   // If I will have a chain, make sure no other instruction that will have a
00510   // chain interposes between I and the return.
00511   if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
00512       !isSafeToSpeculativelyExecute(I))
00513     for (BasicBlock::const_iterator BBI = std::prev(ExitBB->end(), 2);; --BBI) {
00514       if (&*BBI == I)
00515         break;
00516       // Debug info intrinsics do not get in the way of tail call optimization.
00517       if (isa<DbgInfoIntrinsic>(BBI))
00518         continue;
00519       if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
00520           !isSafeToSpeculativelyExecute(&*BBI))
00521         return false;
00522     }
00523 
00524   const Function *F = ExitBB->getParent();
00525   return returnTypeIsEligibleForTailCall(
00526       F, I, Ret, *TM.getSubtargetImpl(*F)->getTargetLowering());
00527 }
00528 
00529 bool llvm::returnTypeIsEligibleForTailCall(const Function *F,
00530                                            const Instruction *I,
00531                                            const ReturnInst *Ret,
00532                                            const TargetLoweringBase &TLI) {
00533   // If the block ends with a void return or unreachable, it doesn't matter
00534   // what the call's return type is.
00535   if (!Ret || Ret->getNumOperands() == 0) return true;
00536 
00537   // If the return value is undef, it doesn't matter what the call's
00538   // return type is.
00539   if (isa<UndefValue>(Ret->getOperand(0))) return true;
00540 
00541   // Make sure the attributes attached to each return are compatible.
00542   AttrBuilder CallerAttrs(F->getAttributes(),
00543                           AttributeSet::ReturnIndex);
00544   AttrBuilder CalleeAttrs(cast<CallInst>(I)->getAttributes(),
00545                           AttributeSet::ReturnIndex);
00546 
00547   // Noalias is completely benign as far as calling convention goes, it
00548   // shouldn't affect whether the call is a tail call.
00549   CallerAttrs = CallerAttrs.removeAttribute(Attribute::NoAlias);
00550   CalleeAttrs = CalleeAttrs.removeAttribute(Attribute::NoAlias);
00551 
00552   bool AllowDifferingSizes = true;
00553   if (CallerAttrs.contains(Attribute::ZExt)) {
00554     if (!CalleeAttrs.contains(Attribute::ZExt))
00555       return false;
00556 
00557     AllowDifferingSizes = false;
00558     CallerAttrs.removeAttribute(Attribute::ZExt);
00559     CalleeAttrs.removeAttribute(Attribute::ZExt);
00560   } else if (CallerAttrs.contains(Attribute::SExt)) {
00561     if (!CalleeAttrs.contains(Attribute::SExt))
00562       return false;
00563 
00564     AllowDifferingSizes = false;
00565     CallerAttrs.removeAttribute(Attribute::SExt);
00566     CalleeAttrs.removeAttribute(Attribute::SExt);
00567   }
00568 
00569   // If they're still different, there's some facet we don't understand
00570   // (currently only "inreg", but in future who knows). It may be OK but the
00571   // only safe option is to reject the tail call.
00572   if (CallerAttrs != CalleeAttrs)
00573     return false;
00574 
00575   const Value *RetVal = Ret->getOperand(0), *CallVal = I;
00576   SmallVector<unsigned, 4> RetPath, CallPath;
00577   SmallVector<CompositeType *, 4> RetSubTypes, CallSubTypes;
00578 
00579   bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath);
00580   bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath);
00581 
00582   // Nothing's actually returned, it doesn't matter what the callee put there
00583   // it's a valid tail call.
00584   if (RetEmpty)
00585     return true;
00586 
00587   // Iterate pairwise through each of the value types making up the tail call
00588   // and the corresponding return. For each one we want to know whether it's
00589   // essentially going directly from the tail call to the ret, via operations
00590   // that end up not generating any code.
00591   //
00592   // We allow a certain amount of covariance here. For example it's permitted
00593   // for the tail call to define more bits than the ret actually cares about
00594   // (e.g. via a truncate).
00595   do {
00596     if (CallEmpty) {
00597       // We've exhausted the values produced by the tail call instruction, the
00598       // rest are essentially undef. The type doesn't really matter, but we need
00599       // *something*.
00600       Type *SlotType = RetSubTypes.back()->getTypeAtIndex(RetPath.back());
00601       CallVal = UndefValue::get(SlotType);
00602     }
00603 
00604     // The manipulations performed when we're looking through an insertvalue or
00605     // an extractvalue would happen at the front of the RetPath list, so since
00606     // we have to copy it anyway it's more efficient to create a reversed copy.
00607     SmallVector<unsigned, 4> TmpRetPath(RetPath.rbegin(), RetPath.rend());
00608     SmallVector<unsigned, 4> TmpCallPath(CallPath.rbegin(), CallPath.rend());
00609 
00610     // Finally, we can check whether the value produced by the tail call at this
00611     // index is compatible with the value we return.
00612     if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath,
00613                               AllowDifferingSizes, TLI,
00614                               F->getParent()->getDataLayout()))
00615       return false;
00616 
00617     CallEmpty  = !nextRealType(CallSubTypes, CallPath);
00618   } while(nextRealType(RetSubTypes, RetPath));
00619 
00620   return true;
00621 }
00622 
00623 bool llvm::canBeOmittedFromSymbolTable(const GlobalValue *GV) {
00624   if (!GV->hasLinkOnceODRLinkage())
00625     return false;
00626 
00627   if (GV->hasUnnamedAddr())
00628     return true;
00629 
00630   // If it is a non constant variable, it needs to be uniqued across shared
00631   // objects.
00632   if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
00633     if (!Var->isConstant())
00634       return false;
00635   }
00636 
00637   // An alias can point to a variable. We could try to resolve the alias to
00638   // decide, but for now just don't hide them.
00639   if (isa<GlobalAlias>(GV))
00640     return false;
00641 
00642   // If we don't see every use, we have to be conservative and assume the value
00643   // address is significant.
00644   if (GV->getParent()->getMaterializer())
00645     return false;
00646 
00647   GlobalStatus GS;
00648   if (GlobalStatus::analyzeGlobal(GV, GS))
00649     return false;
00650 
00651   return !GS.IsCompared;
00652 }
00653 
00654 static void collectFuncletMembers(
00655     DenseMap<const MachineBasicBlock *, int> &FuncletMembership, int Funclet,
00656     const MachineBasicBlock *MBB) {
00657   SmallVector<const MachineBasicBlock *, 16> Worklist = {MBB};
00658   while (!Worklist.empty()) {
00659     const MachineBasicBlock *Visiting = Worklist.pop_back_val();
00660     // Don't follow blocks which start new funclets.
00661     if (Visiting->isEHPad() && Visiting != MBB)
00662       continue;
00663 
00664     // Add this MBB to our funclet.
00665     auto P = FuncletMembership.insert(std::make_pair(Visiting, Funclet));
00666 
00667     // Don't revisit blocks.
00668     if (!P.second) {
00669       assert(P.first->second == Funclet && "MBB is part of two funclets!");
00670       continue;
00671     }
00672 
00673     // Returns are boundaries where funclet transfer can occur, don't follow
00674     // successors.
00675     if (Visiting->isReturnBlock())
00676       continue;
00677 
00678     for (const MachineBasicBlock *Succ : Visiting->successors())
00679       Worklist.push_back(Succ);
00680   }
00681 }
00682 
00683 DenseMap<const MachineBasicBlock *, int>
00684 llvm::getFuncletMembership(const MachineFunction &MF) {
00685   DenseMap<const MachineBasicBlock *, int> FuncletMembership;
00686 
00687   // We don't have anything to do if there aren't any EH pads.
00688   if (!MF.getMMI().hasEHFunclets())
00689     return FuncletMembership;
00690 
00691   int EntryBBNumber = MF.front().getNumber();
00692   bool IsSEH = isAsynchronousEHPersonality(
00693       classifyEHPersonality(MF.getFunction()->getPersonalityFn()));
00694 
00695   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
00696   SmallVector<const MachineBasicBlock *, 16> FuncletBlocks;
00697   SmallVector<const MachineBasicBlock *, 16> UnreachableBlocks;
00698   SmallVector<const MachineBasicBlock *, 16> SEHCatchPads;
00699   SmallVector<std::pair<const MachineBasicBlock *, int>, 16> CatchRetSuccessors;
00700   for (const MachineBasicBlock &MBB : MF) {
00701     if (MBB.isEHFuncletEntry()) {
00702       FuncletBlocks.push_back(&MBB);
00703     } else if (IsSEH && MBB.isEHPad()) {
00704       SEHCatchPads.push_back(&MBB);
00705     } else if (MBB.pred_empty()) {
00706       UnreachableBlocks.push_back(&MBB);
00707     }
00708 
00709     MachineBasicBlock::const_iterator MBBI = MBB.getFirstTerminator();
00710     // CatchPads are not funclets for SEH so do not consider CatchRet to
00711     // transfer control to another funclet.
00712     if (MBBI->getOpcode() != TII->getCatchReturnOpcode())
00713       continue;
00714 
00715     // FIXME: SEH CatchPads are not necessarily in the parent function:
00716     // they could be inside a finally block.
00717     const MachineBasicBlock *Successor = MBBI->getOperand(0).getMBB();
00718     const MachineBasicBlock *SuccessorColor = MBBI->getOperand(1).getMBB();
00719     CatchRetSuccessors.push_back(
00720         {Successor, IsSEH ? EntryBBNumber : SuccessorColor->getNumber()});
00721   }
00722 
00723   // We don't have anything to do if there aren't any EH pads.
00724   if (FuncletBlocks.empty())
00725     return FuncletMembership;
00726 
00727   // Identify all the basic blocks reachable from the function entry.
00728   collectFuncletMembers(FuncletMembership, EntryBBNumber, &MF.front());
00729   // All blocks not part of a funclet are in the parent function.
00730   for (const MachineBasicBlock *MBB : UnreachableBlocks)
00731     collectFuncletMembers(FuncletMembership, EntryBBNumber, MBB);
00732   // Next, identify all the blocks inside the funclets.
00733   for (const MachineBasicBlock *MBB : FuncletBlocks)
00734     collectFuncletMembers(FuncletMembership, MBB->getNumber(), MBB);
00735   // SEH CatchPads aren't really funclets, handle them separately.
00736   for (const MachineBasicBlock *MBB : SEHCatchPads)
00737     collectFuncletMembers(FuncletMembership, EntryBBNumber, MBB);
00738   // Finally, identify all the targets of a catchret.
00739   for (std::pair<const MachineBasicBlock *, int> CatchRetPair :
00740        CatchRetSuccessors)
00741     collectFuncletMembers(FuncletMembership, CatchRetPair.second,
00742                           CatchRetPair.first);
00743   return FuncletMembership;
00744 }