LLVM  10.0.0
CallSiteSplitting.cpp
Go to the documentation of this file.
1 //===- CallSiteSplitting.cpp ----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a transformation that tries to split a call-site to pass
10 // more constrained arguments if its argument is predicated in the control flow
11 // so that we can expose better context to the later passes (e.g, inliner, jump
12 // threading, or IPA-CP based function cloning, etc.).
13 // As of now we support two cases :
14 //
15 // 1) Try to a split call-site with constrained arguments, if any constraints
16 // on any argument can be found by following the single predecessors of the
17 // all site's predecessors. Currently this pass only handles call-sites with 2
18 // predecessors. For example, in the code below, we try to split the call-site
19 // since we can predicate the argument(ptr) based on the OR condition.
20 //
21 // Split from :
22 // if (!ptr || c)
23 // callee(ptr);
24 // to :
25 // if (!ptr)
26 // callee(null) // set the known constant value
27 // else if (c)
28 // callee(nonnull ptr) // set non-null attribute in the argument
29 //
30 // 2) We can also split a call-site based on constant incoming values of a PHI
31 // For example,
32 // from :
33 // Header:
34 // %c = icmp eq i32 %i1, %i2
35 // br i1 %c, label %Tail, label %TBB
36 // TBB:
37 // br label Tail%
38 // Tail:
39 // %p = phi i32 [ 0, %Header], [ 1, %TBB]
40 // call void @bar(i32 %p)
41 // to
42 // Header:
43 // %c = icmp eq i32 %i1, %i2
44 // br i1 %c, label %Tail-split0, label %TBB
45 // TBB:
46 // br label %Tail-split1
47 // Tail-split0:
48 // call void @bar(i32 0)
49 // br label %Tail
50 // Tail-split1:
51 // call void @bar(i32 1)
52 // br label %Tail
53 // Tail:
54 // %p = phi i32 [ 0, %Tail-split0 ], [ 1, %Tail-split1 ]
55 //
56 //===----------------------------------------------------------------------===//
57 
59 #include "llvm/ADT/Statistic.h"
62 #include "llvm/IR/IntrinsicInst.h"
63 #include "llvm/IR/PatternMatch.h"
64 #include "llvm/InitializePasses.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Transforms/Scalar.h"
71 
72 using namespace llvm;
73 using namespace PatternMatch;
74 
75 #define DEBUG_TYPE "callsite-splitting"
76 
77 STATISTIC(NumCallSiteSplit, "Number of call-site split");
78 
79 /// Only allow instructions before a call, if their CodeSize cost is below
80 /// DuplicationThreshold. Those instructions need to be duplicated in all
81 /// split blocks.
82 static cl::opt<unsigned>
83  DuplicationThreshold("callsite-splitting-duplication-threshold", cl::Hidden,
84  cl::desc("Only allow instructions before a call, if "
85  "their cost is below DuplicationThreshold"),
86  cl::init(5));
87 
88 static void addNonNullAttribute(CallSite CS, Value *Op) {
89  unsigned ArgNo = 0;
90  for (auto &I : CS.args()) {
91  if (&*I == Op)
92  CS.addParamAttr(ArgNo, Attribute::NonNull);
93  ++ArgNo;
94  }
95 }
96 
98  Constant *ConstValue) {
99  unsigned ArgNo = 0;
100  for (auto &I : CS.args()) {
101  if (&*I == Op) {
102  // It is possible we have already added the non-null attribute to the
103  // parameter by using an earlier constraining condition.
104  CS.removeParamAttr(ArgNo, Attribute::NonNull);
105  CS.setArgument(ArgNo, ConstValue);
106  }
107  ++ArgNo;
108  }
109 }
110 
112  assert(isa<Constant>(Cmp->getOperand(1)) && "Expected a constant operand.");
113  Value *Op0 = Cmp->getOperand(0);
114  unsigned ArgNo = 0;
115  for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E;
116  ++I, ++ArgNo) {
117  // Don't consider constant or arguments that are already known non-null.
118  if (isa<Constant>(*I) || CS.paramHasAttr(ArgNo, Attribute::NonNull))
119  continue;
120 
121  if (*I == Op0)
122  return true;
123  }
124  return false;
125 }
126 
127 typedef std::pair<ICmpInst *, unsigned> ConditionTy;
129 
130 /// If From has a conditional jump to To, add the condition to Conditions,
131 /// if it is relevant to any argument at CS.
133  ConditionsTy &Conditions) {
134  auto *BI = dyn_cast<BranchInst>(From->getTerminator());
135  if (!BI || !BI->isConditional())
136  return;
137 
138  CmpInst::Predicate Pred;
139  Value *Cond = BI->getCondition();
140  if (!match(Cond, m_ICmp(Pred, m_Value(), m_Constant())))
141  return;
142 
143  ICmpInst *Cmp = cast<ICmpInst>(Cond);
144  if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
145  if (isCondRelevantToAnyCallArgument(Cmp, CS))
146  Conditions.push_back({Cmp, From->getTerminator()->getSuccessor(0) == To
147  ? Pred
148  : Cmp->getInversePredicate()});
149 }
150 
151 /// Record ICmp conditions relevant to any argument in CS following Pred's
152 /// single predecessors. If there are conflicting conditions along a path, like
153 /// x == 1 and x == 0, the first condition will be used. We stop once we reach
154 /// an edge to StopAt.
155 static void recordConditions(CallSite CS, BasicBlock *Pred,
156  ConditionsTy &Conditions, BasicBlock *StopAt) {
157  BasicBlock *From = Pred;
158  BasicBlock *To = Pred;
160  while (To != StopAt && !Visited.count(From->getSinglePredecessor()) &&
161  (From = From->getSinglePredecessor())) {
162  recordCondition(CS, From, To, Conditions);
163  Visited.insert(From);
164  To = From;
165  }
166 }
167 
168 static void addConditions(CallSite CS, const ConditionsTy &Conditions) {
169  for (auto &Cond : Conditions) {
170  Value *Arg = Cond.first->getOperand(0);
171  Constant *ConstVal = cast<Constant>(Cond.first->getOperand(1));
172  if (Cond.second == ICmpInst::ICMP_EQ)
173  setConstantInArgument(CS, Arg, ConstVal);
174  else if (ConstVal->getType()->isPointerTy() && ConstVal->isNullValue()) {
175  assert(Cond.second == ICmpInst::ICMP_NE);
176  addNonNullAttribute(CS, Arg);
177  }
178  }
179 }
180 
183  assert(Preds.size() == 2 && "Expected exactly 2 predecessors!");
184  return Preds;
185 }
186 
188  if (CS.isConvergent() || CS.cannotDuplicate())
189  return false;
190 
191  // FIXME: As of now we handle only CallInst. InvokeInst could be handled
192  // without too much effort.
193  Instruction *Instr = CS.getInstruction();
194  if (!isa<CallInst>(Instr))
195  return false;
196 
197  BasicBlock *CallSiteBB = Instr->getParent();
198  // Need 2 predecessors and cannot split an edge from an IndirectBrInst.
199  SmallVector<BasicBlock *, 2> Preds(predecessors(CallSiteBB));
200  if (Preds.size() != 2 || isa<IndirectBrInst>(Preds[0]->getTerminator()) ||
201  isa<IndirectBrInst>(Preds[1]->getTerminator()))
202  return false;
203 
204  // BasicBlock::canSplitPredecessors is more aggressive, so checking for
205  // BasicBlock::isEHPad as well.
206  if (!CallSiteBB->canSplitPredecessors() || CallSiteBB->isEHPad())
207  return false;
208 
209  // Allow splitting a call-site only when the CodeSize cost of the
210  // instructions before the call is less then DuplicationThreshold. The
211  // instructions before the call will be duplicated in the split blocks and
212  // corresponding uses will be updated.
213  unsigned Cost = 0;
214  for (auto &InstBeforeCall :
215  llvm::make_range(CallSiteBB->begin(), Instr->getIterator())) {
216  Cost += TTI.getInstructionCost(&InstBeforeCall,
218  if (Cost >= DuplicationThreshold)
219  return false;
220  }
221 
222  return true;
223 }
224 
226  Value *V) {
227  Instruction *Copy = I->clone();
228  Copy->setName(I->getName());
229  Copy->insertBefore(Before);
230  if (V)
231  Copy->setOperand(0, V);
232  return Copy;
233 }
234 
235 /// Copy mandatory `musttail` return sequence that follows original `CI`, and
236 /// link it up to `NewCI` value instead:
237 ///
238 /// * (optional) `bitcast NewCI to ...`
239 /// * `ret bitcast or NewCI`
240 ///
241 /// Insert this sequence right before `SplitBB`'s terminator, which will be
242 /// cleaned up later in `splitCallSite` below.
243 static void copyMustTailReturn(BasicBlock *SplitBB, Instruction *CI,
244  Instruction *NewCI) {
245  bool IsVoid = SplitBB->getParent()->getReturnType()->isVoidTy();
246  auto II = std::next(CI->getIterator());
247 
248  BitCastInst* BCI = dyn_cast<BitCastInst>(&*II);
249  if (BCI)
250  ++II;
251 
252  ReturnInst* RI = dyn_cast<ReturnInst>(&*II);
253  assert(RI && "`musttail` call must be followed by `ret` instruction");
254 
255  Instruction *TI = SplitBB->getTerminator();
256  Value *V = NewCI;
257  if (BCI)
258  V = cloneInstForMustTail(BCI, TI, V);
259  cloneInstForMustTail(RI, TI, IsVoid ? nullptr : V);
260 
261  // FIXME: remove TI here, `DuplicateInstructionsInSplitBetween` has a bug
262  // that prevents doing this now.
263 }
264 
265 /// For each (predecessor, conditions from predecessors) pair, it will split the
266 /// basic block containing the call site, hook it up to the predecessor and
267 /// replace the call instruction with new call instructions, which contain
268 /// constraints based on the conditions from their predecessors.
269 /// For example, in the IR below with an OR condition, the call-site can
270 /// be split. In this case, Preds for Tail is [(Header, a == null),
271 /// (TBB, a != null, b == null)]. Tail is replaced by 2 split blocks, containing
272 /// CallInst1, which has constraints based on the conditions from Head and
273 /// CallInst2, which has constraints based on the conditions coming from TBB.
274 ///
275 /// From :
276 ///
277 /// Header:
278 /// %c = icmp eq i32* %a, null
279 /// br i1 %c %Tail, %TBB
280 /// TBB:
281 /// %c2 = icmp eq i32* %b, null
282 /// br i1 %c %Tail, %End
283 /// Tail:
284 /// %ca = call i1 @callee (i32* %a, i32* %b)
285 ///
286 /// to :
287 ///
288 /// Header: // PredBB1 is Header
289 /// %c = icmp eq i32* %a, null
290 /// br i1 %c %Tail-split1, %TBB
291 /// TBB: // PredBB2 is TBB
292 /// %c2 = icmp eq i32* %b, null
293 /// br i1 %c %Tail-split2, %End
294 /// Tail-split1:
295 /// %ca1 = call @callee (i32* null, i32* %b) // CallInst1
296 /// br %Tail
297 /// Tail-split2:
298 /// %ca2 = call @callee (i32* nonnull %a, i32* null) // CallInst2
299 /// br %Tail
300 /// Tail:
301 /// %p = phi i1 [%ca1, %Tail-split1],[%ca2, %Tail-split2]
302 ///
303 /// Note that in case any arguments at the call-site are constrained by its
304 /// predecessors, new call-sites with more constrained arguments will be
305 /// created in createCallSitesOnPredicatedArgument().
306 static void splitCallSite(
307  CallSite CS,
308  const SmallVectorImpl<std::pair<BasicBlock *, ConditionsTy>> &Preds,
309  DomTreeUpdater &DTU) {
310  Instruction *Instr = CS.getInstruction();
311  BasicBlock *TailBB = Instr->getParent();
312  bool IsMustTailCall = CS.isMustTailCall();
313 
314  PHINode *CallPN = nullptr;
315 
316  // `musttail` calls must be followed by optional `bitcast`, and `ret`. The
317  // split blocks will be terminated right after that so there're no users for
318  // this phi in a `TailBB`.
319  if (!IsMustTailCall && !Instr->use_empty()) {
320  CallPN = PHINode::Create(Instr->getType(), Preds.size(), "phi.call");
321  CallPN->setDebugLoc(Instr->getDebugLoc());
322  }
323 
324  LLVM_DEBUG(dbgs() << "split call-site : " << *Instr << " into \n");
325 
326  assert(Preds.size() == 2 && "The ValueToValueMaps array has size 2.");
327  // ValueToValueMapTy is neither copy nor moveable, so we use a simple array
328  // here.
329  ValueToValueMapTy ValueToValueMaps[2];
330  for (unsigned i = 0; i < Preds.size(); i++) {
331  BasicBlock *PredBB = Preds[i].first;
333  TailBB, PredBB, &*std::next(Instr->getIterator()), ValueToValueMaps[i],
334  DTU);
335  assert(SplitBlock && "Unexpected new basic block split.");
336 
337  Instruction *NewCI =
338  &*std::prev(SplitBlock->getTerminator()->getIterator());
339  CallSite NewCS(NewCI);
340  addConditions(NewCS, Preds[i].second);
341 
342  // Handle PHIs used as arguments in the call-site.
343  for (PHINode &PN : TailBB->phis()) {
344  unsigned ArgNo = 0;
345  for (auto &CI : CS.args()) {
346  if (&*CI == &PN) {
347  NewCS.setArgument(ArgNo, PN.getIncomingValueForBlock(SplitBlock));
348  }
349  ++ArgNo;
350  }
351  }
352  LLVM_DEBUG(dbgs() << " " << *NewCI << " in " << SplitBlock->getName()
353  << "\n");
354  if (CallPN)
355  CallPN->addIncoming(NewCI, SplitBlock);
356 
357  // Clone and place bitcast and return instructions before `TI`
358  if (IsMustTailCall)
359  copyMustTailReturn(SplitBlock, Instr, NewCI);
360  }
361 
362  NumCallSiteSplit++;
363 
364  // FIXME: remove TI in `copyMustTailReturn`
365  if (IsMustTailCall) {
366  // Remove superfluous `br` terminators from the end of the Split blocks
367  // NOTE: Removing terminator removes the SplitBlock from the TailBB's
368  // predecessors. Therefore we must get complete list of Splits before
369  // attempting removal.
370  SmallVector<BasicBlock *, 2> Splits(predecessors((TailBB)));
371  assert(Splits.size() == 2 && "Expected exactly 2 splits!");
372  for (unsigned i = 0; i < Splits.size(); i++) {
373  Splits[i]->getTerminator()->eraseFromParent();
374  DTU.applyUpdatesPermissive({{DominatorTree::Delete, Splits[i], TailBB}});
375  }
376 
377  // Erase the tail block once done with musttail patching
378  DTU.deleteBB(TailBB);
379  return;
380  }
381 
382  auto *OriginalBegin = &*TailBB->begin();
383  // Replace users of the original call with a PHI mering call-sites split.
384  if (CallPN) {
385  CallPN->insertBefore(OriginalBegin);
386  Instr->replaceAllUsesWith(CallPN);
387  }
388 
389  // Remove instructions moved to split blocks from TailBB, from the duplicated
390  // call instruction to the beginning of the basic block. If an instruction
391  // has any uses, add a new PHI node to combine the values coming from the
392  // split blocks. The new PHI nodes are placed before the first original
393  // instruction, so we do not end up deleting them. By using reverse-order, we
394  // do not introduce unnecessary PHI nodes for def-use chains from the call
395  // instruction to the beginning of the block.
396  auto I = Instr->getReverseIterator();
397  while (I != TailBB->rend()) {
398  Instruction *CurrentI = &*I++;
399  if (!CurrentI->use_empty()) {
400  // If an existing PHI has users after the call, there is no need to create
401  // a new one.
402  if (isa<PHINode>(CurrentI))
403  continue;
404  PHINode *NewPN = PHINode::Create(CurrentI->getType(), Preds.size());
405  NewPN->setDebugLoc(CurrentI->getDebugLoc());
406  for (auto &Mapping : ValueToValueMaps)
407  NewPN->addIncoming(Mapping[CurrentI],
408  cast<Instruction>(Mapping[CurrentI])->getParent());
409  NewPN->insertBefore(&*TailBB->begin());
410  CurrentI->replaceAllUsesWith(NewPN);
411  }
412  CurrentI->eraseFromParent();
413  // We are done once we handled the first original instruction in TailBB.
414  if (CurrentI == OriginalBegin)
415  break;
416  }
417 }
418 
419 // Return true if the call-site has an argument which is a PHI with only
420 // constant incoming values.
421 static bool isPredicatedOnPHI(CallSite CS) {
422  Instruction *Instr = CS.getInstruction();
423  BasicBlock *Parent = Instr->getParent();
424  if (Instr != Parent->getFirstNonPHIOrDbg())
425  return false;
426 
427  for (auto &BI : *Parent) {
428  if (PHINode *PN = dyn_cast<PHINode>(&BI)) {
429  for (auto &I : CS.args())
430  if (&*I == PN) {
431  assert(PN->getNumIncomingValues() == 2 &&
432  "Unexpected number of incoming values");
433  if (PN->getIncomingBlock(0) == PN->getIncomingBlock(1))
434  return false;
435  if (PN->getIncomingValue(0) == PN->getIncomingValue(1))
436  continue;
437  if (isa<Constant>(PN->getIncomingValue(0)) &&
438  isa<Constant>(PN->getIncomingValue(1)))
439  return true;
440  }
441  }
442  break;
443  }
444  return false;
445 }
446 
448 
449 // Check if any of the arguments in CS are predicated on a PHI node and return
450 // the set of predecessors we should use for splitting.
452  if (!isPredicatedOnPHI(CS))
453  return {};
454 
455  auto Preds = getTwoPredecessors(CS.getInstruction()->getParent());
456  return {{Preds[0], {}}, {Preds[1], {}}};
457 }
458 
459 // Checks if any of the arguments in CS are predicated in a predecessor and
460 // returns a list of predecessors with the conditions that hold on their edges
461 // to CS.
463  DomTreeUpdater &DTU) {
464  auto Preds = getTwoPredecessors(CS.getInstruction()->getParent());
465  if (Preds[0] == Preds[1])
466  return {};
467 
468  // We can stop recording conditions once we reached the immediate dominator
469  // for the block containing the call site. Conditions in predecessors of the
470  // that node will be the same for all paths to the call site and splitting
471  // is not beneficial.
472  assert(DTU.hasDomTree() && "We need a DTU with a valid DT!");
473  auto *CSDTNode = DTU.getDomTree().getNode(CS.getInstruction()->getParent());
474  BasicBlock *StopAt = CSDTNode ? CSDTNode->getIDom()->getBlock() : nullptr;
475 
477  for (auto *Pred : make_range(Preds.rbegin(), Preds.rend())) {
478  ConditionsTy Conditions;
479  // Record condition on edge BB(CS) <- Pred
480  recordCondition(CS, Pred, CS.getInstruction()->getParent(), Conditions);
481  // Record conditions following Pred's single predecessors.
482  recordConditions(CS, Pred, Conditions, StopAt);
483  PredsCS.push_back({Pred, Conditions});
484  }
485 
486  if (all_of(PredsCS, [](const std::pair<BasicBlock *, ConditionsTy> &P) {
487  return P.second.empty();
488  }))
489  return {};
490 
491  return PredsCS;
492 }
493 
495  DomTreeUpdater &DTU) {
496  // Check if we can split the call site.
497  if (!CS.arg_size() || !canSplitCallSite(CS, TTI))
498  return false;
499 
500  auto PredsWithConds = shouldSplitOnPredicatedArgument(CS, DTU);
501  if (PredsWithConds.empty())
502  PredsWithConds = shouldSplitOnPHIPredicatedArgument(CS);
503  if (PredsWithConds.empty())
504  return false;
505 
506  splitCallSite(CS, PredsWithConds, DTU);
507  return true;
508 }
509 
512 
514  bool Changed = false;
515  for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE;) {
516  BasicBlock &BB = *BI++;
517  auto II = BB.getFirstNonPHIOrDbg()->getIterator();
518  auto IE = BB.getTerminator()->getIterator();
519  // Iterate until we reach the terminator instruction. tryToSplitCallSite
520  // can replace BB's terminator in case BB is a successor of itself. In that
521  // case, IE will be invalidated and we also have to check the current
522  // terminator.
523  while (II != IE && &*II != BB.getTerminator()) {
524  Instruction *I = &*II++;
525  CallSite CS(cast<Value>(I));
526  if (!CS || isa<IntrinsicInst>(I) || isInstructionTriviallyDead(I, &TLI))
527  continue;
528 
530  if (!Callee || Callee->isDeclaration())
531  continue;
532 
533  // Successful musttail call-site splits result in erased CI and erased BB.
534  // Check if such path is possible before attempting the splitting.
535  bool IsMustTail = CS.isMustTailCall();
536 
537  Changed |= tryToSplitCallSite(CS, TTI, DTU);
538 
539  // There're no interesting instructions after this. The call site
540  // itself might have been erased on splitting.
541  if (IsMustTail)
542  break;
543  }
544  }
545  return Changed;
546 }
547 
548 namespace {
549 struct CallSiteSplittingLegacyPass : public FunctionPass {
550  static char ID;
551  CallSiteSplittingLegacyPass() : FunctionPass(ID) {
553  }
554 
555  void getAnalysisUsage(AnalysisUsage &AU) const override {
561  }
562 
563  bool runOnFunction(Function &F) override {
564  if (skipFunction(F))
565  return false;
566 
567  auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
568  auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
569  auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
570  return doCallSiteSplitting(F, TLI, TTI, DT);
571  }
572 };
573 } // namespace
574 
576 INITIALIZE_PASS_BEGIN(CallSiteSplittingLegacyPass, "callsite-splitting",
577  "Call-site splitting", false, false)
581 INITIALIZE_PASS_END(CallSiteSplittingLegacyPass, "callsite-splitting",
582  "Call-site splitting", false, false)
584  return new CallSiteSplittingLegacyPass();
585 }
586 
589  auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
590  auto &TTI = AM.getResult<TargetIRAnalysis>(F);
591  auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
592 
593  if (!doCallSiteSplitting(F, TLI, TTI, DT))
594  return PreservedAnalyses::all();
597  return PA;
598 }
IterTy arg_end() const
Definition: CallSite.h:588
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:67
bool canSplitPredecessors() const
Definition: BasicBlock.cpp:378
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:71
static bool canSplitCallSite(CallSite CS, TargetTransformInfo &TTI)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
BasicBlock * DuplicateInstructionsInSplitBetween(BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt, ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU)
Split edge between BB and PredBB and duplicate all non-Phi instructions from BB between its beginning...
static PredsWithCondsTy shouldSplitOnPHIPredicatedArgument(CallSite CS)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:777
IterTy arg_begin() const
Definition: CallSite.h:584
This class represents lattice values for constants.
Definition: AllocatorList.h:23
static bool tryToSplitCallSite(CallSite CS, TargetTransformInfo &TTI, DomTreeUpdater &DTU)
iterator end()
Definition: Function.h:693
SmallVector< ConditionTy, 2 > ConditionsTy
void push_back(const T &Elt)
Definition: SmallVector.h:211
DominatorTree & getDomTree()
Flush DomTree updates and return DomTree.
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Definition: PatternMatch.h:90
Analysis pass providing the TargetTransformInfo.
unsigned second
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1182
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:230
F(f)
reverse_iterator rend()
Definition: BasicBlock.h:280
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it&#39;s an indirect...
Definition: CallSite.h:111
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:144
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
static void recordConditions(CallSite CS, BasicBlock *Pred, ConditionsTy &Conditions, BasicBlock *StopAt)
Record ICmp conditions relevant to any argument in CS following Pred&#39;s single predecessors.
static void copyMustTailReturn(BasicBlock *SplitBB, Instruction *CI, Instruction *NewCI)
Copy mandatory musttail return sequence that follows original CI, and link it up to NewCI value inste...
int getInstructionCost(const Instruction *I, enum TargetCostKind kind) const
Query the cost of a specified instruction.
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:273
INITIALIZE_PASS_BEGIN(CallSiteSplittingLegacyPass, "callsite-splitting", "Call-site splitting", false, false) INITIALIZE_PASS_END(CallSiteSplittingLegacyPass
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:48
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
static void splitCallSite(CallSite CS, const SmallVectorImpl< std::pair< BasicBlock *, ConditionsTy >> &Preds, DomTreeUpdater &DTU)
For each (predecessor, conditions from predecessors) pair, it will split the basic block containing t...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
void initializeCallSiteSplittingLegacyPassPass(PassRegistry &)
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:286
static cl::opt< unsigned > DuplicationThreshold("callsite-splitting-duplication-threshold", cl::Hidden, cl::desc("Only allow instructions before a call, if " "their cost is below DuplicationThreshold"), cl::init(5))
Only allow instructions before a call, if their CodeSize cost is below DuplicationThreshold.
InstrTy * getInstruction() const
Definition: CallSite.h:96
Instruction * clone() const
Create a copy of &#39;this&#39; instruction that is identical in all ways except the following: ...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:86
void setArgument(unsigned ArgNo, Value *newVal)
Definition: CallSite.h:198
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:96
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
bool isMustTailCall() const
Tests if this call site must be tail call optimized.
Definition: CallSite.h:279
This class represents a no-op cast from one type to another.
bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the call or the callee has the given attribute.
Definition: CallSite.h:385
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:430
iterator begin()
Definition: Function.h:691
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
Value * getOperand(unsigned i) const
Definition: User.h:169
bool isVoidTy() const
Return true if this is &#39;void&#39;.
Definition: Type.h:141
static bool runOnFunction(Function &F, bool PostInlining)
#define P(N)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
Type * getReturnType() const
Returns the type of the ret val.
Definition: Function.h:168
Wrapper pass for TargetTransformInfo.
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:328
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:240
static void addNonNullAttribute(CallSite CS, Value *Op)
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
Definition: Instruction.cpp:73
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Conditional or Unconditional Branch instruction.
bool cannotDuplicate() const
Determine if the call can be duplicated.
Definition: CallSite.h:526
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Definition: CallSite.h:365
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:224
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:370
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
Represent the analysis usage information of a pass.
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:732
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:282
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
self_iterator getIterator()
Definition: ilist_node.h:81
void applyUpdatesPermissive(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
static void setConstantInArgument(CallSite CS, Value *Op, Constant *ConstValue)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
size_t size() const
Definition: SmallVector.h:52
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
static bool doCallSiteSplitting(Function &F, TargetLibraryInfo &TLI, TargetTransformInfo &TTI, DominatorTree &DT)
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
iterator_range< IterTy > args() const
Definition: CallSite.h:222
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
std::pair< ICmpInst *, unsigned > ConditionTy
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:443
BlockVerifier::State From
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
static void recordCondition(CallSite CS, BasicBlock *From, BasicBlock *To, ConditionsTy &Conditions)
If From has a conditional jump to To, add the condition to Conditions, if it is relevant to any argum...
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
Provides information about what library functions are available for the current target.
bool isConvergent() const
Determine if the call is convergent.
Definition: CallSite.h:534
unsigned arg_size() const
Definition: CallSite.h:226
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...
pred_range predecessors(BasicBlock *BB)
Definition: CFG.h:124
User::op_iterator arg_iterator
The type of iterator to use when looping over actual arguments at this call site. ...
Definition: CallSite.h:220
void setOperand(unsigned i, Value *Val)
Definition: User.h:174
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
static bool isCondRelevantToAnyCallArgument(ICmpInst *Cmp, CallSite CS)
amdgpu Simplify well known AMD library false FunctionCallee Callee
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:331
reverse_self_iterator getReverseIterator()
Definition: ilist_node.h:84
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:215
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
#define I(x, y, z)
Definition: MD5.cpp:58
static Instruction * cloneInstForMustTail(Instruction *I, Instruction *Before, Value *V)
callsite splitting
static bool isPredicatedOnPHI(CallSite CS)
LLVM_NODISCARD 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:332
static SmallVector< BasicBlock *, 2 > getTwoPredecessors(BasicBlock *BB)
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:175
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:329
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:231
Analysis pass providing the TargetLibraryInfo.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition: BasicBlock.h:411
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
Definition: Local.cpp:359
LLVM Value Representation.
Definition: Value.h:74
static void addConditions(CallSite CS, const ConditionsTy &Conditions)
static const Function * getParent(const Value *V)
A container for analyses that lazily runs them and caches their results.
const Instruction * getFirstNonPHIOrDbg() const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic...
Definition: BasicBlock.cpp:203
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:259
bool hasDomTree() const
Returns true if it holds a DominatorTree.
This pass exposes codegen information to IR-level passes.
#define LLVM_DEBUG(X)
Definition: Debug.h:122
bool use_empty() const
Definition: Value.h:343
const BasicBlock * getParent() const
Definition: Instruction.h:66
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Definition: CallSite.h:353
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
static PredsWithCondsTy shouldSplitOnPredicatedArgument(CallSite CS, DomTreeUpdater &DTU)
FunctionPass * createCallSiteSplittingPass()