CodeExtractor.cpp 32 KB

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