LLVM  3.7.0
CodeExtractor.cpp
Go to the documentation of this file.
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 
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Verifier.h"
31 #include "llvm/Pass.h"
33 #include "llvm/Support/Debug.h"
37 #include <algorithm>
38 #include <set>
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "code-extractor"
42 
43 // Provide a command-line option to aggregate function arguments into a struct
44 // for functions produced by the code extractor. This is useful when converting
45 // extracted functions to pthread-based code, as only one argument (void*) can
46 // be passed in to pthread_create().
47 static cl::opt<bool>
48 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
49  cl::desc("Aggregate arguments to code-extracted functions"));
50 
51 /// \brief Test whether a block is valid for extraction.
52 static bool isBlockValidForExtraction(const BasicBlock &BB) {
53  // Landing pads must be in the function where they were inserted for cleanup.
54  if (BB.isLandingPad())
55  return false;
56 
57  // Don't hoist code containing allocas, invokes, or vastarts.
58  for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
59  if (isa<AllocaInst>(I) || isa<InvokeInst>(I))
60  return false;
61  if (const CallInst *CI = dyn_cast<CallInst>(I))
62  if (const Function *F = CI->getCalledFunction())
63  if (F->getIntrinsicID() == Intrinsic::vastart)
64  return false;
65  }
66 
67  return true;
68 }
69 
70 /// \brief Build a set of blocks to extract if the input blocks are viable.
71 template <typename IteratorT>
73  IteratorT BBEnd) {
75 
76  assert(BBBegin != BBEnd);
77 
78  // Loop over the blocks, adding them to our set-vector, and aborting with an
79  // empty set if we encounter invalid blocks.
80  for (IteratorT I = BBBegin, E = BBEnd; I != E; ++I) {
81  if (!Result.insert(*I))
82  llvm_unreachable("Repeated basic blocks in extraction input");
83 
84  if (!isBlockValidForExtraction(**I)) {
85  Result.clear();
86  return Result;
87  }
88  }
89 
90 #ifndef NDEBUG
91  for (SetVector<BasicBlock *>::iterator I = std::next(Result.begin()),
92  E = Result.end();
93  I != E; ++I)
94  for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I);
95  PI != PE; ++PI)
96  assert(Result.count(*PI) &&
97  "No blocks in this region may have entries from outside the region"
98  " except for the first block!");
99 #endif
100 
101  return Result;
102 }
103 
104 /// \brief Helper to call buildExtractionBlockSet with an ArrayRef.
107  return buildExtractionBlockSet(BBs.begin(), BBs.end());
108 }
109 
110 /// \brief Helper to call buildExtractionBlockSet with a RegionNode.
113  if (!RN.isSubRegion())
114  // Just a single BasicBlock.
116 
117  const Region &R = *RN.getNodeAs<Region>();
118 
120 }
121 
122 CodeExtractor::CodeExtractor(BasicBlock *BB, bool AggregateArgs)
123  : DT(nullptr), AggregateArgs(AggregateArgs||AggregateArgsOpt),
124  Blocks(buildExtractionBlockSet(BB)), NumExitBlocks(~0U) {}
125 
127  bool AggregateArgs)
128  : DT(DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
129  Blocks(buildExtractionBlockSet(BBs)), NumExitBlocks(~0U) {}
130 
131 CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs)
132  : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
133  Blocks(buildExtractionBlockSet(L.getBlocks())), NumExitBlocks(~0U) {}
134 
136  bool AggregateArgs)
137  : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
138  Blocks(buildExtractionBlockSet(RN)), NumExitBlocks(~0U) {}
139 
140 /// definedInRegion - Return true if the specified value is defined in the
141 /// extracted region.
142 static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
143  if (Instruction *I = dyn_cast<Instruction>(V))
144  if (Blocks.count(I->getParent()))
145  return true;
146  return false;
147 }
148 
149 /// definedInCaller - Return true if the specified value is defined in the
150 /// function being code extracted, but not in the region being extracted.
151 /// These values must be passed in as live-ins to the function.
152 static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
153  if (isa<Argument>(V)) return true;
154  if (Instruction *I = dyn_cast<Instruction>(V))
155  if (!Blocks.count(I->getParent()))
156  return true;
157  return false;
158 }
159 
161  ValueSet &Outputs) const {
162  for (SetVector<BasicBlock *>::const_iterator I = Blocks.begin(),
163  E = Blocks.end();
164  I != E; ++I) {
165  BasicBlock *BB = *I;
166 
167  // If a used value is defined outside the region, it's an input. If an
168  // instruction is used outside the region, it's an output.
169  for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
170  II != IE; ++II) {
171  for (User::op_iterator OI = II->op_begin(), OE = II->op_end();
172  OI != OE; ++OI)
173  if (definedInCaller(Blocks, *OI))
174  Inputs.insert(*OI);
175 
176  for (User *U : II->users())
177  if (!definedInRegion(Blocks, U)) {
178  Outputs.insert(II);
179  break;
180  }
181  }
182  }
183 }
184 
185 /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
186 /// region, we need to split the entry block of the region so that the PHI node
187 /// is easier to deal with.
188 void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
189  unsigned NumPredsFromRegion = 0;
190  unsigned NumPredsOutsideRegion = 0;
191 
192  if (Header != &Header->getParent()->getEntryBlock()) {
193  PHINode *PN = dyn_cast<PHINode>(Header->begin());
194  if (!PN) return; // No PHI nodes.
195 
196  // If the header node contains any PHI nodes, check to see if there is more
197  // than one entry from outside the region. If so, we need to sever the
198  // header block into two.
199  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
200  if (Blocks.count(PN->getIncomingBlock(i)))
201  ++NumPredsFromRegion;
202  else
203  ++NumPredsOutsideRegion;
204 
205  // If there is one (or fewer) predecessor from outside the region, we don't
206  // need to do anything special.
207  if (NumPredsOutsideRegion <= 1) return;
208  }
209 
210  // Otherwise, we need to split the header block into two pieces: one
211  // containing PHI nodes merging values from outside of the region, and a
212  // second that contains all of the code for the block and merges back any
213  // incoming values from inside of the region.
214  BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI();
215  BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
216  Header->getName()+".ce");
217 
218  // We only want to code extract the second block now, and it becomes the new
219  // header of the region.
220  BasicBlock *OldPred = Header;
221  Blocks.remove(OldPred);
222  Blocks.insert(NewBB);
223  Header = NewBB;
224 
225  // Okay, update dominator sets. The blocks that dominate the new one are the
226  // blocks that dominate TIBB plus the new block itself.
227  if (DT)
228  DT->splitBlock(NewBB);
229 
230  // Okay, now we need to adjust the PHI nodes and any branches from within the
231  // region to go to the new header block instead of the old header block.
232  if (NumPredsFromRegion) {
233  PHINode *PN = cast<PHINode>(OldPred->begin());
234  // Loop over all of the predecessors of OldPred that are in the region,
235  // changing them to branch to NewBB instead.
236  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
237  if (Blocks.count(PN->getIncomingBlock(i))) {
239  TI->replaceUsesOfWith(OldPred, NewBB);
240  }
241 
242  // Okay, everything within the region is now branching to the right block, we
243  // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
244  for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
245  PHINode *PN = cast<PHINode>(AfterPHIs);
246  // Create a new PHI node in the new region, which has an incoming value
247  // from OldPred of PN.
248  PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
249  PN->getName()+".ce", NewBB->begin());
250  NewPN->addIncoming(PN, OldPred);
251 
252  // Loop over all of the incoming value in PN, moving them to NewPN if they
253  // are from the extracted region.
254  for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
255  if (Blocks.count(PN->getIncomingBlock(i))) {
256  NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
257  PN->removeIncomingValue(i);
258  --i;
259  }
260  }
261  }
262  }
263 }
264 
265 void CodeExtractor::splitReturnBlocks() {
266  for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end();
267  I != E; ++I)
268  if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) {
269  BasicBlock *New = (*I)->splitBasicBlock(RI, (*I)->getName()+".ret");
270  if (DT) {
271  // Old dominates New. New node dominates all other nodes dominated
272  // by Old.
273  DomTreeNode *OldNode = DT->getNode(*I);
275  for (DomTreeNode::iterator DI = OldNode->begin(), DE = OldNode->end();
276  DI != DE; ++DI)
277  Children.push_back(*DI);
278 
279  DomTreeNode *NewNode = DT->addNewBlock(New, *I);
280 
282  E = Children.end(); I != E; ++I)
283  DT->changeImmediateDominator(*I, NewNode);
284  }
285  }
286 }
287 
288 /// constructFunction - make a function based on inputs and outputs, as follows:
289 /// f(in0, ..., inN, out0, ..., outN)
290 ///
291 Function *CodeExtractor::constructFunction(const ValueSet &inputs,
292  const ValueSet &outputs,
293  BasicBlock *header,
294  BasicBlock *newRootNode,
295  BasicBlock *newHeader,
296  Function *oldFunction,
297  Module *M) {
298  DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
299  DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
300 
301  // This function returns unsigned, outputs will go back by reference.
302  switch (NumExitBlocks) {
303  case 0:
304  case 1: RetTy = Type::getVoidTy(header->getContext()); break;
305  case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
306  default: RetTy = Type::getInt16Ty(header->getContext()); break;
307  }
308 
309  std::vector<Type*> paramTy;
310 
311  // Add the types of the input values to the function's argument list
312  for (ValueSet::const_iterator i = inputs.begin(), e = inputs.end();
313  i != e; ++i) {
314  const Value *value = *i;
315  DEBUG(dbgs() << "value used in func: " << *value << "\n");
316  paramTy.push_back(value->getType());
317  }
318 
319  // Add the types of the output values to the function's argument list.
320  for (ValueSet::const_iterator I = outputs.begin(), E = outputs.end();
321  I != E; ++I) {
322  DEBUG(dbgs() << "instr used in func: " << **I << "\n");
323  if (AggregateArgs)
324  paramTy.push_back((*I)->getType());
325  else
326  paramTy.push_back(PointerType::getUnqual((*I)->getType()));
327  }
328 
329  DEBUG(dbgs() << "Function type: " << *RetTy << " f(");
330  for (std::vector<Type*>::iterator i = paramTy.begin(),
331  e = paramTy.end(); i != e; ++i)
332  DEBUG(dbgs() << **i << ", ");
333  DEBUG(dbgs() << ")\n");
334 
335  StructType *StructTy;
336  if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
337  StructTy = StructType::get(M->getContext(), paramTy);
338  paramTy.clear();
339  paramTy.push_back(PointerType::getUnqual(StructTy));
340  }
341  FunctionType *funcType =
342  FunctionType::get(RetTy, paramTy, false);
343 
344  // Create the new function
345  Function *newFunction = Function::Create(funcType,
347  oldFunction->getName() + "_" +
348  header->getName(), M);
349  // If the old function is no-throw, so is the new one.
350  if (oldFunction->doesNotThrow())
351  newFunction->setDoesNotThrow();
352 
353  newFunction->getBasicBlockList().push_back(newRootNode);
354 
355  // Create an iterator to name all of the arguments we inserted.
356  Function::arg_iterator AI = newFunction->arg_begin();
357 
358  // Rewrite all users of the inputs in the extracted region to use the
359  // arguments (or appropriate addressing into struct) instead.
360  for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
361  Value *RewriteVal;
362  if (AggregateArgs) {
363  Value *Idx[2];
365  Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
366  TerminatorInst *TI = newFunction->begin()->getTerminator();
368  StructTy, AI, Idx, "gep_" + inputs[i]->getName(), TI);
369  RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
370  } else
371  RewriteVal = AI++;
372 
373  std::vector<User*> Users(inputs[i]->user_begin(), inputs[i]->user_end());
374  for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
375  use != useE; ++use)
376  if (Instruction* inst = dyn_cast<Instruction>(*use))
377  if (Blocks.count(inst->getParent()))
378  inst->replaceUsesOfWith(inputs[i], RewriteVal);
379  }
380 
381  // Set names for input and output arguments.
382  if (!AggregateArgs) {
383  AI = newFunction->arg_begin();
384  for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
385  AI->setName(inputs[i]->getName());
386  for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
387  AI->setName(outputs[i]->getName()+".out");
388  }
389 
390  // Rewrite branches to basic blocks outside of the loop to new dummy blocks
391  // within the new function. This must be done before we lose track of which
392  // blocks were originally in the code region.
393  std::vector<User*> Users(header->user_begin(), header->user_end());
394  for (unsigned i = 0, e = Users.size(); i != e; ++i)
395  // The BasicBlock which contains the branch is not in the region
396  // modify the branch target to a new block
397  if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
398  if (!Blocks.count(TI->getParent()) &&
399  TI->getParent()->getParent() == oldFunction)
400  TI->replaceUsesOfWith(header, newHeader);
401 
402  return newFunction;
403 }
404 
405 /// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI
406 /// that uses the value within the basic block, and return the predecessor
407 /// block associated with that use, or return 0 if none is found.
409  for (Use &U : Used->uses()) {
410  PHINode *P = dyn_cast<PHINode>(U.getUser());
411  if (P && P->getParent() == BB)
412  return P->getIncomingBlock(U);
413  }
414 
415  return nullptr;
416 }
417 
418 /// emitCallAndSwitchStatement - This method sets up the caller side by adding
419 /// the call instruction, splitting any PHI nodes in the header block as
420 /// necessary.
421 void CodeExtractor::
422 emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
423  ValueSet &inputs, ValueSet &outputs) {
424  // Emit a call to the new function, passing in: *pointer to struct (if
425  // aggregating parameters), or plan inputs and allocated memory for outputs
426  std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
427 
428  LLVMContext &Context = newFunction->getContext();
429 
430  // Add inputs as params, or to be filled into the struct
431  for (ValueSet::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i)
432  if (AggregateArgs)
433  StructValues.push_back(*i);
434  else
435  params.push_back(*i);
436 
437  // Create allocas for the outputs
438  for (ValueSet::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) {
439  if (AggregateArgs) {
440  StructValues.push_back(*i);
441  } else {
442  AllocaInst *alloca =
443  new AllocaInst((*i)->getType(), nullptr, (*i)->getName()+".loc",
444  codeReplacer->getParent()->begin()->begin());
445  ReloadOutputs.push_back(alloca);
446  params.push_back(alloca);
447  }
448  }
449 
450  StructType *StructArgTy = nullptr;
451  AllocaInst *Struct = nullptr;
452  if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
453  std::vector<Type*> ArgTypes;
454  for (ValueSet::iterator v = StructValues.begin(),
455  ve = StructValues.end(); v != ve; ++v)
456  ArgTypes.push_back((*v)->getType());
457 
458  // Allocate a struct at the beginning of this function
459  StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
460  Struct =
461  new AllocaInst(StructArgTy, nullptr, "structArg",
462  codeReplacer->getParent()->begin()->begin());
463  params.push_back(Struct);
464 
465  for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
466  Value *Idx[2];
467  Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
468  Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
470  StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());
471  codeReplacer->getInstList().push_back(GEP);
472  StoreInst *SI = new StoreInst(StructValues[i], GEP);
473  codeReplacer->getInstList().push_back(SI);
474  }
475  }
476 
477  // Emit the call to the function
478  CallInst *call = CallInst::Create(newFunction, params,
479  NumExitBlocks > 1 ? "targetBlock" : "");
480  codeReplacer->getInstList().push_back(call);
481 
482  Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
483  unsigned FirstOut = inputs.size();
484  if (!AggregateArgs)
485  std::advance(OutputArgBegin, inputs.size());
486 
487  // Reload the outputs passed in by reference
488  for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
489  Value *Output = nullptr;
490  if (AggregateArgs) {
491  Value *Idx[2];
492  Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
493  Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
495  StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
496  codeReplacer->getInstList().push_back(GEP);
497  Output = GEP;
498  } else {
499  Output = ReloadOutputs[i];
500  }
501  LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
502  Reloads.push_back(load);
503  codeReplacer->getInstList().push_back(load);
504  std::vector<User*> Users(outputs[i]->user_begin(), outputs[i]->user_end());
505  for (unsigned u = 0, e = Users.size(); u != e; ++u) {
506  Instruction *inst = cast<Instruction>(Users[u]);
507  if (!Blocks.count(inst->getParent()))
508  inst->replaceUsesOfWith(outputs[i], load);
509  }
510  }
511 
512  // Now we can emit a switch statement using the call as a value.
513  SwitchInst *TheSwitch =
515  codeReplacer, 0, codeReplacer);
516 
517  // Since there may be multiple exits from the original region, make the new
518  // function return an unsigned, switch on that number. This loop iterates
519  // over all of the blocks in the extracted region, updating any terminator
520  // instructions in the to-be-extracted region that branch to blocks that are
521  // not in the region to be extracted.
522  std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
523 
524  unsigned switchVal = 0;
525  for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(),
526  e = Blocks.end(); i != e; ++i) {
527  TerminatorInst *TI = (*i)->getTerminator();
528  for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
529  if (!Blocks.count(TI->getSuccessor(i))) {
530  BasicBlock *OldTarget = TI->getSuccessor(i);
531  // add a new basic block which returns the appropriate value
532  BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
533  if (!NewTarget) {
534  // If we don't already have an exit stub for this non-extracted
535  // destination, create one now!
536  NewTarget = BasicBlock::Create(Context,
537  OldTarget->getName() + ".exitStub",
538  newFunction);
539  unsigned SuccNum = switchVal++;
540 
541  Value *brVal = nullptr;
542  switch (NumExitBlocks) {
543  case 0:
544  case 1: break; // No value needed.
545  case 2: // Conditional branch, return a bool
546  brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
547  break;
548  default:
549  brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
550  break;
551  }
552 
553  ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget);
554 
555  // Update the switch instruction.
556  TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
557  SuccNum),
558  OldTarget);
559 
560  // Restore values just before we exit
561  Function::arg_iterator OAI = OutputArgBegin;
562  for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
563  // For an invoke, the normal destination is the only one that is
564  // dominated by the result of the invocation
565  BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
566 
567  bool DominatesDef = true;
568 
569  if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out])) {
570  DefBlock = Invoke->getNormalDest();
571 
572  // Make sure we are looking at the original successor block, not
573  // at a newly inserted exit block, which won't be in the dominator
574  // info.
575  for (std::map<BasicBlock*, BasicBlock*>::iterator I =
576  ExitBlockMap.begin(), E = ExitBlockMap.end(); I != E; ++I)
577  if (DefBlock == I->second) {
578  DefBlock = I->first;
579  break;
580  }
581 
582  // In the extract block case, if the block we are extracting ends
583  // with an invoke instruction, make sure that we don't emit a
584  // store of the invoke value for the unwind block.
585  if (!DT && DefBlock != OldTarget)
586  DominatesDef = false;
587  }
588 
589  if (DT) {
590  DominatesDef = DT->dominates(DefBlock, OldTarget);
591 
592  // If the output value is used by a phi in the target block,
593  // then we need to test for dominance of the phi's predecessor
594  // instead. Unfortunately, this a little complicated since we
595  // have already rewritten uses of the value to uses of the reload.
596  BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out],
597  OldTarget);
598  if (pred && DT && DT->dominates(DefBlock, pred))
599  DominatesDef = true;
600  }
601 
602  if (DominatesDef) {
603  if (AggregateArgs) {
604  Value *Idx[2];
605  Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
606  Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
607  FirstOut+out);
609  StructArgTy, OAI, Idx, "gep_" + outputs[out]->getName(),
610  NTRet);
611  new StoreInst(outputs[out], GEP, NTRet);
612  } else {
613  new StoreInst(outputs[out], OAI, NTRet);
614  }
615  }
616  // Advance output iterator even if we don't emit a store
617  if (!AggregateArgs) ++OAI;
618  }
619  }
620 
621  // rewrite the original branch instruction with this new target
622  TI->setSuccessor(i, NewTarget);
623  }
624  }
625 
626  // Now that we've done the deed, simplify the switch instruction.
627  Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
628  switch (NumExitBlocks) {
629  case 0:
630  // There are no successors (the block containing the switch itself), which
631  // means that previously this was the last part of the function, and hence
632  // this should be rewritten as a `ret'
633 
634  // Check if the function should return a value
635  if (OldFnRetTy->isVoidTy()) {
636  ReturnInst::Create(Context, nullptr, TheSwitch); // Return void
637  } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
638  // return what we have
639  ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
640  } else {
641  // Otherwise we must have code extracted an unwind or something, just
642  // return whatever we want.
643  ReturnInst::Create(Context,
644  Constant::getNullValue(OldFnRetTy), TheSwitch);
645  }
646 
647  TheSwitch->eraseFromParent();
648  break;
649  case 1:
650  // Only a single destination, change the switch into an unconditional
651  // branch.
652  BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
653  TheSwitch->eraseFromParent();
654  break;
655  case 2:
656  BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
657  call, TheSwitch);
658  TheSwitch->eraseFromParent();
659  break;
660  default:
661  // Otherwise, make the default destination of the switch instruction be one
662  // of the other successors.
663  TheSwitch->setCondition(call);
664  TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
665  // Remove redundant case
666  TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
667  break;
668  }
669 }
670 
671 void CodeExtractor::moveCodeToFunction(Function *newFunction) {
672  Function *oldFunc = (*Blocks.begin())->getParent();
673  Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
674  Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
675 
676  for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(),
677  e = Blocks.end(); i != e; ++i) {
678  // Delete the basic block from the old function, and the list of blocks
679  oldBlocks.remove(*i);
680 
681  // Insert this basic block into the new function
682  newBlocks.push_back(*i);
683  }
684 }
685 
687  if (!isEligible())
688  return nullptr;
689 
690  ValueSet inputs, outputs;
691 
692  // Assumption: this is a single-entry code region, and the header is the first
693  // block in the region.
694  BasicBlock *header = *Blocks.begin();
695 
696  // If we have to split PHI nodes or the entry block, do so now.
697  severSplitPHINodes(header);
698 
699  // If we have any return instructions in the region, split those blocks so
700  // that the return is not in the region.
701  splitReturnBlocks();
702 
703  Function *oldFunction = header->getParent();
704 
705  // This takes place of the original loop
706  BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
707  "codeRepl", oldFunction,
708  header);
709 
710  // The new function needs a root node because other nodes can branch to the
711  // head of the region, but the entry node of a function cannot have preds.
712  BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
713  "newFuncRoot");
714  newFuncRoot->getInstList().push_back(BranchInst::Create(header));
715 
716  // Find inputs to, outputs from the code region.
717  findInputsOutputs(inputs, outputs);
718 
719  SmallPtrSet<BasicBlock *, 1> ExitBlocks;
720  for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end();
721  I != E; ++I)
722  for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
723  if (!Blocks.count(*SI))
724  ExitBlocks.insert(*SI);
725  NumExitBlocks = ExitBlocks.size();
726 
727  // Construct new function based on inputs/outputs & add allocas for all defs.
728  Function *newFunction = constructFunction(inputs, outputs, header,
729  newFuncRoot,
730  codeReplacer, oldFunction,
731  oldFunction->getParent());
732 
733  emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
734 
735  moveCodeToFunction(newFunction);
736 
737  // Loop over all of the PHI nodes in the header block, and change any
738  // references to the old incoming edge to be the new incoming edge.
739  for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
740  PHINode *PN = cast<PHINode>(I);
741  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
742  if (!Blocks.count(PN->getIncomingBlock(i)))
743  PN->setIncomingBlock(i, newFuncRoot);
744  }
745 
746  // Look at all successors of the codeReplacer block. If any of these blocks
747  // had PHI nodes in them, we need to update the "from" block to be the code
748  // replacer, not the original block in the extracted region.
749  std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
750  succ_end(codeReplacer));
751  for (unsigned i = 0, e = Succs.size(); i != e; ++i)
752  for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
753  PHINode *PN = cast<PHINode>(I);
754  std::set<BasicBlock*> ProcessedPreds;
755  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
756  if (Blocks.count(PN->getIncomingBlock(i))) {
757  if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
758  PN->setIncomingBlock(i, codeReplacer);
759  else {
760  // There were multiple entries in the PHI for this block, now there
761  // is only one, so remove the duplicated entries.
762  PN->removeIncomingValue(i, false);
763  --i; --e;
764  }
765  }
766  }
767 
768  //cerr << "NEW FUNCTION: " << *newFunction;
769  // verifyFunction(*newFunction);
770 
771  // cerr << "OLD FUNCTION: " << *oldFunction;
772  // verifyFunction(*oldFunction);
773 
774  DEBUG(if (verifyFunction(*newFunction))
775  report_fatal_error("verifyFunction failed!"));
776  return newFunction;
777 }
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
addNewBlock - Add a new node to the dominator tree information.
ReturnInst - Return a value (possibly void), from a function.
iplist< Instruction >::iterator eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing basic block and deletes it...
Definition: Instruction.cpp:70
iterator_range< use_iterator > uses()
Definition: Value.h:283
static IntegerType * getInt1Ty(LLVMContext &C)
Definition: Type.cpp:236
void addIncoming(Value *V, BasicBlock *BB)
addIncoming - Add an incoming value to the end of the PHI list
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:223
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:114
static cl::opt< bool > AggregateArgsOpt("aggregate-extracted-args", cl::Hidden, cl::desc("Aggregate arguments to code-extracted functions"))
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
addCase - Add an entry to the switch instruction...
iterator end() const
Definition: ArrayRef.h:123
CallInst - This class represents a function call, abstracting a target machine's calling convention...
Function * extractCodeRegion()
Perform the extraction, returning the new function.
const_iterator begin(StringRef path)
Get begin iterator over path.
Definition: Path.cpp:232
Type * getReturnType() const
Definition: Function.cpp:233
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:111
bool isSubRegion() const
Is this RegionNode a subregion?
Definition: RegionInfo.h:181
F(f)
LoadInst - an instruction for reading from memory.
Definition: Instructions.h:177
Hexagon Common GEP
vector_type::const_iterator const_iterator
Definition: SetVector.h:46
iv Induction Variable Users
Definition: IVUsers.cpp:43
static IntegerType * getInt16Ty(LLVMContext &C)
Definition: Type.cpp:238
iterator end()
Get an iterator to the end of the SetVector.
Definition: SetVector.h:79
T * getNodeAs() const
Get the content of this RegionNode.
static BasicBlock * FindPhiPredForUseInBlock(Value *Used, BasicBlock *BB)
FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI that uses the value within the...
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(const char *reason, bool gen_crash_diag=true)
Reports a serious error, calling any installed error handler.
static Constant * getNullValue(Type *Ty)
Definition: Constants.cpp:178
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:188
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:231
void setDoesNotThrow()
Definition: Function.h:320
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
void push_back(NodeTy *val)
Definition: ilist.h:554
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
removeIncomingValue - Remove an incoming value.
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition: Function.h:316
std::vector< DomTreeNodeBase< NodeT > * >::iterator iterator
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
StructType - Class to represent struct types.
Definition: DerivedTypes.h:191
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:98
A Use represents the edge between a Value definition and its users.
Definition: Use.h:69
static void advance(T &it, size_t Val)
Instruction * getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:165
static StringRef getName(Value *V)
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:104
FunctionType - Class to represent function types.
Definition: DerivedTypes.h:96
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:102
static std::vector< std::string > inputs
iterator begin()
Get an iterator to the beginning of the SetVector.
Definition: SetVector.h:69
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
FunctionType::get - This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:361
Base class for the actual dominator tree node.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: ArrayRef.h:31
void setSuccessor(unsigned idx, BasicBlock *B)
Update the specified successor to point at the provided block.
Definition: InstrTypes.h:67
StoreInst - an instruction for storing to memory.
Definition: Instructions.h:316
iterator begin()
Definition: Function.h:457
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:67
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:107
unsigned getNumIncomingValues() const
getNumIncomingValues - Return the number of incoming edges
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition: User.cpp:24
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
Definition: InstrTypes.h:57
GetElementPtrInst - an instruction for type-safe pointer arithmetic to access elements of arrays and ...
Definition: Instructions.h:830
#define P(N)
void findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs) const
Compute the set of input values and output values for the code.
Subclasses of this class are all able to terminate a basic block.
Definition: InstrTypes.h:35
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
size_type size() const
Definition: SmallPtrSet.h:79
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
Definition: InstrTypes.h:62
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:41
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:264
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:114
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:225
BasicBlock * getIncomingBlock(unsigned i) const
getIncomingBlock - Return incoming basic block number i.
const InstListType & getInstList() const
Return the underlying instruction list container.
Definition: BasicBlock.h:252
iterator begin() const
Definition: ArrayRef.h:122
bool isEligible() const
Test whether this code extractor is eligible.
Definition: CodeExtractor.h:95
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:117
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:103
arg_iterator arg_begin()
Definition: Function.h:472
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Definition: Instructions.h:854
hexagon gen pred
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:214
const BasicBlockListType & getBasicBlockList() const
Definition: Function.h:436
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:299
static PointerType * getUnqual(Type *ElementType)
PointerType::getUnqual - This constructs a pointer to an object of the specified type in the generic ...
Definition: DerivedTypes.h:460
void setIncomingBlock(unsigned i, BasicBlock *BB)
Value * getIncomingValue(unsigned i) const
getIncomingValue - Return incoming value number x
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
StructType::get - This static method is the primary way to create a literal StructType.
Definition: Type.cpp:404
iterator end()
Definition: BasicBlock.h:233
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, Instruction *InsertBefore=nullptr)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:222
static bool definedInRegion(const SetVector< BasicBlock * > &Blocks, Value *V)
definedInRegion - Return true if the specified value is defined in the extracted region.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:582
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
const BasicBlock & getEntryBlock() const
Definition: Function.h:442
CodeExtractor(BasicBlock *BB, bool AggregateArgs=false)
Create a code extractor for a single basic block.
static bool definedInCaller(const SetVector< BasicBlock * > &Blocks, Value *V)
definedInCaller - Return true if the specified value is defined in the function being code extracted...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:123
void clear()
Completely clear the SetVector.
Definition: SetVector.h:161
static SetVector< BasicBlock * > buildExtractionBlockSet(IteratorT BBBegin, IteratorT BBEnd)
Build a set of blocks to extract if the input blocks are viable.
iterator_range< user_iterator > users()
Definition: Value.h:300
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:285
Value * getCondition() const
block_iterator block_begin()
Definition: RegionInfo.h:597
BasicBlock * getSuccessor(unsigned idx) const
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Definition: SetVector.h:156
block_iterator block_end()
Definition: RegionInfo.h:599
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:239
void setCondition(Value *V)
#define I(x, y, z)
Definition: MD5.cpp:54
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:124
bool isLandingPad() const
Return true if this basic block is a landing pad.
Definition: BasicBlock.cpp:413
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
Definition: Verifier.cpp:3639
Rename collisions when linking (static functions).
Definition: GlobalValue.h:47
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:348
void removeCase(CaseIt i)
removeCase - This method removes the specified case and its successor from the switch instruction...
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
SwitchInst - Multiway switch.
user_iterator user_begin()
Definition: Value.h:294
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:32
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:365
LLVM Value Representation.
Definition: Value.h:69
vector_type::const_iterator iterator
Definition: SetVector.h:45
void setDefaultDest(BasicBlock *DefaultCase)
A vector that has set insertion semantics.
Definition: SetVector.h:37
static const Function * getParent(const Value *V)
InvokeInst - Invoke instruction.
#define DEBUG(X)
Definition: Debug.h:92
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
Definition: Function.h:121
DomTreeNodeBase< NodeT > * getNode(NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
NodeTy * remove(iterator &IT)
Definition: ilist.h:435
const BasicBlock * getParent() const
Definition: Instruction.h:72
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:265
static bool isBlockValidForExtraction(const BasicBlock &BB)
Test whether a block is valid for extraction.
bool isVoidTy() const
isVoidTy - Return true if this is 'void'.
Definition: Type.h:137
AllocaInst - an instruction to allocate memory on the stack.
Definition: Instructions.h:76
void splitBlock(NodeT *NewBB)
splitBlock - BB is split and now it has one successor.
user_iterator user_end()
Definition: Value.h:296