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 ai = F->abegin(); 38 while (argno) { ++ai; --argno; } 39 return &*ai; 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 { 83 // Separate incoming values and BasicBlocks as internal/external. We ignore 84 // the case where both the value and BasicBlock are internal, because we don't 85 // need to do a thing. 86 std::vector<unsigned> EValEBB; 87 std::vector<unsigned> EValIBB; 88 std::vector<unsigned> IValEBB; 89 90 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) { 91 Value *phiVal = Phi->getIncomingValue(i); 92 if (Instruction *Inst = dyn_cast<Instruction>(phiVal)) { 93 if (BlocksToExtract.count(Inst->getParent())) { 94 if (!BlocksToExtract.count(Phi->getIncomingBlock(i))) 95 IValEBB.push_back(i); 96 } else { 97 if (BlocksToExtract.count(Phi->getIncomingBlock(i))) 98 EValIBB.push_back(i); 99 else 100 EValEBB.push_back(i); 101 } 102 } else if (Constant *Const = dyn_cast<Constant>(phiVal)) { 103 // Constants are internal, but considered `external' if they are coming 104 // from an external block. 105 if (!BlocksToExtract.count(Phi->getIncomingBlock(i))) 106 EValEBB.push_back(i); 107 } else if (Argument *Arg = dyn_cast<Argument>(phiVal)) { 108 // arguments are external 109 if (BlocksToExtract.count(Phi->getIncomingBlock(i))) 110 EValIBB.push_back(i); 111 else 112 EValEBB.push_back(i); 113 } else { 114 phiVal->dump(); 115 assert(0 && "Unhandled input in a Phi node"); 116 } 117 } 118 119 // Both value and block are external. Need to group all of 120 // these, have an external phi, pass the result as an 121 // argument, and have THIS phi use that result. 122 if (EValEBB.size() > 0) { 123 if (EValEBB.size() == 1) { 124 // Now if it's coming from the newFuncRoot, it's that funky input 125 unsigned phiIdx = EValEBB[0]; 126 if (!dyn_cast<Constant>(Phi->getIncomingValue(phiIdx))) 127 { 128 PhiVal2Arg[Phi].push_back(std::make_pair(phiIdx, inputs.size())); 129 // We can just pass this value in as argument 130 inputs.push_back(Phi->getIncomingValue(phiIdx)); 131 } 132 Phi->setIncomingBlock(phiIdx, newFuncRoot); 133 } else { 134 PHINode *externalPhi = new PHINode(Phi->getType(), "extPhi"); 135 codeReplacer->getInstList().insert(codeReplacer->begin(), externalPhi); 136 for (std::vector<unsigned>::iterator i = EValEBB.begin(), 137 e = EValEBB.end(); i != e; ++i) 138 { 139 externalPhi->addIncoming(Phi->getIncomingValue(*i), 140 Phi->getIncomingBlock(*i)); 141 142 // We make these values invalid instead of deleting them because that 143 // would shift the indices of other values... The fixPhiNodes should 144 // clean these phi nodes up later. 145 Phi->setIncomingValue(*i, 0); 146 Phi->setIncomingBlock(*i, 0); 147 } 148 PhiVal2Arg[Phi].push_back(std::make_pair(Phi->getNumIncomingValues(), 149 inputs.size())); 150 // We can just pass this value in as argument 151 inputs.push_back(externalPhi); 152 } 153 } 154 155 // When the value is external, but block internal... 156 // just pass it in as argument, no change to phi node 157 for (std::vector<unsigned>::iterator i = EValIBB.begin(), 158 e = EValIBB.end(); i != e; ++i) 159 { 160 // rewrite the phi input node to be an argument 161 PhiVal2Arg[Phi].push_back(std::make_pair(*i, inputs.size())); 162 inputs.push_back(Phi->getIncomingValue(*i)); 163 } 164 165 // Value internal, block external 166 // this can happen if we are extracting a part of a loop 167 for (std::vector<unsigned>::iterator i = IValEBB.begin(), 168 e = IValEBB.end(); i != e; ++i) 169 { 170 assert(0 && "Cannot (YET) handle internal values via external blocks"); 171 } 172 } 173 174 175 void CodeExtractor::findInputsOutputs(Values &inputs, 176 Values &outputs, 177 BasicBlock *newHeader, 178 BasicBlock *newRootNode) 179 { 180 for (std::set<BasicBlock*>::const_iterator ci = BlocksToExtract.begin(), 181 ce = BlocksToExtract.end(); ci != ce; ++ci) { 182 BasicBlock *BB = *ci; 183 for (BasicBlock::iterator BBi = BB->begin(), BBe = BB->end(); 184 BBi != BBe; ++BBi) { 185 // If a use is defined outside the region, it's an input. 186 // If a def is used outside the region, it's an output. 187 if (Instruction *I = dyn_cast<Instruction>(&*BBi)) { 188 // If it's a phi node 189 if (PHINode *Phi = dyn_cast<PHINode>(I)) { 190 processPhiNodeInputs(Phi, inputs, newHeader, newRootNode); 191 } else { 192 // All other instructions go through the generic input finder 193 // Loop over the operands of each instruction (inputs) 194 for (User::op_iterator op = I->op_begin(), opE = I->op_end(); 195 op != opE; ++op) { 196 if (Instruction *opI = dyn_cast<Instruction>(op->get())) { 197 // Check if definition of this operand is within the loop 198 if (!BlocksToExtract.count(opI->getParent())) { 199 // add this operand to the inputs 200 inputs.push_back(opI); 201 } 202 } 203 } 204 } 205 206 // Consider uses of this instruction (outputs) 207 for (Value::use_iterator use = I->use_begin(), useE = I->use_end(); 208 use != useE; ++use) { 209 if (Instruction* inst = dyn_cast<Instruction>(*use)) { 210 if (!BlocksToExtract.count(inst->getParent())) { 211 // add this op to the outputs 212 outputs.push_back(I); 213 } 214 } 215 } 216 } /* if */ 217 } /* for: insts */ 218 } /* for: basic blocks */ 219 } 220 221 void CodeExtractor::rewritePhiNodes(Function *F, 222 BasicBlock *newFuncRoot) { 223 // Write any changes that were saved before: use function arguments as inputs 224 for (PhiVal2ArgTy::iterator i = PhiVal2Arg.begin(), e = PhiVal2Arg.end(); 225 i != e; ++i) 226 { 227 PHINode *phi = (*i).first; 228 PhiValChangesTy &values = (*i).second; 229 for (unsigned cIdx = 0, ce = values.size(); cIdx != ce; ++cIdx) 230 { 231 unsigned phiValueIdx = values[cIdx].first, argNum = values[cIdx].second; 232 if (phiValueIdx < phi->getNumIncomingValues()) 233 phi->setIncomingValue(phiValueIdx, getFunctionArg(F, argNum)); 234 else 235 phi->addIncoming(getFunctionArg(F, argNum), newFuncRoot); 236 } 237 } 238 239 // Delete any invalid Phi node inputs that were marked as NULL previously 240 for (PhiVal2ArgTy::iterator i = PhiVal2Arg.begin(), e = PhiVal2Arg.end(); 241 i != e; ++i) 242 { 243 PHINode *phi = (*i).first; 244 for (unsigned idx = 0, end = phi->getNumIncomingValues(); idx != end; ++idx) 245 { 246 if (phi->getIncomingValue(idx) == 0 && phi->getIncomingBlock(idx) == 0) { 247 phi->removeIncomingValue(idx); 248 --idx; 249 --end; 250 } 251 } 252 } 253 254 // We are done with the saved values 255 PhiVal2Arg.clear(); 256 } 257 258 259 /// constructFunction - make a function based on inputs and outputs, as follows: 260 /// f(in0, ..., inN, out0, ..., outN) 261 /// 262 Function *CodeExtractor::constructFunction(const Values &inputs, 263 const Values &outputs, 264 BasicBlock *newRootNode, 265 BasicBlock *newHeader, 266 Function *oldFunction, Module *M) { 267 DEBUG(std::cerr << "inputs: " << inputs.size() << "\n"); 268 DEBUG(std::cerr << "outputs: " << outputs.size() << "\n"); 269 BasicBlock *header = *BlocksToExtract.begin(); 270 271 // This function returns unsigned, outputs will go back by reference. 272 Type *retTy = Type::UShortTy; 273 std::vector<const Type*> paramTy; 274 275 // Add the types of the input values to the function's argument list 276 for (Values::const_iterator i = inputs.begin(), 277 e = inputs.end(); i != e; ++i) { 278 const Value *value = *i; 279 DEBUG(std::cerr << "value used in func: " << value << "\n"); 280 paramTy.push_back(value->getType()); 281 } 282 283 // Add the types of the output values to the function's argument list, but 284 // make them pointer types for scalars 285 for (Values::const_iterator i = outputs.begin(), 286 e = outputs.end(); i != e; ++i) { 287 const Value *value = *i; 288 DEBUG(std::cerr << "instr used in func: " << value << "\n"); 289 const Type *valueType = value->getType(); 290 // Convert scalar types into a pointer of that type 291 if (valueType->isPrimitiveType()) { 292 valueType = PointerType::get(valueType); 293 } 294 paramTy.push_back(valueType); 295 } 296 297 DEBUG(std::cerr << "Function type: " << retTy << " f("); 298 for (std::vector<const Type*>::iterator i = paramTy.begin(), 299 e = paramTy.end(); i != e; ++i) 300 DEBUG(std::cerr << (*i) << ", "); 301 DEBUG(std::cerr << ")\n"); 302 303 const FunctionType *funcType = FunctionType::get(retTy, paramTy, false); 304 305 // Create the new function 306 Function *newFunction = new Function(funcType, 307 GlobalValue::InternalLinkage, 308 oldFunction->getName() + "_code", M); 309 newFunction->getBasicBlockList().push_back(newRootNode); 310 311 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 312 std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end()); 313 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end(); 314 use != useE; ++use) 315 if (Instruction* inst = dyn_cast<Instruction>(*use)) 316 if (BlocksToExtract.count(inst->getParent())) 317 inst->replaceUsesOfWith(inputs[i], getFunctionArg(newFunction, i)); 318 } 319 320 // Rewrite branches to basic blocks outside of the loop to new dummy blocks 321 // within the new function. This must be done before we lose track of which 322 // blocks were originally in the code region. 323 std::vector<User*> Users(header->use_begin(), header->use_end()); 324 for (std::vector<User*>::iterator i = Users.begin(), e = Users.end(); 325 i != e; ++i) { 326 if (BranchInst *inst = dyn_cast<BranchInst>(*i)) { 327 BasicBlock *BB = inst->getParent(); 328 if (!BlocksToExtract.count(BB) && BB->getParent() == oldFunction) { 329 // The BasicBlock which contains the branch is not in the region 330 // modify the branch target to a new block 331 inst->replaceUsesOfWith(header, newHeader); 332 } 333 } 334 } 335 336 return newFunction; 337 } 338 339 void CodeExtractor::moveCodeToFunction(Function *newFunction) 340 { 341 Function *oldFunc = (*BlocksToExtract.begin())->getParent(); 342 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList(); 343 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList(); 344 345 for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(), 346 e = BlocksToExtract.end(); i != e; ++i) { 347 // Delete the basic block from the old function, and the list of blocks 348 oldBlocks.remove(*i); 349 350 // Insert this basic block into the new function 351 newBlocks.push_back(*i); 352 } 353 } 354 355 void 356 CodeExtractor::emitCallAndSwitchStatement(Function *newFunction, 357 BasicBlock *codeReplacer, 358 Values &inputs, 359 Values &outputs) 360 { 361 // Emit a call to the new function, passing allocated memory for outputs and 362 // just plain inputs for non-scalars 363 std::vector<Value*> params; 364 BasicBlock *codeReplacerTail = new BasicBlock("codeReplTail", 365 codeReplacer->getParent()); 366 for (Values::const_iterator i = inputs.begin(), 367 e = inputs.end(); i != e; ++i) 368 params.push_back(*i); 369 for (Values::const_iterator i = outputs.begin(), 370 e = outputs.end(); i != e; ++i) { 371 // Create allocas for scalar outputs 372 if ((*i)->getType()->isPrimitiveType()) { 373 Constant *one = ConstantUInt::get(Type::UIntTy, 1); 374 AllocaInst *alloca = new AllocaInst((*i)->getType(), one); 375 codeReplacer->getInstList().push_back(alloca); 376 params.push_back(alloca); 377 378 LoadInst *load = new LoadInst(alloca, "alloca"); 379 codeReplacerTail->getInstList().push_back(load); 380 std::vector<User*> Users((*i)->use_begin(), (*i)->use_end()); 381 for (std::vector<User*>::iterator use = Users.begin(), useE =Users.end(); 382 use != useE; ++use) { 383 if (Instruction* inst = dyn_cast<Instruction>(*use)) { 384 if (!BlocksToExtract.count(inst->getParent())) { 385 inst->replaceUsesOfWith(*i, load); 386 } 387 } 388 } 389 } else { 390 params.push_back(*i); 391 } 392 } 393 CallInst *call = new CallInst(newFunction, params, "targetBlock"); 394 codeReplacer->getInstList().push_back(call); 395 codeReplacer->getInstList().push_back(new BranchInst(codeReplacerTail)); 396 397 // Now we can emit a switch statement using the call as a value. 398 // FIXME: perhaps instead of default being self BB, it should be a second 399 // dummy block which asserts that the value is not within the range...? 400 //BasicBlock *defaultBlock = new BasicBlock("defaultBlock", oldF); 401 //insert abort() ? 402 //defaultBlock->getInstList().push_back(new BranchInst(codeReplacer)); 403 404 SwitchInst *switchInst = new SwitchInst(call, codeReplacerTail, 405 codeReplacerTail); 406 407 // Since there may be multiple exits from the original region, make the new 408 // function return an unsigned, switch on that number 409 unsigned switchVal = 0; 410 for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(), 411 e = BlocksToExtract.end(); i != e; ++i) { 412 BasicBlock *BB = *i; 413 414 // rewrite the terminator of the original BasicBlock 415 Instruction *term = BB->getTerminator(); 416 if (BranchInst *brInst = dyn_cast<BranchInst>(term)) { 417 418 // Restore values just before we exit 419 // FIXME: Use a GetElementPtr to bunch the outputs in a struct 420 for (unsigned outIdx = 0, outE = outputs.size(); outIdx != outE; ++outIdx) 421 new StoreInst(outputs[outIdx], 422 getFunctionArg(newFunction, outIdx), 423 brInst); 424 425 // Rewrite branches into exits which return a value based on which 426 // exit we take from this function 427 if (brInst->isUnconditional()) { 428 if (!BlocksToExtract.count(brInst->getSuccessor(0))) { 429 ConstantUInt *brVal = ConstantUInt::get(Type::UShortTy, switchVal); 430 ReturnInst *newRet = new ReturnInst(brVal); 431 // add a new target to the switch 432 switchInst->addCase(brVal, brInst->getSuccessor(0)); 433 ++switchVal; 434 // rewrite the branch with a return 435 BasicBlock::iterator ii(brInst); 436 ReplaceInstWithInst(BB->getInstList(), ii, newRet); 437 delete brInst; 438 } 439 } else { 440 // Replace the conditional branch to branch 441 // to two new blocks, each of which returns a different code. 442 for (unsigned idx = 0; idx < 2; ++idx) { 443 BasicBlock *oldTarget = brInst->getSuccessor(idx); 444 if (!BlocksToExtract.count(oldTarget)) { 445 // add a new basic block which returns the appropriate value 446 BasicBlock *newTarget = new BasicBlock("newTarget", newFunction); 447 ConstantUInt *brVal = ConstantUInt::get(Type::UShortTy, switchVal); 448 ReturnInst *newRet = new ReturnInst(brVal); 449 newTarget->getInstList().push_back(newRet); 450 // rewrite the original branch instruction with this new target 451 brInst->setSuccessor(idx, newTarget); 452 // the switch statement knows what to do with this value 453 switchInst->addCase(brVal, oldTarget); 454 ++switchVal; 455 } 456 } 457 } 458 } else if (SwitchInst *swTerm = dyn_cast<SwitchInst>(term)) { 459 460 assert(0 && "Cannot handle switch instructions just yet."); 461 462 } else if (ReturnInst *retTerm = dyn_cast<ReturnInst>(term)) { 463 assert(0 && "Cannot handle return instructions just yet."); 464 // FIXME: what if the terminator is a return!??! 465 // Need to rewrite: add new basic block, move the return there 466 // treat the original as an unconditional branch to that basicblock 467 } else if (InvokeInst *invInst = dyn_cast<InvokeInst>(term)) { 468 assert(0 && "Cannot handle invoke instructions just yet."); 469 } else { 470 assert(0 && "Unrecognized terminator, or badly-formed BasicBlock."); 471 } 472 } 473 } 474 475 476 /// ExtractRegion - Removes a loop from a function, replaces it with a call to 477 /// new function. Returns pointer to the new function. 478 /// 479 /// algorithm: 480 /// 481 /// find inputs and outputs for the region 482 /// 483 /// for inputs: add to function as args, map input instr* to arg# 484 /// for outputs: add allocas for scalars, 485 /// add to func as args, map output instr* to arg# 486 /// 487 /// rewrite func to use argument #s instead of instr* 488 /// 489 /// for each scalar output in the function: at every exit, store intermediate 490 /// computed result back into memory. 491 /// 492 Function *CodeExtractor::ExtractCodeRegion(const std::vector<BasicBlock*> &code) 493 { 494 // 1) Find inputs, outputs 495 // 2) Construct new function 496 // * Add allocas for defs, pass as args by reference 497 // * Pass in uses as args 498 // 3) Move code region, add call instr to func 499 // 500 BlocksToExtract.insert(code.begin(), code.end()); 501 502 Values inputs, outputs; 503 504 // Assumption: this is a single-entry code region, and the header is the first 505 // block in the region. FIXME: is this true for a list of blocks from a 506 // natural function? 507 BasicBlock *header = code[0]; 508 Function *oldFunction = header->getParent(); 509 Module *module = oldFunction->getParent(); 510 511 // This takes place of the original loop 512 BasicBlock *codeReplacer = new BasicBlock("codeRepl", oldFunction); 513 514 // The new function needs a root node because other nodes can branch to the 515 // head of the loop, and the root cannot have predecessors 516 BasicBlock *newFuncRoot = new BasicBlock("newFuncRoot"); 517 newFuncRoot->getInstList().push_back(new BranchInst(header)); 518 519 // Find inputs to, outputs from the code region 520 // 521 // If one of the inputs is coming from a different basic block and it's in a 522 // phi node, we need to rewrite the phi node: 523 // 524 // * All the inputs which involve basic blocks OUTSIDE of this region go into 525 // a NEW phi node that takes care of finding which value really came in. 526 // The result of this phi is passed to the function as an argument. 527 // 528 // * All the other phi values stay. 529 // 530 // FIXME: PHI nodes' incoming blocks aren't being rewritten to accomodate for 531 // blocks moving to a new function. 532 // SOLUTION: move Phi nodes out of the loop header into the codeReplacer, pass 533 // the values as parameters to the function 534 findInputsOutputs(inputs, outputs, codeReplacer, newFuncRoot); 535 536 // Step 2: Construct new function based on inputs/outputs, 537 // Add allocas for all defs 538 Function *newFunction = constructFunction(inputs, outputs, newFuncRoot, 539 codeReplacer, oldFunction, module); 540 541 rewritePhiNodes(newFunction, newFuncRoot); 542 543 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs); 544 545 moveCodeToFunction(newFunction); 546 547 DEBUG(if (verifyFunction(*newFunction)) abort()); 548 return newFunction; 549 } 550 551 /// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new 552 /// function 553 /// 554 Function* llvm::ExtractCodeRegion(const std::vector<BasicBlock*> &code) { 555 return CodeExtractor().ExtractCodeRegion(code); 556 } 557 558 /// ExtractBasicBlock - slurp a natural loop into a brand new function 559 /// 560 Function* llvm::ExtractLoop(Loop *L) { 561 return CodeExtractor().ExtractCodeRegion(L->getBlocks()); 562 } 563 564 /// ExtractBasicBlock - slurp a basic block into a brand new function 565 /// 566 Function* llvm::ExtractBasicBlock(BasicBlock *BB) { 567 std::vector<BasicBlock*> Blocks; 568 Blocks.push_back(BB); 569 return CodeExtractor().ExtractCodeRegion(Blocks); 570 } 571