InlineCost.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  1. //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
  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 implements inline cost analysis.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Analysis/InlineCost.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SetVector.h"
  16. #include "llvm/ADT/SmallPtrSet.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/AssumptionCache.h"
  20. #include "llvm/Analysis/CodeMetrics.h"
  21. #include "llvm/Analysis/ConstantFolding.h"
  22. #include "llvm/Analysis/InstructionSimplify.h"
  23. #include "llvm/Analysis/TargetTransformInfo.h"
  24. #include "llvm/IR/CallSite.h"
  25. #include "llvm/IR/CallingConv.h"
  26. #include "llvm/IR/DataLayout.h"
  27. #include "llvm/IR/GetElementPtrTypeIterator.h"
  28. #include "llvm/IR/GlobalAlias.h"
  29. #include "llvm/IR/InstVisitor.h"
  30. #include "llvm/IR/IntrinsicInst.h"
  31. #include "llvm/IR/Operator.h"
  32. #include "llvm/Support/Debug.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. using namespace llvm;
  35. #define DEBUG_TYPE "inline-cost"
  36. STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
  37. namespace {
  38. class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
  39. typedef InstVisitor<CallAnalyzer, bool> Base;
  40. friend class InstVisitor<CallAnalyzer, bool>;
  41. /// The TargetTransformInfo available for this compilation.
  42. const TargetTransformInfo &TTI;
  43. /// The cache of @llvm.assume intrinsics.
  44. AssumptionCacheTracker *ACT;
  45. // The called function.
  46. Function &F;
  47. // The candidate callsite being analyzed. Please do not use this to do
  48. // analysis in the caller function; we want the inline cost query to be
  49. // easily cacheable. Instead, use the cover function paramHasAttr.
  50. CallSite CandidateCS;
  51. int Threshold;
  52. int Cost;
  53. bool IsCallerRecursive;
  54. bool IsRecursiveCall;
  55. bool ExposesReturnsTwice;
  56. bool HasDynamicAlloca;
  57. bool ContainsNoDuplicateCall;
  58. bool HasReturn;
  59. bool HasIndirectBr;
  60. bool HasFrameEscape;
  61. /// Number of bytes allocated statically by the callee.
  62. uint64_t AllocatedSize;
  63. unsigned NumInstructions, NumVectorInstructions;
  64. int FiftyPercentVectorBonus, TenPercentVectorBonus;
  65. int VectorBonus;
  66. // While we walk the potentially-inlined instructions, we build up and
  67. // maintain a mapping of simplified values specific to this callsite. The
  68. // idea is to propagate any special information we have about arguments to
  69. // this call through the inlinable section of the function, and account for
  70. // likely simplifications post-inlining. The most important aspect we track
  71. // is CFG altering simplifications -- when we prove a basic block dead, that
  72. // can cause dramatic shifts in the cost of inlining a function.
  73. DenseMap<Value *, Constant *> SimplifiedValues;
  74. // Keep track of the values which map back (through function arguments) to
  75. // allocas on the caller stack which could be simplified through SROA.
  76. DenseMap<Value *, Value *> SROAArgValues;
  77. // The mapping of caller Alloca values to their accumulated cost savings. If
  78. // we have to disable SROA for one of the allocas, this tells us how much
  79. // cost must be added.
  80. DenseMap<Value *, int> SROAArgCosts;
  81. // Keep track of values which map to a pointer base and constant offset.
  82. DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs;
  83. // Custom simplification helper routines.
  84. bool isAllocaDerivedArg(Value *V);
  85. bool lookupSROAArgAndCost(Value *V, Value *&Arg,
  86. DenseMap<Value *, int>::iterator &CostIt);
  87. void disableSROA(DenseMap<Value *, int>::iterator CostIt);
  88. void disableSROA(Value *V);
  89. void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
  90. int InstructionCost);
  91. bool isGEPOffsetConstant(GetElementPtrInst &GEP);
  92. bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
  93. bool simplifyCallSite(Function *F, CallSite CS);
  94. ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
  95. /// Return true if the given argument to the function being considered for
  96. /// inlining has the given attribute set either at the call site or the
  97. /// function declaration. Primarily used to inspect call site specific
  98. /// attributes since these can be more precise than the ones on the callee
  99. /// itself.
  100. bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
  101. /// Return true if the given value is known non null within the callee if
  102. /// inlined through this particular callsite.
  103. bool isKnownNonNullInCallee(Value *V);
  104. // Custom analysis routines.
  105. bool analyzeBlock(BasicBlock *BB, SmallPtrSetImpl<const Value *> &EphValues);
  106. // Disable several entry points to the visitor so we don't accidentally use
  107. // them by declaring but not defining them here.
  108. void visit(Module *); void visit(Module &);
  109. void visit(Function *); void visit(Function &);
  110. void visit(BasicBlock *); void visit(BasicBlock &);
  111. // Provide base case for our instruction visit.
  112. bool visitInstruction(Instruction &I);
  113. // Our visit overrides.
  114. bool visitAlloca(AllocaInst &I);
  115. bool visitPHI(PHINode &I);
  116. bool visitGetElementPtr(GetElementPtrInst &I);
  117. bool visitBitCast(BitCastInst &I);
  118. bool visitPtrToInt(PtrToIntInst &I);
  119. bool visitIntToPtr(IntToPtrInst &I);
  120. bool visitCastInst(CastInst &I);
  121. bool visitUnaryInstruction(UnaryInstruction &I);
  122. bool visitCmpInst(CmpInst &I);
  123. bool visitSub(BinaryOperator &I);
  124. bool visitBinaryOperator(BinaryOperator &I);
  125. bool visitLoad(LoadInst &I);
  126. bool visitStore(StoreInst &I);
  127. bool visitExtractValue(ExtractValueInst &I);
  128. bool visitInsertValue(InsertValueInst &I);
  129. bool visitCallSite(CallSite CS);
  130. bool visitReturnInst(ReturnInst &RI);
  131. bool visitBranchInst(BranchInst &BI);
  132. bool visitSwitchInst(SwitchInst &SI);
  133. bool visitIndirectBrInst(IndirectBrInst &IBI);
  134. bool visitResumeInst(ResumeInst &RI);
  135. bool visitUnreachableInst(UnreachableInst &I);
  136. public:
  137. CallAnalyzer(const TargetTransformInfo &TTI, AssumptionCacheTracker *ACT,
  138. Function &Callee, int Threshold, CallSite CSArg)
  139. : TTI(TTI), ACT(ACT), F(Callee), CandidateCS(CSArg), Threshold(Threshold),
  140. Cost(0), IsCallerRecursive(false), IsRecursiveCall(false),
  141. ExposesReturnsTwice(false), HasDynamicAlloca(false),
  142. ContainsNoDuplicateCall(false), HasReturn(false), HasIndirectBr(false),
  143. HasFrameEscape(false), AllocatedSize(0), NumInstructions(0),
  144. NumVectorInstructions(0), FiftyPercentVectorBonus(0),
  145. TenPercentVectorBonus(0), VectorBonus(0), NumConstantArgs(0),
  146. NumConstantOffsetPtrArgs(0), NumAllocaArgs(0), NumConstantPtrCmps(0),
  147. NumConstantPtrDiffs(0), NumInstructionsSimplified(0),
  148. SROACostSavings(0), SROACostSavingsLost(0) {}
  149. bool analyzeCall(CallSite CS);
  150. int getThreshold() { return Threshold; }
  151. int getCost() { return Cost; }
  152. // Keep a bunch of stats about the cost savings found so we can print them
  153. // out when debugging.
  154. unsigned NumConstantArgs;
  155. unsigned NumConstantOffsetPtrArgs;
  156. unsigned NumAllocaArgs;
  157. unsigned NumConstantPtrCmps;
  158. unsigned NumConstantPtrDiffs;
  159. unsigned NumInstructionsSimplified;
  160. unsigned SROACostSavings;
  161. unsigned SROACostSavingsLost;
  162. void dump();
  163. };
  164. } // namespace
  165. /// \brief Test whether the given value is an Alloca-derived function argument.
  166. bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
  167. return SROAArgValues.count(V);
  168. }
  169. /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
  170. /// Returns false if V does not map to a SROA-candidate.
  171. bool CallAnalyzer::lookupSROAArgAndCost(
  172. Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
  173. if (SROAArgValues.empty() || SROAArgCosts.empty())
  174. return false;
  175. DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
  176. if (ArgIt == SROAArgValues.end())
  177. return false;
  178. Arg = ArgIt->second;
  179. CostIt = SROAArgCosts.find(Arg);
  180. return CostIt != SROAArgCosts.end();
  181. }
  182. /// \brief Disable SROA for the candidate marked by this cost iterator.
  183. ///
  184. /// This marks the candidate as no longer viable for SROA, and adds the cost
  185. /// savings associated with it back into the inline cost measurement.
  186. void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
  187. // If we're no longer able to perform SROA we need to undo its cost savings
  188. // and prevent subsequent analysis.
  189. Cost += CostIt->second;
  190. SROACostSavings -= CostIt->second;
  191. SROACostSavingsLost += CostIt->second;
  192. SROAArgCosts.erase(CostIt);
  193. }
  194. /// \brief If 'V' maps to a SROA candidate, disable SROA for it.
  195. void CallAnalyzer::disableSROA(Value *V) {
  196. Value *SROAArg;
  197. DenseMap<Value *, int>::iterator CostIt;
  198. if (lookupSROAArgAndCost(V, SROAArg, CostIt))
  199. disableSROA(CostIt);
  200. }
  201. /// \brief Accumulate the given cost for a particular SROA candidate.
  202. void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
  203. int InstructionCost) {
  204. CostIt->second += InstructionCost;
  205. SROACostSavings += InstructionCost;
  206. }
  207. /// \brief Check whether a GEP's indices are all constant.
  208. ///
  209. /// Respects any simplified values known during the analysis of this callsite.
  210. bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
  211. for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
  212. if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
  213. return false;
  214. return true;
  215. }
  216. /// \brief Accumulate a constant GEP offset into an APInt if possible.
  217. ///
  218. /// Returns false if unable to compute the offset for any reason. Respects any
  219. /// simplified values known during the analysis of this callsite.
  220. bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
  221. const DataLayout &DL = F.getParent()->getDataLayout();
  222. unsigned IntPtrWidth = DL.getPointerSizeInBits();
  223. assert(IntPtrWidth == Offset.getBitWidth());
  224. for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
  225. GTI != GTE; ++GTI) {
  226. ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
  227. if (!OpC)
  228. if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
  229. OpC = dyn_cast<ConstantInt>(SimpleOp);
  230. if (!OpC)
  231. return false;
  232. if (OpC->isZero()) continue;
  233. // Handle a struct index, which adds its field offset to the pointer.
  234. if (StructType *STy = dyn_cast<StructType>(*GTI)) {
  235. unsigned ElementIdx = OpC->getZExtValue();
  236. const StructLayout *SL = DL.getStructLayout(STy);
  237. Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
  238. continue;
  239. }
  240. APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
  241. Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
  242. }
  243. return true;
  244. }
  245. bool CallAnalyzer::visitAlloca(AllocaInst &I) {
  246. // Check whether inlining will turn a dynamic alloca into a static
  247. // alloca, and handle that case.
  248. if (I.isArrayAllocation()) {
  249. if (Constant *Size = SimplifiedValues.lookup(I.getArraySize())) {
  250. ConstantInt *AllocSize = dyn_cast<ConstantInt>(Size);
  251. assert(AllocSize && "Allocation size not a constant int?");
  252. Type *Ty = I.getAllocatedType();
  253. AllocatedSize += Ty->getPrimitiveSizeInBits() * AllocSize->getZExtValue();
  254. return Base::visitAlloca(I);
  255. }
  256. }
  257. // Accumulate the allocated size.
  258. if (I.isStaticAlloca()) {
  259. const DataLayout &DL = F.getParent()->getDataLayout();
  260. Type *Ty = I.getAllocatedType();
  261. AllocatedSize += DL.getTypeAllocSize(Ty);
  262. }
  263. // We will happily inline static alloca instructions.
  264. if (I.isStaticAlloca())
  265. return Base::visitAlloca(I);
  266. // FIXME: This is overly conservative. Dynamic allocas are inefficient for
  267. // a variety of reasons, and so we would like to not inline them into
  268. // functions which don't currently have a dynamic alloca. This simply
  269. // disables inlining altogether in the presence of a dynamic alloca.
  270. HasDynamicAlloca = true;
  271. return false;
  272. }
  273. bool CallAnalyzer::visitPHI(PHINode &I) {
  274. // FIXME: We should potentially be tracking values through phi nodes,
  275. // especially when they collapse to a single value due to deleted CFG edges
  276. // during inlining.
  277. // FIXME: We need to propagate SROA *disabling* through phi nodes, even
  278. // though we don't want to propagate it's bonuses. The idea is to disable
  279. // SROA if it *might* be used in an inappropriate manner.
  280. // Phi nodes are always zero-cost.
  281. return true;
  282. }
  283. bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
  284. Value *SROAArg;
  285. DenseMap<Value *, int>::iterator CostIt;
  286. bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
  287. SROAArg, CostIt);
  288. // Try to fold GEPs of constant-offset call site argument pointers. This
  289. // requires target data and inbounds GEPs.
  290. if (I.isInBounds()) {
  291. // Check if we have a base + offset for the pointer.
  292. Value *Ptr = I.getPointerOperand();
  293. std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
  294. if (BaseAndOffset.first) {
  295. // Check if the offset of this GEP is constant, and if so accumulate it
  296. // into Offset.
  297. if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
  298. // Non-constant GEPs aren't folded, and disable SROA.
  299. if (SROACandidate)
  300. disableSROA(CostIt);
  301. return false;
  302. }
  303. // Add the result as a new mapping to Base + Offset.
  304. ConstantOffsetPtrs[&I] = BaseAndOffset;
  305. // Also handle SROA candidates here, we already know that the GEP is
  306. // all-constant indexed.
  307. if (SROACandidate)
  308. SROAArgValues[&I] = SROAArg;
  309. return true;
  310. }
  311. }
  312. if (isGEPOffsetConstant(I)) {
  313. if (SROACandidate)
  314. SROAArgValues[&I] = SROAArg;
  315. // Constant GEPs are modeled as free.
  316. return true;
  317. }
  318. // Variable GEPs will require math and will disable SROA.
  319. if (SROACandidate)
  320. disableSROA(CostIt);
  321. return false;
  322. }
  323. bool CallAnalyzer::visitBitCast(BitCastInst &I) {
  324. // Propagate constants through bitcasts.
  325. Constant *COp = dyn_cast<Constant>(I.getOperand(0));
  326. if (!COp)
  327. COp = SimplifiedValues.lookup(I.getOperand(0));
  328. if (COp)
  329. if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
  330. SimplifiedValues[&I] = C;
  331. return true;
  332. }
  333. // Track base/offsets through casts
  334. std::pair<Value *, APInt> BaseAndOffset
  335. = ConstantOffsetPtrs.lookup(I.getOperand(0));
  336. // Casts don't change the offset, just wrap it up.
  337. if (BaseAndOffset.first)
  338. ConstantOffsetPtrs[&I] = BaseAndOffset;
  339. // Also look for SROA candidates here.
  340. Value *SROAArg;
  341. DenseMap<Value *, int>::iterator CostIt;
  342. if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
  343. SROAArgValues[&I] = SROAArg;
  344. // Bitcasts are always zero cost.
  345. return true;
  346. }
  347. bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
  348. // Propagate constants through ptrtoint.
  349. Constant *COp = dyn_cast<Constant>(I.getOperand(0));
  350. if (!COp)
  351. COp = SimplifiedValues.lookup(I.getOperand(0));
  352. if (COp)
  353. if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
  354. SimplifiedValues[&I] = C;
  355. return true;
  356. }
  357. // Track base/offset pairs when converted to a plain integer provided the
  358. // integer is large enough to represent the pointer.
  359. unsigned IntegerSize = I.getType()->getScalarSizeInBits();
  360. const DataLayout &DL = F.getParent()->getDataLayout();
  361. if (IntegerSize >= DL.getPointerSizeInBits()) {
  362. std::pair<Value *, APInt> BaseAndOffset
  363. = ConstantOffsetPtrs.lookup(I.getOperand(0));
  364. if (BaseAndOffset.first)
  365. ConstantOffsetPtrs[&I] = BaseAndOffset;
  366. }
  367. // This is really weird. Technically, ptrtoint will disable SROA. However,
  368. // unless that ptrtoint is *used* somewhere in the live basic blocks after
  369. // inlining, it will be nuked, and SROA should proceed. All of the uses which
  370. // would block SROA would also block SROA if applied directly to a pointer,
  371. // and so we can just add the integer in here. The only places where SROA is
  372. // preserved either cannot fire on an integer, or won't in-and-of themselves
  373. // disable SROA (ext) w/o some later use that we would see and disable.
  374. Value *SROAArg;
  375. DenseMap<Value *, int>::iterator CostIt;
  376. if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
  377. SROAArgValues[&I] = SROAArg;
  378. return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
  379. }
  380. bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
  381. // Propagate constants through ptrtoint.
  382. Constant *COp = dyn_cast<Constant>(I.getOperand(0));
  383. if (!COp)
  384. COp = SimplifiedValues.lookup(I.getOperand(0));
  385. if (COp)
  386. if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
  387. SimplifiedValues[&I] = C;
  388. return true;
  389. }
  390. // Track base/offset pairs when round-tripped through a pointer without
  391. // modifications provided the integer is not too large.
  392. Value *Op = I.getOperand(0);
  393. unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
  394. const DataLayout &DL = F.getParent()->getDataLayout();
  395. if (IntegerSize <= DL.getPointerSizeInBits()) {
  396. std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
  397. if (BaseAndOffset.first)
  398. ConstantOffsetPtrs[&I] = BaseAndOffset;
  399. }
  400. // "Propagate" SROA here in the same manner as we do for ptrtoint above.
  401. Value *SROAArg;
  402. DenseMap<Value *, int>::iterator CostIt;
  403. if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
  404. SROAArgValues[&I] = SROAArg;
  405. return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
  406. }
  407. bool CallAnalyzer::visitCastInst(CastInst &I) {
  408. // Propagate constants through ptrtoint.
  409. Constant *COp = dyn_cast<Constant>(I.getOperand(0));
  410. if (!COp)
  411. COp = SimplifiedValues.lookup(I.getOperand(0));
  412. if (COp)
  413. if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
  414. SimplifiedValues[&I] = C;
  415. return true;
  416. }
  417. // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
  418. disableSROA(I.getOperand(0));
  419. return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
  420. }
  421. bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
  422. Value *Operand = I.getOperand(0);
  423. Constant *COp = dyn_cast<Constant>(Operand);
  424. if (!COp)
  425. COp = SimplifiedValues.lookup(Operand);
  426. if (COp) {
  427. const DataLayout &DL = F.getParent()->getDataLayout();
  428. if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(),
  429. COp, DL)) {
  430. SimplifiedValues[&I] = C;
  431. return true;
  432. }
  433. }
  434. // Disable any SROA on the argument to arbitrary unary operators.
  435. disableSROA(Operand);
  436. return false;
  437. }
  438. bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
  439. unsigned ArgNo = A->getArgNo();
  440. return CandidateCS.paramHasAttr(ArgNo+1, Attr);
  441. }
  442. bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
  443. // Does the *call site* have the NonNull attribute set on an argument? We
  444. // use the attribute on the call site to memoize any analysis done in the
  445. // caller. This will also trip if the callee function has a non-null
  446. // parameter attribute, but that's a less interesting case because hopefully
  447. // the callee would already have been simplified based on that.
  448. if (Argument *A = dyn_cast<Argument>(V))
  449. if (paramHasAttr(A, Attribute::NonNull))
  450. return true;
  451. // Is this an alloca in the caller? This is distinct from the attribute case
  452. // above because attributes aren't updated within the inliner itself and we
  453. // always want to catch the alloca derived case.
  454. if (isAllocaDerivedArg(V))
  455. // We can actually predict the result of comparisons between an
  456. // alloca-derived value and null. Note that this fires regardless of
  457. // SROA firing.
  458. return true;
  459. return false;
  460. }
  461. bool CallAnalyzer::visitCmpInst(CmpInst &I) {
  462. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  463. // First try to handle simplified comparisons.
  464. if (!isa<Constant>(LHS))
  465. if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
  466. LHS = SimpleLHS;
  467. if (!isa<Constant>(RHS))
  468. if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
  469. RHS = SimpleRHS;
  470. if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
  471. if (Constant *CRHS = dyn_cast<Constant>(RHS))
  472. if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
  473. SimplifiedValues[&I] = C;
  474. return true;
  475. }
  476. }
  477. if (I.getOpcode() == Instruction::FCmp)
  478. return false;
  479. // Otherwise look for a comparison between constant offset pointers with
  480. // a common base.
  481. Value *LHSBase, *RHSBase;
  482. APInt LHSOffset, RHSOffset;
  483. std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
  484. if (LHSBase) {
  485. std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
  486. if (RHSBase && LHSBase == RHSBase) {
  487. // We have common bases, fold the icmp to a constant based on the
  488. // offsets.
  489. Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
  490. Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
  491. if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
  492. SimplifiedValues[&I] = C;
  493. ++NumConstantPtrCmps;
  494. return true;
  495. }
  496. }
  497. }
  498. // If the comparison is an equality comparison with null, we can simplify it
  499. // if we know the value (argument) can't be null
  500. if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) &&
  501. isKnownNonNullInCallee(I.getOperand(0))) {
  502. bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
  503. SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
  504. : ConstantInt::getFalse(I.getType());
  505. return true;
  506. }
  507. // Finally check for SROA candidates in comparisons.
  508. Value *SROAArg;
  509. DenseMap<Value *, int>::iterator CostIt;
  510. if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
  511. if (isa<ConstantPointerNull>(I.getOperand(1))) {
  512. accumulateSROACost(CostIt, InlineConstants::InstrCost);
  513. return true;
  514. }
  515. disableSROA(CostIt);
  516. }
  517. return false;
  518. }
  519. bool CallAnalyzer::visitSub(BinaryOperator &I) {
  520. // Try to handle a special case: we can fold computing the difference of two
  521. // constant-related pointers.
  522. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  523. Value *LHSBase, *RHSBase;
  524. APInt LHSOffset, RHSOffset;
  525. std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
  526. if (LHSBase) {
  527. std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
  528. if (RHSBase && LHSBase == RHSBase) {
  529. // We have common bases, fold the subtract to a constant based on the
  530. // offsets.
  531. Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
  532. Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
  533. if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
  534. SimplifiedValues[&I] = C;
  535. ++NumConstantPtrDiffs;
  536. return true;
  537. }
  538. }
  539. }
  540. // Otherwise, fall back to the generic logic for simplifying and handling
  541. // instructions.
  542. return Base::visitSub(I);
  543. }
  544. bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
  545. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  546. const DataLayout &DL = F.getParent()->getDataLayout();
  547. if (!isa<Constant>(LHS))
  548. if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
  549. LHS = SimpleLHS;
  550. if (!isa<Constant>(RHS))
  551. if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
  552. RHS = SimpleRHS;
  553. Value *SimpleV = nullptr;
  554. if (auto FI = dyn_cast<FPMathOperator>(&I))
  555. SimpleV =
  556. SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
  557. else
  558. SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
  559. if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
  560. SimplifiedValues[&I] = C;
  561. return true;
  562. }
  563. // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
  564. disableSROA(LHS);
  565. disableSROA(RHS);
  566. return false;
  567. }
  568. bool CallAnalyzer::visitLoad(LoadInst &I) {
  569. Value *SROAArg;
  570. DenseMap<Value *, int>::iterator CostIt;
  571. if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
  572. if (I.isSimple()) {
  573. accumulateSROACost(CostIt, InlineConstants::InstrCost);
  574. return true;
  575. }
  576. disableSROA(CostIt);
  577. }
  578. return false;
  579. }
  580. bool CallAnalyzer::visitStore(StoreInst &I) {
  581. Value *SROAArg;
  582. DenseMap<Value *, int>::iterator CostIt;
  583. if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
  584. if (I.isSimple()) {
  585. accumulateSROACost(CostIt, InlineConstants::InstrCost);
  586. return true;
  587. }
  588. disableSROA(CostIt);
  589. }
  590. return false;
  591. }
  592. bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
  593. // Constant folding for extract value is trivial.
  594. Constant *C = dyn_cast<Constant>(I.getAggregateOperand());
  595. if (!C)
  596. C = SimplifiedValues.lookup(I.getAggregateOperand());
  597. if (C) {
  598. SimplifiedValues[&I] = ConstantExpr::getExtractValue(C, I.getIndices());
  599. return true;
  600. }
  601. // SROA can look through these but give them a cost.
  602. return false;
  603. }
  604. bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
  605. // Constant folding for insert value is trivial.
  606. Constant *AggC = dyn_cast<Constant>(I.getAggregateOperand());
  607. if (!AggC)
  608. AggC = SimplifiedValues.lookup(I.getAggregateOperand());
  609. Constant *InsertedC = dyn_cast<Constant>(I.getInsertedValueOperand());
  610. if (!InsertedC)
  611. InsertedC = SimplifiedValues.lookup(I.getInsertedValueOperand());
  612. if (AggC && InsertedC) {
  613. SimplifiedValues[&I] = ConstantExpr::getInsertValue(AggC, InsertedC,
  614. I.getIndices());
  615. return true;
  616. }
  617. // SROA can look through these but give them a cost.
  618. return false;
  619. }
  620. /// \brief Try to simplify a call site.
  621. ///
  622. /// Takes a concrete function and callsite and tries to actually simplify it by
  623. /// analyzing the arguments and call itself with instsimplify. Returns true if
  624. /// it has simplified the callsite to some other entity (a constant), making it
  625. /// free.
  626. bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) {
  627. // FIXME: Using the instsimplify logic directly for this is inefficient
  628. // because we have to continually rebuild the argument list even when no
  629. // simplifications can be performed. Until that is fixed with remapping
  630. // inside of instsimplify, directly constant fold calls here.
  631. if (!canConstantFoldCallTo(F))
  632. return false;
  633. // Try to re-map the arguments to constants.
  634. SmallVector<Constant *, 4> ConstantArgs;
  635. ConstantArgs.reserve(CS.arg_size());
  636. for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
  637. I != E; ++I) {
  638. Constant *C = dyn_cast<Constant>(*I);
  639. if (!C)
  640. C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I));
  641. if (!C)
  642. return false; // This argument doesn't map to a constant.
  643. ConstantArgs.push_back(C);
  644. }
  645. if (Constant *C = ConstantFoldCall(F, ConstantArgs)) {
  646. SimplifiedValues[CS.getInstruction()] = C;
  647. return true;
  648. }
  649. return false;
  650. }
  651. bool CallAnalyzer::visitCallSite(CallSite CS) {
  652. if (CS.hasFnAttr(Attribute::ReturnsTwice) &&
  653. !F.hasFnAttribute(Attribute::ReturnsTwice)) {
  654. // This aborts the entire analysis.
  655. ExposesReturnsTwice = true;
  656. return false;
  657. }
  658. if (CS.isCall() &&
  659. cast<CallInst>(CS.getInstruction())->cannotDuplicate())
  660. ContainsNoDuplicateCall = true;
  661. if (Function *F = CS.getCalledFunction()) {
  662. // When we have a concrete function, first try to simplify it directly.
  663. if (simplifyCallSite(F, CS))
  664. return true;
  665. // Next check if it is an intrinsic we know about.
  666. // FIXME: Lift this into part of the InstVisitor.
  667. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
  668. switch (II->getIntrinsicID()) {
  669. default:
  670. return Base::visitCallSite(CS);
  671. case Intrinsic::memset:
  672. case Intrinsic::memcpy:
  673. case Intrinsic::memmove:
  674. // SROA can usually chew through these intrinsics, but they aren't free.
  675. return false;
  676. case Intrinsic::localescape:
  677. HasFrameEscape = true;
  678. return false;
  679. }
  680. }
  681. if (F == CS.getInstruction()->getParent()->getParent()) {
  682. // This flag will fully abort the analysis, so don't bother with anything
  683. // else.
  684. IsRecursiveCall = true;
  685. return false;
  686. }
  687. if (TTI.isLoweredToCall(F)) {
  688. // We account for the average 1 instruction per call argument setup
  689. // here.
  690. Cost += CS.arg_size() * InlineConstants::InstrCost;
  691. // Everything other than inline ASM will also have a significant cost
  692. // merely from making the call.
  693. if (!isa<InlineAsm>(CS.getCalledValue()))
  694. Cost += InlineConstants::CallPenalty;
  695. }
  696. return Base::visitCallSite(CS);
  697. }
  698. // Otherwise we're in a very special case -- an indirect function call. See
  699. // if we can be particularly clever about this.
  700. Value *Callee = CS.getCalledValue();
  701. // First, pay the price of the argument setup. We account for the average
  702. // 1 instruction per call argument setup here.
  703. Cost += CS.arg_size() * InlineConstants::InstrCost;
  704. // Next, check if this happens to be an indirect function call to a known
  705. // function in this inline context. If not, we've done all we can.
  706. Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
  707. if (!F)
  708. return Base::visitCallSite(CS);
  709. // If we have a constant that we are calling as a function, we can peer
  710. // through it and see the function target. This happens not infrequently
  711. // during devirtualization and so we want to give it a hefty bonus for
  712. // inlining, but cap that bonus in the event that inlining wouldn't pan
  713. // out. Pretend to inline the function, with a custom threshold.
  714. CallAnalyzer CA(TTI, ACT, *F, InlineConstants::IndirectCallThreshold, CS);
  715. if (CA.analyzeCall(CS)) {
  716. // We were able to inline the indirect call! Subtract the cost from the
  717. // bonus we want to apply, but don't go below zero.
  718. Cost -= std::max(0, InlineConstants::IndirectCallThreshold - CA.getCost());
  719. }
  720. return Base::visitCallSite(CS);
  721. }
  722. bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
  723. // At least one return instruction will be free after inlining.
  724. bool Free = !HasReturn;
  725. HasReturn = true;
  726. return Free;
  727. }
  728. bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
  729. // We model unconditional branches as essentially free -- they really
  730. // shouldn't exist at all, but handling them makes the behavior of the
  731. // inliner more regular and predictable. Interestingly, conditional branches
  732. // which will fold away are also free.
  733. return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
  734. dyn_cast_or_null<ConstantInt>(
  735. SimplifiedValues.lookup(BI.getCondition()));
  736. }
  737. bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
  738. // We model unconditional switches as free, see the comments on handling
  739. // branches.
  740. if (isa<ConstantInt>(SI.getCondition()))
  741. return true;
  742. if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
  743. if (isa<ConstantInt>(V))
  744. return true;
  745. // Otherwise, we need to accumulate a cost proportional to the number of
  746. // distinct successor blocks. This fan-out in the CFG cannot be represented
  747. // for free even if we can represent the core switch as a jumptable that
  748. // takes a single instruction.
  749. //
  750. // NB: We convert large switches which are just used to initialize large phi
  751. // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent
  752. // inlining those. It will prevent inlining in cases where the optimization
  753. // does not (yet) fire.
  754. SmallPtrSet<BasicBlock *, 8> SuccessorBlocks;
  755. SuccessorBlocks.insert(SI.getDefaultDest());
  756. for (auto I = SI.case_begin(), E = SI.case_end(); I != E; ++I)
  757. SuccessorBlocks.insert(I.getCaseSuccessor());
  758. // Add cost corresponding to the number of distinct destinations. The first
  759. // we model as free because of fallthrough.
  760. Cost += (SuccessorBlocks.size() - 1) * InlineConstants::InstrCost;
  761. return false;
  762. }
  763. bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
  764. // We never want to inline functions that contain an indirectbr. This is
  765. // incorrect because all the blockaddress's (in static global initializers
  766. // for example) would be referring to the original function, and this
  767. // indirect jump would jump from the inlined copy of the function into the
  768. // original function which is extremely undefined behavior.
  769. // FIXME: This logic isn't really right; we can safely inline functions with
  770. // indirectbr's as long as no other function or global references the
  771. // blockaddress of a block within the current function.
  772. HasIndirectBr = true;
  773. return false;
  774. }
  775. bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
  776. // FIXME: It's not clear that a single instruction is an accurate model for
  777. // the inline cost of a resume instruction.
  778. return false;
  779. }
  780. bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
  781. // FIXME: It might be reasonably to discount the cost of instructions leading
  782. // to unreachable as they have the lowest possible impact on both runtime and
  783. // code size.
  784. return true; // No actual code is needed for unreachable.
  785. }
  786. bool CallAnalyzer::visitInstruction(Instruction &I) {
  787. // Some instructions are free. All of the free intrinsics can also be
  788. // handled by SROA, etc.
  789. if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I))
  790. return true;
  791. // We found something we don't understand or can't handle. Mark any SROA-able
  792. // values in the operand list as no longer viable.
  793. for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
  794. disableSROA(*OI);
  795. return false;
  796. }
  797. /// \brief Analyze a basic block for its contribution to the inline cost.
  798. ///
  799. /// This method walks the analyzer over every instruction in the given basic
  800. /// block and accounts for their cost during inlining at this callsite. It
  801. /// aborts early if the threshold has been exceeded or an impossible to inline
  802. /// construct has been detected. It returns false if inlining is no longer
  803. /// viable, and true if inlining remains viable.
  804. bool CallAnalyzer::analyzeBlock(BasicBlock *BB,
  805. SmallPtrSetImpl<const Value *> &EphValues) {
  806. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  807. // FIXME: Currently, the number of instructions in a function regardless of
  808. // our ability to simplify them during inline to constants or dead code,
  809. // are actually used by the vector bonus heuristic. As long as that's true,
  810. // we have to special case debug intrinsics here to prevent differences in
  811. // inlining due to debug symbols. Eventually, the number of unsimplified
  812. // instructions shouldn't factor into the cost computation, but until then,
  813. // hack around it here.
  814. if (isa<DbgInfoIntrinsic>(I))
  815. continue;
  816. // Skip ephemeral values.
  817. if (EphValues.count(I))
  818. continue;
  819. ++NumInstructions;
  820. if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
  821. ++NumVectorInstructions;
  822. // If the instruction is floating point, and the target says this operation is
  823. // expensive or the function has the "use-soft-float" attribute, this may
  824. // eventually become a library call. Treat the cost as such.
  825. if (I->getType()->isFloatingPointTy()) {
  826. bool hasSoftFloatAttr = false;
  827. // If the function has the "use-soft-float" attribute, mark it as expensive.
  828. if (F.hasFnAttribute("use-soft-float")) {
  829. Attribute Attr = F.getFnAttribute("use-soft-float");
  830. StringRef Val = Attr.getValueAsString();
  831. if (Val == "true")
  832. hasSoftFloatAttr = true;
  833. }
  834. if (TTI.getFPOpCost(I->getType()) == TargetTransformInfo::TCC_Expensive ||
  835. hasSoftFloatAttr)
  836. Cost += InlineConstants::CallPenalty;
  837. }
  838. // If the instruction simplified to a constant, there is no cost to this
  839. // instruction. Visit the instructions using our InstVisitor to account for
  840. // all of the per-instruction logic. The visit tree returns true if we
  841. // consumed the instruction in any way, and false if the instruction's base
  842. // cost should count against inlining.
  843. if (Base::visit(I))
  844. ++NumInstructionsSimplified;
  845. else
  846. Cost += InlineConstants::InstrCost;
  847. // If the visit this instruction detected an uninlinable pattern, abort.
  848. if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
  849. HasIndirectBr || HasFrameEscape)
  850. return false;
  851. // If the caller is a recursive function then we don't want to inline
  852. // functions which allocate a lot of stack space because it would increase
  853. // the caller stack usage dramatically.
  854. if (IsCallerRecursive &&
  855. AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
  856. return false;
  857. // Check if we've past the maximum possible threshold so we don't spin in
  858. // huge basic blocks that will never inline.
  859. if (Cost > Threshold)
  860. return false;
  861. }
  862. return true;
  863. }
  864. /// \brief Compute the base pointer and cumulative constant offsets for V.
  865. ///
  866. /// This strips all constant offsets off of V, leaving it the base pointer, and
  867. /// accumulates the total constant offset applied in the returned constant. It
  868. /// returns 0 if V is not a pointer, and returns the constant '0' if there are
  869. /// no constant offsets applied.
  870. ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
  871. if (!V->getType()->isPointerTy())
  872. return nullptr;
  873. const DataLayout &DL = F.getParent()->getDataLayout();
  874. unsigned IntPtrWidth = DL.getPointerSizeInBits();
  875. APInt Offset = APInt::getNullValue(IntPtrWidth);
  876. // Even though we don't look through PHI nodes, we could be called on an
  877. // instruction in an unreachable block, which may be on a cycle.
  878. SmallPtrSet<Value *, 4> Visited;
  879. Visited.insert(V);
  880. do {
  881. if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
  882. if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
  883. return nullptr;
  884. V = GEP->getPointerOperand();
  885. } else if (Operator::getOpcode(V) == Instruction::BitCast) {
  886. V = cast<Operator>(V)->getOperand(0);
  887. } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
  888. if (GA->mayBeOverridden())
  889. break;
  890. V = GA->getAliasee();
  891. } else {
  892. break;
  893. }
  894. assert(V->getType()->isPointerTy() && "Unexpected operand type!");
  895. } while (Visited.insert(V).second);
  896. Type *IntPtrTy = DL.getIntPtrType(V->getContext());
  897. return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
  898. }
  899. /// \brief Analyze a call site for potential inlining.
  900. ///
  901. /// Returns true if inlining this call is viable, and false if it is not
  902. /// viable. It computes the cost and adjusts the threshold based on numerous
  903. /// factors and heuristics. If this method returns false but the computed cost
  904. /// is below the computed threshold, then inlining was forcibly disabled by
  905. /// some artifact of the routine.
  906. bool CallAnalyzer::analyzeCall(CallSite CS) {
  907. ++NumCallsAnalyzed;
  908. // Perform some tweaks to the cost and threshold based on the direct
  909. // callsite information.
  910. // We want to more aggressively inline vector-dense kernels, so up the
  911. // threshold, and we'll lower it if the % of vector instructions gets too
  912. // low. Note that these bonuses are some what arbitrary and evolved over time
  913. // by accident as much as because they are principled bonuses.
  914. //
  915. // FIXME: It would be nice to remove all such bonuses. At least it would be
  916. // nice to base the bonus values on something more scientific.
  917. assert(NumInstructions == 0);
  918. assert(NumVectorInstructions == 0);
  919. FiftyPercentVectorBonus = 3 * Threshold / 2;
  920. TenPercentVectorBonus = 3 * Threshold / 4;
  921. const DataLayout &DL = F.getParent()->getDataLayout();
  922. // Track whether the post-inlining function would have more than one basic
  923. // block. A single basic block is often intended for inlining. Balloon the
  924. // threshold by 50% until we pass the single-BB phase.
  925. bool SingleBB = true;
  926. int SingleBBBonus = Threshold / 2;
  927. // Speculatively apply all possible bonuses to Threshold. If cost exceeds
  928. // this Threshold any time, and cost cannot decrease, we can stop processing
  929. // the rest of the function body.
  930. Threshold += (SingleBBBonus + FiftyPercentVectorBonus);
  931. // Give out bonuses per argument, as the instructions setting them up will
  932. // be gone after inlining.
  933. for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
  934. if (CS.isByValArgument(I)) {
  935. // We approximate the number of loads and stores needed by dividing the
  936. // size of the byval type by the target's pointer size.
  937. PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
  938. unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType());
  939. unsigned PointerSize = DL.getPointerSizeInBits();
  940. // Ceiling division.
  941. unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
  942. // If it generates more than 8 stores it is likely to be expanded as an
  943. // inline memcpy so we take that as an upper bound. Otherwise we assume
  944. // one load and one store per word copied.
  945. // FIXME: The maxStoresPerMemcpy setting from the target should be used
  946. // here instead of a magic number of 8, but it's not available via
  947. // DataLayout.
  948. NumStores = std::min(NumStores, 8U);
  949. Cost -= 2 * NumStores * InlineConstants::InstrCost;
  950. } else {
  951. // For non-byval arguments subtract off one instruction per call
  952. // argument.
  953. Cost -= InlineConstants::InstrCost;
  954. }
  955. }
  956. // If there is only one call of the function, and it has internal linkage,
  957. // the cost of inlining it drops dramatically.
  958. bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
  959. &F == CS.getCalledFunction();
  960. if (OnlyOneCallAndLocalLinkage)
  961. Cost += InlineConstants::LastCallToStaticBonus;
  962. // If the instruction after the call, or if the normal destination of the
  963. // invoke is an unreachable instruction, the function is noreturn. As such,
  964. // there is little point in inlining this unless there is literally zero
  965. // cost.
  966. Instruction *Instr = CS.getInstruction();
  967. if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
  968. if (isa<UnreachableInst>(II->getNormalDest()->begin()))
  969. Threshold = 0;
  970. } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr)))
  971. Threshold = 0;
  972. // If this function uses the coldcc calling convention, prefer not to inline
  973. // it.
  974. if (F.getCallingConv() == CallingConv::Cold)
  975. Cost += InlineConstants::ColdccPenalty;
  976. // Check if we're done. This can happen due to bonuses and penalties.
  977. if (Cost > Threshold)
  978. return false;
  979. if (F.empty())
  980. return true;
  981. Function *Caller = CS.getInstruction()->getParent()->getParent();
  982. // Check if the caller function is recursive itself.
  983. for (User *U : Caller->users()) {
  984. CallSite Site(U);
  985. if (!Site)
  986. continue;
  987. Instruction *I = Site.getInstruction();
  988. if (I->getParent()->getParent() == Caller) {
  989. IsCallerRecursive = true;
  990. break;
  991. }
  992. }
  993. // Populate our simplified values by mapping from function arguments to call
  994. // arguments with known important simplifications.
  995. CallSite::arg_iterator CAI = CS.arg_begin();
  996. for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
  997. FAI != FAE; ++FAI, ++CAI) {
  998. assert(CAI != CS.arg_end());
  999. if (Constant *C = dyn_cast<Constant>(CAI))
  1000. SimplifiedValues[FAI] = C;
  1001. Value *PtrArg = *CAI;
  1002. if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
  1003. ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
  1004. // We can SROA any pointer arguments derived from alloca instructions.
  1005. if (isa<AllocaInst>(PtrArg)) {
  1006. SROAArgValues[FAI] = PtrArg;
  1007. SROAArgCosts[PtrArg] = 0;
  1008. }
  1009. }
  1010. }
  1011. NumConstantArgs = SimplifiedValues.size();
  1012. NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
  1013. NumAllocaArgs = SROAArgValues.size();
  1014. // FIXME: If a caller has multiple calls to a callee, we end up recomputing
  1015. // the ephemeral values multiple times (and they're completely determined by
  1016. // the callee, so this is purely duplicate work).
  1017. SmallPtrSet<const Value *, 32> EphValues;
  1018. CodeMetrics::collectEphemeralValues(&F, &ACT->getAssumptionCache(F), EphValues);
  1019. // The worklist of live basic blocks in the callee *after* inlining. We avoid
  1020. // adding basic blocks of the callee which can be proven to be dead for this
  1021. // particular call site in order to get more accurate cost estimates. This
  1022. // requires a somewhat heavyweight iteration pattern: we need to walk the
  1023. // basic blocks in a breadth-first order as we insert live successors. To
  1024. // accomplish this, prioritizing for small iterations because we exit after
  1025. // crossing our threshold, we use a small-size optimized SetVector.
  1026. typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
  1027. SmallPtrSet<BasicBlock *, 16> > BBSetVector;
  1028. BBSetVector BBWorklist;
  1029. BBWorklist.insert(&F.getEntryBlock());
  1030. // Note that we *must not* cache the size, this loop grows the worklist.
  1031. for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
  1032. // Bail out the moment we cross the threshold. This means we'll under-count
  1033. // the cost, but only when undercounting doesn't matter.
  1034. if (Cost > Threshold)
  1035. break;
  1036. BasicBlock *BB = BBWorklist[Idx];
  1037. if (BB->empty())
  1038. continue;
  1039. // Disallow inlining a blockaddress. A blockaddress only has defined
  1040. // behavior for an indirect branch in the same function, and we do not
  1041. // currently support inlining indirect branches. But, the inliner may not
  1042. // see an indirect branch that ends up being dead code at a particular call
  1043. // site. If the blockaddress escapes the function, e.g., via a global
  1044. // variable, inlining may lead to an invalid cross-function reference.
  1045. if (BB->hasAddressTaken())
  1046. return false;
  1047. // Analyze the cost of this block. If we blow through the threshold, this
  1048. // returns false, and we can bail on out.
  1049. if (!analyzeBlock(BB, EphValues)) {
  1050. if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
  1051. HasIndirectBr || HasFrameEscape)
  1052. return false;
  1053. // If the caller is a recursive function then we don't want to inline
  1054. // functions which allocate a lot of stack space because it would increase
  1055. // the caller stack usage dramatically.
  1056. if (IsCallerRecursive &&
  1057. AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
  1058. return false;
  1059. break;
  1060. }
  1061. TerminatorInst *TI = BB->getTerminator();
  1062. // Add in the live successors by first checking whether we have terminator
  1063. // that may be simplified based on the values simplified by this call.
  1064. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  1065. if (BI->isConditional()) {
  1066. Value *Cond = BI->getCondition();
  1067. if (ConstantInt *SimpleCond
  1068. = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
  1069. BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
  1070. continue;
  1071. }
  1072. }
  1073. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  1074. Value *Cond = SI->getCondition();
  1075. if (ConstantInt *SimpleCond
  1076. = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
  1077. BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
  1078. continue;
  1079. }
  1080. }
  1081. // If we're unable to select a particular successor, just count all of
  1082. // them.
  1083. for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
  1084. ++TIdx)
  1085. BBWorklist.insert(TI->getSuccessor(TIdx));
  1086. // If we had any successors at this point, than post-inlining is likely to
  1087. // have them as well. Note that we assume any basic blocks which existed
  1088. // due to branches or switches which folded above will also fold after
  1089. // inlining.
  1090. if (SingleBB && TI->getNumSuccessors() > 1) {
  1091. // Take off the bonus we applied to the threshold.
  1092. Threshold -= SingleBBBonus;
  1093. SingleBB = false;
  1094. }
  1095. }
  1096. // If this is a noduplicate call, we can still inline as long as
  1097. // inlining this would cause the removal of the caller (so the instruction
  1098. // is not actually duplicated, just moved).
  1099. if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
  1100. return false;
  1101. // We applied the maximum possible vector bonus at the beginning. Now,
  1102. // subtract the excess bonus, if any, from the Threshold before
  1103. // comparing against Cost.
  1104. if (NumVectorInstructions <= NumInstructions / 10)
  1105. Threshold -= FiftyPercentVectorBonus;
  1106. else if (NumVectorInstructions <= NumInstructions / 2)
  1107. Threshold -= (FiftyPercentVectorBonus - TenPercentVectorBonus);
  1108. return Cost < Threshold;
  1109. }
  1110. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1111. /// \brief Dump stats about this call's analysis.
  1112. void CallAnalyzer::dump() {
  1113. #define DEBUG_PRINT_STAT(x) dbgs() << " " #x ": " << x << "\n"
  1114. DEBUG_PRINT_STAT(NumConstantArgs);
  1115. DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
  1116. DEBUG_PRINT_STAT(NumAllocaArgs);
  1117. DEBUG_PRINT_STAT(NumConstantPtrCmps);
  1118. DEBUG_PRINT_STAT(NumConstantPtrDiffs);
  1119. DEBUG_PRINT_STAT(NumInstructionsSimplified);
  1120. DEBUG_PRINT_STAT(NumInstructions);
  1121. DEBUG_PRINT_STAT(SROACostSavings);
  1122. DEBUG_PRINT_STAT(SROACostSavingsLost);
  1123. DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
  1124. DEBUG_PRINT_STAT(Cost);
  1125. DEBUG_PRINT_STAT(Threshold);
  1126. #undef DEBUG_PRINT_STAT
  1127. }
  1128. #endif
  1129. INITIALIZE_PASS_BEGIN(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis",
  1130. true, true)
  1131. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  1132. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  1133. INITIALIZE_PASS_END(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis",
  1134. true, true)
  1135. char InlineCostAnalysis::ID = 0;
  1136. InlineCostAnalysis::InlineCostAnalysis() : CallGraphSCCPass(ID) {}
  1137. InlineCostAnalysis::~InlineCostAnalysis() {}
  1138. void InlineCostAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  1139. AU.setPreservesAll();
  1140. AU.addRequired<AssumptionCacheTracker>();
  1141. AU.addRequired<TargetTransformInfoWrapperPass>();
  1142. CallGraphSCCPass::getAnalysisUsage(AU);
  1143. }
  1144. bool InlineCostAnalysis::runOnSCC(CallGraphSCC &SCC) {
  1145. TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
  1146. ACT = &getAnalysis<AssumptionCacheTracker>();
  1147. return false;
  1148. }
  1149. InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, int Threshold) {
  1150. return getInlineCost(CS, CS.getCalledFunction(), Threshold);
  1151. }
  1152. /// \brief Test that two functions either have or have not the given attribute
  1153. /// at the same time.
  1154. template<typename AttrKind>
  1155. static bool attributeMatches(Function *F1, Function *F2, AttrKind Attr) {
  1156. return F1->getFnAttribute(Attr) == F2->getFnAttribute(Attr);
  1157. }
  1158. /// \brief Test that there are no attribute conflicts between Caller and Callee
  1159. /// that prevent inlining.
  1160. static bool functionsHaveCompatibleAttributes(Function *Caller,
  1161. Function *Callee,
  1162. TargetTransformInfo &TTI) {
  1163. return TTI.hasCompatibleFunctionAttributes(Caller, Callee) &&
  1164. attributeMatches(Caller, Callee, Attribute::SanitizeAddress) &&
  1165. attributeMatches(Caller, Callee, Attribute::SanitizeMemory) &&
  1166. attributeMatches(Caller, Callee, Attribute::SanitizeThread);
  1167. }
  1168. InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, Function *Callee,
  1169. int Threshold) {
  1170. // Cannot inline indirect calls.
  1171. if (!Callee)
  1172. return llvm::InlineCost::getNever();
  1173. // Calls to functions with always-inline attributes should be inlined
  1174. // whenever possible.
  1175. if (CS.hasFnAttr(Attribute::AlwaysInline)) {
  1176. if (isInlineViable(*Callee))
  1177. return llvm::InlineCost::getAlways();
  1178. return llvm::InlineCost::getNever();
  1179. }
  1180. // Never inline functions with conflicting attributes (unless callee has
  1181. // always-inline attribute).
  1182. if (!functionsHaveCompatibleAttributes(CS.getCaller(), Callee,
  1183. TTIWP->getTTI(*Callee)))
  1184. return llvm::InlineCost::getNever();
  1185. // Don't inline this call if the caller has the optnone attribute.
  1186. if (CS.getCaller()->hasFnAttribute(Attribute::OptimizeNone))
  1187. return llvm::InlineCost::getNever();
  1188. // Don't inline functions which can be redefined at link-time to mean
  1189. // something else. Don't inline functions marked noinline or call sites
  1190. // marked noinline.
  1191. if (Callee->mayBeOverridden() ||
  1192. Callee->hasFnAttribute(Attribute::NoInline) || CS.isNoInline())
  1193. return llvm::InlineCost::getNever();
  1194. DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName()
  1195. << "...\n");
  1196. CallAnalyzer CA(TTIWP->getTTI(*Callee), ACT, *Callee, Threshold, CS);
  1197. bool ShouldInline = CA.analyzeCall(CS);
  1198. DEBUG(CA.dump());
  1199. // Check if there was a reason to force inlining or no inlining.
  1200. if (!ShouldInline && CA.getCost() < CA.getThreshold())
  1201. return InlineCost::getNever();
  1202. if (ShouldInline && CA.getCost() >= CA.getThreshold())
  1203. return InlineCost::getAlways();
  1204. return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
  1205. }
  1206. bool InlineCostAnalysis::isInlineViable(Function &F) {
  1207. bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
  1208. for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
  1209. // Disallow inlining of functions which contain indirect branches or
  1210. // blockaddresses.
  1211. if (isa<IndirectBrInst>(BI->getTerminator()) || BI->hasAddressTaken())
  1212. return false;
  1213. for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;
  1214. ++II) {
  1215. CallSite CS(II);
  1216. if (!CS)
  1217. continue;
  1218. // Disallow recursive calls.
  1219. if (&F == CS.getCalledFunction())
  1220. return false;
  1221. // Disallow calls which expose returns-twice to a function not previously
  1222. // attributed as such.
  1223. if (!ReturnsTwice && CS.isCall() &&
  1224. cast<CallInst>(CS.getInstruction())->canReturnTwice())
  1225. return false;
  1226. // Disallow inlining functions that call @llvm.localescape. Doing this
  1227. // correctly would require major changes to the inliner.
  1228. if (CS.getCalledFunction() &&
  1229. CS.getCalledFunction()->getIntrinsicID() ==
  1230. llvm::Intrinsic::localescape)
  1231. return false;
  1232. }
  1233. }
  1234. return true;
  1235. }