Analysis.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. //===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines several CodeGen-specific LLVM IR analysis utilties.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/Analysis.h"
  14. #include "llvm/Analysis/ValueTracking.h"
  15. #include "llvm/CodeGen/MachineFunction.h"
  16. #include "llvm/IR/DataLayout.h"
  17. #include "llvm/IR/DerivedTypes.h"
  18. #include "llvm/IR/Function.h"
  19. #include "llvm/IR/Instructions.h"
  20. #include "llvm/IR/IntrinsicInst.h"
  21. #include "llvm/IR/LLVMContext.h"
  22. #include "llvm/IR/Module.h"
  23. #include "llvm/Support/ErrorHandling.h"
  24. #include "llvm/Support/MathExtras.h"
  25. #include "llvm/Target/TargetLowering.h"
  26. using namespace llvm;
  27. /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
  28. /// of insertvalue or extractvalue indices that identify a member, return
  29. /// the linearized index of the start of the member.
  30. ///
  31. unsigned llvm::ComputeLinearIndex(Type *Ty,
  32. const unsigned *Indices,
  33. const unsigned *IndicesEnd,
  34. unsigned CurIndex) {
  35. // Base case: We're done.
  36. if (Indices && Indices == IndicesEnd)
  37. return CurIndex;
  38. // Given a struct type, recursively traverse the elements.
  39. if (StructType *STy = dyn_cast<StructType>(Ty)) {
  40. for (StructType::element_iterator EB = STy->element_begin(),
  41. EI = EB,
  42. EE = STy->element_end();
  43. EI != EE; ++EI) {
  44. if (Indices && *Indices == unsigned(EI - EB))
  45. return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex);
  46. CurIndex = ComputeLinearIndex(*EI, 0, 0, CurIndex);
  47. }
  48. return CurIndex;
  49. }
  50. // Given an array type, recursively traverse the elements.
  51. else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  52. Type *EltTy = ATy->getElementType();
  53. for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
  54. if (Indices && *Indices == i)
  55. return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex);
  56. CurIndex = ComputeLinearIndex(EltTy, 0, 0, CurIndex);
  57. }
  58. return CurIndex;
  59. }
  60. // We haven't found the type we're looking for, so keep searching.
  61. return CurIndex + 1;
  62. }
  63. /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
  64. /// EVTs that represent all the individual underlying
  65. /// non-aggregate types that comprise it.
  66. ///
  67. /// If Offsets is non-null, it points to a vector to be filled in
  68. /// with the in-memory offsets of each of the individual values.
  69. ///
  70. void llvm::ComputeValueVTs(const TargetLowering &TLI, Type *Ty,
  71. SmallVectorImpl<EVT> &ValueVTs,
  72. SmallVectorImpl<uint64_t> *Offsets,
  73. uint64_t StartingOffset) {
  74. // Given a struct type, recursively traverse the elements.
  75. if (StructType *STy = dyn_cast<StructType>(Ty)) {
  76. const StructLayout *SL = TLI.getDataLayout()->getStructLayout(STy);
  77. for (StructType::element_iterator EB = STy->element_begin(),
  78. EI = EB,
  79. EE = STy->element_end();
  80. EI != EE; ++EI)
  81. ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
  82. StartingOffset + SL->getElementOffset(EI - EB));
  83. return;
  84. }
  85. // Given an array type, recursively traverse the elements.
  86. if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  87. Type *EltTy = ATy->getElementType();
  88. uint64_t EltSize = TLI.getDataLayout()->getTypeAllocSize(EltTy);
  89. for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
  90. ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
  91. StartingOffset + i * EltSize);
  92. return;
  93. }
  94. // Interpret void as zero return values.
  95. if (Ty->isVoidTy())
  96. return;
  97. // Base case: we can get an EVT for this LLVM IR type.
  98. ValueVTs.push_back(TLI.getValueType(Ty));
  99. if (Offsets)
  100. Offsets->push_back(StartingOffset);
  101. }
  102. /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
  103. GlobalVariable *llvm::ExtractTypeInfo(Value *V) {
  104. V = V->stripPointerCasts();
  105. GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
  106. if (GV && GV->getName() == "llvm.eh.catch.all.value") {
  107. assert(GV->hasInitializer() &&
  108. "The EH catch-all value must have an initializer");
  109. Value *Init = GV->getInitializer();
  110. GV = dyn_cast<GlobalVariable>(Init);
  111. if (!GV) V = cast<ConstantPointerNull>(Init);
  112. }
  113. assert((GV || isa<ConstantPointerNull>(V)) &&
  114. "TypeInfo must be a global variable or NULL");
  115. return GV;
  116. }
  117. /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
  118. /// processed uses a memory 'm' constraint.
  119. bool
  120. llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos,
  121. const TargetLowering &TLI) {
  122. for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
  123. InlineAsm::ConstraintInfo &CI = CInfos[i];
  124. for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
  125. TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
  126. if (CType == TargetLowering::C_Memory)
  127. return true;
  128. }
  129. // Indirect operand accesses access memory.
  130. if (CI.isIndirect)
  131. return true;
  132. }
  133. return false;
  134. }
  135. /// getFCmpCondCode - Return the ISD condition code corresponding to
  136. /// the given LLVM IR floating-point condition code. This includes
  137. /// consideration of global floating-point math flags.
  138. ///
  139. ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
  140. switch (Pred) {
  141. case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
  142. case FCmpInst::FCMP_OEQ: return ISD::SETOEQ;
  143. case FCmpInst::FCMP_OGT: return ISD::SETOGT;
  144. case FCmpInst::FCMP_OGE: return ISD::SETOGE;
  145. case FCmpInst::FCMP_OLT: return ISD::SETOLT;
  146. case FCmpInst::FCMP_OLE: return ISD::SETOLE;
  147. case FCmpInst::FCMP_ONE: return ISD::SETONE;
  148. case FCmpInst::FCMP_ORD: return ISD::SETO;
  149. case FCmpInst::FCMP_UNO: return ISD::SETUO;
  150. case FCmpInst::FCMP_UEQ: return ISD::SETUEQ;
  151. case FCmpInst::FCMP_UGT: return ISD::SETUGT;
  152. case FCmpInst::FCMP_UGE: return ISD::SETUGE;
  153. case FCmpInst::FCMP_ULT: return ISD::SETULT;
  154. case FCmpInst::FCMP_ULE: return ISD::SETULE;
  155. case FCmpInst::FCMP_UNE: return ISD::SETUNE;
  156. case FCmpInst::FCMP_TRUE: return ISD::SETTRUE;
  157. default: llvm_unreachable("Invalid FCmp predicate opcode!");
  158. }
  159. }
  160. ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
  161. switch (CC) {
  162. case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
  163. case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
  164. case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
  165. case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
  166. case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
  167. case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
  168. default: return CC;
  169. }
  170. }
  171. /// getICmpCondCode - Return the ISD condition code corresponding to
  172. /// the given LLVM IR integer condition code.
  173. ///
  174. ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
  175. switch (Pred) {
  176. case ICmpInst::ICMP_EQ: return ISD::SETEQ;
  177. case ICmpInst::ICMP_NE: return ISD::SETNE;
  178. case ICmpInst::ICMP_SLE: return ISD::SETLE;
  179. case ICmpInst::ICMP_ULE: return ISD::SETULE;
  180. case ICmpInst::ICMP_SGE: return ISD::SETGE;
  181. case ICmpInst::ICMP_UGE: return ISD::SETUGE;
  182. case ICmpInst::ICMP_SLT: return ISD::SETLT;
  183. case ICmpInst::ICMP_ULT: return ISD::SETULT;
  184. case ICmpInst::ICMP_SGT: return ISD::SETGT;
  185. case ICmpInst::ICMP_UGT: return ISD::SETUGT;
  186. default:
  187. llvm_unreachable("Invalid ICmp predicate opcode!");
  188. }
  189. }
  190. /// getNoopInput - If V is a noop (i.e., lowers to no machine code), look
  191. /// through it (and any transitive noop operands to it) and return its input
  192. /// value. This is used to determine if a tail call can be formed.
  193. ///
  194. static const Value *getNoopInput(const Value *V, const TargetLowering &TLI) {
  195. // If V is not an instruction, it can't be looked through.
  196. const Instruction *I = dyn_cast<Instruction>(V);
  197. if (I == 0 || !I->hasOneUse() || I->getNumOperands() == 0) return V;
  198. Value *Op = I->getOperand(0);
  199. // Look through truly no-op truncates.
  200. if (isa<TruncInst>(I) &&
  201. TLI.isTruncateFree(I->getOperand(0)->getType(), I->getType()))
  202. return getNoopInput(I->getOperand(0), TLI);
  203. // Look through truly no-op bitcasts.
  204. if (isa<BitCastInst>(I)) {
  205. // No type change at all.
  206. if (Op->getType() == I->getType())
  207. return getNoopInput(Op, TLI);
  208. // Pointer to pointer cast.
  209. if (Op->getType()->isPointerTy() && I->getType()->isPointerTy())
  210. return getNoopInput(Op, TLI);
  211. if (isa<VectorType>(Op->getType()) && isa<VectorType>(I->getType()) &&
  212. TLI.isTypeLegal(EVT::getEVT(Op->getType())) &&
  213. TLI.isTypeLegal(EVT::getEVT(I->getType())))
  214. return getNoopInput(Op, TLI);
  215. }
  216. // Look through inttoptr.
  217. if (isa<IntToPtrInst>(I) && !isa<VectorType>(I->getType())) {
  218. // Make sure this isn't a truncating or extending cast. We could support
  219. // this eventually, but don't bother for now.
  220. if (TLI.getPointerTy().getSizeInBits() ==
  221. cast<IntegerType>(Op->getType())->getBitWidth())
  222. return getNoopInput(Op, TLI);
  223. }
  224. // Look through ptrtoint.
  225. if (isa<PtrToIntInst>(I) && !isa<VectorType>(I->getType())) {
  226. // Make sure this isn't a truncating or extending cast. We could support
  227. // this eventually, but don't bother for now.
  228. if (TLI.getPointerTy().getSizeInBits() ==
  229. cast<IntegerType>(I->getType())->getBitWidth())
  230. return getNoopInput(Op, TLI);
  231. }
  232. // Otherwise it's not something we can look through.
  233. return V;
  234. }
  235. /// Test if the given instruction is in a position to be optimized
  236. /// with a tail-call. This roughly means that it's in a block with
  237. /// a return and there's nothing that needs to be scheduled
  238. /// between it and the return.
  239. ///
  240. /// This function only tests target-independent requirements.
  241. bool llvm::isInTailCallPosition(ImmutableCallSite CS,const TargetLowering &TLI){
  242. const Instruction *I = CS.getInstruction();
  243. const BasicBlock *ExitBB = I->getParent();
  244. const TerminatorInst *Term = ExitBB->getTerminator();
  245. const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
  246. // The block must end in a return statement or unreachable.
  247. //
  248. // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
  249. // an unreachable, for now. The way tailcall optimization is currently
  250. // implemented means it will add an epilogue followed by a jump. That is
  251. // not profitable. Also, if the callee is a special function (e.g.
  252. // longjmp on x86), it can end up causing miscompilation that has not
  253. // been fully understood.
  254. if (!Ret &&
  255. (!TLI.getTargetMachine().Options.GuaranteedTailCallOpt ||
  256. !isa<UnreachableInst>(Term)))
  257. return false;
  258. // If I will have a chain, make sure no other instruction that will have a
  259. // chain interposes between I and the return.
  260. if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
  261. !isSafeToSpeculativelyExecute(I))
  262. for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
  263. --BBI) {
  264. if (&*BBI == I)
  265. break;
  266. // Debug info intrinsics do not get in the way of tail call optimization.
  267. if (isa<DbgInfoIntrinsic>(BBI))
  268. continue;
  269. if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
  270. !isSafeToSpeculativelyExecute(BBI))
  271. return false;
  272. }
  273. // If the block ends with a void return or unreachable, it doesn't matter
  274. // what the call's return type is.
  275. if (!Ret || Ret->getNumOperands() == 0) return true;
  276. // If the return value is undef, it doesn't matter what the call's
  277. // return type is.
  278. if (isa<UndefValue>(Ret->getOperand(0))) return true;
  279. // Conservatively require the attributes of the call to match those of
  280. // the return. Ignore noalias because it doesn't affect the call sequence.
  281. const Function *F = ExitBB->getParent();
  282. AttributeSet CallerAttrs = F->getAttributes();
  283. if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex).
  284. removeAttribute(Attribute::NoAlias) !=
  285. AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex).
  286. removeAttribute(Attribute::NoAlias))
  287. return false;
  288. // It's not safe to eliminate the sign / zero extension of the return value.
  289. if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
  290. CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
  291. return false;
  292. // Otherwise, make sure the unmodified return value of I is the return value.
  293. // We handle two cases: multiple return values + scalars.
  294. Value *RetVal = Ret->getOperand(0);
  295. if (!isa<InsertValueInst>(RetVal) || !isa<StructType>(RetVal->getType()))
  296. // Handle scalars first.
  297. return getNoopInput(Ret->getOperand(0), TLI) == I;
  298. // If this is an aggregate return, look through the insert/extract values and
  299. // see if each is transparent.
  300. for (unsigned i = 0, e =cast<StructType>(RetVal->getType())->getNumElements();
  301. i != e; ++i) {
  302. const Value *InScalar = FindInsertedValue(RetVal, i);
  303. if (InScalar == 0) return false;
  304. InScalar = getNoopInput(InScalar, TLI);
  305. // If the scalar value being inserted is an extractvalue of the right index
  306. // from the call, then everything is good.
  307. const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(InScalar);
  308. if (EVI == 0 || EVI->getOperand(0) != I || EVI->getNumIndices() != 1 ||
  309. EVI->getIndices()[0] != i)
  310. return false;
  311. }
  312. return true;
  313. }