1 //===- CodeExtractor.cpp - Pull code region into a new function -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the interface to tear out a code region, such as an 11 // individual loop or a parallel section, into a new function, replacing it with 12 // a call to the new function. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/Transforms/Utils/CodeExtractor.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SetVector.h" 19 #include "llvm/ADT/StringExtras.h" 20 #include "llvm/Analysis/BlockFrequencyInfo.h" 21 #include "llvm/Analysis/BlockFrequencyInfoImpl.h" 22 #include "llvm/Analysis/BranchProbabilityInfo.h" 23 #include "llvm/Analysis/LoopInfo.h" 24 #include "llvm/Analysis/RegionInfo.h" 25 #include "llvm/Analysis/RegionIterator.h" 26 #include "llvm/IR/Constants.h" 27 #include "llvm/IR/DerivedTypes.h" 28 #include "llvm/IR/Dominators.h" 29 #include "llvm/IR/Instructions.h" 30 #include "llvm/IR/IntrinsicInst.h" 31 #include "llvm/IR/Intrinsics.h" 32 #include "llvm/IR/LLVMContext.h" 33 #include "llvm/IR/MDBuilder.h" 34 #include "llvm/IR/Module.h" 35 #include "llvm/IR/Verifier.h" 36 #include "llvm/Pass.h" 37 #include "llvm/Support/BlockFrequency.h" 38 #include "llvm/Support/CommandLine.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Support/ErrorHandling.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 43 #include <algorithm> 44 #include <set> 45 using namespace llvm; 46 47 #define DEBUG_TYPE "code-extractor" 48 49 // Provide a command-line option to aggregate function arguments into a struct 50 // for functions produced by the code extractor. This is useful when converting 51 // extracted functions to pthread-based code, as only one argument (void*) can 52 // be passed in to pthread_create(). 53 static cl::opt<bool> 54 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden, 55 cl::desc("Aggregate arguments to code-extracted functions")); 56 57 /// \brief Test whether a block is valid for extraction. 58 bool CodeExtractor::isBlockValidForExtraction(const BasicBlock &BB) { 59 // Landing pads must be in the function where they were inserted for cleanup. 60 if (BB.isEHPad()) 61 return false; 62 63 // Don't hoist code containing allocas, invokes, or vastarts. 64 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) { 65 if (isa<AllocaInst>(I) || isa<InvokeInst>(I)) 66 return false; 67 if (const CallInst *CI = dyn_cast<CallInst>(I)) 68 if (const Function *F = CI->getCalledFunction()) 69 if (F->getIntrinsicID() == Intrinsic::vastart) 70 return false; 71 } 72 73 return true; 74 } 75 76 /// \brief Build a set of blocks to extract if the input blocks are viable. 77 static SetVector<BasicBlock *> 78 buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT) { 79 assert(!BBs.empty() && "The set of blocks to extract must be non-empty"); 80 SetVector<BasicBlock *> Result; 81 82 // Loop over the blocks, adding them to our set-vector, and aborting with an 83 // empty set if we encounter invalid blocks. 84 for (BasicBlock *BB : BBs) { 85 86 // If this block is dead, don't process it. 87 if (DT && !DT->isReachableFromEntry(BB)) 88 continue; 89 90 if (!Result.insert(BB)) 91 llvm_unreachable("Repeated basic blocks in extraction input"); 92 if (!CodeExtractor::isBlockValidForExtraction(*BB)) { 93 Result.clear(); 94 return Result; 95 } 96 } 97 98 #ifndef NDEBUG 99 for (SetVector<BasicBlock *>::iterator I = std::next(Result.begin()), 100 E = Result.end(); 101 I != E; ++I) 102 for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I); 103 PI != PE; ++PI) 104 assert(Result.count(*PI) && 105 "No blocks in this region may have entries from outside the region" 106 " except for the first block!"); 107 #endif 108 109 return Result; 110 } 111 112 CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, 113 bool AggregateArgs, BlockFrequencyInfo *BFI, 114 BranchProbabilityInfo *BPI) 115 : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), 116 BPI(BPI), Blocks(buildExtractionBlockSet(BBs, DT)), NumExitBlocks(~0U) {} 117 118 CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs, 119 BlockFrequencyInfo *BFI, 120 BranchProbabilityInfo *BPI) 121 : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), 122 BPI(BPI), Blocks(buildExtractionBlockSet(L.getBlocks(), &DT)), 123 NumExitBlocks(~0U) {} 124 125 /// definedInRegion - Return true if the specified value is defined in the 126 /// extracted region. 127 static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) { 128 if (Instruction *I = dyn_cast<Instruction>(V)) 129 if (Blocks.count(I->getParent())) 130 return true; 131 return false; 132 } 133 134 /// definedInCaller - Return true if the specified value is defined in the 135 /// function being code extracted, but not in the region being extracted. 136 /// These values must be passed in as live-ins to the function. 137 static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) { 138 if (isa<Argument>(V)) return true; 139 if (Instruction *I = dyn_cast<Instruction>(V)) 140 if (!Blocks.count(I->getParent())) 141 return true; 142 return false; 143 } 144 145 void CodeExtractor::findAllocas(ValueSet &SinkCands) const { 146 Function *Func = (*Blocks.begin())->getParent(); 147 for (BasicBlock &BB : *Func) { 148 if (Blocks.count(&BB)) 149 continue; 150 for (Instruction &II : BB) { 151 auto *AI = dyn_cast<AllocaInst>(&II); 152 if (!AI) 153 continue; 154 155 // Returns true if matching life time markers are found within 156 // the outlined region. 157 auto GetLifeTimeMarkers = [&](Instruction *Addr) { 158 Instruction *LifeStart = nullptr, *LifeEnd = nullptr; 159 for (User *U : Addr->users()) { 160 if (!definedInRegion(Blocks, U)) 161 return false; 162 163 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U); 164 if (IntrInst) { 165 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) 166 LifeStart = IntrInst; 167 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) 168 LifeEnd = IntrInst; 169 } 170 } 171 return LifeStart && LifeEnd; 172 }; 173 174 if (GetLifeTimeMarkers(AI)) { 175 SinkCands.insert(AI); 176 continue; 177 } 178 179 // Follow the bitcast: 180 Instruction *MarkerAddr = nullptr; 181 for (User *U : AI->users()) { 182 if (U->stripPointerCasts() == AI) { 183 Instruction *Bitcast = cast<Instruction>(U); 184 if (GetLifeTimeMarkers(Bitcast)) { 185 MarkerAddr = Bitcast; 186 continue; 187 } 188 } 189 if (!definedInRegion(Blocks, U)) { 190 MarkerAddr = nullptr; 191 break; 192 } 193 } 194 if (MarkerAddr) { 195 if (!definedInRegion(Blocks, MarkerAddr)) 196 SinkCands.insert(MarkerAddr); 197 SinkCands.insert(AI); 198 } 199 } 200 } 201 } 202 203 void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs, 204 const ValueSet &SinkCands) const { 205 206 for (BasicBlock *BB : Blocks) { 207 // If a used value is defined outside the region, it's an input. If an 208 // instruction is used outside the region, it's an output. 209 for (Instruction &II : *BB) { 210 for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE; 211 ++OI) { 212 Value *V = *OI; 213 if (!SinkCands.count(V) && definedInCaller(Blocks, V)) 214 Inputs.insert(V); 215 } 216 217 for (User *U : II.users()) 218 if (!definedInRegion(Blocks, U)) { 219 Outputs.insert(&II); 220 break; 221 } 222 } 223 } 224 } 225 226 /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the 227 /// region, we need to split the entry block of the region so that the PHI node 228 /// is easier to deal with. 229 void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) { 230 unsigned NumPredsFromRegion = 0; 231 unsigned NumPredsOutsideRegion = 0; 232 233 if (Header != &Header->getParent()->getEntryBlock()) { 234 PHINode *PN = dyn_cast<PHINode>(Header->begin()); 235 if (!PN) return; // No PHI nodes. 236 237 // If the header node contains any PHI nodes, check to see if there is more 238 // than one entry from outside the region. If so, we need to sever the 239 // header block into two. 240 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 241 if (Blocks.count(PN->getIncomingBlock(i))) 242 ++NumPredsFromRegion; 243 else 244 ++NumPredsOutsideRegion; 245 246 // If there is one (or fewer) predecessor from outside the region, we don't 247 // need to do anything special. 248 if (NumPredsOutsideRegion <= 1) return; 249 } 250 251 // Otherwise, we need to split the header block into two pieces: one 252 // containing PHI nodes merging values from outside of the region, and a 253 // second that contains all of the code for the block and merges back any 254 // incoming values from inside of the region. 255 BasicBlock *NewBB = llvm::SplitBlock(Header, Header->getFirstNonPHI(), DT); 256 257 // We only want to code extract the second block now, and it becomes the new 258 // header of the region. 259 BasicBlock *OldPred = Header; 260 Blocks.remove(OldPred); 261 Blocks.insert(NewBB); 262 Header = NewBB; 263 264 // Okay, now we need to adjust the PHI nodes and any branches from within the 265 // region to go to the new header block instead of the old header block. 266 if (NumPredsFromRegion) { 267 PHINode *PN = cast<PHINode>(OldPred->begin()); 268 // Loop over all of the predecessors of OldPred that are in the region, 269 // changing them to branch to NewBB instead. 270 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 271 if (Blocks.count(PN->getIncomingBlock(i))) { 272 TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator(); 273 TI->replaceUsesOfWith(OldPred, NewBB); 274 } 275 276 // Okay, everything within the region is now branching to the right block, we 277 // just have to update the PHI nodes now, inserting PHI nodes into NewBB. 278 BasicBlock::iterator AfterPHIs; 279 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) { 280 PHINode *PN = cast<PHINode>(AfterPHIs); 281 // Create a new PHI node in the new region, which has an incoming value 282 // from OldPred of PN. 283 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion, 284 PN->getName() + ".ce", &NewBB->front()); 285 PN->replaceAllUsesWith(NewPN); 286 NewPN->addIncoming(PN, OldPred); 287 288 // Loop over all of the incoming value in PN, moving them to NewPN if they 289 // are from the extracted region. 290 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) { 291 if (Blocks.count(PN->getIncomingBlock(i))) { 292 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i)); 293 PN->removeIncomingValue(i); 294 --i; 295 } 296 } 297 } 298 } 299 } 300 301 void CodeExtractor::splitReturnBlocks() { 302 for (BasicBlock *Block : Blocks) 303 if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) { 304 BasicBlock *New = 305 Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret"); 306 if (DT) { 307 // Old dominates New. New node dominates all other nodes dominated 308 // by Old. 309 DomTreeNode *OldNode = DT->getNode(Block); 310 SmallVector<DomTreeNode *, 8> Children(OldNode->begin(), 311 OldNode->end()); 312 313 DomTreeNode *NewNode = DT->addNewBlock(New, Block); 314 315 for (DomTreeNode *I : Children) 316 DT->changeImmediateDominator(I, NewNode); 317 } 318 } 319 } 320 321 /// constructFunction - make a function based on inputs and outputs, as follows: 322 /// f(in0, ..., inN, out0, ..., outN) 323 /// 324 Function *CodeExtractor::constructFunction(const ValueSet &inputs, 325 const ValueSet &outputs, 326 BasicBlock *header, 327 BasicBlock *newRootNode, 328 BasicBlock *newHeader, 329 Function *oldFunction, 330 Module *M) { 331 DEBUG(dbgs() << "inputs: " << inputs.size() << "\n"); 332 DEBUG(dbgs() << "outputs: " << outputs.size() << "\n"); 333 334 // This function returns unsigned, outputs will go back by reference. 335 switch (NumExitBlocks) { 336 case 0: 337 case 1: RetTy = Type::getVoidTy(header->getContext()); break; 338 case 2: RetTy = Type::getInt1Ty(header->getContext()); break; 339 default: RetTy = Type::getInt16Ty(header->getContext()); break; 340 } 341 342 std::vector<Type*> paramTy; 343 344 // Add the types of the input values to the function's argument list 345 for (Value *value : inputs) { 346 DEBUG(dbgs() << "value used in func: " << *value << "\n"); 347 paramTy.push_back(value->getType()); 348 } 349 350 // Add the types of the output values to the function's argument list. 351 for (Value *output : outputs) { 352 DEBUG(dbgs() << "instr used in func: " << *output << "\n"); 353 if (AggregateArgs) 354 paramTy.push_back(output->getType()); 355 else 356 paramTy.push_back(PointerType::getUnqual(output->getType())); 357 } 358 359 DEBUG({ 360 dbgs() << "Function type: " << *RetTy << " f("; 361 for (Type *i : paramTy) 362 dbgs() << *i << ", "; 363 dbgs() << ")\n"; 364 }); 365 366 StructType *StructTy; 367 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { 368 StructTy = StructType::get(M->getContext(), paramTy); 369 paramTy.clear(); 370 paramTy.push_back(PointerType::getUnqual(StructTy)); 371 } 372 FunctionType *funcType = 373 FunctionType::get(RetTy, paramTy, false); 374 375 // Create the new function 376 Function *newFunction = Function::Create(funcType, 377 GlobalValue::InternalLinkage, 378 oldFunction->getName() + "_" + 379 header->getName(), M); 380 // If the old function is no-throw, so is the new one. 381 if (oldFunction->doesNotThrow()) 382 newFunction->setDoesNotThrow(); 383 384 // Inherit the uwtable attribute if we need to. 385 if (oldFunction->hasUWTable()) 386 newFunction->setHasUWTable(); 387 388 // Inherit all of the target dependent attributes. 389 // (e.g. If the extracted region contains a call to an x86.sse 390 // instruction we need to make sure that the extracted region has the 391 // "target-features" attribute allowing it to be lowered. 392 // FIXME: This should be changed to check to see if a specific 393 // attribute can not be inherited. 394 AttrBuilder AB(oldFunction->getAttributes().getFnAttributes()); 395 for (const auto &Attr : AB.td_attrs()) 396 newFunction->addFnAttr(Attr.first, Attr.second); 397 398 newFunction->getBasicBlockList().push_back(newRootNode); 399 400 // Create an iterator to name all of the arguments we inserted. 401 Function::arg_iterator AI = newFunction->arg_begin(); 402 403 // Rewrite all users of the inputs in the extracted region to use the 404 // arguments (or appropriate addressing into struct) instead. 405 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 406 Value *RewriteVal; 407 if (AggregateArgs) { 408 Value *Idx[2]; 409 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext())); 410 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i); 411 TerminatorInst *TI = newFunction->begin()->getTerminator(); 412 GetElementPtrInst *GEP = GetElementPtrInst::Create( 413 StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI); 414 RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI); 415 } else 416 RewriteVal = &*AI++; 417 418 std::vector<User*> Users(inputs[i]->user_begin(), inputs[i]->user_end()); 419 for (User *use : Users) 420 if (Instruction *inst = dyn_cast<Instruction>(use)) 421 if (Blocks.count(inst->getParent())) 422 inst->replaceUsesOfWith(inputs[i], RewriteVal); 423 } 424 425 // Set names for input and output arguments. 426 if (!AggregateArgs) { 427 AI = newFunction->arg_begin(); 428 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI) 429 AI->setName(inputs[i]->getName()); 430 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI) 431 AI->setName(outputs[i]->getName()+".out"); 432 } 433 434 // Rewrite branches to basic blocks outside of the loop to new dummy blocks 435 // within the new function. This must be done before we lose track of which 436 // blocks were originally in the code region. 437 std::vector<User*> Users(header->user_begin(), header->user_end()); 438 for (unsigned i = 0, e = Users.size(); i != e; ++i) 439 // The BasicBlock which contains the branch is not in the region 440 // modify the branch target to a new block 441 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i])) 442 if (!Blocks.count(TI->getParent()) && 443 TI->getParent()->getParent() == oldFunction) 444 TI->replaceUsesOfWith(header, newHeader); 445 446 return newFunction; 447 } 448 449 /// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI 450 /// that uses the value within the basic block, and return the predecessor 451 /// block associated with that use, or return 0 if none is found. 452 static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) { 453 for (Use &U : Used->uses()) { 454 PHINode *P = dyn_cast<PHINode>(U.getUser()); 455 if (P && P->getParent() == BB) 456 return P->getIncomingBlock(U); 457 } 458 459 return nullptr; 460 } 461 462 /// emitCallAndSwitchStatement - This method sets up the caller side by adding 463 /// the call instruction, splitting any PHI nodes in the header block as 464 /// necessary. 465 void CodeExtractor:: 466 emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer, 467 ValueSet &inputs, ValueSet &outputs) { 468 // Emit a call to the new function, passing in: *pointer to struct (if 469 // aggregating parameters), or plan inputs and allocated memory for outputs 470 std::vector<Value*> params, StructValues, ReloadOutputs, Reloads; 471 472 Module *M = newFunction->getParent(); 473 LLVMContext &Context = M->getContext(); 474 const DataLayout &DL = M->getDataLayout(); 475 476 // Add inputs as params, or to be filled into the struct 477 for (Value *input : inputs) 478 if (AggregateArgs) 479 StructValues.push_back(input); 480 else 481 params.push_back(input); 482 483 // Create allocas for the outputs 484 for (Value *output : outputs) { 485 if (AggregateArgs) { 486 StructValues.push_back(output); 487 } else { 488 AllocaInst *alloca = 489 new AllocaInst(output->getType(), DL.getAllocaAddrSpace(), 490 nullptr, output->getName() + ".loc", 491 &codeReplacer->getParent()->front().front()); 492 ReloadOutputs.push_back(alloca); 493 params.push_back(alloca); 494 } 495 } 496 497 StructType *StructArgTy = nullptr; 498 AllocaInst *Struct = nullptr; 499 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { 500 std::vector<Type*> ArgTypes; 501 for (ValueSet::iterator v = StructValues.begin(), 502 ve = StructValues.end(); v != ve; ++v) 503 ArgTypes.push_back((*v)->getType()); 504 505 // Allocate a struct at the beginning of this function 506 StructArgTy = StructType::get(newFunction->getContext(), ArgTypes); 507 Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr, 508 "structArg", 509 &codeReplacer->getParent()->front().front()); 510 params.push_back(Struct); 511 512 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 513 Value *Idx[2]; 514 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 515 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i); 516 GetElementPtrInst *GEP = GetElementPtrInst::Create( 517 StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName()); 518 codeReplacer->getInstList().push_back(GEP); 519 StoreInst *SI = new StoreInst(StructValues[i], GEP); 520 codeReplacer->getInstList().push_back(SI); 521 } 522 } 523 524 // Emit the call to the function 525 CallInst *call = CallInst::Create(newFunction, params, 526 NumExitBlocks > 1 ? "targetBlock" : ""); 527 codeReplacer->getInstList().push_back(call); 528 529 Function::arg_iterator OutputArgBegin = newFunction->arg_begin(); 530 unsigned FirstOut = inputs.size(); 531 if (!AggregateArgs) 532 std::advance(OutputArgBegin, inputs.size()); 533 534 // Reload the outputs passed in by reference 535 for (unsigned i = 0, e = outputs.size(); i != e; ++i) { 536 Value *Output = nullptr; 537 if (AggregateArgs) { 538 Value *Idx[2]; 539 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 540 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i); 541 GetElementPtrInst *GEP = GetElementPtrInst::Create( 542 StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName()); 543 codeReplacer->getInstList().push_back(GEP); 544 Output = GEP; 545 } else { 546 Output = ReloadOutputs[i]; 547 } 548 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload"); 549 Reloads.push_back(load); 550 codeReplacer->getInstList().push_back(load); 551 std::vector<User*> Users(outputs[i]->user_begin(), outputs[i]->user_end()); 552 for (unsigned u = 0, e = Users.size(); u != e; ++u) { 553 Instruction *inst = cast<Instruction>(Users[u]); 554 if (!Blocks.count(inst->getParent())) 555 inst->replaceUsesOfWith(outputs[i], load); 556 } 557 } 558 559 // Now we can emit a switch statement using the call as a value. 560 SwitchInst *TheSwitch = 561 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)), 562 codeReplacer, 0, codeReplacer); 563 564 // Since there may be multiple exits from the original region, make the new 565 // function return an unsigned, switch on that number. This loop iterates 566 // over all of the blocks in the extracted region, updating any terminator 567 // instructions in the to-be-extracted region that branch to blocks that are 568 // not in the region to be extracted. 569 std::map<BasicBlock*, BasicBlock*> ExitBlockMap; 570 571 unsigned switchVal = 0; 572 for (BasicBlock *Block : Blocks) { 573 TerminatorInst *TI = Block->getTerminator(); 574 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 575 if (!Blocks.count(TI->getSuccessor(i))) { 576 BasicBlock *OldTarget = TI->getSuccessor(i); 577 // add a new basic block which returns the appropriate value 578 BasicBlock *&NewTarget = ExitBlockMap[OldTarget]; 579 if (!NewTarget) { 580 // If we don't already have an exit stub for this non-extracted 581 // destination, create one now! 582 NewTarget = BasicBlock::Create(Context, 583 OldTarget->getName() + ".exitStub", 584 newFunction); 585 unsigned SuccNum = switchVal++; 586 587 Value *brVal = nullptr; 588 switch (NumExitBlocks) { 589 case 0: 590 case 1: break; // No value needed. 591 case 2: // Conditional branch, return a bool 592 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum); 593 break; 594 default: 595 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum); 596 break; 597 } 598 599 ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget); 600 601 // Update the switch instruction. 602 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context), 603 SuccNum), 604 OldTarget); 605 606 // Restore values just before we exit 607 Function::arg_iterator OAI = OutputArgBegin; 608 for (unsigned out = 0, e = outputs.size(); out != e; ++out) { 609 // For an invoke, the normal destination is the only one that is 610 // dominated by the result of the invocation 611 BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent(); 612 613 bool DominatesDef = true; 614 615 BasicBlock *NormalDest = nullptr; 616 if (auto *Invoke = dyn_cast<InvokeInst>(outputs[out])) 617 NormalDest = Invoke->getNormalDest(); 618 619 if (NormalDest) { 620 DefBlock = NormalDest; 621 622 // Make sure we are looking at the original successor block, not 623 // at a newly inserted exit block, which won't be in the dominator 624 // info. 625 for (const auto &I : ExitBlockMap) 626 if (DefBlock == I.second) { 627 DefBlock = I.first; 628 break; 629 } 630 631 // In the extract block case, if the block we are extracting ends 632 // with an invoke instruction, make sure that we don't emit a 633 // store of the invoke value for the unwind block. 634 if (!DT && DefBlock != OldTarget) 635 DominatesDef = false; 636 } 637 638 if (DT) { 639 DominatesDef = DT->dominates(DefBlock, OldTarget); 640 641 // If the output value is used by a phi in the target block, 642 // then we need to test for dominance of the phi's predecessor 643 // instead. Unfortunately, this a little complicated since we 644 // have already rewritten uses of the value to uses of the reload. 645 BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out], 646 OldTarget); 647 if (pred && DT && DT->dominates(DefBlock, pred)) 648 DominatesDef = true; 649 } 650 651 if (DominatesDef) { 652 if (AggregateArgs) { 653 Value *Idx[2]; 654 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 655 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), 656 FirstOut+out); 657 GetElementPtrInst *GEP = GetElementPtrInst::Create( 658 StructArgTy, &*OAI, Idx, "gep_" + outputs[out]->getName(), 659 NTRet); 660 new StoreInst(outputs[out], GEP, NTRet); 661 } else { 662 new StoreInst(outputs[out], &*OAI, NTRet); 663 } 664 } 665 // Advance output iterator even if we don't emit a store 666 if (!AggregateArgs) ++OAI; 667 } 668 } 669 670 // rewrite the original branch instruction with this new target 671 TI->setSuccessor(i, NewTarget); 672 } 673 } 674 675 // Now that we've done the deed, simplify the switch instruction. 676 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType(); 677 switch (NumExitBlocks) { 678 case 0: 679 // There are no successors (the block containing the switch itself), which 680 // means that previously this was the last part of the function, and hence 681 // this should be rewritten as a `ret' 682 683 // Check if the function should return a value 684 if (OldFnRetTy->isVoidTy()) { 685 ReturnInst::Create(Context, nullptr, TheSwitch); // Return void 686 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) { 687 // return what we have 688 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch); 689 } else { 690 // Otherwise we must have code extracted an unwind or something, just 691 // return whatever we want. 692 ReturnInst::Create(Context, 693 Constant::getNullValue(OldFnRetTy), TheSwitch); 694 } 695 696 TheSwitch->eraseFromParent(); 697 break; 698 case 1: 699 // Only a single destination, change the switch into an unconditional 700 // branch. 701 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch); 702 TheSwitch->eraseFromParent(); 703 break; 704 case 2: 705 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2), 706 call, TheSwitch); 707 TheSwitch->eraseFromParent(); 708 break; 709 default: 710 // Otherwise, make the default destination of the switch instruction be one 711 // of the other successors. 712 TheSwitch->setCondition(call); 713 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks)); 714 // Remove redundant case 715 TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1)); 716 break; 717 } 718 } 719 720 void CodeExtractor::moveCodeToFunction(Function *newFunction) { 721 Function *oldFunc = (*Blocks.begin())->getParent(); 722 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList(); 723 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList(); 724 725 for (BasicBlock *Block : Blocks) { 726 // Delete the basic block from the old function, and the list of blocks 727 oldBlocks.remove(Block); 728 729 // Insert this basic block into the new function 730 newBlocks.push_back(Block); 731 } 732 } 733 734 void CodeExtractor::calculateNewCallTerminatorWeights( 735 BasicBlock *CodeReplacer, 736 DenseMap<BasicBlock *, BlockFrequency> &ExitWeights, 737 BranchProbabilityInfo *BPI) { 738 typedef BlockFrequencyInfoImplBase::Distribution Distribution; 739 typedef BlockFrequencyInfoImplBase::BlockNode BlockNode; 740 741 // Update the branch weights for the exit block. 742 TerminatorInst *TI = CodeReplacer->getTerminator(); 743 SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0); 744 745 // Block Frequency distribution with dummy node. 746 Distribution BranchDist; 747 748 // Add each of the frequencies of the successors. 749 for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) { 750 BlockNode ExitNode(i); 751 uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency(); 752 if (ExitFreq != 0) 753 BranchDist.addExit(ExitNode, ExitFreq); 754 else 755 BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero()); 756 } 757 758 // Check for no total weight. 759 if (BranchDist.Total == 0) 760 return; 761 762 // Normalize the distribution so that they can fit in unsigned. 763 BranchDist.normalize(); 764 765 // Create normalized branch weights and set the metadata. 766 for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) { 767 const auto &Weight = BranchDist.Weights[I]; 768 769 // Get the weight and update the current BFI. 770 BranchWeights[Weight.TargetNode.Index] = Weight.Amount; 771 BranchProbability BP(Weight.Amount, BranchDist.Total); 772 BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP); 773 } 774 TI->setMetadata( 775 LLVMContext::MD_prof, 776 MDBuilder(TI->getContext()).createBranchWeights(BranchWeights)); 777 } 778 779 Function *CodeExtractor::extractCodeRegion() { 780 if (!isEligible()) 781 return nullptr; 782 783 ValueSet inputs, outputs, SinkingCands; 784 785 // Assumption: this is a single-entry code region, and the header is the first 786 // block in the region. 787 BasicBlock *header = *Blocks.begin(); 788 789 // Calculate the entry frequency of the new function before we change the root 790 // block. 791 BlockFrequency EntryFreq; 792 if (BFI) { 793 assert(BPI && "Both BPI and BFI are required to preserve profile info"); 794 for (BasicBlock *Pred : predecessors(header)) { 795 if (Blocks.count(Pred)) 796 continue; 797 EntryFreq += 798 BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header); 799 } 800 } 801 802 // If we have to split PHI nodes or the entry block, do so now. 803 severSplitPHINodes(header); 804 805 // If we have any return instructions in the region, split those blocks so 806 // that the return is not in the region. 807 splitReturnBlocks(); 808 809 Function *oldFunction = header->getParent(); 810 811 // This takes place of the original loop 812 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(), 813 "codeRepl", oldFunction, 814 header); 815 816 // The new function needs a root node because other nodes can branch to the 817 // head of the region, but the entry node of a function cannot have preds. 818 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(), 819 "newFuncRoot"); 820 newFuncRoot->getInstList().push_back(BranchInst::Create(header)); 821 822 findAllocas(SinkingCands); 823 824 // Find inputs to, outputs from the code region. 825 findInputsOutputs(inputs, outputs, SinkingCands); 826 827 // Now sink all instructions which only have non-phi uses inside the region 828 for (auto *II : SinkingCands) 829 cast<Instruction>(II)->moveBefore(*newFuncRoot, 830 newFuncRoot->getFirstInsertionPt()); 831 832 // Calculate the exit blocks for the extracted region and the total exit 833 // weights for each of those blocks. 834 DenseMap<BasicBlock *, BlockFrequency> ExitWeights; 835 SmallPtrSet<BasicBlock *, 1> ExitBlocks; 836 for (BasicBlock *Block : Blocks) { 837 for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE; 838 ++SI) { 839 if (!Blocks.count(*SI)) { 840 // Update the branch weight for this successor. 841 if (BFI) { 842 BlockFrequency &BF = ExitWeights[*SI]; 843 BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI); 844 } 845 ExitBlocks.insert(*SI); 846 } 847 } 848 } 849 NumExitBlocks = ExitBlocks.size(); 850 851 // Construct new function based on inputs/outputs & add allocas for all defs. 852 Function *newFunction = constructFunction(inputs, outputs, header, 853 newFuncRoot, 854 codeReplacer, oldFunction, 855 oldFunction->getParent()); 856 857 // Update the entry count of the function. 858 if (BFI) { 859 Optional<uint64_t> EntryCount = 860 BFI->getProfileCountFromFreq(EntryFreq.getFrequency()); 861 if (EntryCount.hasValue()) 862 newFunction->setEntryCount(EntryCount.getValue()); 863 BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency()); 864 } 865 866 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs); 867 868 moveCodeToFunction(newFunction); 869 870 // Update the branch weights for the exit block. 871 if (BFI && NumExitBlocks > 1) 872 calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI); 873 874 // Loop over all of the PHI nodes in the header block, and change any 875 // references to the old incoming edge to be the new incoming edge. 876 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) { 877 PHINode *PN = cast<PHINode>(I); 878 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 879 if (!Blocks.count(PN->getIncomingBlock(i))) 880 PN->setIncomingBlock(i, newFuncRoot); 881 } 882 883 // Look at all successors of the codeReplacer block. If any of these blocks 884 // had PHI nodes in them, we need to update the "from" block to be the code 885 // replacer, not the original block in the extracted region. 886 std::vector<BasicBlock*> Succs(succ_begin(codeReplacer), 887 succ_end(codeReplacer)); 888 for (unsigned i = 0, e = Succs.size(); i != e; ++i) 889 for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) { 890 PHINode *PN = cast<PHINode>(I); 891 std::set<BasicBlock*> ProcessedPreds; 892 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 893 if (Blocks.count(PN->getIncomingBlock(i))) { 894 if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second) 895 PN->setIncomingBlock(i, codeReplacer); 896 else { 897 // There were multiple entries in the PHI for this block, now there 898 // is only one, so remove the duplicated entries. 899 PN->removeIncomingValue(i, false); 900 --i; --e; 901 } 902 } 903 } 904 905 //cerr << "NEW FUNCTION: " << *newFunction; 906 // verifyFunction(*newFunction); 907 908 // cerr << "OLD FUNCTION: " << *oldFunction; 909 // verifyFunction(*oldFunction); 910 911 DEBUG(if (verifyFunction(*newFunction)) 912 report_fatal_error("verifyFunction failed!")); 913 return newFunction; 914 } 915