LLVM API Documentation

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