CodeExtractor.cpp 70 KB

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