LLVM API Documentation
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 utilties. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "llvm/CodeGen/Analysis.h" 00015 #include "llvm/Analysis/ValueTracking.h" 00016 #include "llvm/CodeGen/MachineFunction.h" 00017 #include "llvm/IR/DataLayout.h" 00018 #include "llvm/IR/DerivedTypes.h" 00019 #include "llvm/IR/Function.h" 00020 #include "llvm/IR/Instructions.h" 00021 #include "llvm/IR/IntrinsicInst.h" 00022 #include "llvm/IR/LLVMContext.h" 00023 #include "llvm/IR/Module.h" 00024 #include "llvm/Support/ErrorHandling.h" 00025 #include "llvm/Support/MathExtras.h" 00026 #include "llvm/Target/TargetLowering.h" 00027 using namespace llvm; 00028 00029 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence 00030 /// of insertvalue or extractvalue indices that identify a member, return 00031 /// the linearized index of the start of the member. 00032 /// 00033 unsigned llvm::ComputeLinearIndex(Type *Ty, 00034 const unsigned *Indices, 00035 const unsigned *IndicesEnd, 00036 unsigned CurIndex) { 00037 // Base case: We're done. 00038 if (Indices && Indices == IndicesEnd) 00039 return CurIndex; 00040 00041 // Given a struct type, recursively traverse the elements. 00042 if (StructType *STy = dyn_cast<StructType>(Ty)) { 00043 for (StructType::element_iterator EB = STy->element_begin(), 00044 EI = EB, 00045 EE = STy->element_end(); 00046 EI != EE; ++EI) { 00047 if (Indices && *Indices == unsigned(EI - EB)) 00048 return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex); 00049 CurIndex = ComputeLinearIndex(*EI, 0, 0, CurIndex); 00050 } 00051 return CurIndex; 00052 } 00053 // Given an array type, recursively traverse the elements. 00054 else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 00055 Type *EltTy = ATy->getElementType(); 00056 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) { 00057 if (Indices && *Indices == i) 00058 return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex); 00059 CurIndex = ComputeLinearIndex(EltTy, 0, 0, CurIndex); 00060 } 00061 return CurIndex; 00062 } 00063 // We haven't found the type we're looking for, so keep searching. 00064 return CurIndex + 1; 00065 } 00066 00067 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of 00068 /// EVTs that represent all the individual underlying 00069 /// non-aggregate types that comprise it. 00070 /// 00071 /// If Offsets is non-null, it points to a vector to be filled in 00072 /// with the in-memory offsets of each of the individual values. 00073 /// 00074 void llvm::ComputeValueVTs(const TargetLowering &TLI, Type *Ty, 00075 SmallVectorImpl<EVT> &ValueVTs, 00076 SmallVectorImpl<uint64_t> *Offsets, 00077 uint64_t StartingOffset) { 00078 // Given a struct type, recursively traverse the elements. 00079 if (StructType *STy = dyn_cast<StructType>(Ty)) { 00080 const StructLayout *SL = TLI.getDataLayout()->getStructLayout(STy); 00081 for (StructType::element_iterator EB = STy->element_begin(), 00082 EI = EB, 00083 EE = STy->element_end(); 00084 EI != EE; ++EI) 00085 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets, 00086 StartingOffset + SL->getElementOffset(EI - EB)); 00087 return; 00088 } 00089 // Given an array type, recursively traverse the elements. 00090 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 00091 Type *EltTy = ATy->getElementType(); 00092 uint64_t EltSize = TLI.getDataLayout()->getTypeAllocSize(EltTy); 00093 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) 00094 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets, 00095 StartingOffset + i * EltSize); 00096 return; 00097 } 00098 // Interpret void as zero return values. 00099 if (Ty->isVoidTy()) 00100 return; 00101 // Base case: we can get an EVT for this LLVM IR type. 00102 ValueVTs.push_back(TLI.getValueType(Ty)); 00103 if (Offsets) 00104 Offsets->push_back(StartingOffset); 00105 } 00106 00107 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V. 00108 GlobalVariable *llvm::ExtractTypeInfo(Value *V) { 00109 V = V->stripPointerCasts(); 00110 GlobalVariable *GV = dyn_cast<GlobalVariable>(V); 00111 00112 if (GV && GV->getName() == "llvm.eh.catch.all.value") { 00113 assert(GV->hasInitializer() && 00114 "The EH catch-all value must have an initializer"); 00115 Value *Init = GV->getInitializer(); 00116 GV = dyn_cast<GlobalVariable>(Init); 00117 if (!GV) V = cast<ConstantPointerNull>(Init); 00118 } 00119 00120 assert((GV || isa<ConstantPointerNull>(V)) && 00121 "TypeInfo must be a global variable or NULL"); 00122 return GV; 00123 } 00124 00125 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being 00126 /// processed uses a memory 'm' constraint. 00127 bool 00128 llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos, 00129 const TargetLowering &TLI) { 00130 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) { 00131 InlineAsm::ConstraintInfo &CI = CInfos[i]; 00132 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) { 00133 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]); 00134 if (CType == TargetLowering::C_Memory) 00135 return true; 00136 } 00137 00138 // Indirect operand accesses access memory. 00139 if (CI.isIndirect) 00140 return true; 00141 } 00142 00143 return false; 00144 } 00145 00146 /// getFCmpCondCode - Return the ISD condition code corresponding to 00147 /// the given LLVM IR floating-point condition code. This includes 00148 /// consideration of global floating-point math flags. 00149 /// 00150 ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) { 00151 switch (Pred) { 00152 case FCmpInst::FCMP_FALSE: return ISD::SETFALSE; 00153 case FCmpInst::FCMP_OEQ: return ISD::SETOEQ; 00154 case FCmpInst::FCMP_OGT: return ISD::SETOGT; 00155 case FCmpInst::FCMP_OGE: return ISD::SETOGE; 00156 case FCmpInst::FCMP_OLT: return ISD::SETOLT; 00157 case FCmpInst::FCMP_OLE: return ISD::SETOLE; 00158 case FCmpInst::FCMP_ONE: return ISD::SETONE; 00159 case FCmpInst::FCMP_ORD: return ISD::SETO; 00160 case FCmpInst::FCMP_UNO: return ISD::SETUO; 00161 case FCmpInst::FCMP_UEQ: return ISD::SETUEQ; 00162 case FCmpInst::FCMP_UGT: return ISD::SETUGT; 00163 case FCmpInst::FCMP_UGE: return ISD::SETUGE; 00164 case FCmpInst::FCMP_ULT: return ISD::SETULT; 00165 case FCmpInst::FCMP_ULE: return ISD::SETULE; 00166 case FCmpInst::FCMP_UNE: return ISD::SETUNE; 00167 case FCmpInst::FCMP_TRUE: return ISD::SETTRUE; 00168 default: llvm_unreachable("Invalid FCmp predicate opcode!"); 00169 } 00170 } 00171 00172 ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) { 00173 switch (CC) { 00174 case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ; 00175 case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE; 00176 case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT; 00177 case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE; 00178 case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT; 00179 case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE; 00180 default: return CC; 00181 } 00182 } 00183 00184 /// getICmpCondCode - Return the ISD condition code corresponding to 00185 /// the given LLVM IR integer condition code. 00186 /// 00187 ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) { 00188 switch (Pred) { 00189 case ICmpInst::ICMP_EQ: return ISD::SETEQ; 00190 case ICmpInst::ICMP_NE: return ISD::SETNE; 00191 case ICmpInst::ICMP_SLE: return ISD::SETLE; 00192 case ICmpInst::ICMP_ULE: return ISD::SETULE; 00193 case ICmpInst::ICMP_SGE: return ISD::SETGE; 00194 case ICmpInst::ICMP_UGE: return ISD::SETUGE; 00195 case ICmpInst::ICMP_SLT: return ISD::SETLT; 00196 case ICmpInst::ICMP_ULT: return ISD::SETULT; 00197 case ICmpInst::ICMP_SGT: return ISD::SETGT; 00198 case ICmpInst::ICMP_UGT: return ISD::SETUGT; 00199 default: 00200 llvm_unreachable("Invalid ICmp predicate opcode!"); 00201 } 00202 } 00203 00204 static bool isNoopBitcast(Type *T1, Type *T2, 00205 const TargetLowering& TLI) { 00206 return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) || 00207 (isa<VectorType>(T1) && isa<VectorType>(T2) && 00208 TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2))); 00209 } 00210 00211 /// sameNoopInput - Return true if V1 == V2, else if either V1 or V2 is a noop 00212 /// (i.e., lowers to no machine code), look through it (and any transitive noop 00213 /// operands to it) and check if it has the same noop input value. This is 00214 /// used to determine if a tail call can be formed. 00215 static bool sameNoopInput(const Value *V1, const Value *V2, 00216 SmallVectorImpl<unsigned> &Els1, 00217 SmallVectorImpl<unsigned> &Els2, 00218 const TargetLowering &TLI) { 00219 using std::swap; 00220 bool swapParity = false; 00221 bool equalEls = Els1 == Els2; 00222 while (true) { 00223 if ((equalEls && V1 == V2) || isa<UndefValue>(V1) || isa<UndefValue>(V2)) { 00224 if (swapParity) 00225 // Revert to original Els1 and Els2 to avoid confusing recursive calls 00226 swap(Els1, Els2); 00227 return true; 00228 } 00229 00230 // Try to look through V1; if V1 is not an instruction, it can't be looked 00231 // through. 00232 const Instruction *I = dyn_cast<Instruction>(V1); 00233 const Value *NoopInput = 0; 00234 if (I != 0 && I->getNumOperands() > 0) { 00235 Value *Op = I->getOperand(0); 00236 if (isa<TruncInst>(I)) { 00237 // Look through truly no-op truncates. 00238 if (TLI.isTruncateFree(Op->getType(), I->getType())) 00239 NoopInput = Op; 00240 } else if (isa<BitCastInst>(I)) { 00241 // Look through truly no-op bitcasts. 00242 if (isNoopBitcast(Op->getType(), I->getType(), TLI)) 00243 NoopInput = Op; 00244 } else if (isa<GetElementPtrInst>(I)) { 00245 // Look through getelementptr 00246 if (cast<GetElementPtrInst>(I)->hasAllZeroIndices()) 00247 NoopInput = Op; 00248 } else if (isa<IntToPtrInst>(I)) { 00249 // Look through inttoptr. 00250 // Make sure this isn't a truncating or extending cast. We could 00251 // support this eventually, but don't bother for now. 00252 if (!isa<VectorType>(I->getType()) && 00253 TLI.getPointerTy().getSizeInBits() == 00254 cast<IntegerType>(Op->getType())->getBitWidth()) 00255 NoopInput = Op; 00256 } else if (isa<PtrToIntInst>(I)) { 00257 // Look through ptrtoint. 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 TLI.getPointerTy().getSizeInBits() == 00262 cast<IntegerType>(I->getType())->getBitWidth()) 00263 NoopInput = Op; 00264 } else if (isa<CallInst>(I)) { 00265 // Look through call 00266 for (User::const_op_iterator i = I->op_begin(), 00267 // Skip Callee 00268 e = I->op_end() - 1; 00269 i != e; ++i) { 00270 unsigned attrInd = i - I->op_begin() + 1; 00271 if (cast<CallInst>(I)->paramHasAttr(attrInd, Attribute::Returned) && 00272 isNoopBitcast((*i)->getType(), I->getType(), TLI)) { 00273 NoopInput = *i; 00274 break; 00275 } 00276 } 00277 } else if (isa<InvokeInst>(I)) { 00278 // Look through invoke 00279 for (User::const_op_iterator i = I->op_begin(), 00280 // Skip BB, BB, Callee 00281 e = I->op_end() - 3; 00282 i != e; ++i) { 00283 unsigned attrInd = i - I->op_begin() + 1; 00284 if (cast<InvokeInst>(I)->paramHasAttr(attrInd, Attribute::Returned) && 00285 isNoopBitcast((*i)->getType(), I->getType(), TLI)) { 00286 NoopInput = *i; 00287 break; 00288 } 00289 } 00290 } 00291 } 00292 00293 if (NoopInput) { 00294 V1 = NoopInput; 00295 continue; 00296 } 00297 00298 // If we already swapped, avoid infinite loop 00299 if (swapParity) 00300 break; 00301 00302 // Otherwise, swap V1<->V2, Els1<->Els2 00303 swap(V1, V2); 00304 swap(Els1, Els2); 00305 swapParity = !swapParity; 00306 } 00307 00308 for (unsigned n = 0; n < 2; ++n) { 00309 if (isa<InsertValueInst>(V1)) { 00310 if (isa<StructType>(V1->getType())) { 00311 // Look through insertvalue 00312 unsigned i, e; 00313 for (i = 0, e = cast<StructType>(V1->getType())->getNumElements(); 00314 i != e; ++i) { 00315 const Value *InScalar = FindInsertedValue(const_cast<Value*>(V1), i); 00316 if (InScalar == 0) 00317 break; 00318 Els1.push_back(i); 00319 if (!sameNoopInput(InScalar, V2, Els1, Els2, TLI)) { 00320 Els1.pop_back(); 00321 break; 00322 } 00323 Els1.pop_back(); 00324 } 00325 if (i == e) { 00326 if (swapParity) 00327 swap(Els1, Els2); 00328 return true; 00329 } 00330 } 00331 } else if (!Els1.empty() && isa<ExtractValueInst>(V1)) { 00332 const ExtractValueInst *EVI = cast<ExtractValueInst>(V1); 00333 unsigned i = Els1.back(); 00334 // If the scalar value being inserted is an extractvalue of the right 00335 // index from the call, then everything is good. 00336 if (isa<StructType>(EVI->getOperand(0)->getType()) && 00337 EVI->getNumIndices() == 1 && EVI->getIndices()[0] == i) { 00338 // Look through extractvalue 00339 Els1.pop_back(); 00340 if (sameNoopInput(EVI->getOperand(0), V2, Els1, Els2, TLI)) { 00341 Els1.push_back(i); 00342 if (swapParity) 00343 swap(Els1, Els2); 00344 return true; 00345 } 00346 Els1.push_back(i); 00347 } 00348 } 00349 00350 swap(V1, V2); 00351 swap(Els1, Els2); 00352 swapParity = !swapParity; 00353 } 00354 00355 if (swapParity) 00356 swap(Els1, Els2); 00357 return false; 00358 } 00359 00360 /// Test if the given instruction is in a position to be optimized 00361 /// with a tail-call. This roughly means that it's in a block with 00362 /// a return and there's nothing that needs to be scheduled 00363 /// between it and the return. 00364 /// 00365 /// This function only tests target-independent requirements. 00366 bool llvm::isInTailCallPosition(ImmutableCallSite CS, 00367 const TargetLowering &TLI) { 00368 const Instruction *I = CS.getInstruction(); 00369 const BasicBlock *ExitBB = I->getParent(); 00370 const TerminatorInst *Term = ExitBB->getTerminator(); 00371 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term); 00372 00373 // The block must end in a return statement or unreachable. 00374 // 00375 // FIXME: Decline tailcall if it's not guaranteed and if the block ends in 00376 // an unreachable, for now. The way tailcall optimization is currently 00377 // implemented means it will add an epilogue followed by a jump. That is 00378 // not profitable. Also, if the callee is a special function (e.g. 00379 // longjmp on x86), it can end up causing miscompilation that has not 00380 // been fully understood. 00381 if (!Ret && 00382 (!TLI.getTargetMachine().Options.GuaranteedTailCallOpt || 00383 !isa<UnreachableInst>(Term))) 00384 return false; 00385 00386 // If I will have a chain, make sure no other instruction that will have a 00387 // chain interposes between I and the return. 00388 if (I->mayHaveSideEffects() || I->mayReadFromMemory() || 00389 !isSafeToSpeculativelyExecute(I)) 00390 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ; 00391 --BBI) { 00392 if (&*BBI == I) 00393 break; 00394 // Debug info intrinsics do not get in the way of tail call optimization. 00395 if (isa<DbgInfoIntrinsic>(BBI)) 00396 continue; 00397 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() || 00398 !isSafeToSpeculativelyExecute(BBI)) 00399 return false; 00400 } 00401 00402 // If the block ends with a void return or unreachable, it doesn't matter 00403 // what the call's return type is. 00404 if (!Ret || Ret->getNumOperands() == 0) return true; 00405 00406 // If the return value is undef, it doesn't matter what the call's 00407 // return type is. 00408 if (isa<UndefValue>(Ret->getOperand(0))) return true; 00409 00410 // Conservatively require the attributes of the call to match those of 00411 // the return. Ignore noalias because it doesn't affect the call sequence. 00412 const Function *F = ExitBB->getParent(); 00413 AttributeSet CallerAttrs = F->getAttributes(); 00414 if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex). 00415 removeAttribute(Attribute::NoAlias) != 00416 AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex). 00417 removeAttribute(Attribute::NoAlias)) 00418 return false; 00419 00420 // It's not safe to eliminate the sign / zero extension of the return value. 00421 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) || 00422 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt)) 00423 return false; 00424 00425 // Otherwise, make sure the return value and I have the same value 00426 SmallVector<unsigned, 4> Els1, Els2; 00427 return sameNoopInput(Ret->getOperand(0), I, Els1, Els2, TLI); 00428 }