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