CodeExtractor.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809
  1. //===- CodeExtractor.cpp - Pull code region into a new function -----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the interface to tear out a code region, such as an
  10. // individual loop or a parallel section, into a new function, replacing it with
  11. // a call to the new function.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/CodeExtractor.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/Optional.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SetVector.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/Analysis/AssumptionCache.h"
  23. #include "llvm/Analysis/BlockFrequencyInfo.h"
  24. #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
  25. #include "llvm/Analysis/BranchProbabilityInfo.h"
  26. #include "llvm/Analysis/LoopInfo.h"
  27. #include "llvm/IR/Argument.h"
  28. #include "llvm/IR/Attributes.h"
  29. #include "llvm/IR/BasicBlock.h"
  30. #include "llvm/IR/CFG.h"
  31. #include "llvm/IR/Constant.h"
  32. #include "llvm/IR/Constants.h"
  33. #include "llvm/IR/DIBuilder.h"
  34. #include "llvm/IR/DataLayout.h"
  35. #include "llvm/IR/DebugInfoMetadata.h"
  36. #include "llvm/IR/DerivedTypes.h"
  37. #include "llvm/IR/Dominators.h"
  38. #include "llvm/IR/Function.h"
  39. #include "llvm/IR/GlobalValue.h"
  40. #include "llvm/IR/InstIterator.h"
  41. #include "llvm/IR/InstrTypes.h"
  42. #include "llvm/IR/Instruction.h"
  43. #include "llvm/IR/Instructions.h"
  44. #include "llvm/IR/IntrinsicInst.h"
  45. #include "llvm/IR/Intrinsics.h"
  46. #include "llvm/IR/LLVMContext.h"
  47. #include "llvm/IR/MDBuilder.h"
  48. #include "llvm/IR/Module.h"
  49. #include "llvm/IR/PatternMatch.h"
  50. #include "llvm/IR/Type.h"
  51. #include "llvm/IR/User.h"
  52. #include "llvm/IR/Value.h"
  53. #include "llvm/IR/Verifier.h"
  54. #include "llvm/Pass.h"
  55. #include "llvm/Support/BlockFrequency.h"
  56. #include "llvm/Support/BranchProbability.h"
  57. #include "llvm/Support/Casting.h"
  58. #include "llvm/Support/CommandLine.h"
  59. #include "llvm/Support/Debug.h"
  60. #include "llvm/Support/ErrorHandling.h"
  61. #include "llvm/Support/raw_ostream.h"
  62. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  63. #include "llvm/Transforms/Utils/Local.h"
  64. #include <cassert>
  65. #include <cstdint>
  66. #include <iterator>
  67. #include <map>
  68. #include <set>
  69. #include <utility>
  70. #include <vector>
  71. using namespace llvm;
  72. using namespace llvm::PatternMatch;
  73. using ProfileCount = Function::ProfileCount;
  74. #define DEBUG_TYPE "code-extractor"
  75. // Provide a command-line option to aggregate function arguments into a struct
  76. // for functions produced by the code extractor. This is useful when converting
  77. // extracted functions to pthread-based code, as only one argument (void*) can
  78. // be passed in to pthread_create().
  79. static cl::opt<bool>
  80. AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
  81. cl::desc("Aggregate arguments to code-extracted functions"));
  82. /// Test whether a block is valid for extraction.
  83. static bool isBlockValidForExtraction(const BasicBlock &BB,
  84. const SetVector<BasicBlock *> &Result,
  85. bool AllowVarArgs, bool AllowAlloca) {
  86. // taking the address of a basic block moved to another function is illegal
  87. if (BB.hasAddressTaken())
  88. return false;
  89. // don't hoist code that uses another basicblock address, as it's likely to
  90. // lead to unexpected behavior, like cross-function jumps
  91. SmallPtrSet<User const *, 16> Visited;
  92. SmallVector<User const *, 16> ToVisit;
  93. for (Instruction const &Inst : BB)
  94. ToVisit.push_back(&Inst);
  95. while (!ToVisit.empty()) {
  96. User const *Curr = ToVisit.pop_back_val();
  97. if (!Visited.insert(Curr).second)
  98. continue;
  99. if (isa<BlockAddress const>(Curr))
  100. return false; // even a reference to self is likely to be not compatible
  101. if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB)
  102. continue;
  103. for (auto const &U : Curr->operands()) {
  104. if (auto *UU = dyn_cast<User>(U))
  105. ToVisit.push_back(UU);
  106. }
  107. }
  108. // If explicitly requested, allow vastart and alloca. For invoke instructions
  109. // verify that extraction is valid.
  110. for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
  111. if (isa<AllocaInst>(I)) {
  112. if (!AllowAlloca)
  113. return false;
  114. continue;
  115. }
  116. if (const auto *II = dyn_cast<InvokeInst>(I)) {
  117. // Unwind destination (either a landingpad, catchswitch, or cleanuppad)
  118. // must be a part of the subgraph which is being extracted.
  119. if (auto *UBB = II->getUnwindDest())
  120. if (!Result.count(UBB))
  121. return false;
  122. continue;
  123. }
  124. // All catch handlers of a catchswitch instruction as well as the unwind
  125. // destination must be in the subgraph.
  126. if (const auto *CSI = dyn_cast<CatchSwitchInst>(I)) {
  127. if (auto *UBB = CSI->getUnwindDest())
  128. if (!Result.count(UBB))
  129. return false;
  130. for (auto *HBB : CSI->handlers())
  131. if (!Result.count(const_cast<BasicBlock*>(HBB)))
  132. return false;
  133. continue;
  134. }
  135. // Make sure that entire catch handler is within subgraph. It is sufficient
  136. // to check that catch return's block is in the list.
  137. if (const auto *CPI = dyn_cast<CatchPadInst>(I)) {
  138. for (const auto *U : CPI->users())
  139. if (const auto *CRI = dyn_cast<CatchReturnInst>(U))
  140. if (!Result.count(const_cast<BasicBlock*>(CRI->getParent())))
  141. return false;
  142. continue;
  143. }
  144. // And do similar checks for cleanup handler - the entire handler must be
  145. // in subgraph which is going to be extracted. For cleanup return should
  146. // additionally check that the unwind destination is also in the subgraph.
  147. if (const auto *CPI = dyn_cast<CleanupPadInst>(I)) {
  148. for (const auto *U : CPI->users())
  149. if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
  150. if (!Result.count(const_cast<BasicBlock*>(CRI->getParent())))
  151. return false;
  152. continue;
  153. }
  154. if (const auto *CRI = dyn_cast<CleanupReturnInst>(I)) {
  155. if (auto *UBB = CRI->getUnwindDest())
  156. if (!Result.count(UBB))
  157. return false;
  158. continue;
  159. }
  160. if (const CallInst *CI = dyn_cast<CallInst>(I)) {
  161. if (const Function *F = CI->getCalledFunction()) {
  162. auto IID = F->getIntrinsicID();
  163. if (IID == Intrinsic::vastart) {
  164. if (AllowVarArgs)
  165. continue;
  166. else
  167. return false;
  168. }
  169. // Currently, we miscompile outlined copies of eh_typid_for. There are
  170. // proposals for fixing this in llvm.org/PR39545.
  171. if (IID == Intrinsic::eh_typeid_for)
  172. return false;
  173. }
  174. }
  175. }
  176. return true;
  177. }
  178. /// Build a set of blocks to extract if the input blocks are viable.
  179. static SetVector<BasicBlock *>
  180. buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
  181. bool AllowVarArgs, bool AllowAlloca) {
  182. assert(!BBs.empty() && "The set of blocks to extract must be non-empty");
  183. SetVector<BasicBlock *> Result;
  184. // Loop over the blocks, adding them to our set-vector, and aborting with an
  185. // empty set if we encounter invalid blocks.
  186. for (BasicBlock *BB : BBs) {
  187. // If this block is dead, don't process it.
  188. if (DT && !DT->isReachableFromEntry(BB))
  189. continue;
  190. if (!Result.insert(BB))
  191. llvm_unreachable("Repeated basic blocks in extraction input");
  192. }
  193. LLVM_DEBUG(dbgs() << "Region front block: " << Result.front()->getName()
  194. << '\n');
  195. for (auto *BB : Result) {
  196. if (!isBlockValidForExtraction(*BB, Result, AllowVarArgs, AllowAlloca))
  197. return {};
  198. // Make sure that the first block is not a landing pad.
  199. if (BB == Result.front()) {
  200. if (BB->isEHPad()) {
  201. LLVM_DEBUG(dbgs() << "The first block cannot be an unwind block\n");
  202. return {};
  203. }
  204. continue;
  205. }
  206. // All blocks other than the first must not have predecessors outside of
  207. // the subgraph which is being extracted.
  208. for (auto *PBB : predecessors(BB))
  209. if (!Result.count(PBB)) {
  210. LLVM_DEBUG(dbgs() << "No blocks in this region may have entries from "
  211. "outside the region except for the first block!\n"
  212. << "Problematic source BB: " << BB->getName() << "\n"
  213. << "Problematic destination BB: " << PBB->getName()
  214. << "\n");
  215. return {};
  216. }
  217. }
  218. return Result;
  219. }
  220. CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
  221. bool AggregateArgs, BlockFrequencyInfo *BFI,
  222. BranchProbabilityInfo *BPI, AssumptionCache *AC,
  223. bool AllowVarArgs, bool AllowAlloca,
  224. std::string Suffix)
  225. : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
  226. BPI(BPI), AC(AC), AllowVarArgs(AllowVarArgs),
  227. Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs, AllowAlloca)),
  228. Suffix(Suffix) {}
  229. CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs,
  230. BlockFrequencyInfo *BFI,
  231. BranchProbabilityInfo *BPI, AssumptionCache *AC,
  232. std::string Suffix)
  233. : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
  234. BPI(BPI), AC(AC), AllowVarArgs(false),
  235. Blocks(buildExtractionBlockSet(L.getBlocks(), &DT,
  236. /* AllowVarArgs */ false,
  237. /* AllowAlloca */ false)),
  238. Suffix(Suffix) {}
  239. /// definedInRegion - Return true if the specified value is defined in the
  240. /// extracted region.
  241. static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
  242. if (Instruction *I = dyn_cast<Instruction>(V))
  243. if (Blocks.count(I->getParent()))
  244. return true;
  245. return false;
  246. }
  247. /// definedInCaller - Return true if the specified value is defined in the
  248. /// function being code extracted, but not in the region being extracted.
  249. /// These values must be passed in as live-ins to the function.
  250. static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
  251. if (isa<Argument>(V)) return true;
  252. if (Instruction *I = dyn_cast<Instruction>(V))
  253. if (!Blocks.count(I->getParent()))
  254. return true;
  255. return false;
  256. }
  257. static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) {
  258. BasicBlock *CommonExitBlock = nullptr;
  259. auto hasNonCommonExitSucc = [&](BasicBlock *Block) {
  260. for (auto *Succ : successors(Block)) {
  261. // Internal edges, ok.
  262. if (Blocks.count(Succ))
  263. continue;
  264. if (!CommonExitBlock) {
  265. CommonExitBlock = Succ;
  266. continue;
  267. }
  268. if (CommonExitBlock != Succ)
  269. return true;
  270. }
  271. return false;
  272. };
  273. if (any_of(Blocks, hasNonCommonExitSucc))
  274. return nullptr;
  275. return CommonExitBlock;
  276. }
  277. CodeExtractorAnalysisCache::CodeExtractorAnalysisCache(Function &F) {
  278. for (BasicBlock &BB : F) {
  279. for (Instruction &II : BB.instructionsWithoutDebug())
  280. if (auto *AI = dyn_cast<AllocaInst>(&II))
  281. Allocas.push_back(AI);
  282. findSideEffectInfoForBlock(BB);
  283. }
  284. }
  285. void CodeExtractorAnalysisCache::findSideEffectInfoForBlock(BasicBlock &BB) {
  286. for (Instruction &II : BB.instructionsWithoutDebug()) {
  287. unsigned Opcode = II.getOpcode();
  288. Value *MemAddr = nullptr;
  289. switch (Opcode) {
  290. case Instruction::Store:
  291. case Instruction::Load: {
  292. if (Opcode == Instruction::Store) {
  293. StoreInst *SI = cast<StoreInst>(&II);
  294. MemAddr = SI->getPointerOperand();
  295. } else {
  296. LoadInst *LI = cast<LoadInst>(&II);
  297. MemAddr = LI->getPointerOperand();
  298. }
  299. // Global variable can not be aliased with locals.
  300. if (dyn_cast<Constant>(MemAddr))
  301. break;
  302. Value *Base = MemAddr->stripInBoundsConstantOffsets();
  303. if (!isa<AllocaInst>(Base)) {
  304. SideEffectingBlocks.insert(&BB);
  305. return;
  306. }
  307. BaseMemAddrs[&BB].insert(Base);
  308. break;
  309. }
  310. default: {
  311. IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(&II);
  312. if (IntrInst) {
  313. if (IntrInst->isLifetimeStartOrEnd())
  314. break;
  315. SideEffectingBlocks.insert(&BB);
  316. return;
  317. }
  318. // Treat all the other cases conservatively if it has side effects.
  319. if (II.mayHaveSideEffects()) {
  320. SideEffectingBlocks.insert(&BB);
  321. return;
  322. }
  323. }
  324. }
  325. }
  326. }
  327. bool CodeExtractorAnalysisCache::doesBlockContainClobberOfAddr(
  328. BasicBlock &BB, AllocaInst *Addr) const {
  329. if (SideEffectingBlocks.count(&BB))
  330. return true;
  331. auto It = BaseMemAddrs.find(&BB);
  332. if (It != BaseMemAddrs.end())
  333. return It->second.count(Addr);
  334. return false;
  335. }
  336. bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers(
  337. const CodeExtractorAnalysisCache &CEAC, Instruction *Addr) const {
  338. AllocaInst *AI = cast<AllocaInst>(Addr->stripInBoundsConstantOffsets());
  339. Function *Func = (*Blocks.begin())->getParent();
  340. for (BasicBlock &BB : *Func) {
  341. if (Blocks.count(&BB))
  342. continue;
  343. if (CEAC.doesBlockContainClobberOfAddr(BB, AI))
  344. return false;
  345. }
  346. return true;
  347. }
  348. BasicBlock *
  349. CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) {
  350. BasicBlock *SinglePredFromOutlineRegion = nullptr;
  351. assert(!Blocks.count(CommonExitBlock) &&
  352. "Expect a block outside the region!");
  353. for (auto *Pred : predecessors(CommonExitBlock)) {
  354. if (!Blocks.count(Pred))
  355. continue;
  356. if (!SinglePredFromOutlineRegion) {
  357. SinglePredFromOutlineRegion = Pred;
  358. } else if (SinglePredFromOutlineRegion != Pred) {
  359. SinglePredFromOutlineRegion = nullptr;
  360. break;
  361. }
  362. }
  363. if (SinglePredFromOutlineRegion)
  364. return SinglePredFromOutlineRegion;
  365. #ifndef NDEBUG
  366. auto getFirstPHI = [](BasicBlock *BB) {
  367. BasicBlock::iterator I = BB->begin();
  368. PHINode *FirstPhi = nullptr;
  369. while (I != BB->end()) {
  370. PHINode *Phi = dyn_cast<PHINode>(I);
  371. if (!Phi)
  372. break;
  373. if (!FirstPhi) {
  374. FirstPhi = Phi;
  375. break;
  376. }
  377. }
  378. return FirstPhi;
  379. };
  380. // If there are any phi nodes, the single pred either exists or has already
  381. // be created before code extraction.
  382. assert(!getFirstPHI(CommonExitBlock) && "Phi not expected");
  383. #endif
  384. BasicBlock *NewExitBlock = CommonExitBlock->splitBasicBlock(
  385. CommonExitBlock->getFirstNonPHI()->getIterator());
  386. for (auto PI = pred_begin(CommonExitBlock), PE = pred_end(CommonExitBlock);
  387. PI != PE;) {
  388. BasicBlock *Pred = *PI++;
  389. if (Blocks.count(Pred))
  390. continue;
  391. Pred->getTerminator()->replaceUsesOfWith(CommonExitBlock, NewExitBlock);
  392. }
  393. // Now add the old exit block to the outline region.
  394. Blocks.insert(CommonExitBlock);
  395. return CommonExitBlock;
  396. }
  397. // Find the pair of life time markers for address 'Addr' that are either
  398. // defined inside the outline region or can legally be shrinkwrapped into the
  399. // outline region. If there are not other untracked uses of the address, return
  400. // the pair of markers if found; otherwise return a pair of nullptr.
  401. CodeExtractor::LifetimeMarkerInfo
  402. CodeExtractor::getLifetimeMarkers(const CodeExtractorAnalysisCache &CEAC,
  403. Instruction *Addr,
  404. BasicBlock *ExitBlock) const {
  405. LifetimeMarkerInfo Info;
  406. for (User *U : Addr->users()) {
  407. IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U);
  408. if (IntrInst) {
  409. // We don't model addresses with multiple start/end markers, but the
  410. // markers do not need to be in the region.
  411. if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) {
  412. if (Info.LifeStart)
  413. return {};
  414. Info.LifeStart = IntrInst;
  415. continue;
  416. }
  417. if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) {
  418. if (Info.LifeEnd)
  419. return {};
  420. Info.LifeEnd = IntrInst;
  421. continue;
  422. }
  423. // At this point, permit debug uses outside of the region.
  424. // This is fixed in a later call to fixupDebugInfoPostExtraction().
  425. if (isa<DbgInfoIntrinsic>(IntrInst))
  426. continue;
  427. }
  428. // Find untracked uses of the address, bail.
  429. if (!definedInRegion(Blocks, U))
  430. return {};
  431. }
  432. if (!Info.LifeStart || !Info.LifeEnd)
  433. return {};
  434. Info.SinkLifeStart = !definedInRegion(Blocks, Info.LifeStart);
  435. Info.HoistLifeEnd = !definedInRegion(Blocks, Info.LifeEnd);
  436. // Do legality check.
  437. if ((Info.SinkLifeStart || Info.HoistLifeEnd) &&
  438. !isLegalToShrinkwrapLifetimeMarkers(CEAC, Addr))
  439. return {};
  440. // Check to see if we have a place to do hoisting, if not, bail.
  441. if (Info.HoistLifeEnd && !ExitBlock)
  442. return {};
  443. return Info;
  444. }
  445. void CodeExtractor::findAllocas(const CodeExtractorAnalysisCache &CEAC,
  446. ValueSet &SinkCands, ValueSet &HoistCands,
  447. BasicBlock *&ExitBlock) const {
  448. Function *Func = (*Blocks.begin())->getParent();
  449. ExitBlock = getCommonExitBlock(Blocks);
  450. auto moveOrIgnoreLifetimeMarkers =
  451. [&](const LifetimeMarkerInfo &LMI) -> bool {
  452. if (!LMI.LifeStart)
  453. return false;
  454. if (LMI.SinkLifeStart) {
  455. LLVM_DEBUG(dbgs() << "Sinking lifetime.start: " << *LMI.LifeStart
  456. << "\n");
  457. SinkCands.insert(LMI.LifeStart);
  458. }
  459. if (LMI.HoistLifeEnd) {
  460. LLVM_DEBUG(dbgs() << "Hoisting lifetime.end: " << *LMI.LifeEnd << "\n");
  461. HoistCands.insert(LMI.LifeEnd);
  462. }
  463. return true;
  464. };
  465. // Look up allocas in the original function in CodeExtractorAnalysisCache, as
  466. // this is much faster than walking all the instructions.
  467. for (AllocaInst *AI : CEAC.getAllocas()) {
  468. BasicBlock *BB = AI->getParent();
  469. if (Blocks.count(BB))
  470. continue;
  471. // As a prior call to extractCodeRegion() may have shrinkwrapped the alloca,
  472. // check whether it is actually still in the original function.
  473. Function *AIFunc = BB->getParent();
  474. if (AIFunc != Func)
  475. continue;
  476. LifetimeMarkerInfo MarkerInfo = getLifetimeMarkers(CEAC, AI, ExitBlock);
  477. bool Moved = moveOrIgnoreLifetimeMarkers(MarkerInfo);
  478. if (Moved) {
  479. LLVM_DEBUG(dbgs() << "Sinking alloca: " << *AI << "\n");
  480. SinkCands.insert(AI);
  481. continue;
  482. }
  483. // Find bitcasts in the outlined region that have lifetime marker users
  484. // outside that region. Replace the lifetime marker use with an
  485. // outside region bitcast to avoid unnecessary alloca/reload instructions
  486. // and extra lifetime markers.
  487. SmallVector<Instruction *, 2> LifetimeBitcastUsers;
  488. for (User *U : AI->users()) {
  489. if (!definedInRegion(Blocks, U))
  490. continue;
  491. if (U->stripInBoundsConstantOffsets() != AI)
  492. continue;
  493. Instruction *Bitcast = cast<Instruction>(U);
  494. for (User *BU : Bitcast->users()) {
  495. IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(BU);
  496. if (!IntrInst)
  497. continue;
  498. if (!IntrInst->isLifetimeStartOrEnd())
  499. continue;
  500. if (definedInRegion(Blocks, IntrInst))
  501. continue;
  502. LLVM_DEBUG(dbgs() << "Replace use of extracted region bitcast"
  503. << *Bitcast << " in out-of-region lifetime marker "
  504. << *IntrInst << "\n");
  505. LifetimeBitcastUsers.push_back(IntrInst);
  506. }
  507. }
  508. for (Instruction *I : LifetimeBitcastUsers) {
  509. Module *M = AIFunc->getParent();
  510. LLVMContext &Ctx = M->getContext();
  511. auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
  512. CastInst *CastI =
  513. CastInst::CreatePointerCast(AI, Int8PtrTy, "lt.cast", I);
  514. I->replaceUsesOfWith(I->getOperand(1), CastI);
  515. }
  516. // Follow any bitcasts.
  517. SmallVector<Instruction *, 2> Bitcasts;
  518. SmallVector<LifetimeMarkerInfo, 2> BitcastLifetimeInfo;
  519. for (User *U : AI->users()) {
  520. if (U->stripInBoundsConstantOffsets() == AI) {
  521. Instruction *Bitcast = cast<Instruction>(U);
  522. LifetimeMarkerInfo LMI = getLifetimeMarkers(CEAC, Bitcast, ExitBlock);
  523. if (LMI.LifeStart) {
  524. Bitcasts.push_back(Bitcast);
  525. BitcastLifetimeInfo.push_back(LMI);
  526. continue;
  527. }
  528. }
  529. // Found unknown use of AI.
  530. if (!definedInRegion(Blocks, U)) {
  531. Bitcasts.clear();
  532. break;
  533. }
  534. }
  535. // Either no bitcasts reference the alloca or there are unknown uses.
  536. if (Bitcasts.empty())
  537. continue;
  538. LLVM_DEBUG(dbgs() << "Sinking alloca (via bitcast): " << *AI << "\n");
  539. SinkCands.insert(AI);
  540. for (unsigned I = 0, E = Bitcasts.size(); I != E; ++I) {
  541. Instruction *BitcastAddr = Bitcasts[I];
  542. const LifetimeMarkerInfo &LMI = BitcastLifetimeInfo[I];
  543. assert(LMI.LifeStart &&
  544. "Unsafe to sink bitcast without lifetime markers");
  545. moveOrIgnoreLifetimeMarkers(LMI);
  546. if (!definedInRegion(Blocks, BitcastAddr)) {
  547. LLVM_DEBUG(dbgs() << "Sinking bitcast-of-alloca: " << *BitcastAddr
  548. << "\n");
  549. SinkCands.insert(BitcastAddr);
  550. }
  551. }
  552. }
  553. }
  554. bool CodeExtractor::isEligible() const {
  555. if (Blocks.empty())
  556. return false;
  557. BasicBlock *Header = *Blocks.begin();
  558. Function *F = Header->getParent();
  559. // For functions with varargs, check that varargs handling is only done in the
  560. // outlined function, i.e vastart and vaend are only used in outlined blocks.
  561. if (AllowVarArgs && F->getFunctionType()->isVarArg()) {
  562. auto containsVarArgIntrinsic = [](const Instruction &I) {
  563. if (const CallInst *CI = dyn_cast<CallInst>(&I))
  564. if (const Function *Callee = CI->getCalledFunction())
  565. return Callee->getIntrinsicID() == Intrinsic::vastart ||
  566. Callee->getIntrinsicID() == Intrinsic::vaend;
  567. return false;
  568. };
  569. for (auto &BB : *F) {
  570. if (Blocks.count(&BB))
  571. continue;
  572. if (llvm::any_of(BB, containsVarArgIntrinsic))
  573. return false;
  574. }
  575. }
  576. return true;
  577. }
  578. void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs,
  579. const ValueSet &SinkCands) const {
  580. for (BasicBlock *BB : Blocks) {
  581. // If a used value is defined outside the region, it's an input. If an
  582. // instruction is used outside the region, it's an output.
  583. for (Instruction &II : *BB) {
  584. for (auto &OI : II.operands()) {
  585. Value *V = OI;
  586. if (!SinkCands.count(V) && definedInCaller(Blocks, V))
  587. Inputs.insert(V);
  588. }
  589. for (User *U : II.users())
  590. if (!definedInRegion(Blocks, U)) {
  591. Outputs.insert(&II);
  592. break;
  593. }
  594. }
  595. }
  596. }
  597. /// severSplitPHINodesOfEntry - If a PHI node has multiple inputs from outside
  598. /// of the region, we need to split the entry block of the region so that the
  599. /// PHI node is easier to deal with.
  600. void CodeExtractor::severSplitPHINodesOfEntry(BasicBlock *&Header) {
  601. unsigned NumPredsFromRegion = 0;
  602. unsigned NumPredsOutsideRegion = 0;
  603. if (Header != &Header->getParent()->getEntryBlock()) {
  604. PHINode *PN = dyn_cast<PHINode>(Header->begin());
  605. if (!PN) return; // No PHI nodes.
  606. // If the header node contains any PHI nodes, check to see if there is more
  607. // than one entry from outside the region. If so, we need to sever the
  608. // header block into two.
  609. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  610. if (Blocks.count(PN->getIncomingBlock(i)))
  611. ++NumPredsFromRegion;
  612. else
  613. ++NumPredsOutsideRegion;
  614. // If there is one (or fewer) predecessor from outside the region, we don't
  615. // need to do anything special.
  616. if (NumPredsOutsideRegion <= 1) return;
  617. }
  618. // Otherwise, we need to split the header block into two pieces: one
  619. // containing PHI nodes merging values from outside of the region, and a
  620. // second that contains all of the code for the block and merges back any
  621. // incoming values from inside of the region.
  622. BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHI(), DT);
  623. // We only want to code extract the second block now, and it becomes the new
  624. // header of the region.
  625. BasicBlock *OldPred = Header;
  626. Blocks.remove(OldPred);
  627. Blocks.insert(NewBB);
  628. Header = NewBB;
  629. // Okay, now we need to adjust the PHI nodes and any branches from within the
  630. // region to go to the new header block instead of the old header block.
  631. if (NumPredsFromRegion) {
  632. PHINode *PN = cast<PHINode>(OldPred->begin());
  633. // Loop over all of the predecessors of OldPred that are in the region,
  634. // changing them to branch to NewBB instead.
  635. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  636. if (Blocks.count(PN->getIncomingBlock(i))) {
  637. Instruction *TI = PN->getIncomingBlock(i)->getTerminator();
  638. TI->replaceUsesOfWith(OldPred, NewBB);
  639. }
  640. // Okay, everything within the region is now branching to the right block, we
  641. // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
  642. BasicBlock::iterator AfterPHIs;
  643. for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
  644. PHINode *PN = cast<PHINode>(AfterPHIs);
  645. // Create a new PHI node in the new region, which has an incoming value
  646. // from OldPred of PN.
  647. PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
  648. PN->getName() + ".ce", &NewBB->front());
  649. PN->replaceAllUsesWith(NewPN);
  650. NewPN->addIncoming(PN, OldPred);
  651. // Loop over all of the incoming value in PN, moving them to NewPN if they
  652. // are from the extracted region.
  653. for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
  654. if (Blocks.count(PN->getIncomingBlock(i))) {
  655. NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
  656. PN->removeIncomingValue(i);
  657. --i;
  658. }
  659. }
  660. }
  661. }
  662. }
  663. /// severSplitPHINodesOfExits - if PHI nodes in exit blocks have inputs from
  664. /// outlined region, we split these PHIs on two: one with inputs from region
  665. /// and other with remaining incoming blocks; then first PHIs are placed in
  666. /// outlined region.
  667. void CodeExtractor::severSplitPHINodesOfExits(
  668. const SmallPtrSetImpl<BasicBlock *> &Exits) {
  669. for (BasicBlock *ExitBB : Exits) {
  670. BasicBlock *NewBB = nullptr;
  671. for (PHINode &PN : ExitBB->phis()) {
  672. // Find all incoming values from the outlining region.
  673. SmallVector<unsigned, 2> IncomingVals;
  674. for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i)
  675. if (Blocks.count(PN.getIncomingBlock(i)))
  676. IncomingVals.push_back(i);
  677. // Do not process PHI if there is one (or fewer) predecessor from region.
  678. // If PHI has exactly one predecessor from region, only this one incoming
  679. // will be replaced on codeRepl block, so it should be safe to skip PHI.
  680. if (IncomingVals.size() <= 1)
  681. continue;
  682. // Create block for new PHIs and add it to the list of outlined if it
  683. // wasn't done before.
  684. if (!NewBB) {
  685. NewBB = BasicBlock::Create(ExitBB->getContext(),
  686. ExitBB->getName() + ".split",
  687. ExitBB->getParent(), ExitBB);
  688. SmallVector<BasicBlock *, 4> Preds(predecessors(ExitBB));
  689. for (BasicBlock *PredBB : Preds)
  690. if (Blocks.count(PredBB))
  691. PredBB->getTerminator()->replaceUsesOfWith(ExitBB, NewBB);
  692. BranchInst::Create(ExitBB, NewBB);
  693. Blocks.insert(NewBB);
  694. }
  695. // Split this PHI.
  696. PHINode *NewPN =
  697. PHINode::Create(PN.getType(), IncomingVals.size(),
  698. PN.getName() + ".ce", NewBB->getFirstNonPHI());
  699. for (unsigned i : IncomingVals)
  700. NewPN->addIncoming(PN.getIncomingValue(i), PN.getIncomingBlock(i));
  701. for (unsigned i : reverse(IncomingVals))
  702. PN.removeIncomingValue(i, false);
  703. PN.addIncoming(NewPN, NewBB);
  704. }
  705. }
  706. }
  707. void CodeExtractor::splitReturnBlocks() {
  708. for (BasicBlock *Block : Blocks)
  709. if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {
  710. BasicBlock *New =
  711. Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret");
  712. if (DT) {
  713. // Old dominates New. New node dominates all other nodes dominated
  714. // by Old.
  715. DomTreeNode *OldNode = DT->getNode(Block);
  716. SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),
  717. OldNode->end());
  718. DomTreeNode *NewNode = DT->addNewBlock(New, Block);
  719. for (DomTreeNode *I : Children)
  720. DT->changeImmediateDominator(I, NewNode);
  721. }
  722. }
  723. }
  724. /// constructFunction - make a function based on inputs and outputs, as follows:
  725. /// f(in0, ..., inN, out0, ..., outN)
  726. Function *CodeExtractor::constructFunction(const ValueSet &inputs,
  727. const ValueSet &outputs,
  728. BasicBlock *header,
  729. BasicBlock *newRootNode,
  730. BasicBlock *newHeader,
  731. Function *oldFunction,
  732. Module *M) {
  733. LLVM_DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
  734. LLVM_DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
  735. // This function returns unsigned, outputs will go back by reference.
  736. switch (NumExitBlocks) {
  737. case 0:
  738. case 1: RetTy = Type::getVoidTy(header->getContext()); break;
  739. case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
  740. default: RetTy = Type::getInt16Ty(header->getContext()); break;
  741. }
  742. std::vector<Type *> paramTy;
  743. // Add the types of the input values to the function's argument list
  744. for (Value *value : inputs) {
  745. LLVM_DEBUG(dbgs() << "value used in func: " << *value << "\n");
  746. paramTy.push_back(value->getType());
  747. }
  748. // Add the types of the output values to the function's argument list.
  749. for (Value *output : outputs) {
  750. LLVM_DEBUG(dbgs() << "instr used in func: " << *output << "\n");
  751. if (AggregateArgs)
  752. paramTy.push_back(output->getType());
  753. else
  754. paramTy.push_back(PointerType::getUnqual(output->getType()));
  755. }
  756. LLVM_DEBUG({
  757. dbgs() << "Function type: " << *RetTy << " f(";
  758. for (Type *i : paramTy)
  759. dbgs() << *i << ", ";
  760. dbgs() << ")\n";
  761. });
  762. StructType *StructTy = nullptr;
  763. if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
  764. StructTy = StructType::get(M->getContext(), paramTy);
  765. paramTy.clear();
  766. paramTy.push_back(PointerType::getUnqual(StructTy));
  767. }
  768. FunctionType *funcType =
  769. FunctionType::get(RetTy, paramTy,
  770. AllowVarArgs && oldFunction->isVarArg());
  771. std::string SuffixToUse =
  772. Suffix.empty()
  773. ? (header->getName().empty() ? "extracted" : header->getName().str())
  774. : Suffix;
  775. // Create the new function
  776. Function *newFunction = Function::Create(
  777. funcType, GlobalValue::InternalLinkage, oldFunction->getAddressSpace(),
  778. oldFunction->getName() + "." + SuffixToUse, M);
  779. // If the old function is no-throw, so is the new one.
  780. if (oldFunction->doesNotThrow())
  781. newFunction->setDoesNotThrow();
  782. // Inherit the uwtable attribute if we need to.
  783. if (oldFunction->hasUWTable())
  784. newFunction->setHasUWTable();
  785. // Inherit all of the target dependent attributes and white-listed
  786. // target independent attributes.
  787. // (e.g. If the extracted region contains a call to an x86.sse
  788. // instruction we need to make sure that the extracted region has the
  789. // "target-features" attribute allowing it to be lowered.
  790. // FIXME: This should be changed to check to see if a specific
  791. // attribute can not be inherited.
  792. for (const auto &Attr : oldFunction->getAttributes().getFnAttributes()) {
  793. if (Attr.isStringAttribute()) {
  794. if (Attr.getKindAsString() == "thunk")
  795. continue;
  796. } else
  797. switch (Attr.getKindAsEnum()) {
  798. // Those attributes cannot be propagated safely. Explicitly list them
  799. // here so we get a warning if new attributes are added. This list also
  800. // includes non-function attributes.
  801. case Attribute::Alignment:
  802. case Attribute::AllocSize:
  803. case Attribute::ArgMemOnly:
  804. case Attribute::Builtin:
  805. case Attribute::ByVal:
  806. case Attribute::Convergent:
  807. case Attribute::Dereferenceable:
  808. case Attribute::DereferenceableOrNull:
  809. case Attribute::InAlloca:
  810. case Attribute::InReg:
  811. case Attribute::InaccessibleMemOnly:
  812. case Attribute::InaccessibleMemOrArgMemOnly:
  813. case Attribute::JumpTable:
  814. case Attribute::Naked:
  815. case Attribute::Nest:
  816. case Attribute::NoAlias:
  817. case Attribute::NoBuiltin:
  818. case Attribute::NoCapture:
  819. case Attribute::NoMerge:
  820. case Attribute::NoReturn:
  821. case Attribute::NoSync:
  822. case Attribute::NoUndef:
  823. case Attribute::None:
  824. case Attribute::NonNull:
  825. case Attribute::Preallocated:
  826. case Attribute::ReadNone:
  827. case Attribute::ReadOnly:
  828. case Attribute::Returned:
  829. case Attribute::ReturnsTwice:
  830. case Attribute::SExt:
  831. case Attribute::Speculatable:
  832. case Attribute::StackAlignment:
  833. case Attribute::StructRet:
  834. case Attribute::SwiftError:
  835. case Attribute::SwiftSelf:
  836. case Attribute::WillReturn:
  837. case Attribute::WriteOnly:
  838. case Attribute::ZExt:
  839. case Attribute::ImmArg:
  840. case Attribute::ByRef:
  841. case Attribute::EndAttrKinds:
  842. case Attribute::EmptyKey:
  843. case Attribute::TombstoneKey:
  844. continue;
  845. // Those attributes should be safe to propagate to the extracted function.
  846. case Attribute::AlwaysInline:
  847. case Attribute::Cold:
  848. case Attribute::Hot:
  849. case Attribute::NoRecurse:
  850. case Attribute::InlineHint:
  851. case Attribute::MinSize:
  852. case Attribute::NoCallback:
  853. case Attribute::NoDuplicate:
  854. case Attribute::NoFree:
  855. case Attribute::NoImplicitFloat:
  856. case Attribute::NoInline:
  857. case Attribute::NonLazyBind:
  858. case Attribute::NoRedZone:
  859. case Attribute::NoUnwind:
  860. case Attribute::NullPointerIsValid:
  861. case Attribute::OptForFuzzing:
  862. case Attribute::OptimizeNone:
  863. case Attribute::OptimizeForSize:
  864. case Attribute::SafeStack:
  865. case Attribute::ShadowCallStack:
  866. case Attribute::SanitizeAddress:
  867. case Attribute::SanitizeMemory:
  868. case Attribute::SanitizeThread:
  869. case Attribute::SanitizeHWAddress:
  870. case Attribute::SanitizeMemTag:
  871. case Attribute::SpeculativeLoadHardening:
  872. case Attribute::StackProtect:
  873. case Attribute::StackProtectReq:
  874. case Attribute::StackProtectStrong:
  875. case Attribute::StrictFP:
  876. case Attribute::UWTable:
  877. case Attribute::NoCfCheck:
  878. case Attribute::MustProgress:
  879. case Attribute::NoProfile:
  880. break;
  881. }
  882. newFunction->addFnAttr(Attr);
  883. }
  884. newFunction->getBasicBlockList().push_back(newRootNode);
  885. // Create an iterator to name all of the arguments we inserted.
  886. Function::arg_iterator AI = newFunction->arg_begin();
  887. // Rewrite all users of the inputs in the extracted region to use the
  888. // arguments (or appropriate addressing into struct) instead.
  889. for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
  890. Value *RewriteVal;
  891. if (AggregateArgs) {
  892. Value *Idx[2];
  893. Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
  894. Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
  895. Instruction *TI = newFunction->begin()->getTerminator();
  896. GetElementPtrInst *GEP = GetElementPtrInst::Create(
  897. StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI);
  898. RewriteVal = new LoadInst(StructTy->getElementType(i), GEP,
  899. "loadgep_" + inputs[i]->getName(), TI);
  900. } else
  901. RewriteVal = &*AI++;
  902. std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end());
  903. for (User *use : Users)
  904. if (Instruction *inst = dyn_cast<Instruction>(use))
  905. if (Blocks.count(inst->getParent()))
  906. inst->replaceUsesOfWith(inputs[i], RewriteVal);
  907. }
  908. // Set names for input and output arguments.
  909. if (!AggregateArgs) {
  910. AI = newFunction->arg_begin();
  911. for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
  912. AI->setName(inputs[i]->getName());
  913. for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
  914. AI->setName(outputs[i]->getName()+".out");
  915. }
  916. // Rewrite branches to basic blocks outside of the loop to new dummy blocks
  917. // within the new function. This must be done before we lose track of which
  918. // blocks were originally in the code region.
  919. std::vector<User *> Users(header->user_begin(), header->user_end());
  920. for (auto &U : Users)
  921. // The BasicBlock which contains the branch is not in the region
  922. // modify the branch target to a new block
  923. if (Instruction *I = dyn_cast<Instruction>(U))
  924. if (I->isTerminator() && I->getFunction() == oldFunction &&
  925. !Blocks.count(I->getParent()))
  926. I->replaceUsesOfWith(header, newHeader);
  927. return newFunction;
  928. }
  929. /// Erase lifetime.start markers which reference inputs to the extraction
  930. /// region, and insert the referenced memory into \p LifetimesStart.
  931. ///
  932. /// The extraction region is defined by a set of blocks (\p Blocks), and a set
  933. /// of allocas which will be moved from the caller function into the extracted
  934. /// function (\p SunkAllocas).
  935. static void eraseLifetimeMarkersOnInputs(const SetVector<BasicBlock *> &Blocks,
  936. const SetVector<Value *> &SunkAllocas,
  937. SetVector<Value *> &LifetimesStart) {
  938. for (BasicBlock *BB : Blocks) {
  939. for (auto It = BB->begin(), End = BB->end(); It != End;) {
  940. auto *II = dyn_cast<IntrinsicInst>(&*It);
  941. ++It;
  942. if (!II || !II->isLifetimeStartOrEnd())
  943. continue;
  944. // Get the memory operand of the lifetime marker. If the underlying
  945. // object is a sunk alloca, or is otherwise defined in the extraction
  946. // region, the lifetime marker must not be erased.
  947. Value *Mem = II->getOperand(1)->stripInBoundsOffsets();
  948. if (SunkAllocas.count(Mem) || definedInRegion(Blocks, Mem))
  949. continue;
  950. if (II->getIntrinsicID() == Intrinsic::lifetime_start)
  951. LifetimesStart.insert(Mem);
  952. II->eraseFromParent();
  953. }
  954. }
  955. }
  956. /// Insert lifetime start/end markers surrounding the call to the new function
  957. /// for objects defined in the caller.
  958. static void insertLifetimeMarkersSurroundingCall(
  959. Module *M, ArrayRef<Value *> LifetimesStart, ArrayRef<Value *> LifetimesEnd,
  960. CallInst *TheCall) {
  961. LLVMContext &Ctx = M->getContext();
  962. auto Int8PtrTy = Type::getInt8PtrTy(Ctx);
  963. auto NegativeOne = ConstantInt::getSigned(Type::getInt64Ty(Ctx), -1);
  964. Instruction *Term = TheCall->getParent()->getTerminator();
  965. // The memory argument to a lifetime marker must be a i8*. Cache any bitcasts
  966. // needed to satisfy this requirement so they may be reused.
  967. DenseMap<Value *, Value *> Bitcasts;
  968. // Emit lifetime markers for the pointers given in \p Objects. Insert the
  969. // markers before the call if \p InsertBefore, and after the call otherwise.
  970. auto insertMarkers = [&](Function *MarkerFunc, ArrayRef<Value *> Objects,
  971. bool InsertBefore) {
  972. for (Value *Mem : Objects) {
  973. assert((!isa<Instruction>(Mem) || cast<Instruction>(Mem)->getFunction() ==
  974. TheCall->getFunction()) &&
  975. "Input memory not defined in original function");
  976. Value *&MemAsI8Ptr = Bitcasts[Mem];
  977. if (!MemAsI8Ptr) {
  978. if (Mem->getType() == Int8PtrTy)
  979. MemAsI8Ptr = Mem;
  980. else
  981. MemAsI8Ptr =
  982. CastInst::CreatePointerCast(Mem, Int8PtrTy, "lt.cast", TheCall);
  983. }
  984. auto Marker = CallInst::Create(MarkerFunc, {NegativeOne, MemAsI8Ptr});
  985. if (InsertBefore)
  986. Marker->insertBefore(TheCall);
  987. else
  988. Marker->insertBefore(Term);
  989. }
  990. };
  991. if (!LifetimesStart.empty()) {
  992. auto StartFn = llvm::Intrinsic::getDeclaration(
  993. M, llvm::Intrinsic::lifetime_start, Int8PtrTy);
  994. insertMarkers(StartFn, LifetimesStart, /*InsertBefore=*/true);
  995. }
  996. if (!LifetimesEnd.empty()) {
  997. auto EndFn = llvm::Intrinsic::getDeclaration(
  998. M, llvm::Intrinsic::lifetime_end, Int8PtrTy);
  999. insertMarkers(EndFn, LifetimesEnd, /*InsertBefore=*/false);
  1000. }
  1001. }
  1002. /// emitCallAndSwitchStatement - This method sets up the caller side by adding
  1003. /// the call instruction, splitting any PHI nodes in the header block as
  1004. /// necessary.
  1005. CallInst *CodeExtractor::emitCallAndSwitchStatement(Function *newFunction,
  1006. BasicBlock *codeReplacer,
  1007. ValueSet &inputs,
  1008. ValueSet &outputs) {
  1009. // Emit a call to the new function, passing in: *pointer to struct (if
  1010. // aggregating parameters), or plan inputs and allocated memory for outputs
  1011. std::vector<Value *> params, StructValues, ReloadOutputs, Reloads;
  1012. Module *M = newFunction->getParent();
  1013. LLVMContext &Context = M->getContext();
  1014. const DataLayout &DL = M->getDataLayout();
  1015. CallInst *call = nullptr;
  1016. // Add inputs as params, or to be filled into the struct
  1017. unsigned ArgNo = 0;
  1018. SmallVector<unsigned, 1> SwiftErrorArgs;
  1019. for (Value *input : inputs) {
  1020. if (AggregateArgs)
  1021. StructValues.push_back(input);
  1022. else {
  1023. params.push_back(input);
  1024. if (input->isSwiftError())
  1025. SwiftErrorArgs.push_back(ArgNo);
  1026. }
  1027. ++ArgNo;
  1028. }
  1029. // Create allocas for the outputs
  1030. for (Value *output : outputs) {
  1031. if (AggregateArgs) {
  1032. StructValues.push_back(output);
  1033. } else {
  1034. AllocaInst *alloca =
  1035. new AllocaInst(output->getType(), DL.getAllocaAddrSpace(),
  1036. nullptr, output->getName() + ".loc",
  1037. &codeReplacer->getParent()->front().front());
  1038. ReloadOutputs.push_back(alloca);
  1039. params.push_back(alloca);
  1040. }
  1041. }
  1042. StructType *StructArgTy = nullptr;
  1043. AllocaInst *Struct = nullptr;
  1044. if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
  1045. std::vector<Type *> ArgTypes;
  1046. for (ValueSet::iterator v = StructValues.begin(),
  1047. ve = StructValues.end(); v != ve; ++v)
  1048. ArgTypes.push_back((*v)->getType());
  1049. // Allocate a struct at the beginning of this function
  1050. StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
  1051. Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr,
  1052. "structArg",
  1053. &codeReplacer->getParent()->front().front());
  1054. params.push_back(Struct);
  1055. for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
  1056. Value *Idx[2];
  1057. Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
  1058. Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
  1059. GetElementPtrInst *GEP = GetElementPtrInst::Create(
  1060. StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());
  1061. codeReplacer->getInstList().push_back(GEP);
  1062. new StoreInst(StructValues[i], GEP, codeReplacer);
  1063. }
  1064. }
  1065. // Emit the call to the function
  1066. call = CallInst::Create(newFunction, params,
  1067. NumExitBlocks > 1 ? "targetBlock" : "");
  1068. // Add debug location to the new call, if the original function has debug
  1069. // info. In that case, the terminator of the entry block of the extracted
  1070. // function contains the first debug location of the extracted function,
  1071. // set in extractCodeRegion.
  1072. if (codeReplacer->getParent()->getSubprogram()) {
  1073. if (auto DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc())
  1074. call->setDebugLoc(DL);
  1075. }
  1076. codeReplacer->getInstList().push_back(call);
  1077. // Set swifterror parameter attributes.
  1078. for (unsigned SwiftErrArgNo : SwiftErrorArgs) {
  1079. call->addParamAttr(SwiftErrArgNo, Attribute::SwiftError);
  1080. newFunction->addParamAttr(SwiftErrArgNo, Attribute::SwiftError);
  1081. }
  1082. Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
  1083. unsigned FirstOut = inputs.size();
  1084. if (!AggregateArgs)
  1085. std::advance(OutputArgBegin, inputs.size());
  1086. // Reload the outputs passed in by reference.
  1087. for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
  1088. Value *Output = nullptr;
  1089. if (AggregateArgs) {
  1090. Value *Idx[2];
  1091. Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
  1092. Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
  1093. GetElementPtrInst *GEP = GetElementPtrInst::Create(
  1094. StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
  1095. codeReplacer->getInstList().push_back(GEP);
  1096. Output = GEP;
  1097. } else {
  1098. Output = ReloadOutputs[i];
  1099. }
  1100. LoadInst *load = new LoadInst(outputs[i]->getType(), Output,
  1101. outputs[i]->getName() + ".reload",
  1102. codeReplacer);
  1103. Reloads.push_back(load);
  1104. std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end());
  1105. for (unsigned u = 0, e = Users.size(); u != e; ++u) {
  1106. Instruction *inst = cast<Instruction>(Users[u]);
  1107. if (!Blocks.count(inst->getParent()))
  1108. inst->replaceUsesOfWith(outputs[i], load);
  1109. }
  1110. }
  1111. // Now we can emit a switch statement using the call as a value.
  1112. SwitchInst *TheSwitch =
  1113. SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
  1114. codeReplacer, 0, codeReplacer);
  1115. // Since there may be multiple exits from the original region, make the new
  1116. // function return an unsigned, switch on that number. This loop iterates
  1117. // over all of the blocks in the extracted region, updating any terminator
  1118. // instructions in the to-be-extracted region that branch to blocks that are
  1119. // not in the region to be extracted.
  1120. std::map<BasicBlock *, BasicBlock *> ExitBlockMap;
  1121. unsigned switchVal = 0;
  1122. for (BasicBlock *Block : Blocks) {
  1123. Instruction *TI = Block->getTerminator();
  1124. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  1125. if (!Blocks.count(TI->getSuccessor(i))) {
  1126. BasicBlock *OldTarget = TI->getSuccessor(i);
  1127. // add a new basic block which returns the appropriate value
  1128. BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
  1129. if (!NewTarget) {
  1130. // If we don't already have an exit stub for this non-extracted
  1131. // destination, create one now!
  1132. NewTarget = BasicBlock::Create(Context,
  1133. OldTarget->getName() + ".exitStub",
  1134. newFunction);
  1135. unsigned SuccNum = switchVal++;
  1136. Value *brVal = nullptr;
  1137. switch (NumExitBlocks) {
  1138. case 0:
  1139. case 1: break; // No value needed.
  1140. case 2: // Conditional branch, return a bool
  1141. brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
  1142. break;
  1143. default:
  1144. brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
  1145. break;
  1146. }
  1147. ReturnInst::Create(Context, brVal, NewTarget);
  1148. // Update the switch instruction.
  1149. TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
  1150. SuccNum),
  1151. OldTarget);
  1152. }
  1153. // rewrite the original branch instruction with this new target
  1154. TI->setSuccessor(i, NewTarget);
  1155. }
  1156. }
  1157. // Store the arguments right after the definition of output value.
  1158. // This should be proceeded after creating exit stubs to be ensure that invoke
  1159. // result restore will be placed in the outlined function.
  1160. Function::arg_iterator OAI = OutputArgBegin;
  1161. for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
  1162. auto *OutI = dyn_cast<Instruction>(outputs[i]);
  1163. if (!OutI)
  1164. continue;
  1165. // Find proper insertion point.
  1166. BasicBlock::iterator InsertPt;
  1167. // In case OutI is an invoke, we insert the store at the beginning in the
  1168. // 'normal destination' BB. Otherwise we insert the store right after OutI.
  1169. if (auto *InvokeI = dyn_cast<InvokeInst>(OutI))
  1170. InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt();
  1171. else if (auto *Phi = dyn_cast<PHINode>(OutI))
  1172. InsertPt = Phi->getParent()->getFirstInsertionPt();
  1173. else
  1174. InsertPt = std::next(OutI->getIterator());
  1175. Instruction *InsertBefore = &*InsertPt;
  1176. assert((InsertBefore->getFunction() == newFunction ||
  1177. Blocks.count(InsertBefore->getParent())) &&
  1178. "InsertPt should be in new function");
  1179. assert(OAI != newFunction->arg_end() &&
  1180. "Number of output arguments should match "
  1181. "the amount of defined values");
  1182. if (AggregateArgs) {
  1183. Value *Idx[2];
  1184. Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
  1185. Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
  1186. GetElementPtrInst *GEP = GetElementPtrInst::Create(
  1187. StructArgTy, &*OAI, Idx, "gep_" + outputs[i]->getName(),
  1188. InsertBefore);
  1189. new StoreInst(outputs[i], GEP, InsertBefore);
  1190. // Since there should be only one struct argument aggregating
  1191. // all the output values, we shouldn't increment OAI, which always
  1192. // points to the struct argument, in this case.
  1193. } else {
  1194. new StoreInst(outputs[i], &*OAI, InsertBefore);
  1195. ++OAI;
  1196. }
  1197. }
  1198. // Now that we've done the deed, simplify the switch instruction.
  1199. Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
  1200. switch (NumExitBlocks) {
  1201. case 0:
  1202. // There are no successors (the block containing the switch itself), which
  1203. // means that previously this was the last part of the function, and hence
  1204. // this should be rewritten as a `ret'
  1205. // Check if the function should return a value
  1206. if (OldFnRetTy->isVoidTy()) {
  1207. ReturnInst::Create(Context, nullptr, TheSwitch); // Return void
  1208. } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
  1209. // return what we have
  1210. ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
  1211. } else {
  1212. // Otherwise we must have code extracted an unwind or something, just
  1213. // return whatever we want.
  1214. ReturnInst::Create(Context,
  1215. Constant::getNullValue(OldFnRetTy), TheSwitch);
  1216. }
  1217. TheSwitch->eraseFromParent();
  1218. break;
  1219. case 1:
  1220. // Only a single destination, change the switch into an unconditional
  1221. // branch.
  1222. BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
  1223. TheSwitch->eraseFromParent();
  1224. break;
  1225. case 2:
  1226. BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
  1227. call, TheSwitch);
  1228. TheSwitch->eraseFromParent();
  1229. break;
  1230. default:
  1231. // Otherwise, make the default destination of the switch instruction be one
  1232. // of the other successors.
  1233. TheSwitch->setCondition(call);
  1234. TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
  1235. // Remove redundant case
  1236. TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
  1237. break;
  1238. }
  1239. // Insert lifetime markers around the reloads of any output values. The
  1240. // allocas output values are stored in are only in-use in the codeRepl block.
  1241. insertLifetimeMarkersSurroundingCall(M, ReloadOutputs, ReloadOutputs, call);
  1242. return call;
  1243. }
  1244. void CodeExtractor::moveCodeToFunction(Function *newFunction) {
  1245. Function *oldFunc = (*Blocks.begin())->getParent();
  1246. Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
  1247. Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
  1248. for (BasicBlock *Block : Blocks) {
  1249. // Delete the basic block from the old function, and the list of blocks
  1250. oldBlocks.remove(Block);
  1251. // Insert this basic block into the new function
  1252. newBlocks.push_back(Block);
  1253. }
  1254. }
  1255. void CodeExtractor::calculateNewCallTerminatorWeights(
  1256. BasicBlock *CodeReplacer,
  1257. DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,
  1258. BranchProbabilityInfo *BPI) {
  1259. using Distribution = BlockFrequencyInfoImplBase::Distribution;
  1260. using BlockNode = BlockFrequencyInfoImplBase::BlockNode;
  1261. // Update the branch weights for the exit block.
  1262. Instruction *TI = CodeReplacer->getTerminator();
  1263. SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);
  1264. // Block Frequency distribution with dummy node.
  1265. Distribution BranchDist;
  1266. SmallVector<BranchProbability, 4> EdgeProbabilities(
  1267. TI->getNumSuccessors(), BranchProbability::getUnknown());
  1268. // Add each of the frequencies of the successors.
  1269. for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {
  1270. BlockNode ExitNode(i);
  1271. uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency();
  1272. if (ExitFreq != 0)
  1273. BranchDist.addExit(ExitNode, ExitFreq);
  1274. else
  1275. EdgeProbabilities[i] = BranchProbability::getZero();
  1276. }
  1277. // Check for no total weight.
  1278. if (BranchDist.Total == 0) {
  1279. BPI->setEdgeProbability(CodeReplacer, EdgeProbabilities);
  1280. return;
  1281. }
  1282. // Normalize the distribution so that they can fit in unsigned.
  1283. BranchDist.normalize();
  1284. // Create normalized branch weights and set the metadata.
  1285. for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {
  1286. const auto &Weight = BranchDist.Weights[I];
  1287. // Get the weight and update the current BFI.
  1288. BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
  1289. BranchProbability BP(Weight.Amount, BranchDist.Total);
  1290. EdgeProbabilities[Weight.TargetNode.Index] = BP;
  1291. }
  1292. BPI->setEdgeProbability(CodeReplacer, EdgeProbabilities);
  1293. TI->setMetadata(
  1294. LLVMContext::MD_prof,
  1295. MDBuilder(TI->getContext()).createBranchWeights(BranchWeights));
  1296. }
  1297. /// Erase debug info intrinsics which refer to values in \p F but aren't in
  1298. /// \p F.
  1299. static void eraseDebugIntrinsicsWithNonLocalRefs(Function &F) {
  1300. for (Instruction &I : instructions(F)) {
  1301. SmallVector<DbgVariableIntrinsic *, 4> DbgUsers;
  1302. findDbgUsers(DbgUsers, &I);
  1303. for (DbgVariableIntrinsic *DVI : DbgUsers)
  1304. if (DVI->getFunction() != &F)
  1305. DVI->eraseFromParent();
  1306. }
  1307. }
  1308. /// Fix up the debug info in the old and new functions by pointing line
  1309. /// locations and debug intrinsics to the new subprogram scope, and by deleting
  1310. /// intrinsics which point to values outside of the new function.
  1311. static void fixupDebugInfoPostExtraction(Function &OldFunc, Function &NewFunc,
  1312. CallInst &TheCall) {
  1313. DISubprogram *OldSP = OldFunc.getSubprogram();
  1314. LLVMContext &Ctx = OldFunc.getContext();
  1315. if (!OldSP) {
  1316. // Erase any debug info the new function contains.
  1317. stripDebugInfo(NewFunc);
  1318. // Make sure the old function doesn't contain any non-local metadata refs.
  1319. eraseDebugIntrinsicsWithNonLocalRefs(NewFunc);
  1320. return;
  1321. }
  1322. // Create a subprogram for the new function. Leave out a description of the
  1323. // function arguments, as the parameters don't correspond to anything at the
  1324. // source level.
  1325. assert(OldSP->getUnit() && "Missing compile unit for subprogram");
  1326. DIBuilder DIB(*OldFunc.getParent(), /*AllowUnresolved=*/false,
  1327. OldSP->getUnit());
  1328. auto SPType = DIB.createSubroutineType(DIB.getOrCreateTypeArray(None));
  1329. DISubprogram::DISPFlags SPFlags = DISubprogram::SPFlagDefinition |
  1330. DISubprogram::SPFlagOptimized |
  1331. DISubprogram::SPFlagLocalToUnit;
  1332. auto NewSP = DIB.createFunction(
  1333. OldSP->getUnit(), NewFunc.getName(), NewFunc.getName(), OldSP->getFile(),
  1334. /*LineNo=*/0, SPType, /*ScopeLine=*/0, DINode::FlagZero, SPFlags);
  1335. NewFunc.setSubprogram(NewSP);
  1336. // Debug intrinsics in the new function need to be updated in one of two
  1337. // ways:
  1338. // 1) They need to be deleted, because they describe a value in the old
  1339. // function.
  1340. // 2) They need to point to fresh metadata, e.g. because they currently
  1341. // point to a variable in the wrong scope.
  1342. SmallDenseMap<DINode *, DINode *> RemappedMetadata;
  1343. SmallVector<Instruction *, 4> DebugIntrinsicsToDelete;
  1344. for (Instruction &I : instructions(NewFunc)) {
  1345. auto *DII = dyn_cast<DbgInfoIntrinsic>(&I);
  1346. if (!DII)
  1347. continue;
  1348. // Point the intrinsic to a fresh label within the new function.
  1349. if (auto *DLI = dyn_cast<DbgLabelInst>(&I)) {
  1350. DILabel *OldLabel = DLI->getLabel();
  1351. DINode *&NewLabel = RemappedMetadata[OldLabel];
  1352. if (!NewLabel)
  1353. NewLabel = DILabel::get(Ctx, NewSP, OldLabel->getName(),
  1354. OldLabel->getFile(), OldLabel->getLine());
  1355. DLI->setArgOperand(0, MetadataAsValue::get(Ctx, NewLabel));
  1356. continue;
  1357. }
  1358. // If the location isn't a constant or an instruction, delete the
  1359. // intrinsic.
  1360. auto *DVI = cast<DbgVariableIntrinsic>(DII);
  1361. Value *Location = DVI->getVariableLocation();
  1362. if (!Location ||
  1363. (!isa<Constant>(Location) && !isa<Instruction>(Location))) {
  1364. DebugIntrinsicsToDelete.push_back(DVI);
  1365. continue;
  1366. }
  1367. // If the variable location is an instruction but isn't in the new
  1368. // function, delete the intrinsic.
  1369. Instruction *LocationInst = dyn_cast<Instruction>(Location);
  1370. if (LocationInst && LocationInst->getFunction() != &NewFunc) {
  1371. DebugIntrinsicsToDelete.push_back(DVI);
  1372. continue;
  1373. }
  1374. // Point the intrinsic to a fresh variable within the new function.
  1375. DILocalVariable *OldVar = DVI->getVariable();
  1376. DINode *&NewVar = RemappedMetadata[OldVar];
  1377. if (!NewVar)
  1378. NewVar = DIB.createAutoVariable(
  1379. NewSP, OldVar->getName(), OldVar->getFile(), OldVar->getLine(),
  1380. OldVar->getType(), /*AlwaysPreserve=*/false, DINode::FlagZero,
  1381. OldVar->getAlignInBits());
  1382. DVI->setArgOperand(1, MetadataAsValue::get(Ctx, NewVar));
  1383. }
  1384. for (auto *DII : DebugIntrinsicsToDelete)
  1385. DII->eraseFromParent();
  1386. DIB.finalizeSubprogram(NewSP);
  1387. // Fix up the scope information attached to the line locations in the new
  1388. // function.
  1389. for (Instruction &I : instructions(NewFunc)) {
  1390. if (const DebugLoc &DL = I.getDebugLoc())
  1391. I.setDebugLoc(DILocation::get(Ctx, DL.getLine(), DL.getCol(), NewSP));
  1392. // Loop info metadata may contain line locations. Fix them up.
  1393. auto updateLoopInfoLoc = [&Ctx,
  1394. NewSP](const DILocation &Loc) -> DILocation * {
  1395. return DILocation::get(Ctx, Loc.getLine(), Loc.getColumn(), NewSP,
  1396. nullptr);
  1397. };
  1398. updateLoopMetadataDebugLocations(I, updateLoopInfoLoc);
  1399. }
  1400. if (!TheCall.getDebugLoc())
  1401. TheCall.setDebugLoc(DILocation::get(Ctx, 0, 0, OldSP));
  1402. eraseDebugIntrinsicsWithNonLocalRefs(NewFunc);
  1403. }
  1404. Function *
  1405. CodeExtractor::extractCodeRegion(const CodeExtractorAnalysisCache &CEAC) {
  1406. if (!isEligible())
  1407. return nullptr;
  1408. // Assumption: this is a single-entry code region, and the header is the first
  1409. // block in the region.
  1410. BasicBlock *header = *Blocks.begin();
  1411. Function *oldFunction = header->getParent();
  1412. // Calculate the entry frequency of the new function before we change the root
  1413. // block.
  1414. BlockFrequency EntryFreq;
  1415. if (BFI) {
  1416. assert(BPI && "Both BPI and BFI are required to preserve profile info");
  1417. for (BasicBlock *Pred : predecessors(header)) {
  1418. if (Blocks.count(Pred))
  1419. continue;
  1420. EntryFreq +=
  1421. BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header);
  1422. }
  1423. }
  1424. // Remove @llvm.assume calls that will be moved to the new function from the
  1425. // old function's assumption cache.
  1426. for (BasicBlock *Block : Blocks) {
  1427. for (auto It = Block->begin(), End = Block->end(); It != End;) {
  1428. Instruction *I = &*It;
  1429. ++It;
  1430. if (match(I, m_Intrinsic<Intrinsic::assume>())) {
  1431. if (AC)
  1432. AC->unregisterAssumption(cast<CallInst>(I));
  1433. I->eraseFromParent();
  1434. }
  1435. }
  1436. }
  1437. // If we have any return instructions in the region, split those blocks so
  1438. // that the return is not in the region.
  1439. splitReturnBlocks();
  1440. // Calculate the exit blocks for the extracted region and the total exit
  1441. // weights for each of those blocks.
  1442. DenseMap<BasicBlock *, BlockFrequency> ExitWeights;
  1443. SmallPtrSet<BasicBlock *, 1> ExitBlocks;
  1444. for (BasicBlock *Block : Blocks) {
  1445. for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE;
  1446. ++SI) {
  1447. if (!Blocks.count(*SI)) {
  1448. // Update the branch weight for this successor.
  1449. if (BFI) {
  1450. BlockFrequency &BF = ExitWeights[*SI];
  1451. BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI);
  1452. }
  1453. ExitBlocks.insert(*SI);
  1454. }
  1455. }
  1456. }
  1457. NumExitBlocks = ExitBlocks.size();
  1458. // If we have to split PHI nodes of the entry or exit blocks, do so now.
  1459. severSplitPHINodesOfEntry(header);
  1460. severSplitPHINodesOfExits(ExitBlocks);
  1461. // This takes place of the original loop
  1462. BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
  1463. "codeRepl", oldFunction,
  1464. header);
  1465. // The new function needs a root node because other nodes can branch to the
  1466. // head of the region, but the entry node of a function cannot have preds.
  1467. BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
  1468. "newFuncRoot");
  1469. auto *BranchI = BranchInst::Create(header);
  1470. // If the original function has debug info, we have to add a debug location
  1471. // to the new branch instruction from the artificial entry block.
  1472. // We use the debug location of the first instruction in the extracted
  1473. // blocks, as there is no other equivalent line in the source code.
  1474. if (oldFunction->getSubprogram()) {
  1475. any_of(Blocks, [&BranchI](const BasicBlock *BB) {
  1476. return any_of(*BB, [&BranchI](const Instruction &I) {
  1477. if (!I.getDebugLoc())
  1478. return false;
  1479. BranchI->setDebugLoc(I.getDebugLoc());
  1480. return true;
  1481. });
  1482. });
  1483. }
  1484. newFuncRoot->getInstList().push_back(BranchI);
  1485. ValueSet inputs, outputs, SinkingCands, HoistingCands;
  1486. BasicBlock *CommonExit = nullptr;
  1487. findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
  1488. assert(HoistingCands.empty() || CommonExit);
  1489. // Find inputs to, outputs from the code region.
  1490. findInputsOutputs(inputs, outputs, SinkingCands);
  1491. // Now sink all instructions which only have non-phi uses inside the region.
  1492. // Group the allocas at the start of the block, so that any bitcast uses of
  1493. // the allocas are well-defined.
  1494. AllocaInst *FirstSunkAlloca = nullptr;
  1495. for (auto *II : SinkingCands) {
  1496. if (auto *AI = dyn_cast<AllocaInst>(II)) {
  1497. AI->moveBefore(*newFuncRoot, newFuncRoot->getFirstInsertionPt());
  1498. if (!FirstSunkAlloca)
  1499. FirstSunkAlloca = AI;
  1500. }
  1501. }
  1502. assert((SinkingCands.empty() || FirstSunkAlloca) &&
  1503. "Did not expect a sink candidate without any allocas");
  1504. for (auto *II : SinkingCands) {
  1505. if (!isa<AllocaInst>(II)) {
  1506. cast<Instruction>(II)->moveAfter(FirstSunkAlloca);
  1507. }
  1508. }
  1509. if (!HoistingCands.empty()) {
  1510. auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit);
  1511. Instruction *TI = HoistToBlock->getTerminator();
  1512. for (auto *II : HoistingCands)
  1513. cast<Instruction>(II)->moveBefore(TI);
  1514. }
  1515. // Collect objects which are inputs to the extraction region and also
  1516. // referenced by lifetime start markers within it. The effects of these
  1517. // markers must be replicated in the calling function to prevent the stack
  1518. // coloring pass from merging slots which store input objects.
  1519. ValueSet LifetimesStart;
  1520. eraseLifetimeMarkersOnInputs(Blocks, SinkingCands, LifetimesStart);
  1521. // Construct new function based on inputs/outputs & add allocas for all defs.
  1522. Function *newFunction =
  1523. constructFunction(inputs, outputs, header, newFuncRoot, codeReplacer,
  1524. oldFunction, oldFunction->getParent());
  1525. // Update the entry count of the function.
  1526. if (BFI) {
  1527. auto Count = BFI->getProfileCountFromFreq(EntryFreq.getFrequency());
  1528. if (Count.hasValue())
  1529. newFunction->setEntryCount(
  1530. ProfileCount(Count.getValue(), Function::PCT_Real)); // FIXME
  1531. BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency());
  1532. }
  1533. CallInst *TheCall =
  1534. emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
  1535. moveCodeToFunction(newFunction);
  1536. // Replicate the effects of any lifetime start/end markers which referenced
  1537. // input objects in the extraction region by placing markers around the call.
  1538. insertLifetimeMarkersSurroundingCall(
  1539. oldFunction->getParent(), LifetimesStart.getArrayRef(), {}, TheCall);
  1540. // Propagate personality info to the new function if there is one.
  1541. if (oldFunction->hasPersonalityFn())
  1542. newFunction->setPersonalityFn(oldFunction->getPersonalityFn());
  1543. // Update the branch weights for the exit block.
  1544. if (BFI && NumExitBlocks > 1)
  1545. calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);
  1546. // Loop over all of the PHI nodes in the header and exit blocks, and change
  1547. // any references to the old incoming edge to be the new incoming edge.
  1548. for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
  1549. PHINode *PN = cast<PHINode>(I);
  1550. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  1551. if (!Blocks.count(PN->getIncomingBlock(i)))
  1552. PN->setIncomingBlock(i, newFuncRoot);
  1553. }
  1554. for (BasicBlock *ExitBB : ExitBlocks)
  1555. for (PHINode &PN : ExitBB->phis()) {
  1556. Value *IncomingCodeReplacerVal = nullptr;
  1557. for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
  1558. // Ignore incoming values from outside of the extracted region.
  1559. if (!Blocks.count(PN.getIncomingBlock(i)))
  1560. continue;
  1561. // Ensure that there is only one incoming value from codeReplacer.
  1562. if (!IncomingCodeReplacerVal) {
  1563. PN.setIncomingBlock(i, codeReplacer);
  1564. IncomingCodeReplacerVal = PN.getIncomingValue(i);
  1565. } else
  1566. assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) &&
  1567. "PHI has two incompatbile incoming values from codeRepl");
  1568. }
  1569. }
  1570. fixupDebugInfoPostExtraction(*oldFunction, *newFunction, *TheCall);
  1571. // Mark the new function `noreturn` if applicable. Terminators which resume
  1572. // exception propagation are treated as returning instructions. This is to
  1573. // avoid inserting traps after calls to outlined functions which unwind.
  1574. bool doesNotReturn = none_of(*newFunction, [](const BasicBlock &BB) {
  1575. const Instruction *Term = BB.getTerminator();
  1576. return isa<ReturnInst>(Term) || isa<ResumeInst>(Term);
  1577. });
  1578. if (doesNotReturn)
  1579. newFunction->setDoesNotReturn();
  1580. LLVM_DEBUG(if (verifyFunction(*newFunction, &errs())) {
  1581. newFunction->dump();
  1582. report_fatal_error("verification of newFunction failed!");
  1583. });
  1584. LLVM_DEBUG(if (verifyFunction(*oldFunction))
  1585. report_fatal_error("verification of oldFunction failed!"));
  1586. LLVM_DEBUG(if (AC && verifyAssumptionCache(*oldFunction, *newFunction, AC))
  1587. report_fatal_error("Stale Asumption cache for old Function!"));
  1588. return newFunction;
  1589. }
  1590. bool CodeExtractor::verifyAssumptionCache(const Function &OldFunc,
  1591. const Function &NewFunc,
  1592. AssumptionCache *AC) {
  1593. for (auto AssumeVH : AC->assumptions()) {
  1594. auto *I = dyn_cast_or_null<CallInst>(AssumeVH);
  1595. if (!I)
  1596. continue;
  1597. // There shouldn't be any llvm.assume intrinsics in the new function.
  1598. if (I->getFunction() != &OldFunc)
  1599. return true;
  1600. // There shouldn't be any stale affected values in the assumption cache
  1601. // that were previously in the old function, but that have now been moved
  1602. // to the new function.
  1603. for (auto AffectedValVH : AC->assumptionsFor(I->getOperand(0))) {
  1604. auto *AffectedCI = dyn_cast_or_null<CallInst>(AffectedValVH);
  1605. if (!AffectedCI)
  1606. continue;
  1607. if (AffectedCI->getFunction() != &OldFunc)
  1608. return true;
  1609. auto *AssumedInst = cast<Instruction>(AffectedCI->getOperand(0));
  1610. if (AssumedInst->getFunction() != &OldFunc)
  1611. return true;
  1612. }
  1613. }
  1614. return false;
  1615. }