1 //===- CodeExtractor.cpp - Pull code region into a new function -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file was developed by the LLVM research group and is distributed under 6 // the University of Illinois Open Source 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 16 #include "llvm/BasicBlock.h" 17 #include "llvm/Constants.h" 18 #include "llvm/DerivedTypes.h" 19 #include "llvm/Instructions.h" 20 #include "llvm/Module.h" 21 #include "llvm/Pass.h" 22 #include "llvm/Analysis/LoopInfo.h" 23 #include "llvm/Analysis/Verifier.h" 24 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 25 #include "llvm/Transforms/Utils/FunctionUtils.h" 26 #include "Support/Debug.h" 27 #include "Support/StringExtras.h" 28 #include <algorithm> 29 #include <set> 30 using namespace llvm; 31 32 namespace { 33 34 /// getFunctionArg - Return a pointer to F's ARGNOth argument. 35 /// 36 Argument *getFunctionArg(Function *F, unsigned argno) { 37 Function::aiterator I = F->abegin(); 38 std::advance(I, argno); 39 return I; 40 } 41 42 struct CodeExtractor { 43 typedef std::vector<Value*> Values; 44 typedef std::vector<std::pair<unsigned, unsigned> > PhiValChangesTy; 45 typedef std::map<PHINode*, PhiValChangesTy> PhiVal2ArgTy; 46 PhiVal2ArgTy PhiVal2Arg; 47 std::set<BasicBlock*> BlocksToExtract; 48 public: 49 Function *ExtractCodeRegion(const std::vector<BasicBlock*> &code); 50 51 private: 52 void findInputsOutputs(Values &inputs, Values &outputs, 53 BasicBlock *newHeader, 54 BasicBlock *newRootNode); 55 56 void processPhiNodeInputs(PHINode *Phi, 57 Values &inputs, 58 BasicBlock *newHeader, 59 BasicBlock *newRootNode); 60 61 void rewritePhiNodes(Function *F, BasicBlock *newFuncRoot); 62 63 Function *constructFunction(const Values &inputs, 64 const Values &outputs, 65 BasicBlock *newRootNode, BasicBlock *newHeader, 66 Function *oldFunction, Module *M); 67 68 void moveCodeToFunction(Function *newFunction); 69 70 void emitCallAndSwitchStatement(Function *newFunction, 71 BasicBlock *newHeader, 72 Values &inputs, 73 Values &outputs); 74 75 }; 76 } 77 78 void CodeExtractor::processPhiNodeInputs(PHINode *Phi, 79 Values &inputs, 80 BasicBlock *codeReplacer, 81 BasicBlock *newFuncRoot) { 82 // Separate incoming values and BasicBlocks as internal/external. We ignore 83 // the case where both the value and BasicBlock are internal, because we don't 84 // need to do a thing. 85 std::vector<unsigned> EValEBB; 86 std::vector<unsigned> EValIBB; 87 std::vector<unsigned> IValEBB; 88 89 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) { 90 Value *phiVal = Phi->getIncomingValue(i); 91 if (Instruction *Inst = dyn_cast<Instruction>(phiVal)) { 92 if (BlocksToExtract.count(Inst->getParent())) { 93 if (!BlocksToExtract.count(Phi->getIncomingBlock(i))) 94 IValEBB.push_back(i); 95 } else { 96 if (BlocksToExtract.count(Phi->getIncomingBlock(i))) 97 EValIBB.push_back(i); 98 else 99 EValEBB.push_back(i); 100 } 101 } else if (Argument *Arg = dyn_cast<Argument>(phiVal)) { 102 // arguments are external 103 if (BlocksToExtract.count(Phi->getIncomingBlock(i))) 104 EValIBB.push_back(i); 105 else 106 EValEBB.push_back(i); 107 } else { 108 // Globals/Constants are internal, but considered `external' if they are 109 // coming from an external block. 110 if (!BlocksToExtract.count(Phi->getIncomingBlock(i))) 111 EValEBB.push_back(i); 112 } 113 } 114 115 // Both value and block are external. Need to group all of these, have an 116 // external phi, pass the result as an argument, and have THIS phi use that 117 // result. 118 if (EValEBB.size() > 0) { 119 if (EValEBB.size() == 1) { 120 // Now if it's coming from the newFuncRoot, it's that funky input 121 unsigned phiIdx = EValEBB[0]; 122 if (!isa<Constant>(Phi->getIncomingValue(phiIdx))) { 123 PhiVal2Arg[Phi].push_back(std::make_pair(phiIdx, inputs.size())); 124 // We can just pass this value in as argument 125 inputs.push_back(Phi->getIncomingValue(phiIdx)); 126 } 127 Phi->setIncomingBlock(phiIdx, newFuncRoot); 128 } else { 129 PHINode *externalPhi = new PHINode(Phi->getType(), "extPhi"); 130 codeReplacer->getInstList().insert(codeReplacer->begin(), externalPhi); 131 for (std::vector<unsigned>::iterator i = EValEBB.begin(), 132 e = EValEBB.end(); i != e; ++i) { 133 externalPhi->addIncoming(Phi->getIncomingValue(*i), 134 Phi->getIncomingBlock(*i)); 135 136 // We make these values invalid instead of deleting them because that 137 // would shift the indices of other values... The fixPhiNodes should 138 // clean these phi nodes up later. 139 Phi->setIncomingValue(*i, 0); 140 Phi->setIncomingBlock(*i, 0); 141 } 142 PhiVal2Arg[Phi].push_back(std::make_pair(Phi->getNumIncomingValues(), 143 inputs.size())); 144 // We can just pass this value in as argument 145 inputs.push_back(externalPhi); 146 } 147 } 148 149 // When the value is external, but block internal... just pass it in as 150 // argument, no change to phi node 151 for (std::vector<unsigned>::iterator i = EValIBB.begin(), 152 e = EValIBB.end(); i != e; ++i) { 153 // rewrite the phi input node to be an argument 154 PhiVal2Arg[Phi].push_back(std::make_pair(*i, inputs.size())); 155 inputs.push_back(Phi->getIncomingValue(*i)); 156 } 157 158 // Value internal, block external this can happen if we are extracting a part 159 // of a loop. 160 for (std::vector<unsigned>::iterator i = IValEBB.begin(), 161 e = IValEBB.end(); i != e; ++i) { 162 assert(0 && "Cannot (YET) handle internal values via external blocks"); 163 } 164 } 165 166 167 void CodeExtractor::findInputsOutputs(Values &inputs, Values &outputs, 168 BasicBlock *newHeader, 169 BasicBlock *newRootNode) { 170 for (std::set<BasicBlock*>::const_iterator ci = BlocksToExtract.begin(), 171 ce = BlocksToExtract.end(); ci != ce; ++ci) { 172 BasicBlock *BB = *ci; 173 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 174 // If a used value is defined outside the region, it's an input. If an 175 // instruction is used outside the region, it's an output. 176 if (PHINode *Phi = dyn_cast<PHINode>(I)) { 177 processPhiNodeInputs(Phi, inputs, newHeader, newRootNode); 178 } else { 179 // All other instructions go through the generic input finder 180 // Loop over the operands of each instruction (inputs) 181 for (User::op_iterator op = I->op_begin(), opE = I->op_end(); 182 op != opE; ++op) 183 if (Instruction *opI = dyn_cast<Instruction>(*op)) { 184 // Check if definition of this operand is within the loop 185 if (!BlocksToExtract.count(opI->getParent())) 186 inputs.push_back(opI); 187 } else if (isa<Argument>(*op)) { 188 inputs.push_back(*op); 189 } 190 } 191 192 // Consider uses of this instruction (outputs) 193 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 194 UI != E; ++UI) 195 if (!BlocksToExtract.count(cast<Instruction>(*UI)->getParent())) 196 outputs.push_back(*UI); 197 } // for: insts 198 } // for: basic blocks 199 } 200 201 void CodeExtractor::rewritePhiNodes(Function *F, 202 BasicBlock *newFuncRoot) { 203 // Write any changes that were saved before: use function arguments as inputs 204 for (PhiVal2ArgTy::iterator i = PhiVal2Arg.begin(), e = PhiVal2Arg.end(); 205 i != e; ++i) { 206 PHINode *phi = i->first; 207 PhiValChangesTy &values = i->second; 208 for (unsigned cIdx = 0, ce = values.size(); cIdx != ce; ++cIdx) 209 { 210 unsigned phiValueIdx = values[cIdx].first, argNum = values[cIdx].second; 211 if (phiValueIdx < phi->getNumIncomingValues()) 212 phi->setIncomingValue(phiValueIdx, getFunctionArg(F, argNum)); 213 else 214 phi->addIncoming(getFunctionArg(F, argNum), newFuncRoot); 215 } 216 } 217 218 // Delete any invalid Phi node inputs that were marked as NULL previously 219 for (PhiVal2ArgTy::iterator i = PhiVal2Arg.begin(), e = PhiVal2Arg.end(); 220 i != e; ++i) { 221 PHINode *phi = i->first; 222 for (unsigned idx = 0, end = phi->getNumIncomingValues(); idx != end; ++idx) 223 { 224 if (phi->getIncomingValue(idx) == 0 && phi->getIncomingBlock(idx) == 0) { 225 phi->removeIncomingValue(idx); 226 --idx; 227 --end; 228 } 229 } 230 } 231 232 // We are done with the saved values 233 PhiVal2Arg.clear(); 234 } 235 236 237 /// constructFunction - make a function based on inputs and outputs, as follows: 238 /// f(in0, ..., inN, out0, ..., outN) 239 /// 240 Function *CodeExtractor::constructFunction(const Values &inputs, 241 const Values &outputs, 242 BasicBlock *newRootNode, 243 BasicBlock *newHeader, 244 Function *oldFunction, Module *M) { 245 DEBUG(std::cerr << "inputs: " << inputs.size() << "\n"); 246 DEBUG(std::cerr << "outputs: " << outputs.size() << "\n"); 247 BasicBlock *header = *BlocksToExtract.begin(); 248 249 // This function returns unsigned, outputs will go back by reference. 250 Type *retTy = Type::UShortTy; 251 std::vector<const Type*> paramTy; 252 253 // Add the types of the input values to the function's argument list 254 for (Values::const_iterator i = inputs.begin(), 255 e = inputs.end(); i != e; ++i) { 256 const Value *value = *i; 257 DEBUG(std::cerr << "value used in func: " << value << "\n"); 258 paramTy.push_back(value->getType()); 259 } 260 261 // Add the types of the output values to the function's argument list, but 262 // make them pointer types for scalars 263 for (Values::const_iterator i = outputs.begin(), 264 e = outputs.end(); i != e; ++i) { 265 const Value *value = *i; 266 DEBUG(std::cerr << "instr used in func: " << value << "\n"); 267 const Type *valueType = value->getType(); 268 // Convert scalar types into a pointer of that type 269 if (valueType->isPrimitiveType()) { 270 valueType = PointerType::get(valueType); 271 } 272 paramTy.push_back(valueType); 273 } 274 275 DEBUG(std::cerr << "Function type: " << retTy << " f("); 276 for (std::vector<const Type*>::iterator i = paramTy.begin(), 277 e = paramTy.end(); i != e; ++i) 278 DEBUG(std::cerr << *i << ", "); 279 DEBUG(std::cerr << ")\n"); 280 281 const FunctionType *funcType = FunctionType::get(retTy, paramTy, false); 282 283 // Create the new function 284 Function *newFunction = new Function(funcType, 285 GlobalValue::InternalLinkage, 286 oldFunction->getName() + "_code", M); 287 newFunction->getBasicBlockList().push_back(newRootNode); 288 289 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 290 std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end()); 291 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end(); 292 use != useE; ++use) 293 if (Instruction* inst = dyn_cast<Instruction>(*use)) 294 if (BlocksToExtract.count(inst->getParent())) 295 inst->replaceUsesOfWith(inputs[i], getFunctionArg(newFunction, i)); 296 } 297 298 // Rewrite branches to basic blocks outside of the loop to new dummy blocks 299 // within the new function. This must be done before we lose track of which 300 // blocks were originally in the code region. 301 std::vector<User*> Users(header->use_begin(), header->use_end()); 302 for (std::vector<User*>::iterator i = Users.begin(), e = Users.end(); 303 i != e; ++i) { 304 if (BranchInst *inst = dyn_cast<BranchInst>(*i)) { 305 BasicBlock *BB = inst->getParent(); 306 if (!BlocksToExtract.count(BB) && BB->getParent() == oldFunction) { 307 // The BasicBlock which contains the branch is not in the region 308 // modify the branch target to a new block 309 inst->replaceUsesOfWith(header, newHeader); 310 } 311 } 312 } 313 314 return newFunction; 315 } 316 317 void CodeExtractor::moveCodeToFunction(Function *newFunction) { 318 Function *oldFunc = (*BlocksToExtract.begin())->getParent(); 319 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList(); 320 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList(); 321 322 for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(), 323 e = BlocksToExtract.end(); i != e; ++i) { 324 // Delete the basic block from the old function, and the list of blocks 325 oldBlocks.remove(*i); 326 327 // Insert this basic block into the new function 328 newBlocks.push_back(*i); 329 } 330 } 331 332 void 333 CodeExtractor::emitCallAndSwitchStatement(Function *newFunction, 334 BasicBlock *codeReplacer, 335 Values &inputs, 336 Values &outputs) 337 { 338 // Emit a call to the new function, passing allocated memory for outputs and 339 // just plain inputs for non-scalars 340 std::vector<Value*> params(inputs); 341 342 for (Values::const_iterator i = outputs.begin(), e = outputs.end(); i != e; 343 ++i) { 344 Value *Output = *i; 345 // Create allocas for scalar outputs 346 if (Output->getType()->isPrimitiveType()) { 347 AllocaInst *alloca = 348 new AllocaInst((*i)->getType(), 0, Output->getName()+".loc", 349 codeReplacer->getParent()->begin()->begin()); 350 params.push_back(alloca); 351 352 LoadInst *load = new LoadInst(alloca, Output->getName()+".reload"); 353 codeReplacer->getInstList().push_back(load); 354 std::vector<User*> Users((*i)->use_begin(), (*i)->use_end()); 355 for (std::vector<User*>::iterator use = Users.begin(), useE =Users.end(); 356 use != useE; ++use) { 357 if (Instruction* inst = dyn_cast<Instruction>(*use)) { 358 if (!BlocksToExtract.count(inst->getParent())) 359 inst->replaceUsesOfWith(*i, load); 360 } 361 } 362 } else { 363 params.push_back(*i); 364 } 365 } 366 367 CallInst *call = new CallInst(newFunction, params, "targetBlock"); 368 codeReplacer->getInstList().push_front(call); 369 370 // Now we can emit a switch statement using the call as a value. 371 SwitchInst *TheSwitch = new SwitchInst(call, codeReplacer, codeReplacer); 372 373 // Since there may be multiple exits from the original region, make the new 374 // function return an unsigned, switch on that number. This loop iterates 375 // over all of the blocks in the extracted region, updating any terminator 376 // instructions in the to-be-extracted region that branch to blocks that are 377 // not in the region to be extracted. 378 std::map<BasicBlock*, BasicBlock*> ExitBlockMap; 379 380 unsigned switchVal = 0; 381 for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(), 382 e = BlocksToExtract.end(); i != e; ++i) { 383 TerminatorInst *TI = (*i)->getTerminator(); 384 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 385 if (!BlocksToExtract.count(TI->getSuccessor(i))) { 386 BasicBlock *OldTarget = TI->getSuccessor(i); 387 // add a new basic block which returns the appropriate value 388 BasicBlock *&NewTarget = ExitBlockMap[OldTarget]; 389 if (!NewTarget) { 390 // If we don't already have an exit stub for this non-extracted 391 // destination, create one now! 392 NewTarget = new BasicBlock(OldTarget->getName() + ".exitStub", 393 newFunction); 394 395 ConstantUInt *brVal = ConstantUInt::get(Type::UShortTy, switchVal++); 396 ReturnInst *NTRet = new ReturnInst(brVal, NewTarget); 397 398 // Update the switch instruction. 399 TheSwitch->addCase(brVal, OldTarget); 400 401 // Restore values just before we exit 402 // FIXME: Use a GetElementPtr to bunch the outputs in a struct 403 for (unsigned out = 0, e = outputs.size(); out != e; ++out) 404 new StoreInst(outputs[out], getFunctionArg(newFunction, out),NTRet); 405 } 406 407 // rewrite the original branch instruction with this new target 408 TI->setSuccessor(i, NewTarget); 409 } 410 } 411 412 // Now that we've done the deed, make the default destination of the switch 413 // instruction be one of the exit blocks of the region. 414 if (TheSwitch->getNumSuccessors() > 1) { 415 // FIXME: this is broken w.r.t. PHI nodes, but the old code was more broken. 416 // This edge is not traversable. 417 TheSwitch->setSuccessor(0, TheSwitch->getSuccessor(1)); 418 } 419 } 420 421 422 /// ExtractRegion - Removes a loop from a function, replaces it with a call to 423 /// new function. Returns pointer to the new function. 424 /// 425 /// algorithm: 426 /// 427 /// find inputs and outputs for the region 428 /// 429 /// for inputs: add to function as args, map input instr* to arg# 430 /// for outputs: add allocas for scalars, 431 /// add to func as args, map output instr* to arg# 432 /// 433 /// rewrite func to use argument #s instead of instr* 434 /// 435 /// for each scalar output in the function: at every exit, store intermediate 436 /// computed result back into memory. 437 /// 438 Function *CodeExtractor::ExtractCodeRegion(const std::vector<BasicBlock*> &code) 439 { 440 // 1) Find inputs, outputs 441 // 2) Construct new function 442 // * Add allocas for defs, pass as args by reference 443 // * Pass in uses as args 444 // 3) Move code region, add call instr to func 445 // 446 BlocksToExtract.insert(code.begin(), code.end()); 447 448 Values inputs, outputs; 449 450 // Assumption: this is a single-entry code region, and the header is the first 451 // block in the region. 452 BasicBlock *header = code[0]; 453 for (unsigned i = 1, e = code.size(); i != e; ++i) 454 for (pred_iterator PI = pred_begin(code[i]), E = pred_end(code[i]); 455 PI != E; ++PI) 456 assert(BlocksToExtract.count(*PI) && 457 "No blocks in this region may have entries from outside the region" 458 " except for the first block!"); 459 460 Function *oldFunction = header->getParent(); 461 462 // This takes place of the original loop 463 BasicBlock *codeReplacer = new BasicBlock("codeRepl", oldFunction); 464 465 // The new function needs a root node because other nodes can branch to the 466 // head of the loop, and the root cannot have predecessors 467 BasicBlock *newFuncRoot = new BasicBlock("newFuncRoot"); 468 newFuncRoot->getInstList().push_back(new BranchInst(header)); 469 470 // Find inputs to, outputs from the code region 471 // 472 // If one of the inputs is coming from a different basic block and it's in a 473 // phi node, we need to rewrite the phi node: 474 // 475 // * All the inputs which involve basic blocks OUTSIDE of this region go into 476 // a NEW phi node that takes care of finding which value really came in. 477 // The result of this phi is passed to the function as an argument. 478 // 479 // * All the other phi values stay. 480 // 481 // FIXME: PHI nodes' incoming blocks aren't being rewritten to accomodate for 482 // blocks moving to a new function. 483 // SOLUTION: move Phi nodes out of the loop header into the codeReplacer, pass 484 // the values as parameters to the function 485 findInputsOutputs(inputs, outputs, codeReplacer, newFuncRoot); 486 487 // Step 2: Construct new function based on inputs/outputs, 488 // Add allocas for all defs 489 Function *newFunction = constructFunction(inputs, outputs, newFuncRoot, 490 codeReplacer, oldFunction, 491 oldFunction->getParent()); 492 493 rewritePhiNodes(newFunction, newFuncRoot); 494 495 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs); 496 497 moveCodeToFunction(newFunction); 498 499 DEBUG(if (verifyFunction(*newFunction)) abort()); 500 return newFunction; 501 } 502 503 /// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new 504 /// function 505 /// 506 Function* llvm::ExtractCodeRegion(const std::vector<BasicBlock*> &code) { 507 return CodeExtractor().ExtractCodeRegion(code); 508 } 509 510 /// ExtractBasicBlock - slurp a natural loop into a brand new function 511 /// 512 Function* llvm::ExtractLoop(Loop *L) { 513 return CodeExtractor().ExtractCodeRegion(L->getBlocks()); 514 } 515 516 /// ExtractBasicBlock - slurp a basic block into a brand new function 517 /// 518 Function* llvm::ExtractBasicBlock(BasicBlock *BB) { 519 std::vector<BasicBlock*> Blocks; 520 Blocks.push_back(BB); 521 return CodeExtractor().ExtractCodeRegion(Blocks); 522 } 523