Analysis.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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. static bool isNoopBitcast(Type *T1, Type *T2,
  191. const TargetLoweringBase& TLI) {
  192. return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) ||
  193. (isa<VectorType>(T1) && isa<VectorType>(T2) &&
  194. TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2)));
  195. }
  196. /// Look through operations that will be free to find the earliest source of
  197. /// this value.
  198. ///
  199. /// @param ValLoc If V has aggegate type, we will be interested in a particular
  200. /// scalar component. This records its address; the reverse of this list gives a
  201. /// sequence of indices appropriate for an extractvalue to locate the important
  202. /// value. This value is updated during the function and on exit will indicate
  203. /// similar information for the Value returned.
  204. ///
  205. /// @param DataBits If this function looks through truncate instructions, this
  206. /// will record the smallest size attained.
  207. static const Value *getNoopInput(const Value *V,
  208. SmallVectorImpl<unsigned> &ValLoc,
  209. unsigned &DataBits,
  210. const TargetLoweringBase &TLI) {
  211. while (true) {
  212. // Try to look through V1; if V1 is not an instruction, it can't be looked
  213. // through.
  214. const Instruction *I = dyn_cast<Instruction>(V);
  215. if (!I || I->getNumOperands() == 0) return V;
  216. const Value *NoopInput = 0;
  217. Value *Op = I->getOperand(0);
  218. if (isa<BitCastInst>(I)) {
  219. // Look through truly no-op bitcasts.
  220. if (isNoopBitcast(Op->getType(), I->getType(), TLI))
  221. NoopInput = Op;
  222. } else if (isa<GetElementPtrInst>(I)) {
  223. // Look through getelementptr
  224. if (cast<GetElementPtrInst>(I)->hasAllZeroIndices())
  225. NoopInput = Op;
  226. } else if (isa<IntToPtrInst>(I)) {
  227. // Look through inttoptr.
  228. // Make sure this isn't a truncating or extending cast. We could
  229. // support this eventually, but don't bother for now.
  230. if (!isa<VectorType>(I->getType()) &&
  231. TLI.getPointerTy().getSizeInBits() ==
  232. cast<IntegerType>(Op->getType())->getBitWidth())
  233. NoopInput = Op;
  234. } else if (isa<PtrToIntInst>(I)) {
  235. // Look through ptrtoint.
  236. // Make sure this isn't a truncating or extending cast. We could
  237. // support this eventually, but don't bother for now.
  238. if (!isa<VectorType>(I->getType()) &&
  239. TLI.getPointerTy().getSizeInBits() ==
  240. cast<IntegerType>(I->getType())->getBitWidth())
  241. NoopInput = Op;
  242. } else if (isa<TruncInst>(I) &&
  243. TLI.allowTruncateForTailCall(Op->getType(), I->getType())) {
  244. DataBits = std::min(DataBits, I->getType()->getPrimitiveSizeInBits());
  245. NoopInput = Op;
  246. } else if (isa<CallInst>(I)) {
  247. // Look through call (skipping callee)
  248. for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 1;
  249. i != e; ++i) {
  250. unsigned attrInd = i - I->op_begin() + 1;
  251. if (cast<CallInst>(I)->paramHasAttr(attrInd, Attribute::Returned) &&
  252. isNoopBitcast((*i)->getType(), I->getType(), TLI)) {
  253. NoopInput = *i;
  254. break;
  255. }
  256. }
  257. } else if (isa<InvokeInst>(I)) {
  258. // Look through invoke (skipping BB, BB, Callee)
  259. for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 3;
  260. i != e; ++i) {
  261. unsigned attrInd = i - I->op_begin() + 1;
  262. if (cast<InvokeInst>(I)->paramHasAttr(attrInd, Attribute::Returned) &&
  263. isNoopBitcast((*i)->getType(), I->getType(), TLI)) {
  264. NoopInput = *i;
  265. break;
  266. }
  267. }
  268. } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(V)) {
  269. // Value may come from either the aggregate or the scalar
  270. ArrayRef<unsigned> InsertLoc = IVI->getIndices();
  271. if (std::equal(InsertLoc.rbegin(), InsertLoc.rend(),
  272. ValLoc.rbegin())) {
  273. // The type being inserted is a nested sub-type of the aggregate; we
  274. // have to remove those initial indices to get the location we're
  275. // interested in for the operand.
  276. ValLoc.resize(ValLoc.size() - InsertLoc.size());
  277. NoopInput = IVI->getInsertedValueOperand();
  278. } else {
  279. // The struct we're inserting into has the value we're interested in, no
  280. // change of address.
  281. NoopInput = Op;
  282. }
  283. } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
  284. // The part we're interested in will inevitably be some sub-section of the
  285. // previous aggregate. Combine the two paths to obtain the true address of
  286. // our element.
  287. ArrayRef<unsigned> ExtractLoc = EVI->getIndices();
  288. std::copy(ExtractLoc.rbegin(), ExtractLoc.rend(),
  289. std::back_inserter(ValLoc));
  290. NoopInput = Op;
  291. }
  292. // Terminate if we couldn't find anything to look through.
  293. if (!NoopInput)
  294. return V;
  295. V = NoopInput;
  296. }
  297. }
  298. /// Return true if this scalar return value only has bits discarded on its path
  299. /// from the "tail call" to the "ret". This includes the obvious noop
  300. /// instructions handled by getNoopInput above as well as free truncations (or
  301. /// extensions prior to the call).
  302. static bool slotOnlyDiscardsData(const Value *RetVal, const Value *CallVal,
  303. SmallVectorImpl<unsigned> &RetIndices,
  304. SmallVectorImpl<unsigned> &CallIndices,
  305. bool AllowDifferingSizes,
  306. const TargetLoweringBase &TLI) {
  307. // Trace the sub-value needed by the return value as far back up the graph as
  308. // possible, in the hope that it will intersect with the value produced by the
  309. // call. In the simple case with no "returned" attribute, the hope is actually
  310. // that we end up back at the tail call instruction itself.
  311. unsigned BitsRequired = UINT_MAX;
  312. RetVal = getNoopInput(RetVal, RetIndices, BitsRequired, TLI);
  313. // If this slot in the value returned is undef, it doesn't matter what the
  314. // call puts there, it'll be fine.
  315. if (isa<UndefValue>(RetVal))
  316. return true;
  317. // Now do a similar search up through the graph to find where the value
  318. // actually returned by the "tail call" comes from. In the simple case without
  319. // a "returned" attribute, the search will be blocked immediately and the loop
  320. // a Noop.
  321. unsigned BitsProvided = UINT_MAX;
  322. CallVal = getNoopInput(CallVal, CallIndices, BitsProvided, TLI);
  323. // There's no hope if we can't actually trace them to (the same part of!) the
  324. // same value.
  325. if (CallVal != RetVal || CallIndices != RetIndices)
  326. return false;
  327. // However, intervening truncates may have made the call non-tail. Make sure
  328. // all the bits that are needed by the "ret" have been provided by the "tail
  329. // call". FIXME: with sufficiently cunning bit-tracking, we could look through
  330. // extensions too.
  331. if (BitsProvided < BitsRequired ||
  332. (!AllowDifferingSizes && BitsProvided != BitsRequired))
  333. return false;
  334. return true;
  335. }
  336. /// For an aggregate type, determine whether a given index is within bounds or
  337. /// not.
  338. static bool indexReallyValid(CompositeType *T, unsigned Idx) {
  339. if (ArrayType *AT = dyn_cast<ArrayType>(T))
  340. return Idx < AT->getNumElements();
  341. return Idx < cast<StructType>(T)->getNumElements();
  342. }
  343. /// Move the given iterators to the next leaf type in depth first traversal.
  344. ///
  345. /// Performs a depth-first traversal of the type as specified by its arguments,
  346. /// stopping at the next leaf node (which may be a legitimate scalar type or an
  347. /// empty struct or array).
  348. ///
  349. /// @param SubTypes List of the partial components making up the type from
  350. /// outermost to innermost non-empty aggregate. The element currently
  351. /// represented is SubTypes.back()->getTypeAtIndex(Path.back() - 1).
  352. ///
  353. /// @param Path Set of extractvalue indices leading from the outermost type
  354. /// (SubTypes[0]) to the leaf node currently represented.
  355. ///
  356. /// @returns true if a new type was found, false otherwise. Calling this
  357. /// function again on a finished iterator will repeatedly return
  358. /// false. SubTypes.back()->getTypeAtIndex(Path.back()) is either an empty
  359. /// aggregate or a non-aggregate
  360. static bool advanceToNextLeafType(SmallVectorImpl<CompositeType *> &SubTypes,
  361. SmallVectorImpl<unsigned> &Path) {
  362. // First march back up the tree until we can successfully increment one of the
  363. // coordinates in Path.
  364. while (!Path.empty() && !indexReallyValid(SubTypes.back(), Path.back() + 1)) {
  365. Path.pop_back();
  366. SubTypes.pop_back();
  367. }
  368. // If we reached the top, then the iterator is done.
  369. if (Path.empty())
  370. return false;
  371. // We know there's *some* valid leaf now, so march back down the tree picking
  372. // out the left-most element at each node.
  373. ++Path.back();
  374. Type *DeeperType = SubTypes.back()->getTypeAtIndex(Path.back());
  375. while (DeeperType->isAggregateType()) {
  376. CompositeType *CT = cast<CompositeType>(DeeperType);
  377. if (!indexReallyValid(CT, 0))
  378. return true;
  379. SubTypes.push_back(CT);
  380. Path.push_back(0);
  381. DeeperType = CT->getTypeAtIndex(0U);
  382. }
  383. return true;
  384. }
  385. /// Find the first non-empty, scalar-like type in Next and setup the iterator
  386. /// components.
  387. ///
  388. /// Assuming Next is an aggregate of some kind, this function will traverse the
  389. /// tree from left to right (i.e. depth-first) looking for the first
  390. /// non-aggregate type which will play a role in function return.
  391. ///
  392. /// For example, if Next was {[0 x i64], {{}, i32, {}}, i32} then we would setup
  393. /// Path as [1, 1] and SubTypes as [Next, {{}, i32, {}}] to represent the first
  394. /// i32 in that type.
  395. static bool firstRealType(Type *Next,
  396. SmallVectorImpl<CompositeType *> &SubTypes,
  397. SmallVectorImpl<unsigned> &Path) {
  398. // First initialise the iterator components to the first "leaf" node
  399. // (i.e. node with no valid sub-type at any index, so {} does count as a leaf
  400. // despite nominally being an aggregate).
  401. while (Next->isAggregateType() &&
  402. indexReallyValid(cast<CompositeType>(Next), 0)) {
  403. SubTypes.push_back(cast<CompositeType>(Next));
  404. Path.push_back(0);
  405. Next = cast<CompositeType>(Next)->getTypeAtIndex(0U);
  406. }
  407. // If there's no Path now, Next was originally scalar already (or empty
  408. // leaf). We're done.
  409. if (Path.empty())
  410. return true;
  411. // Otherwise, use normal iteration to keep looking through the tree until we
  412. // find a non-aggregate type.
  413. while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType()) {
  414. if (!advanceToNextLeafType(SubTypes, Path))
  415. return false;
  416. }
  417. return true;
  418. }
  419. /// Set the iterator data-structures to the next non-empty, non-aggregate
  420. /// subtype.
  421. static bool nextRealType(SmallVectorImpl<CompositeType *> &SubTypes,
  422. SmallVectorImpl<unsigned> &Path) {
  423. do {
  424. if (!advanceToNextLeafType(SubTypes, Path))
  425. return false;
  426. assert(!Path.empty() && "found a leaf but didn't set the path?");
  427. } while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType());
  428. return true;
  429. }
  430. /// Test if the given instruction is in a position to be optimized
  431. /// with a tail-call. This roughly means that it's in a block with
  432. /// a return and there's nothing that needs to be scheduled
  433. /// between it and the return.
  434. ///
  435. /// This function only tests target-independent requirements.
  436. bool llvm::isInTailCallPosition(ImmutableCallSite CS,
  437. const TargetLowering &TLI) {
  438. const Instruction *I = CS.getInstruction();
  439. const BasicBlock *ExitBB = I->getParent();
  440. const TerminatorInst *Term = ExitBB->getTerminator();
  441. const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
  442. // The block must end in a return statement or unreachable.
  443. //
  444. // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
  445. // an unreachable, for now. The way tailcall optimization is currently
  446. // implemented means it will add an epilogue followed by a jump. That is
  447. // not profitable. Also, if the callee is a special function (e.g.
  448. // longjmp on x86), it can end up causing miscompilation that has not
  449. // been fully understood.
  450. if (!Ret &&
  451. (!TLI.getTargetMachine().Options.GuaranteedTailCallOpt ||
  452. !isa<UnreachableInst>(Term)))
  453. return false;
  454. // If I will have a chain, make sure no other instruction that will have a
  455. // chain interposes between I and the return.
  456. if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
  457. !isSafeToSpeculativelyExecute(I))
  458. for (BasicBlock::const_iterator BBI = std::prev(ExitBB->end(), 2);; --BBI) {
  459. if (&*BBI == I)
  460. break;
  461. // Debug info intrinsics do not get in the way of tail call optimization.
  462. if (isa<DbgInfoIntrinsic>(BBI))
  463. continue;
  464. if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
  465. !isSafeToSpeculativelyExecute(BBI))
  466. return false;
  467. }
  468. return returnTypeIsEligibleForTailCall(ExitBB->getParent(), I, Ret, TLI);
  469. }
  470. bool llvm::returnTypeIsEligibleForTailCall(const Function *F,
  471. const Instruction *I,
  472. const ReturnInst *Ret,
  473. const TargetLoweringBase &TLI) {
  474. // If the block ends with a void return or unreachable, it doesn't matter
  475. // what the call's return type is.
  476. if (!Ret || Ret->getNumOperands() == 0) return true;
  477. // If the return value is undef, it doesn't matter what the call's
  478. // return type is.
  479. if (isa<UndefValue>(Ret->getOperand(0))) return true;
  480. // Make sure the attributes attached to each return are compatible.
  481. AttrBuilder CallerAttrs(F->getAttributes(),
  482. AttributeSet::ReturnIndex);
  483. AttrBuilder CalleeAttrs(cast<CallInst>(I)->getAttributes(),
  484. AttributeSet::ReturnIndex);
  485. // Noalias is completely benign as far as calling convention goes, it
  486. // shouldn't affect whether the call is a tail call.
  487. CallerAttrs = CallerAttrs.removeAttribute(Attribute::NoAlias);
  488. CalleeAttrs = CalleeAttrs.removeAttribute(Attribute::NoAlias);
  489. bool AllowDifferingSizes = true;
  490. if (CallerAttrs.contains(Attribute::ZExt)) {
  491. if (!CalleeAttrs.contains(Attribute::ZExt))
  492. return false;
  493. AllowDifferingSizes = false;
  494. CallerAttrs.removeAttribute(Attribute::ZExt);
  495. CalleeAttrs.removeAttribute(Attribute::ZExt);
  496. } else if (CallerAttrs.contains(Attribute::SExt)) {
  497. if (!CalleeAttrs.contains(Attribute::SExt))
  498. return false;
  499. AllowDifferingSizes = false;
  500. CallerAttrs.removeAttribute(Attribute::SExt);
  501. CalleeAttrs.removeAttribute(Attribute::SExt);
  502. }
  503. // If they're still different, there's some facet we don't understand
  504. // (currently only "inreg", but in future who knows). It may be OK but the
  505. // only safe option is to reject the tail call.
  506. if (CallerAttrs != CalleeAttrs)
  507. return false;
  508. const Value *RetVal = Ret->getOperand(0), *CallVal = I;
  509. SmallVector<unsigned, 4> RetPath, CallPath;
  510. SmallVector<CompositeType *, 4> RetSubTypes, CallSubTypes;
  511. bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath);
  512. bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath);
  513. // Nothing's actually returned, it doesn't matter what the callee put there
  514. // it's a valid tail call.
  515. if (RetEmpty)
  516. return true;
  517. // Iterate pairwise through each of the value types making up the tail call
  518. // and the corresponding return. For each one we want to know whether it's
  519. // essentially going directly from the tail call to the ret, via operations
  520. // that end up not generating any code.
  521. //
  522. // We allow a certain amount of covariance here. For example it's permitted
  523. // for the tail call to define more bits than the ret actually cares about
  524. // (e.g. via a truncate).
  525. do {
  526. if (CallEmpty) {
  527. // We've exhausted the values produced by the tail call instruction, the
  528. // rest are essentially undef. The type doesn't really matter, but we need
  529. // *something*.
  530. Type *SlotType = RetSubTypes.back()->getTypeAtIndex(RetPath.back());
  531. CallVal = UndefValue::get(SlotType);
  532. }
  533. // The manipulations performed when we're looking through an insertvalue or
  534. // an extractvalue would happen at the front of the RetPath list, so since
  535. // we have to copy it anyway it's more efficient to create a reversed copy.
  536. using std::copy;
  537. SmallVector<unsigned, 4> TmpRetPath, TmpCallPath;
  538. copy(RetPath.rbegin(), RetPath.rend(), std::back_inserter(TmpRetPath));
  539. copy(CallPath.rbegin(), CallPath.rend(), std::back_inserter(TmpCallPath));
  540. // Finally, we can check whether the value produced by the tail call at this
  541. // index is compatible with the value we return.
  542. if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath,
  543. AllowDifferingSizes, TLI))
  544. return false;
  545. CallEmpty = !nextRealType(CallSubTypes, CallPath);
  546. } while(nextRealType(RetSubTypes, RetPath));
  547. return true;
  548. }