LLVM API Documentation

CodeExtractor.cpp
Go to the documentation of this file.
00001 //===- CodeExtractor.cpp - Pull code region into a new function -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the interface to tear out a code region, such as an
00011 // individual loop or a parallel section, into a new function, replacing it with
00012 // a call to the new function.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/Transforms/Utils/CodeExtractor.h"
00017 #include "llvm/ADT/STLExtras.h"
00018 #include "llvm/ADT/SetVector.h"
00019 #include "llvm/ADT/StringExtras.h"
00020 #include "llvm/Analysis/LoopInfo.h"
00021 #include "llvm/Analysis/RegionInfo.h"
00022 #include "llvm/Analysis/RegionIterator.h"
00023 #include "llvm/IR/Constants.h"
00024 #include "llvm/IR/DerivedTypes.h"
00025 #include "llvm/IR/Dominators.h"
00026 #include "llvm/IR/Instructions.h"
00027 #include "llvm/IR/Intrinsics.h"
00028 #include "llvm/IR/LLVMContext.h"
00029 #include "llvm/IR/Module.h"
00030 #include "llvm/IR/Verifier.h"
00031 #include "llvm/Pass.h"
00032 #include "llvm/Support/CommandLine.h"
00033 #include "llvm/Support/Debug.h"
00034 #include "llvm/Support/ErrorHandling.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00037 #include <algorithm>
00038 #include <set>
00039 using namespace llvm;
00040 
00041 #define DEBUG_TYPE "code-extractor"
00042 
00043 // Provide a command-line option to aggregate function arguments into a struct
00044 // for functions produced by the code extractor. This is useful when converting
00045 // extracted functions to pthread-based code, as only one argument (void*) can
00046 // be passed in to pthread_create().
00047 static cl::opt<bool>
00048 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
00049                  cl::desc("Aggregate arguments to code-extracted functions"));
00050 
00051 /// \brief Test whether a block is valid for extraction.
00052 static bool isBlockValidForExtraction(const BasicBlock &BB) {
00053   // Landing pads must be in the function where they were inserted for cleanup.
00054   if (BB.isLandingPad())
00055     return false;
00056 
00057   // Don't hoist code containing allocas, invokes, or vastarts.
00058   for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
00059     if (isa<AllocaInst>(I) || isa<InvokeInst>(I))
00060       return false;
00061     if (const CallInst *CI = dyn_cast<CallInst>(I))
00062       if (const Function *F = CI->getCalledFunction())
00063         if (F->getIntrinsicID() == Intrinsic::vastart)
00064           return false;
00065   }
00066 
00067   return true;
00068 }
00069 
00070 /// \brief Build a set of blocks to extract if the input blocks are viable.
00071 template <typename IteratorT>
00072 static SetVector<BasicBlock *> buildExtractionBlockSet(IteratorT BBBegin,
00073                                                        IteratorT BBEnd) {
00074   SetVector<BasicBlock *> Result;
00075 
00076   assert(BBBegin != BBEnd);
00077 
00078   // Loop over the blocks, adding them to our set-vector, and aborting with an
00079   // empty set if we encounter invalid blocks.
00080   for (IteratorT I = BBBegin, E = BBEnd; I != E; ++I) {
00081     if (!Result.insert(*I))
00082       llvm_unreachable("Repeated basic blocks in extraction input");
00083 
00084     if (!isBlockValidForExtraction(**I)) {
00085       Result.clear();
00086       return Result;
00087     }
00088   }
00089 
00090 #ifndef NDEBUG
00091   for (SetVector<BasicBlock *>::iterator I = std::next(Result.begin()),
00092                                          E = Result.end();
00093        I != E; ++I)
00094     for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I);
00095          PI != PE; ++PI)
00096       assert(Result.count(*PI) &&
00097              "No blocks in this region may have entries from outside the region"
00098              " except for the first block!");
00099 #endif
00100 
00101   return Result;
00102 }
00103 
00104 /// \brief Helper to call buildExtractionBlockSet with an ArrayRef.
00105 static SetVector<BasicBlock *>
00106 buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs) {
00107   return buildExtractionBlockSet(BBs.begin(), BBs.end());
00108 }
00109 
00110 /// \brief Helper to call buildExtractionBlockSet with a RegionNode.
00111 static SetVector<BasicBlock *>
00112 buildExtractionBlockSet(const RegionNode &RN) {
00113   if (!RN.isSubRegion())
00114     // Just a single BasicBlock.
00115     return buildExtractionBlockSet(RN.getNodeAs<BasicBlock>());
00116 
00117   const Region &R = *RN.getNodeAs<Region>();
00118 
00119   return buildExtractionBlockSet(R.block_begin(), R.block_end());
00120 }
00121 
00122 CodeExtractor::CodeExtractor(BasicBlock *BB, bool AggregateArgs)
00123   : DT(nullptr), AggregateArgs(AggregateArgs||AggregateArgsOpt),
00124     Blocks(buildExtractionBlockSet(BB)), NumExitBlocks(~0U) {}
00125 
00126 CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
00127                              bool AggregateArgs)
00128   : DT(DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
00129     Blocks(buildExtractionBlockSet(BBs)), NumExitBlocks(~0U) {}
00130 
00131 CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs)
00132   : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
00133     Blocks(buildExtractionBlockSet(L.getBlocks())), NumExitBlocks(~0U) {}
00134 
00135 CodeExtractor::CodeExtractor(DominatorTree &DT, const RegionNode &RN,
00136                              bool AggregateArgs)
00137   : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
00138     Blocks(buildExtractionBlockSet(RN)), NumExitBlocks(~0U) {}
00139 
00140 /// definedInRegion - Return true if the specified value is defined in the
00141 /// extracted region.
00142 static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
00143   if (Instruction *I = dyn_cast<Instruction>(V))
00144     if (Blocks.count(I->getParent()))
00145       return true;
00146   return false;
00147 }
00148 
00149 /// definedInCaller - Return true if the specified value is defined in the
00150 /// function being code extracted, but not in the region being extracted.
00151 /// These values must be passed in as live-ins to the function.
00152 static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
00153   if (isa<Argument>(V)) return true;
00154   if (Instruction *I = dyn_cast<Instruction>(V))
00155     if (!Blocks.count(I->getParent()))
00156       return true;
00157   return false;
00158 }
00159 
00160 void CodeExtractor::findInputsOutputs(ValueSet &Inputs,
00161                                       ValueSet &Outputs) const {
00162   for (SetVector<BasicBlock *>::const_iterator I = Blocks.begin(),
00163                                                E = Blocks.end();
00164        I != E; ++I) {
00165     BasicBlock *BB = *I;
00166 
00167     // If a used value is defined outside the region, it's an input.  If an
00168     // instruction is used outside the region, it's an output.
00169     for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
00170          II != IE; ++II) {
00171       for (User::op_iterator OI = II->op_begin(), OE = II->op_end();
00172            OI != OE; ++OI)
00173         if (definedInCaller(Blocks, *OI))
00174           Inputs.insert(*OI);
00175 
00176       for (User *U : II->users())
00177         if (!definedInRegion(Blocks, U)) {
00178           Outputs.insert(II);
00179           break;
00180         }
00181     }
00182   }
00183 }
00184 
00185 /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
00186 /// region, we need to split the entry block of the region so that the PHI node
00187 /// is easier to deal with.
00188 void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
00189   unsigned NumPredsFromRegion = 0;
00190   unsigned NumPredsOutsideRegion = 0;
00191 
00192   if (Header != &Header->getParent()->getEntryBlock()) {
00193     PHINode *PN = dyn_cast<PHINode>(Header->begin());
00194     if (!PN) return;  // No PHI nodes.
00195 
00196     // If the header node contains any PHI nodes, check to see if there is more
00197     // than one entry from outside the region.  If so, we need to sever the
00198     // header block into two.
00199     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00200       if (Blocks.count(PN->getIncomingBlock(i)))
00201         ++NumPredsFromRegion;
00202       else
00203         ++NumPredsOutsideRegion;
00204 
00205     // If there is one (or fewer) predecessor from outside the region, we don't
00206     // need to do anything special.
00207     if (NumPredsOutsideRegion <= 1) return;
00208   }
00209 
00210   // Otherwise, we need to split the header block into two pieces: one
00211   // containing PHI nodes merging values from outside of the region, and a
00212   // second that contains all of the code for the block and merges back any
00213   // incoming values from inside of the region.
00214   BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI();
00215   BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
00216                                               Header->getName()+".ce");
00217 
00218   // We only want to code extract the second block now, and it becomes the new
00219   // header of the region.
00220   BasicBlock *OldPred = Header;
00221   Blocks.remove(OldPred);
00222   Blocks.insert(NewBB);
00223   Header = NewBB;
00224 
00225   // Okay, update dominator sets. The blocks that dominate the new one are the
00226   // blocks that dominate TIBB plus the new block itself.
00227   if (DT)
00228     DT->splitBlock(NewBB);
00229 
00230   // Okay, now we need to adjust the PHI nodes and any branches from within the
00231   // region to go to the new header block instead of the old header block.
00232   if (NumPredsFromRegion) {
00233     PHINode *PN = cast<PHINode>(OldPred->begin());
00234     // Loop over all of the predecessors of OldPred that are in the region,
00235     // changing them to branch to NewBB instead.
00236     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00237       if (Blocks.count(PN->getIncomingBlock(i))) {
00238         TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
00239         TI->replaceUsesOfWith(OldPred, NewBB);
00240       }
00241 
00242     // Okay, everything within the region is now branching to the right block, we
00243     // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
00244     for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
00245       PHINode *PN = cast<PHINode>(AfterPHIs);
00246       // Create a new PHI node in the new region, which has an incoming value
00247       // from OldPred of PN.
00248       PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
00249                                        PN->getName()+".ce", NewBB->begin());
00250       NewPN->addIncoming(PN, OldPred);
00251 
00252       // Loop over all of the incoming value in PN, moving them to NewPN if they
00253       // are from the extracted region.
00254       for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
00255         if (Blocks.count(PN->getIncomingBlock(i))) {
00256           NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
00257           PN->removeIncomingValue(i);
00258           --i;
00259         }
00260       }
00261     }
00262   }
00263 }
00264 
00265 void CodeExtractor::splitReturnBlocks() {
00266   for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end();
00267        I != E; ++I)
00268     if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) {
00269       BasicBlock *New = (*I)->splitBasicBlock(RI, (*I)->getName()+".ret");
00270       if (DT) {
00271         // Old dominates New. New node dominates all other nodes dominated
00272         // by Old.
00273         DomTreeNode *OldNode = DT->getNode(*I);
00274         SmallVector<DomTreeNode*, 8> Children;
00275         for (DomTreeNode::iterator DI = OldNode->begin(), DE = OldNode->end();
00276              DI != DE; ++DI) 
00277           Children.push_back(*DI);
00278 
00279         DomTreeNode *NewNode = DT->addNewBlock(New, *I);
00280 
00281         for (SmallVectorImpl<DomTreeNode *>::iterator I = Children.begin(),
00282                E = Children.end(); I != E; ++I)
00283           DT->changeImmediateDominator(*I, NewNode);
00284       }
00285     }
00286 }
00287 
00288 /// constructFunction - make a function based on inputs and outputs, as follows:
00289 /// f(in0, ..., inN, out0, ..., outN)
00290 ///
00291 Function *CodeExtractor::constructFunction(const ValueSet &inputs,
00292                                            const ValueSet &outputs,
00293                                            BasicBlock *header,
00294                                            BasicBlock *newRootNode,
00295                                            BasicBlock *newHeader,
00296                                            Function *oldFunction,
00297                                            Module *M) {
00298   DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
00299   DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
00300 
00301   // This function returns unsigned, outputs will go back by reference.
00302   switch (NumExitBlocks) {
00303   case 0:
00304   case 1: RetTy = Type::getVoidTy(header->getContext()); break;
00305   case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
00306   default: RetTy = Type::getInt16Ty(header->getContext()); break;
00307   }
00308 
00309   std::vector<Type*> paramTy;
00310 
00311   // Add the types of the input values to the function's argument list
00312   for (ValueSet::const_iterator i = inputs.begin(), e = inputs.end();
00313        i != e; ++i) {
00314     const Value *value = *i;
00315     DEBUG(dbgs() << "value used in func: " << *value << "\n");
00316     paramTy.push_back(value->getType());
00317   }
00318 
00319   // Add the types of the output values to the function's argument list.
00320   for (ValueSet::const_iterator I = outputs.begin(), E = outputs.end();
00321        I != E; ++I) {
00322     DEBUG(dbgs() << "instr used in func: " << **I << "\n");
00323     if (AggregateArgs)
00324       paramTy.push_back((*I)->getType());
00325     else
00326       paramTy.push_back(PointerType::getUnqual((*I)->getType()));
00327   }
00328 
00329   DEBUG(dbgs() << "Function type: " << *RetTy << " f(");
00330   for (std::vector<Type*>::iterator i = paramTy.begin(),
00331          e = paramTy.end(); i != e; ++i)
00332     DEBUG(dbgs() << **i << ", ");
00333   DEBUG(dbgs() << ")\n");
00334 
00335   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
00336     PointerType *StructPtr =
00337            PointerType::getUnqual(StructType::get(M->getContext(), paramTy));
00338     paramTy.clear();
00339     paramTy.push_back(StructPtr);
00340   }
00341   FunctionType *funcType =
00342                   FunctionType::get(RetTy, paramTy, false);
00343 
00344   // Create the new function
00345   Function *newFunction = Function::Create(funcType,
00346                                            GlobalValue::InternalLinkage,
00347                                            oldFunction->getName() + "_" +
00348                                            header->getName(), M);
00349   // If the old function is no-throw, so is the new one.
00350   if (oldFunction->doesNotThrow())
00351     newFunction->setDoesNotThrow();
00352   
00353   newFunction->getBasicBlockList().push_back(newRootNode);
00354 
00355   // Create an iterator to name all of the arguments we inserted.
00356   Function::arg_iterator AI = newFunction->arg_begin();
00357 
00358   // Rewrite all users of the inputs in the extracted region to use the
00359   // arguments (or appropriate addressing into struct) instead.
00360   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
00361     Value *RewriteVal;
00362     if (AggregateArgs) {
00363       Value *Idx[2];
00364       Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
00365       Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
00366       TerminatorInst *TI = newFunction->begin()->getTerminator();
00367       GetElementPtrInst *GEP = 
00368         GetElementPtrInst::Create(AI, Idx, "gep_" + inputs[i]->getName(), TI);
00369       RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
00370     } else
00371       RewriteVal = AI++;
00372 
00373     std::vector<User*> Users(inputs[i]->user_begin(), inputs[i]->user_end());
00374     for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
00375          use != useE; ++use)
00376       if (Instruction* inst = dyn_cast<Instruction>(*use))
00377         if (Blocks.count(inst->getParent()))
00378           inst->replaceUsesOfWith(inputs[i], RewriteVal);
00379   }
00380 
00381   // Set names for input and output arguments.
00382   if (!AggregateArgs) {
00383     AI = newFunction->arg_begin();
00384     for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
00385       AI->setName(inputs[i]->getName());
00386     for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
00387       AI->setName(outputs[i]->getName()+".out");
00388   }
00389 
00390   // Rewrite branches to basic blocks outside of the loop to new dummy blocks
00391   // within the new function. This must be done before we lose track of which
00392   // blocks were originally in the code region.
00393   std::vector<User*> Users(header->user_begin(), header->user_end());
00394   for (unsigned i = 0, e = Users.size(); i != e; ++i)
00395     // The BasicBlock which contains the branch is not in the region
00396     // modify the branch target to a new block
00397     if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
00398       if (!Blocks.count(TI->getParent()) &&
00399           TI->getParent()->getParent() == oldFunction)
00400         TI->replaceUsesOfWith(header, newHeader);
00401 
00402   return newFunction;
00403 }
00404 
00405 /// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI
00406 /// that uses the value within the basic block, and return the predecessor
00407 /// block associated with that use, or return 0 if none is found.
00408 static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) {
00409   for (Use &U : Used->uses()) {
00410      PHINode *P = dyn_cast<PHINode>(U.getUser());
00411      if (P && P->getParent() == BB)
00412        return P->getIncomingBlock(U);
00413   }
00414 
00415   return nullptr;
00416 }
00417 
00418 /// emitCallAndSwitchStatement - This method sets up the caller side by adding
00419 /// the call instruction, splitting any PHI nodes in the header block as
00420 /// necessary.
00421 void CodeExtractor::
00422 emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
00423                            ValueSet &inputs, ValueSet &outputs) {
00424   // Emit a call to the new function, passing in: *pointer to struct (if
00425   // aggregating parameters), or plan inputs and allocated memory for outputs
00426   std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
00427   
00428   LLVMContext &Context = newFunction->getContext();
00429 
00430   // Add inputs as params, or to be filled into the struct
00431   for (ValueSet::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i)
00432     if (AggregateArgs)
00433       StructValues.push_back(*i);
00434     else
00435       params.push_back(*i);
00436 
00437   // Create allocas for the outputs
00438   for (ValueSet::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) {
00439     if (AggregateArgs) {
00440       StructValues.push_back(*i);
00441     } else {
00442       AllocaInst *alloca =
00443         new AllocaInst((*i)->getType(), nullptr, (*i)->getName()+".loc",
00444                        codeReplacer->getParent()->begin()->begin());
00445       ReloadOutputs.push_back(alloca);
00446       params.push_back(alloca);
00447     }
00448   }
00449 
00450   AllocaInst *Struct = nullptr;
00451   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
00452     std::vector<Type*> ArgTypes;
00453     for (ValueSet::iterator v = StructValues.begin(),
00454            ve = StructValues.end(); v != ve; ++v)
00455       ArgTypes.push_back((*v)->getType());
00456 
00457     // Allocate a struct at the beginning of this function
00458     Type *StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
00459     Struct =
00460       new AllocaInst(StructArgTy, nullptr, "structArg",
00461                      codeReplacer->getParent()->begin()->begin());
00462     params.push_back(Struct);
00463 
00464     for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
00465       Value *Idx[2];
00466       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
00467       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
00468       GetElementPtrInst *GEP =
00469         GetElementPtrInst::Create(Struct, Idx,
00470                                   "gep_" + StructValues[i]->getName());
00471       codeReplacer->getInstList().push_back(GEP);
00472       StoreInst *SI = new StoreInst(StructValues[i], GEP);
00473       codeReplacer->getInstList().push_back(SI);
00474     }
00475   }
00476 
00477   // Emit the call to the function
00478   CallInst *call = CallInst::Create(newFunction, params,
00479                                     NumExitBlocks > 1 ? "targetBlock" : "");
00480   codeReplacer->getInstList().push_back(call);
00481 
00482   Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
00483   unsigned FirstOut = inputs.size();
00484   if (!AggregateArgs)
00485     std::advance(OutputArgBegin, inputs.size());
00486 
00487   // Reload the outputs passed in by reference
00488   for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
00489     Value *Output = nullptr;
00490     if (AggregateArgs) {
00491       Value *Idx[2];
00492       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
00493       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
00494       GetElementPtrInst *GEP
00495         = GetElementPtrInst::Create(Struct, Idx,
00496                                     "gep_reload_" + outputs[i]->getName());
00497       codeReplacer->getInstList().push_back(GEP);
00498       Output = GEP;
00499     } else {
00500       Output = ReloadOutputs[i];
00501     }
00502     LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
00503     Reloads.push_back(load);
00504     codeReplacer->getInstList().push_back(load);
00505     std::vector<User*> Users(outputs[i]->user_begin(), outputs[i]->user_end());
00506     for (unsigned u = 0, e = Users.size(); u != e; ++u) {
00507       Instruction *inst = cast<Instruction>(Users[u]);
00508       if (!Blocks.count(inst->getParent()))
00509         inst->replaceUsesOfWith(outputs[i], load);
00510     }
00511   }
00512 
00513   // Now we can emit a switch statement using the call as a value.
00514   SwitchInst *TheSwitch =
00515       SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
00516                          codeReplacer, 0, codeReplacer);
00517 
00518   // Since there may be multiple exits from the original region, make the new
00519   // function return an unsigned, switch on that number.  This loop iterates
00520   // over all of the blocks in the extracted region, updating any terminator
00521   // instructions in the to-be-extracted region that branch to blocks that are
00522   // not in the region to be extracted.
00523   std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
00524 
00525   unsigned switchVal = 0;
00526   for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(),
00527          e = Blocks.end(); i != e; ++i) {
00528     TerminatorInst *TI = (*i)->getTerminator();
00529     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
00530       if (!Blocks.count(TI->getSuccessor(i))) {
00531         BasicBlock *OldTarget = TI->getSuccessor(i);
00532         // add a new basic block which returns the appropriate value
00533         BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
00534         if (!NewTarget) {
00535           // If we don't already have an exit stub for this non-extracted
00536           // destination, create one now!
00537           NewTarget = BasicBlock::Create(Context,
00538                                          OldTarget->getName() + ".exitStub",
00539                                          newFunction);
00540           unsigned SuccNum = switchVal++;
00541 
00542           Value *brVal = nullptr;
00543           switch (NumExitBlocks) {
00544           case 0:
00545           case 1: break;  // No value needed.
00546           case 2:         // Conditional branch, return a bool
00547             brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
00548             break;
00549           default:
00550             brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
00551             break;
00552           }
00553 
00554           ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget);
00555 
00556           // Update the switch instruction.
00557           TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
00558                                               SuccNum),
00559                              OldTarget);
00560 
00561           // Restore values just before we exit
00562           Function::arg_iterator OAI = OutputArgBegin;
00563           for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
00564             // For an invoke, the normal destination is the only one that is
00565             // dominated by the result of the invocation
00566             BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
00567 
00568             bool DominatesDef = true;
00569 
00570             if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out])) {
00571               DefBlock = Invoke->getNormalDest();
00572 
00573               // Make sure we are looking at the original successor block, not
00574               // at a newly inserted exit block, which won't be in the dominator
00575               // info.
00576               for (std::map<BasicBlock*, BasicBlock*>::iterator I =
00577                      ExitBlockMap.begin(), E = ExitBlockMap.end(); I != E; ++I)
00578                 if (DefBlock == I->second) {
00579                   DefBlock = I->first;
00580                   break;
00581                 }
00582 
00583               // In the extract block case, if the block we are extracting ends
00584               // with an invoke instruction, make sure that we don't emit a
00585               // store of the invoke value for the unwind block.
00586               if (!DT && DefBlock != OldTarget)
00587                 DominatesDef = false;
00588             }
00589 
00590             if (DT) {
00591               DominatesDef = DT->dominates(DefBlock, OldTarget);
00592               
00593               // If the output value is used by a phi in the target block,
00594               // then we need to test for dominance of the phi's predecessor
00595               // instead.  Unfortunately, this a little complicated since we
00596               // have already rewritten uses of the value to uses of the reload.
00597               BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out], 
00598                                                           OldTarget);
00599               if (pred && DT && DT->dominates(DefBlock, pred))
00600                 DominatesDef = true;
00601             }
00602 
00603             if (DominatesDef) {
00604               if (AggregateArgs) {
00605                 Value *Idx[2];
00606                 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
00607                 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
00608                                           FirstOut+out);
00609                 GetElementPtrInst *GEP =
00610                   GetElementPtrInst::Create(OAI, Idx,
00611                                             "gep_" + outputs[out]->getName(),
00612                                             NTRet);
00613                 new StoreInst(outputs[out], GEP, NTRet);
00614               } else {
00615                 new StoreInst(outputs[out], OAI, NTRet);
00616               }
00617             }
00618             // Advance output iterator even if we don't emit a store
00619             if (!AggregateArgs) ++OAI;
00620           }
00621         }
00622 
00623         // rewrite the original branch instruction with this new target
00624         TI->setSuccessor(i, NewTarget);
00625       }
00626   }
00627 
00628   // Now that we've done the deed, simplify the switch instruction.
00629   Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
00630   switch (NumExitBlocks) {
00631   case 0:
00632     // There are no successors (the block containing the switch itself), which
00633     // means that previously this was the last part of the function, and hence
00634     // this should be rewritten as a `ret'
00635 
00636     // Check if the function should return a value
00637     if (OldFnRetTy->isVoidTy()) {
00638       ReturnInst::Create(Context, nullptr, TheSwitch);  // Return void
00639     } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
00640       // return what we have
00641       ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
00642     } else {
00643       // Otherwise we must have code extracted an unwind or something, just
00644       // return whatever we want.
00645       ReturnInst::Create(Context, 
00646                          Constant::getNullValue(OldFnRetTy), TheSwitch);
00647     }
00648 
00649     TheSwitch->eraseFromParent();
00650     break;
00651   case 1:
00652     // Only a single destination, change the switch into an unconditional
00653     // branch.
00654     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
00655     TheSwitch->eraseFromParent();
00656     break;
00657   case 2:
00658     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
00659                        call, TheSwitch);
00660     TheSwitch->eraseFromParent();
00661     break;
00662   default:
00663     // Otherwise, make the default destination of the switch instruction be one
00664     // of the other successors.
00665     TheSwitch->setCondition(call);
00666     TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
00667     // Remove redundant case
00668     TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
00669     break;
00670   }
00671 }
00672 
00673 void CodeExtractor::moveCodeToFunction(Function *newFunction) {
00674   Function *oldFunc = (*Blocks.begin())->getParent();
00675   Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
00676   Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
00677 
00678   for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(),
00679          e = Blocks.end(); i != e; ++i) {
00680     // Delete the basic block from the old function, and the list of blocks
00681     oldBlocks.remove(*i);
00682 
00683     // Insert this basic block into the new function
00684     newBlocks.push_back(*i);
00685   }
00686 }
00687 
00688 Function *CodeExtractor::extractCodeRegion() {
00689   if (!isEligible())
00690     return nullptr;
00691 
00692   ValueSet inputs, outputs;
00693 
00694   // Assumption: this is a single-entry code region, and the header is the first
00695   // block in the region.
00696   BasicBlock *header = *Blocks.begin();
00697 
00698   // If we have to split PHI nodes or the entry block, do so now.
00699   severSplitPHINodes(header);
00700 
00701   // If we have any return instructions in the region, split those blocks so
00702   // that the return is not in the region.
00703   splitReturnBlocks();
00704 
00705   Function *oldFunction = header->getParent();
00706 
00707   // This takes place of the original loop
00708   BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(), 
00709                                                 "codeRepl", oldFunction,
00710                                                 header);
00711 
00712   // The new function needs a root node because other nodes can branch to the
00713   // head of the region, but the entry node of a function cannot have preds.
00714   BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(), 
00715                                                "newFuncRoot");
00716   newFuncRoot->getInstList().push_back(BranchInst::Create(header));
00717 
00718   // Find inputs to, outputs from the code region.
00719   findInputsOutputs(inputs, outputs);
00720 
00721   SmallPtrSet<BasicBlock *, 1> ExitBlocks;
00722   for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end();
00723        I != E; ++I)
00724     for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
00725       if (!Blocks.count(*SI))
00726         ExitBlocks.insert(*SI);
00727   NumExitBlocks = ExitBlocks.size();
00728 
00729   // Construct new function based on inputs/outputs & add allocas for all defs.
00730   Function *newFunction = constructFunction(inputs, outputs, header,
00731                                             newFuncRoot,
00732                                             codeReplacer, oldFunction,
00733                                             oldFunction->getParent());
00734 
00735   emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
00736 
00737   moveCodeToFunction(newFunction);
00738 
00739   // Loop over all of the PHI nodes in the header block, and change any
00740   // references to the old incoming edge to be the new incoming edge.
00741   for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
00742     PHINode *PN = cast<PHINode>(I);
00743     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00744       if (!Blocks.count(PN->getIncomingBlock(i)))
00745         PN->setIncomingBlock(i, newFuncRoot);
00746   }
00747 
00748   // Look at all successors of the codeReplacer block.  If any of these blocks
00749   // had PHI nodes in them, we need to update the "from" block to be the code
00750   // replacer, not the original block in the extracted region.
00751   std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
00752                                  succ_end(codeReplacer));
00753   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
00754     for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
00755       PHINode *PN = cast<PHINode>(I);
00756       std::set<BasicBlock*> ProcessedPreds;
00757       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00758         if (Blocks.count(PN->getIncomingBlock(i))) {
00759           if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
00760             PN->setIncomingBlock(i, codeReplacer);
00761           else {
00762             // There were multiple entries in the PHI for this block, now there
00763             // is only one, so remove the duplicated entries.
00764             PN->removeIncomingValue(i, false);
00765             --i; --e;
00766           }
00767         }
00768     }
00769 
00770   //cerr << "NEW FUNCTION: " << *newFunction;
00771   //  verifyFunction(*newFunction);
00772 
00773   //  cerr << "OLD FUNCTION: " << *oldFunction;
00774   //  verifyFunction(*oldFunction);
00775 
00776   DEBUG(if (verifyFunction(*newFunction)) 
00777         report_fatal_error("verifyFunction failed!"));
00778   return newFunction;
00779 }