Analysis.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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 utilities.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/Analysis.h"
  14. #include "llvm/Analysis/ValueTracking.h"
  15. #include "llvm/CodeGen/MachineFunction.h"
  16. #include "llvm/CodeGen/SelectionDAG.h"
  17. #include "llvm/IR/DataLayout.h"
  18. #include "llvm/IR/DerivedTypes.h"
  19. #include "llvm/IR/Function.h"
  20. #include "llvm/IR/Instructions.h"
  21. #include "llvm/IR/IntrinsicInst.h"
  22. #include "llvm/IR/LLVMContext.h"
  23. #include "llvm/IR/Module.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include "llvm/Support/MathExtras.h"
  26. #include "llvm/Target/TargetLowering.h"
  27. #include "llvm/Target/TargetSubtargetInfo.h"
  28. #include "llvm/Transforms/Utils/GlobalStatus.h"
  29. using namespace llvm;
  30. /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
  31. /// of insertvalue or extractvalue indices that identify a member, return
  32. /// the linearized index of the start of the member.
  33. ///
  34. unsigned llvm::ComputeLinearIndex(Type *Ty,
  35. const unsigned *Indices,
  36. const unsigned *IndicesEnd,
  37. unsigned CurIndex) {
  38. // Base case: We're done.
  39. if (Indices && Indices == IndicesEnd)
  40. return CurIndex;
  41. // Given a struct type, recursively traverse the elements.
  42. if (StructType *STy = dyn_cast<StructType>(Ty)) {
  43. for (StructType::element_iterator EB = STy->element_begin(),
  44. EI = EB,
  45. EE = STy->element_end();
  46. EI != EE; ++EI) {
  47. if (Indices && *Indices == unsigned(EI - EB))
  48. return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex);
  49. CurIndex = ComputeLinearIndex(*EI, nullptr, nullptr, CurIndex);
  50. }
  51. return CurIndex;
  52. }
  53. // Given an array type, recursively traverse the elements.
  54. else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  55. Type *EltTy = ATy->getElementType();
  56. for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
  57. if (Indices && *Indices == i)
  58. return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex);
  59. CurIndex = ComputeLinearIndex(EltTy, nullptr, nullptr, CurIndex);
  60. }
  61. return CurIndex;
  62. }
  63. // We haven't found the type we're looking for, so keep searching.
  64. return CurIndex + 1;
  65. }
  66. /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
  67. /// EVTs that represent all the individual underlying
  68. /// non-aggregate types that comprise it.
  69. ///
  70. /// If Offsets is non-null, it points to a vector to be filled in
  71. /// with the in-memory offsets of each of the individual values.
  72. ///
  73. void llvm::ComputeValueVTs(const TargetLowering &TLI, Type *Ty,
  74. SmallVectorImpl<EVT> &ValueVTs,
  75. SmallVectorImpl<uint64_t> *Offsets,
  76. uint64_t StartingOffset) {
  77. // Given a struct type, recursively traverse the elements.
  78. if (StructType *STy = dyn_cast<StructType>(Ty)) {
  79. const StructLayout *SL = TLI.getDataLayout()->getStructLayout(STy);
  80. for (StructType::element_iterator EB = STy->element_begin(),
  81. EI = EB,
  82. EE = STy->element_end();
  83. EI != EE; ++EI)
  84. ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
  85. StartingOffset + SL->getElementOffset(EI - EB));
  86. return;
  87. }
  88. // Given an array type, recursively traverse the elements.
  89. if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  90. Type *EltTy = ATy->getElementType();
  91. uint64_t EltSize = TLI.getDataLayout()->getTypeAllocSize(EltTy);
  92. for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
  93. ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
  94. StartingOffset + i * EltSize);
  95. return;
  96. }
  97. // Interpret void as zero return values.
  98. if (Ty->isVoidTy())
  99. return;
  100. // Base case: we can get an EVT for this LLVM IR type.
  101. ValueVTs.push_back(TLI.getValueType(Ty));
  102. if (Offsets)
  103. Offsets->push_back(StartingOffset);
  104. }
  105. /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
  106. GlobalVariable *llvm::ExtractTypeInfo(Value *V) {
  107. V = V->stripPointerCasts();
  108. GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
  109. if (GV && GV->getName() == "llvm.eh.catch.all.value") {
  110. assert(GV->hasInitializer() &&
  111. "The EH catch-all value must have an initializer");
  112. Value *Init = GV->getInitializer();
  113. GV = dyn_cast<GlobalVariable>(Init);
  114. if (!GV) V = cast<ConstantPointerNull>(Init);
  115. }
  116. assert((GV || isa<ConstantPointerNull>(V)) &&
  117. "TypeInfo must be a global variable or NULL");
  118. return GV;
  119. }
  120. /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
  121. /// processed uses a memory 'm' constraint.
  122. bool
  123. llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos,
  124. const TargetLowering &TLI) {
  125. for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
  126. InlineAsm::ConstraintInfo &CI = CInfos[i];
  127. for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
  128. TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
  129. if (CType == TargetLowering::C_Memory)
  130. return true;
  131. }
  132. // Indirect operand accesses access memory.
  133. if (CI.isIndirect)
  134. return true;
  135. }
  136. return false;
  137. }
  138. /// getFCmpCondCode - Return the ISD condition code corresponding to
  139. /// the given LLVM IR floating-point condition code. This includes
  140. /// consideration of global floating-point math flags.
  141. ///
  142. ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
  143. switch (Pred) {
  144. case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
  145. case FCmpInst::FCMP_OEQ: return ISD::SETOEQ;
  146. case FCmpInst::FCMP_OGT: return ISD::SETOGT;
  147. case FCmpInst::FCMP_OGE: return ISD::SETOGE;
  148. case FCmpInst::FCMP_OLT: return ISD::SETOLT;
  149. case FCmpInst::FCMP_OLE: return ISD::SETOLE;
  150. case FCmpInst::FCMP_ONE: return ISD::SETONE;
  151. case FCmpInst::FCMP_ORD: return ISD::SETO;
  152. case FCmpInst::FCMP_UNO: return ISD::SETUO;
  153. case FCmpInst::FCMP_UEQ: return ISD::SETUEQ;
  154. case FCmpInst::FCMP_UGT: return ISD::SETUGT;
  155. case FCmpInst::FCMP_UGE: return ISD::SETUGE;
  156. case FCmpInst::FCMP_ULT: return ISD::SETULT;
  157. case FCmpInst::FCMP_ULE: return ISD::SETULE;
  158. case FCmpInst::FCMP_UNE: return ISD::SETUNE;
  159. case FCmpInst::FCMP_TRUE: return ISD::SETTRUE;
  160. default: llvm_unreachable("Invalid FCmp predicate opcode!");
  161. }
  162. }
  163. ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
  164. switch (CC) {
  165. case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
  166. case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
  167. case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
  168. case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
  169. case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
  170. case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
  171. default: return CC;
  172. }
  173. }
  174. /// getICmpCondCode - Return the ISD condition code corresponding to
  175. /// the given LLVM IR integer condition code.
  176. ///
  177. ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
  178. switch (Pred) {
  179. case ICmpInst::ICMP_EQ: return ISD::SETEQ;
  180. case ICmpInst::ICMP_NE: return ISD::SETNE;
  181. case ICmpInst::ICMP_SLE: return ISD::SETLE;
  182. case ICmpInst::ICMP_ULE: return ISD::SETULE;
  183. case ICmpInst::ICMP_SGE: return ISD::SETGE;
  184. case ICmpInst::ICMP_UGE: return ISD::SETUGE;
  185. case ICmpInst::ICMP_SLT: return ISD::SETLT;
  186. case ICmpInst::ICMP_ULT: return ISD::SETULT;
  187. case ICmpInst::ICMP_SGT: return ISD::SETGT;
  188. case ICmpInst::ICMP_UGT: return ISD::SETUGT;
  189. default:
  190. llvm_unreachable("Invalid ICmp predicate opcode!");
  191. }
  192. }
  193. static bool isNoopBitcast(Type *T1, Type *T2,
  194. const TargetLoweringBase& TLI) {
  195. return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) ||
  196. (isa<VectorType>(T1) && isa<VectorType>(T2) &&
  197. TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2)));
  198. }
  199. /// Look through operations that will be free to find the earliest source of
  200. /// this value.
  201. ///
  202. /// @param ValLoc If V has aggegate type, we will be interested in a particular
  203. /// scalar component. This records its address; the reverse of this list gives a
  204. /// sequence of indices appropriate for an extractvalue to locate the important
  205. /// value. This value is updated during the function and on exit will indicate
  206. /// similar information for the Value returned.
  207. ///
  208. /// @param DataBits If this function looks through truncate instructions, this
  209. /// will record the smallest size attained.
  210. static const Value *getNoopInput(const Value *V,
  211. SmallVectorImpl<unsigned> &ValLoc,
  212. unsigned &DataBits,
  213. const TargetLoweringBase &TLI) {
  214. while (true) {
  215. // Try to look through V1; if V1 is not an instruction, it can't be looked
  216. // through.
  217. const Instruction *I = dyn_cast<Instruction>(V);
  218. if (!I || I->getNumOperands() == 0) return V;
  219. const Value *NoopInput = nullptr;
  220. Value *Op = I->getOperand(0);
  221. if (isa<BitCastInst>(I)) {
  222. // Look through truly no-op bitcasts.
  223. if (isNoopBitcast(Op->getType(), I->getType(), TLI))
  224. NoopInput = Op;
  225. } else if (isa<GetElementPtrInst>(I)) {
  226. // Look through getelementptr
  227. if (cast<GetElementPtrInst>(I)->hasAllZeroIndices())
  228. NoopInput = Op;
  229. } else if (isa<IntToPtrInst>(I)) {
  230. // Look through inttoptr.
  231. // Make sure this isn't a truncating or extending cast. We could
  232. // support this eventually, but don't bother for now.
  233. if (!isa<VectorType>(I->getType()) &&
  234. TLI.getPointerTy().getSizeInBits() ==
  235. cast<IntegerType>(Op->getType())->getBitWidth())
  236. NoopInput = Op;
  237. } else if (isa<PtrToIntInst>(I)) {
  238. // Look through ptrtoint.
  239. // Make sure this isn't a truncating or extending cast. We could
  240. // support this eventually, but don't bother for now.
  241. if (!isa<VectorType>(I->getType()) &&
  242. TLI.getPointerTy().getSizeInBits() ==
  243. cast<IntegerType>(I->getType())->getBitWidth())
  244. NoopInput = Op;
  245. } else if (isa<TruncInst>(I) &&
  246. TLI.allowTruncateForTailCall(Op->getType(), I->getType())) {
  247. DataBits = std::min(DataBits, I->getType()->getPrimitiveSizeInBits());
  248. NoopInput = Op;
  249. } else if (isa<CallInst>(I)) {
  250. // Look through call (skipping callee)
  251. for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 1;
  252. i != e; ++i) {
  253. unsigned attrInd = i - I->op_begin() + 1;
  254. if (cast<CallInst>(I)->paramHasAttr(attrInd, Attribute::Returned) &&
  255. isNoopBitcast((*i)->getType(), I->getType(), TLI)) {
  256. NoopInput = *i;
  257. break;
  258. }
  259. }
  260. } else if (isa<InvokeInst>(I)) {
  261. // Look through invoke (skipping BB, BB, Callee)
  262. for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 3;
  263. i != e; ++i) {
  264. unsigned attrInd = i - I->op_begin() + 1;
  265. if (cast<InvokeInst>(I)->paramHasAttr(attrInd, Attribute::Returned) &&
  266. isNoopBitcast((*i)->getType(), I->getType(), TLI)) {
  267. NoopInput = *i;
  268. break;
  269. }
  270. }
  271. } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(V)) {
  272. // Value may come from either the aggregate or the scalar
  273. ArrayRef<unsigned> InsertLoc = IVI->getIndices();
  274. if (std::equal(InsertLoc.rbegin(), InsertLoc.rend(),
  275. ValLoc.rbegin())) {
  276. // The type being inserted is a nested sub-type of the aggregate; we
  277. // have to remove those initial indices to get the location we're
  278. // interested in for the operand.
  279. ValLoc.resize(ValLoc.size() - InsertLoc.size());
  280. NoopInput = IVI->getInsertedValueOperand();
  281. } else {
  282. // The struct we're inserting into has the value we're interested in, no
  283. // change of address.
  284. NoopInput = Op;
  285. }
  286. } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
  287. // The part we're interested in will inevitably be some sub-section of the
  288. // previous aggregate. Combine the two paths to obtain the true address of
  289. // our element.
  290. ArrayRef<unsigned> ExtractLoc = EVI->getIndices();
  291. std::copy(ExtractLoc.rbegin(), ExtractLoc.rend(),
  292. std::back_inserter(ValLoc));
  293. NoopInput = Op;
  294. }
  295. // Terminate if we couldn't find anything to look through.
  296. if (!NoopInput)
  297. return V;
  298. V = NoopInput;
  299. }
  300. }
  301. /// Return true if this scalar return value only has bits discarded on its path
  302. /// from the "tail call" to the "ret". This includes the obvious noop
  303. /// instructions handled by getNoopInput above as well as free truncations (or
  304. /// extensions prior to the call).
  305. static bool slotOnlyDiscardsData(const Value *RetVal, const Value *CallVal,
  306. SmallVectorImpl<unsigned> &RetIndices,
  307. SmallVectorImpl<unsigned> &CallIndices,
  308. bool AllowDifferingSizes,
  309. const TargetLoweringBase &TLI) {
  310. // Trace the sub-value needed by the return value as far back up the graph as
  311. // possible, in the hope that it will intersect with the value produced by the
  312. // call. In the simple case with no "returned" attribute, the hope is actually
  313. // that we end up back at the tail call instruction itself.
  314. unsigned BitsRequired = UINT_MAX;
  315. RetVal = getNoopInput(RetVal, RetIndices, BitsRequired, TLI);
  316. // If this slot in the value returned is undef, it doesn't matter what the
  317. // call puts there, it'll be fine.
  318. if (isa<UndefValue>(RetVal))
  319. return true;
  320. // Now do a similar search up through the graph to find where the value
  321. // actually returned by the "tail call" comes from. In the simple case without
  322. // a "returned" attribute, the search will be blocked immediately and the loop
  323. // a Noop.
  324. unsigned BitsProvided = UINT_MAX;
  325. CallVal = getNoopInput(CallVal, CallIndices, BitsProvided, TLI);
  326. // There's no hope if we can't actually trace them to (the same part of!) the
  327. // same value.
  328. if (CallVal != RetVal || CallIndices != RetIndices)
  329. return false;
  330. // However, intervening truncates may have made the call non-tail. Make sure
  331. // all the bits that are needed by the "ret" have been provided by the "tail
  332. // call". FIXME: with sufficiently cunning bit-tracking, we could look through
  333. // extensions too.
  334. if (BitsProvided < BitsRequired ||
  335. (!AllowDifferingSizes && BitsProvided != BitsRequired))
  336. return false;
  337. return true;
  338. }
  339. /// For an aggregate type, determine whether a given index is within bounds or
  340. /// not.
  341. static bool indexReallyValid(CompositeType *T, unsigned Idx) {
  342. if (ArrayType *AT = dyn_cast<ArrayType>(T))
  343. return Idx < AT->getNumElements();
  344. return Idx < cast<StructType>(T)->getNumElements();
  345. }
  346. /// Move the given iterators to the next leaf type in depth first traversal.
  347. ///
  348. /// Performs a depth-first traversal of the type as specified by its arguments,
  349. /// stopping at the next leaf node (which may be a legitimate scalar type or an
  350. /// empty struct or array).
  351. ///
  352. /// @param SubTypes List of the partial components making up the type from
  353. /// outermost to innermost non-empty aggregate. The element currently
  354. /// represented is SubTypes.back()->getTypeAtIndex(Path.back() - 1).
  355. ///
  356. /// @param Path Set of extractvalue indices leading from the outermost type
  357. /// (SubTypes[0]) to the leaf node currently represented.
  358. ///
  359. /// @returns true if a new type was found, false otherwise. Calling this
  360. /// function again on a finished iterator will repeatedly return
  361. /// false. SubTypes.back()->getTypeAtIndex(Path.back()) is either an empty
  362. /// aggregate or a non-aggregate
  363. static bool advanceToNextLeafType(SmallVectorImpl<CompositeType *> &SubTypes,
  364. SmallVectorImpl<unsigned> &Path) {
  365. // First march back up the tree until we can successfully increment one of the
  366. // coordinates in Path.
  367. while (!Path.empty() && !indexReallyValid(SubTypes.back(), Path.back() + 1)) {
  368. Path.pop_back();
  369. SubTypes.pop_back();
  370. }
  371. // If we reached the top, then the iterator is done.
  372. if (Path.empty())
  373. return false;
  374. // We know there's *some* valid leaf now, so march back down the tree picking
  375. // out the left-most element at each node.
  376. ++Path.back();
  377. Type *DeeperType = SubTypes.back()->getTypeAtIndex(Path.back());
  378. while (DeeperType->isAggregateType()) {
  379. CompositeType *CT = cast<CompositeType>(DeeperType);
  380. if (!indexReallyValid(CT, 0))
  381. return true;
  382. SubTypes.push_back(CT);
  383. Path.push_back(0);
  384. DeeperType = CT->getTypeAtIndex(0U);
  385. }
  386. return true;
  387. }
  388. /// Find the first non-empty, scalar-like type in Next and setup the iterator
  389. /// components.
  390. ///
  391. /// Assuming Next is an aggregate of some kind, this function will traverse the
  392. /// tree from left to right (i.e. depth-first) looking for the first
  393. /// non-aggregate type which will play a role in function return.
  394. ///
  395. /// For example, if Next was {[0 x i64], {{}, i32, {}}, i32} then we would setup
  396. /// Path as [1, 1] and SubTypes as [Next, {{}, i32, {}}] to represent the first
  397. /// i32 in that type.
  398. static bool firstRealType(Type *Next,
  399. SmallVectorImpl<CompositeType *> &SubTypes,
  400. SmallVectorImpl<unsigned> &Path) {
  401. // First initialise the iterator components to the first "leaf" node
  402. // (i.e. node with no valid sub-type at any index, so {} does count as a leaf
  403. // despite nominally being an aggregate).
  404. while (Next->isAggregateType() &&
  405. indexReallyValid(cast<CompositeType>(Next), 0)) {
  406. SubTypes.push_back(cast<CompositeType>(Next));
  407. Path.push_back(0);
  408. Next = cast<CompositeType>(Next)->getTypeAtIndex(0U);
  409. }
  410. // If there's no Path now, Next was originally scalar already (or empty
  411. // leaf). We're done.
  412. if (Path.empty())
  413. return true;
  414. // Otherwise, use normal iteration to keep looking through the tree until we
  415. // find a non-aggregate type.
  416. while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType()) {
  417. if (!advanceToNextLeafType(SubTypes, Path))
  418. return false;
  419. }
  420. return true;
  421. }
  422. /// Set the iterator data-structures to the next non-empty, non-aggregate
  423. /// subtype.
  424. static bool nextRealType(SmallVectorImpl<CompositeType *> &SubTypes,
  425. SmallVectorImpl<unsigned> &Path) {
  426. do {
  427. if (!advanceToNextLeafType(SubTypes, Path))
  428. return false;
  429. assert(!Path.empty() && "found a leaf but didn't set the path?");
  430. } while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType());
  431. return true;
  432. }
  433. /// Test if the given instruction is in a position to be optimized
  434. /// with a tail-call. This roughly means that it's in a block with
  435. /// a return and there's nothing that needs to be scheduled
  436. /// between it and the return.
  437. ///
  438. /// This function only tests target-independent requirements.
  439. bool llvm::isInTailCallPosition(ImmutableCallSite CS, const TargetMachine &TM) {
  440. const Instruction *I = CS.getInstruction();
  441. const BasicBlock *ExitBB = I->getParent();
  442. const TerminatorInst *Term = ExitBB->getTerminator();
  443. const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
  444. // The block must end in a return statement or unreachable.
  445. //
  446. // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
  447. // an unreachable, for now. The way tailcall optimization is currently
  448. // implemented means it will add an epilogue followed by a jump. That is
  449. // not profitable. Also, if the callee is a special function (e.g.
  450. // longjmp on x86), it can end up causing miscompilation that has not
  451. // been fully understood.
  452. if (!Ret &&
  453. (!TM.Options.GuaranteedTailCallOpt || !isa<UnreachableInst>(Term)))
  454. return false;
  455. // If I will have a chain, make sure no other instruction that will have a
  456. // chain interposes between I and the return.
  457. if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
  458. !isSafeToSpeculativelyExecute(I))
  459. for (BasicBlock::const_iterator BBI = std::prev(ExitBB->end(), 2);; --BBI) {
  460. if (&*BBI == I)
  461. break;
  462. // Debug info intrinsics do not get in the way of tail call optimization.
  463. if (isa<DbgInfoIntrinsic>(BBI))
  464. continue;
  465. if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
  466. !isSafeToSpeculativelyExecute(BBI))
  467. return false;
  468. }
  469. return returnTypeIsEligibleForTailCall(
  470. ExitBB->getParent(), I, Ret, *TM.getSubtargetImpl()->getTargetLowering());
  471. }
  472. bool llvm::returnTypeIsEligibleForTailCall(const Function *F,
  473. const Instruction *I,
  474. const ReturnInst *Ret,
  475. const TargetLoweringBase &TLI) {
  476. // If the block ends with a void return or unreachable, it doesn't matter
  477. // what the call's return type is.
  478. if (!Ret || Ret->getNumOperands() == 0) return true;
  479. // If the return value is undef, it doesn't matter what the call's
  480. // return type is.
  481. if (isa<UndefValue>(Ret->getOperand(0))) return true;
  482. // Make sure the attributes attached to each return are compatible.
  483. AttrBuilder CallerAttrs(F->getAttributes(),
  484. AttributeSet::ReturnIndex);
  485. AttrBuilder CalleeAttrs(cast<CallInst>(I)->getAttributes(),
  486. AttributeSet::ReturnIndex);
  487. // Noalias is completely benign as far as calling convention goes, it
  488. // shouldn't affect whether the call is a tail call.
  489. CallerAttrs = CallerAttrs.removeAttribute(Attribute::NoAlias);
  490. CalleeAttrs = CalleeAttrs.removeAttribute(Attribute::NoAlias);
  491. bool AllowDifferingSizes = true;
  492. if (CallerAttrs.contains(Attribute::ZExt)) {
  493. if (!CalleeAttrs.contains(Attribute::ZExt))
  494. return false;
  495. AllowDifferingSizes = false;
  496. CallerAttrs.removeAttribute(Attribute::ZExt);
  497. CalleeAttrs.removeAttribute(Attribute::ZExt);
  498. } else if (CallerAttrs.contains(Attribute::SExt)) {
  499. if (!CalleeAttrs.contains(Attribute::SExt))
  500. return false;
  501. AllowDifferingSizes = false;
  502. CallerAttrs.removeAttribute(Attribute::SExt);
  503. CalleeAttrs.removeAttribute(Attribute::SExt);
  504. }
  505. // If they're still different, there's some facet we don't understand
  506. // (currently only "inreg", but in future who knows). It may be OK but the
  507. // only safe option is to reject the tail call.
  508. if (CallerAttrs != CalleeAttrs)
  509. return false;
  510. const Value *RetVal = Ret->getOperand(0), *CallVal = I;
  511. SmallVector<unsigned, 4> RetPath, CallPath;
  512. SmallVector<CompositeType *, 4> RetSubTypes, CallSubTypes;
  513. bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath);
  514. bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath);
  515. // Nothing's actually returned, it doesn't matter what the callee put there
  516. // it's a valid tail call.
  517. if (RetEmpty)
  518. return true;
  519. // Iterate pairwise through each of the value types making up the tail call
  520. // and the corresponding return. For each one we want to know whether it's
  521. // essentially going directly from the tail call to the ret, via operations
  522. // that end up not generating any code.
  523. //
  524. // We allow a certain amount of covariance here. For example it's permitted
  525. // for the tail call to define more bits than the ret actually cares about
  526. // (e.g. via a truncate).
  527. do {
  528. if (CallEmpty) {
  529. // We've exhausted the values produced by the tail call instruction, the
  530. // rest are essentially undef. The type doesn't really matter, but we need
  531. // *something*.
  532. Type *SlotType = RetSubTypes.back()->getTypeAtIndex(RetPath.back());
  533. CallVal = UndefValue::get(SlotType);
  534. }
  535. // The manipulations performed when we're looking through an insertvalue or
  536. // an extractvalue would happen at the front of the RetPath list, so since
  537. // we have to copy it anyway it's more efficient to create a reversed copy.
  538. using std::copy;
  539. SmallVector<unsigned, 4> TmpRetPath, TmpCallPath;
  540. copy(RetPath.rbegin(), RetPath.rend(), std::back_inserter(TmpRetPath));
  541. copy(CallPath.rbegin(), CallPath.rend(), std::back_inserter(TmpCallPath));
  542. // Finally, we can check whether the value produced by the tail call at this
  543. // index is compatible with the value we return.
  544. if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath,
  545. AllowDifferingSizes, TLI))
  546. return false;
  547. CallEmpty = !nextRealType(CallSubTypes, CallPath);
  548. } while(nextRealType(RetSubTypes, RetPath));
  549. return true;
  550. }
  551. bool llvm::canBeOmittedFromSymbolTable(const GlobalValue *GV) {
  552. if (!GV->hasLinkOnceODRLinkage())
  553. return false;
  554. if (GV->hasUnnamedAddr())
  555. return true;
  556. // If it is a non constant variable, it needs to be uniqued across shared
  557. // objects.
  558. if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
  559. if (!Var->isConstant())
  560. return false;
  561. }
  562. // An alias can point to a variable. We could try to resolve the alias to
  563. // decide, but for now just don't hide them.
  564. if (isa<GlobalAlias>(GV))
  565. return false;
  566. GlobalStatus GS;
  567. if (GlobalStatus::analyzeGlobal(GV, GS))
  568. return false;
  569. return !GS.IsCompared;
  570. }