CodeExtractor.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. //===- CodeExtractor.cpp - Pull code region into a new function -----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the interface to tear out a code region, such as an
  11. // individual loop or a parallel section, into a new function, replacing it with
  12. // a call to the new function.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Transforms/Utils/FunctionUtils.h"
  16. #include "llvm/Constants.h"
  17. #include "llvm/DerivedTypes.h"
  18. #include "llvm/Instructions.h"
  19. #include "llvm/Intrinsics.h"
  20. #include "llvm/LLVMContext.h"
  21. #include "llvm/Module.h"
  22. #include "llvm/Pass.h"
  23. #include "llvm/Analysis/Dominators.h"
  24. #include "llvm/Analysis/LoopInfo.h"
  25. #include "llvm/Analysis/Verifier.h"
  26. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/ErrorHandling.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include "llvm/ADT/StringExtras.h"
  32. #include <algorithm>
  33. #include <set>
  34. using namespace llvm;
  35. // Provide a command-line option to aggregate function arguments into a struct
  36. // for functions produced by the code extractor. This is useful when converting
  37. // extracted functions to pthread-based code, as only one argument (void*) can
  38. // be passed in to pthread_create().
  39. static cl::opt<bool>
  40. AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
  41. cl::desc("Aggregate arguments to code-extracted functions"));
  42. namespace {
  43. class CodeExtractor {
  44. typedef std::vector<Value*> Values;
  45. std::set<BasicBlock*> BlocksToExtract;
  46. DominatorTree* DT;
  47. bool AggregateArgs;
  48. unsigned NumExitBlocks;
  49. const Type *RetTy;
  50. public:
  51. CodeExtractor(DominatorTree* dt = 0, bool AggArgs = false)
  52. : DT(dt), AggregateArgs(AggArgs||AggregateArgsOpt), NumExitBlocks(~0U) {}
  53. Function *ExtractCodeRegion(const std::vector<BasicBlock*> &code);
  54. bool isEligible(const std::vector<BasicBlock*> &code);
  55. private:
  56. /// definedInRegion - Return true if the specified value is defined in the
  57. /// extracted region.
  58. bool definedInRegion(Value *V) const {
  59. if (Instruction *I = dyn_cast<Instruction>(V))
  60. if (BlocksToExtract.count(I->getParent()))
  61. return true;
  62. return false;
  63. }
  64. /// definedInCaller - Return true if the specified value is defined in the
  65. /// function being code extracted, but not in the region being extracted.
  66. /// These values must be passed in as live-ins to the function.
  67. bool definedInCaller(Value *V) const {
  68. if (isa<Argument>(V)) return true;
  69. if (Instruction *I = dyn_cast<Instruction>(V))
  70. if (!BlocksToExtract.count(I->getParent()))
  71. return true;
  72. return false;
  73. }
  74. void severSplitPHINodes(BasicBlock *&Header);
  75. void splitReturnBlocks();
  76. void findInputsOutputs(Values &inputs, Values &outputs);
  77. Function *constructFunction(const Values &inputs,
  78. const Values &outputs,
  79. BasicBlock *header,
  80. BasicBlock *newRootNode, BasicBlock *newHeader,
  81. Function *oldFunction, Module *M);
  82. void moveCodeToFunction(Function *newFunction);
  83. void emitCallAndSwitchStatement(Function *newFunction,
  84. BasicBlock *newHeader,
  85. Values &inputs,
  86. Values &outputs);
  87. };
  88. }
  89. /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
  90. /// region, we need to split the entry block of the region so that the PHI node
  91. /// is easier to deal with.
  92. void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
  93. bool HasPredsFromRegion = false;
  94. unsigned NumPredsOutsideRegion = 0;
  95. if (Header != &Header->getParent()->getEntryBlock()) {
  96. PHINode *PN = dyn_cast<PHINode>(Header->begin());
  97. if (!PN) return; // No PHI nodes.
  98. // If the header node contains any PHI nodes, check to see if there is more
  99. // than one entry from outside the region. If so, we need to sever the
  100. // header block into two.
  101. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  102. if (BlocksToExtract.count(PN->getIncomingBlock(i)))
  103. HasPredsFromRegion = true;
  104. else
  105. ++NumPredsOutsideRegion;
  106. // If there is one (or fewer) predecessor from outside the region, we don't
  107. // need to do anything special.
  108. if (NumPredsOutsideRegion <= 1) return;
  109. }
  110. // Otherwise, we need to split the header block into two pieces: one
  111. // containing PHI nodes merging values from outside of the region, and a
  112. // second that contains all of the code for the block and merges back any
  113. // incoming values from inside of the region.
  114. BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI();
  115. BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
  116. Header->getName()+".ce");
  117. // We only want to code extract the second block now, and it becomes the new
  118. // header of the region.
  119. BasicBlock *OldPred = Header;
  120. BlocksToExtract.erase(OldPred);
  121. BlocksToExtract.insert(NewBB);
  122. Header = NewBB;
  123. // Okay, update dominator sets. The blocks that dominate the new one are the
  124. // blocks that dominate TIBB plus the new block itself.
  125. if (DT)
  126. DT->splitBlock(NewBB);
  127. // Okay, now we need to adjust the PHI nodes and any branches from within the
  128. // region to go to the new header block instead of the old header block.
  129. if (HasPredsFromRegion) {
  130. PHINode *PN = cast<PHINode>(OldPred->begin());
  131. // Loop over all of the predecessors of OldPred that are in the region,
  132. // changing them to branch to NewBB instead.
  133. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  134. if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
  135. TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
  136. TI->replaceUsesOfWith(OldPred, NewBB);
  137. }
  138. // Okay, everthing within the region is now branching to the right block, we
  139. // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
  140. for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
  141. PHINode *PN = cast<PHINode>(AfterPHIs);
  142. // Create a new PHI node in the new region, which has an incoming value
  143. // from OldPred of PN.
  144. PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".ce",
  145. NewBB->begin());
  146. NewPN->addIncoming(PN, OldPred);
  147. // Loop over all of the incoming value in PN, moving them to NewPN if they
  148. // are from the extracted region.
  149. for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
  150. if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
  151. NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
  152. PN->removeIncomingValue(i);
  153. --i;
  154. }
  155. }
  156. }
  157. }
  158. }
  159. void CodeExtractor::splitReturnBlocks() {
  160. for (std::set<BasicBlock*>::iterator I = BlocksToExtract.begin(),
  161. E = BlocksToExtract.end(); I != E; ++I)
  162. if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) {
  163. BasicBlock *New = (*I)->splitBasicBlock(RI, (*I)->getName()+".ret");
  164. if (DT) {
  165. // Old dominates New. New node domiantes all other nodes dominated
  166. //by Old.
  167. DomTreeNode *OldNode = DT->getNode(*I);
  168. SmallVector<DomTreeNode*, 8> Children;
  169. for (DomTreeNode::iterator DI = OldNode->begin(), DE = OldNode->end();
  170. DI != DE; ++DI)
  171. Children.push_back(*DI);
  172. DomTreeNode *NewNode = DT->addNewBlock(New, *I);
  173. for (SmallVector<DomTreeNode*, 8>::iterator I = Children.begin(),
  174. E = Children.end(); I != E; ++I)
  175. DT->changeImmediateDominator(*I, NewNode);
  176. }
  177. }
  178. }
  179. // findInputsOutputs - Find inputs to, outputs from the code region.
  180. //
  181. void CodeExtractor::findInputsOutputs(Values &inputs, Values &outputs) {
  182. std::set<BasicBlock*> ExitBlocks;
  183. for (std::set<BasicBlock*>::const_iterator ci = BlocksToExtract.begin(),
  184. ce = BlocksToExtract.end(); ci != ce; ++ci) {
  185. BasicBlock *BB = *ci;
  186. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  187. // If a used value is defined outside the region, it's an input. If an
  188. // instruction is used outside the region, it's an output.
  189. for (User::op_iterator O = I->op_begin(), E = I->op_end(); O != E; ++O)
  190. if (definedInCaller(*O))
  191. inputs.push_back(*O);
  192. // Consider uses of this instruction (outputs).
  193. for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
  194. UI != E; ++UI)
  195. if (!definedInRegion(*UI)) {
  196. outputs.push_back(I);
  197. break;
  198. }
  199. } // for: insts
  200. // Keep track of the exit blocks from the region.
  201. TerminatorInst *TI = BB->getTerminator();
  202. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  203. if (!BlocksToExtract.count(TI->getSuccessor(i)))
  204. ExitBlocks.insert(TI->getSuccessor(i));
  205. } // for: basic blocks
  206. NumExitBlocks = ExitBlocks.size();
  207. // Eliminate duplicates.
  208. std::sort(inputs.begin(), inputs.end());
  209. inputs.erase(std::unique(inputs.begin(), inputs.end()), inputs.end());
  210. std::sort(outputs.begin(), outputs.end());
  211. outputs.erase(std::unique(outputs.begin(), outputs.end()), outputs.end());
  212. }
  213. /// constructFunction - make a function based on inputs and outputs, as follows:
  214. /// f(in0, ..., inN, out0, ..., outN)
  215. ///
  216. Function *CodeExtractor::constructFunction(const Values &inputs,
  217. const Values &outputs,
  218. BasicBlock *header,
  219. BasicBlock *newRootNode,
  220. BasicBlock *newHeader,
  221. Function *oldFunction,
  222. Module *M) {
  223. DEBUG(errs() << "inputs: " << inputs.size() << "\n");
  224. DEBUG(errs() << "outputs: " << outputs.size() << "\n");
  225. // This function returns unsigned, outputs will go back by reference.
  226. switch (NumExitBlocks) {
  227. case 0:
  228. case 1: RetTy = Type::getVoidTy(header->getContext()); break;
  229. case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
  230. default: RetTy = Type::getInt16Ty(header->getContext()); break;
  231. }
  232. std::vector<const Type*> paramTy;
  233. // Add the types of the input values to the function's argument list
  234. for (Values::const_iterator i = inputs.begin(),
  235. e = inputs.end(); i != e; ++i) {
  236. const Value *value = *i;
  237. DEBUG(errs() << "value used in func: " << *value << "\n");
  238. paramTy.push_back(value->getType());
  239. }
  240. // Add the types of the output values to the function's argument list.
  241. for (Values::const_iterator I = outputs.begin(), E = outputs.end();
  242. I != E; ++I) {
  243. DEBUG(errs() << "instr used in func: " << **I << "\n");
  244. if (AggregateArgs)
  245. paramTy.push_back((*I)->getType());
  246. else
  247. paramTy.push_back(PointerType::getUnqual((*I)->getType()));
  248. }
  249. DEBUG(errs() << "Function type: " << *RetTy << " f(");
  250. for (std::vector<const Type*>::iterator i = paramTy.begin(),
  251. e = paramTy.end(); i != e; ++i)
  252. DEBUG(errs() << **i << ", ");
  253. DEBUG(errs() << ")\n");
  254. if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
  255. PointerType *StructPtr =
  256. PointerType::getUnqual(StructType::get(M->getContext(), paramTy));
  257. paramTy.clear();
  258. paramTy.push_back(StructPtr);
  259. }
  260. const FunctionType *funcType =
  261. FunctionType::get(RetTy, paramTy, false);
  262. // Create the new function
  263. Function *newFunction = Function::Create(funcType,
  264. GlobalValue::InternalLinkage,
  265. oldFunction->getName() + "_" +
  266. header->getName(), M);
  267. // If the old function is no-throw, so is the new one.
  268. if (oldFunction->doesNotThrow())
  269. newFunction->setDoesNotThrow(true);
  270. newFunction->getBasicBlockList().push_back(newRootNode);
  271. // Create an iterator to name all of the arguments we inserted.
  272. Function::arg_iterator AI = newFunction->arg_begin();
  273. // Rewrite all users of the inputs in the extracted region to use the
  274. // arguments (or appropriate addressing into struct) instead.
  275. for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
  276. Value *RewriteVal;
  277. if (AggregateArgs) {
  278. Value *Idx[2];
  279. Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
  280. Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
  281. TerminatorInst *TI = newFunction->begin()->getTerminator();
  282. GetElementPtrInst *GEP =
  283. GetElementPtrInst::Create(AI, Idx, Idx+2,
  284. "gep_" + inputs[i]->getName(), TI);
  285. RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
  286. } else
  287. RewriteVal = AI++;
  288. std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
  289. for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
  290. use != useE; ++use)
  291. if (Instruction* inst = dyn_cast<Instruction>(*use))
  292. if (BlocksToExtract.count(inst->getParent()))
  293. inst->replaceUsesOfWith(inputs[i], RewriteVal);
  294. }
  295. // Set names for input and output arguments.
  296. if (!AggregateArgs) {
  297. AI = newFunction->arg_begin();
  298. for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
  299. AI->setName(inputs[i]->getName());
  300. for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
  301. AI->setName(outputs[i]->getName()+".out");
  302. }
  303. // Rewrite branches to basic blocks outside of the loop to new dummy blocks
  304. // within the new function. This must be done before we lose track of which
  305. // blocks were originally in the code region.
  306. std::vector<User*> Users(header->use_begin(), header->use_end());
  307. for (unsigned i = 0, e = Users.size(); i != e; ++i)
  308. // The BasicBlock which contains the branch is not in the region
  309. // modify the branch target to a new block
  310. if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
  311. if (!BlocksToExtract.count(TI->getParent()) &&
  312. TI->getParent()->getParent() == oldFunction)
  313. TI->replaceUsesOfWith(header, newHeader);
  314. return newFunction;
  315. }
  316. /// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI
  317. /// that uses the value within the basic block, and return the predecessor
  318. /// block associated with that use, or return 0 if none is found.
  319. static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) {
  320. for (Value::use_iterator UI = Used->use_begin(),
  321. UE = Used->use_end(); UI != UE; ++UI) {
  322. PHINode *P = dyn_cast<PHINode>(*UI);
  323. if (P && P->getParent() == BB)
  324. return P->getIncomingBlock(UI);
  325. }
  326. return 0;
  327. }
  328. /// emitCallAndSwitchStatement - This method sets up the caller side by adding
  329. /// the call instruction, splitting any PHI nodes in the header block as
  330. /// necessary.
  331. void CodeExtractor::
  332. emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
  333. Values &inputs, Values &outputs) {
  334. // Emit a call to the new function, passing in: *pointer to struct (if
  335. // aggregating parameters), or plan inputs and allocated memory for outputs
  336. std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
  337. LLVMContext &Context = newFunction->getContext();
  338. // Add inputs as params, or to be filled into the struct
  339. for (Values::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i)
  340. if (AggregateArgs)
  341. StructValues.push_back(*i);
  342. else
  343. params.push_back(*i);
  344. // Create allocas for the outputs
  345. for (Values::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) {
  346. if (AggregateArgs) {
  347. StructValues.push_back(*i);
  348. } else {
  349. AllocaInst *alloca =
  350. new AllocaInst((*i)->getType(), 0, (*i)->getName()+".loc",
  351. codeReplacer->getParent()->begin()->begin());
  352. ReloadOutputs.push_back(alloca);
  353. params.push_back(alloca);
  354. }
  355. }
  356. AllocaInst *Struct = 0;
  357. if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
  358. std::vector<const Type*> ArgTypes;
  359. for (Values::iterator v = StructValues.begin(),
  360. ve = StructValues.end(); v != ve; ++v)
  361. ArgTypes.push_back((*v)->getType());
  362. // Allocate a struct at the beginning of this function
  363. Type *StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
  364. Struct =
  365. new AllocaInst(StructArgTy, 0, "structArg",
  366. codeReplacer->getParent()->begin()->begin());
  367. params.push_back(Struct);
  368. for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
  369. Value *Idx[2];
  370. Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
  371. Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
  372. GetElementPtrInst *GEP =
  373. GetElementPtrInst::Create(Struct, Idx, Idx + 2,
  374. "gep_" + StructValues[i]->getName());
  375. codeReplacer->getInstList().push_back(GEP);
  376. StoreInst *SI = new StoreInst(StructValues[i], GEP);
  377. codeReplacer->getInstList().push_back(SI);
  378. }
  379. }
  380. // Emit the call to the function
  381. CallInst *call = CallInst::Create(newFunction, params.begin(), params.end(),
  382. NumExitBlocks > 1 ? "targetBlock" : "");
  383. codeReplacer->getInstList().push_back(call);
  384. Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
  385. unsigned FirstOut = inputs.size();
  386. if (!AggregateArgs)
  387. std::advance(OutputArgBegin, inputs.size());
  388. // Reload the outputs passed in by reference
  389. for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
  390. Value *Output = 0;
  391. if (AggregateArgs) {
  392. Value *Idx[2];
  393. Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
  394. Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
  395. GetElementPtrInst *GEP
  396. = GetElementPtrInst::Create(Struct, Idx, Idx + 2,
  397. "gep_reload_" + outputs[i]->getName());
  398. codeReplacer->getInstList().push_back(GEP);
  399. Output = GEP;
  400. } else {
  401. Output = ReloadOutputs[i];
  402. }
  403. LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
  404. Reloads.push_back(load);
  405. codeReplacer->getInstList().push_back(load);
  406. std::vector<User*> Users(outputs[i]->use_begin(), outputs[i]->use_end());
  407. for (unsigned u = 0, e = Users.size(); u != e; ++u) {
  408. Instruction *inst = cast<Instruction>(Users[u]);
  409. if (!BlocksToExtract.count(inst->getParent()))
  410. inst->replaceUsesOfWith(outputs[i], load);
  411. }
  412. }
  413. // Now we can emit a switch statement using the call as a value.
  414. SwitchInst *TheSwitch =
  415. SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
  416. codeReplacer, 0, codeReplacer);
  417. // Since there may be multiple exits from the original region, make the new
  418. // function return an unsigned, switch on that number. This loop iterates
  419. // over all of the blocks in the extracted region, updating any terminator
  420. // instructions in the to-be-extracted region that branch to blocks that are
  421. // not in the region to be extracted.
  422. std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
  423. unsigned switchVal = 0;
  424. for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
  425. e = BlocksToExtract.end(); i != e; ++i) {
  426. TerminatorInst *TI = (*i)->getTerminator();
  427. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  428. if (!BlocksToExtract.count(TI->getSuccessor(i))) {
  429. BasicBlock *OldTarget = TI->getSuccessor(i);
  430. // add a new basic block which returns the appropriate value
  431. BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
  432. if (!NewTarget) {
  433. // If we don't already have an exit stub for this non-extracted
  434. // destination, create one now!
  435. NewTarget = BasicBlock::Create(Context,
  436. OldTarget->getName() + ".exitStub",
  437. newFunction);
  438. unsigned SuccNum = switchVal++;
  439. Value *brVal = 0;
  440. switch (NumExitBlocks) {
  441. case 0:
  442. case 1: break; // No value needed.
  443. case 2: // Conditional branch, return a bool
  444. brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
  445. break;
  446. default:
  447. brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
  448. break;
  449. }
  450. ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget);
  451. // Update the switch instruction.
  452. TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
  453. SuccNum),
  454. OldTarget);
  455. // Restore values just before we exit
  456. Function::arg_iterator OAI = OutputArgBegin;
  457. for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
  458. // For an invoke, the normal destination is the only one that is
  459. // dominated by the result of the invocation
  460. BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
  461. bool DominatesDef = true;
  462. if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out])) {
  463. DefBlock = Invoke->getNormalDest();
  464. // Make sure we are looking at the original successor block, not
  465. // at a newly inserted exit block, which won't be in the dominator
  466. // info.
  467. for (std::map<BasicBlock*, BasicBlock*>::iterator I =
  468. ExitBlockMap.begin(), E = ExitBlockMap.end(); I != E; ++I)
  469. if (DefBlock == I->second) {
  470. DefBlock = I->first;
  471. break;
  472. }
  473. // In the extract block case, if the block we are extracting ends
  474. // with an invoke instruction, make sure that we don't emit a
  475. // store of the invoke value for the unwind block.
  476. if (!DT && DefBlock != OldTarget)
  477. DominatesDef = false;
  478. }
  479. if (DT) {
  480. DominatesDef = DT->dominates(DefBlock, OldTarget);
  481. // If the output value is used by a phi in the target block,
  482. // then we need to test for dominance of the phi's predecessor
  483. // instead. Unfortunately, this a little complicated since we
  484. // have already rewritten uses of the value to uses of the reload.
  485. BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out],
  486. OldTarget);
  487. if (pred && DT && DT->dominates(DefBlock, pred))
  488. DominatesDef = true;
  489. }
  490. if (DominatesDef) {
  491. if (AggregateArgs) {
  492. Value *Idx[2];
  493. Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
  494. Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
  495. FirstOut+out);
  496. GetElementPtrInst *GEP =
  497. GetElementPtrInst::Create(OAI, Idx, Idx + 2,
  498. "gep_" + outputs[out]->getName(),
  499. NTRet);
  500. new StoreInst(outputs[out], GEP, NTRet);
  501. } else {
  502. new StoreInst(outputs[out], OAI, NTRet);
  503. }
  504. }
  505. // Advance output iterator even if we don't emit a store
  506. if (!AggregateArgs) ++OAI;
  507. }
  508. }
  509. // rewrite the original branch instruction with this new target
  510. TI->setSuccessor(i, NewTarget);
  511. }
  512. }
  513. // Now that we've done the deed, simplify the switch instruction.
  514. const Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
  515. switch (NumExitBlocks) {
  516. case 0:
  517. // There are no successors (the block containing the switch itself), which
  518. // means that previously this was the last part of the function, and hence
  519. // this should be rewritten as a `ret'
  520. // Check if the function should return a value
  521. if (OldFnRetTy == Type::getVoidTy(Context)) {
  522. ReturnInst::Create(Context, 0, TheSwitch); // Return void
  523. } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
  524. // return what we have
  525. ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
  526. } else {
  527. // Otherwise we must have code extracted an unwind or something, just
  528. // return whatever we want.
  529. ReturnInst::Create(Context,
  530. Constant::getNullValue(OldFnRetTy), TheSwitch);
  531. }
  532. TheSwitch->eraseFromParent();
  533. break;
  534. case 1:
  535. // Only a single destination, change the switch into an unconditional
  536. // branch.
  537. BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
  538. TheSwitch->eraseFromParent();
  539. break;
  540. case 2:
  541. BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
  542. call, TheSwitch);
  543. TheSwitch->eraseFromParent();
  544. break;
  545. default:
  546. // Otherwise, make the default destination of the switch instruction be one
  547. // of the other successors.
  548. TheSwitch->setOperand(0, call);
  549. TheSwitch->setSuccessor(0, TheSwitch->getSuccessor(NumExitBlocks));
  550. TheSwitch->removeCase(NumExitBlocks); // Remove redundant case
  551. break;
  552. }
  553. }
  554. void CodeExtractor::moveCodeToFunction(Function *newFunction) {
  555. Function *oldFunc = (*BlocksToExtract.begin())->getParent();
  556. Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
  557. Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
  558. for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
  559. e = BlocksToExtract.end(); i != e; ++i) {
  560. // Delete the basic block from the old function, and the list of blocks
  561. oldBlocks.remove(*i);
  562. // Insert this basic block into the new function
  563. newBlocks.push_back(*i);
  564. }
  565. }
  566. /// ExtractRegion - Removes a loop from a function, replaces it with a call to
  567. /// new function. Returns pointer to the new function.
  568. ///
  569. /// algorithm:
  570. ///
  571. /// find inputs and outputs for the region
  572. ///
  573. /// for inputs: add to function as args, map input instr* to arg#
  574. /// for outputs: add allocas for scalars,
  575. /// add to func as args, map output instr* to arg#
  576. ///
  577. /// rewrite func to use argument #s instead of instr*
  578. ///
  579. /// for each scalar output in the function: at every exit, store intermediate
  580. /// computed result back into memory.
  581. ///
  582. Function *CodeExtractor::
  583. ExtractCodeRegion(const std::vector<BasicBlock*> &code) {
  584. if (!isEligible(code))
  585. return 0;
  586. // 1) Find inputs, outputs
  587. // 2) Construct new function
  588. // * Add allocas for defs, pass as args by reference
  589. // * Pass in uses as args
  590. // 3) Move code region, add call instr to func
  591. //
  592. BlocksToExtract.insert(code.begin(), code.end());
  593. Values inputs, outputs;
  594. // Assumption: this is a single-entry code region, and the header is the first
  595. // block in the region.
  596. BasicBlock *header = code[0];
  597. for (unsigned i = 1, e = code.size(); i != e; ++i)
  598. for (pred_iterator PI = pred_begin(code[i]), E = pred_end(code[i]);
  599. PI != E; ++PI)
  600. assert(BlocksToExtract.count(*PI) &&
  601. "No blocks in this region may have entries from outside the region"
  602. " except for the first block!");
  603. // If we have to split PHI nodes or the entry block, do so now.
  604. severSplitPHINodes(header);
  605. // If we have any return instructions in the region, split those blocks so
  606. // that the return is not in the region.
  607. splitReturnBlocks();
  608. Function *oldFunction = header->getParent();
  609. // This takes place of the original loop
  610. BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
  611. "codeRepl", oldFunction,
  612. header);
  613. // The new function needs a root node because other nodes can branch to the
  614. // head of the region, but the entry node of a function cannot have preds.
  615. BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
  616. "newFuncRoot");
  617. newFuncRoot->getInstList().push_back(BranchInst::Create(header));
  618. // Find inputs to, outputs from the code region.
  619. findInputsOutputs(inputs, outputs);
  620. // Construct new function based on inputs/outputs & add allocas for all defs.
  621. Function *newFunction = constructFunction(inputs, outputs, header,
  622. newFuncRoot,
  623. codeReplacer, oldFunction,
  624. oldFunction->getParent());
  625. emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
  626. moveCodeToFunction(newFunction);
  627. // Loop over all of the PHI nodes in the header block, and change any
  628. // references to the old incoming edge to be the new incoming edge.
  629. for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
  630. PHINode *PN = cast<PHINode>(I);
  631. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  632. if (!BlocksToExtract.count(PN->getIncomingBlock(i)))
  633. PN->setIncomingBlock(i, newFuncRoot);
  634. }
  635. // Look at all successors of the codeReplacer block. If any of these blocks
  636. // had PHI nodes in them, we need to update the "from" block to be the code
  637. // replacer, not the original block in the extracted region.
  638. std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
  639. succ_end(codeReplacer));
  640. for (unsigned i = 0, e = Succs.size(); i != e; ++i)
  641. for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
  642. PHINode *PN = cast<PHINode>(I);
  643. std::set<BasicBlock*> ProcessedPreds;
  644. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  645. if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
  646. if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
  647. PN->setIncomingBlock(i, codeReplacer);
  648. else {
  649. // There were multiple entries in the PHI for this block, now there
  650. // is only one, so remove the duplicated entries.
  651. PN->removeIncomingValue(i, false);
  652. --i; --e;
  653. }
  654. }
  655. }
  656. //cerr << "NEW FUNCTION: " << *newFunction;
  657. // verifyFunction(*newFunction);
  658. // cerr << "OLD FUNCTION: " << *oldFunction;
  659. // verifyFunction(*oldFunction);
  660. DEBUG(if (verifyFunction(*newFunction))
  661. llvm_report_error("verifyFunction failed!"));
  662. return newFunction;
  663. }
  664. bool CodeExtractor::isEligible(const std::vector<BasicBlock*> &code) {
  665. // Deny code region if it contains allocas or vastarts.
  666. for (std::vector<BasicBlock*>::const_iterator BB = code.begin(), e=code.end();
  667. BB != e; ++BB)
  668. for (BasicBlock::const_iterator I = (*BB)->begin(), Ie = (*BB)->end();
  669. I != Ie; ++I)
  670. if (isa<AllocaInst>(*I))
  671. return false;
  672. else if (const CallInst *CI = dyn_cast<CallInst>(I))
  673. if (const Function *F = CI->getCalledFunction())
  674. if (F->getIntrinsicID() == Intrinsic::vastart)
  675. return false;
  676. return true;
  677. }
  678. /// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new
  679. /// function
  680. ///
  681. Function* llvm::ExtractCodeRegion(DominatorTree &DT,
  682. const std::vector<BasicBlock*> &code,
  683. bool AggregateArgs) {
  684. return CodeExtractor(&DT, AggregateArgs).ExtractCodeRegion(code);
  685. }
  686. /// ExtractBasicBlock - slurp a natural loop into a brand new function
  687. ///
  688. Function* llvm::ExtractLoop(DominatorTree &DT, Loop *L, bool AggregateArgs) {
  689. return CodeExtractor(&DT, AggregateArgs).ExtractCodeRegion(L->getBlocks());
  690. }
  691. /// ExtractBasicBlock - slurp a basic block into a brand new function
  692. ///
  693. Function* llvm::ExtractBasicBlock(BasicBlock *BB, bool AggregateArgs) {
  694. std::vector<BasicBlock*> Blocks;
  695. Blocks.push_back(BB);
  696. return CodeExtractor(0, AggregateArgs).ExtractCodeRegion(Blocks);
  697. }