JumpThreading.cpp revision 3cda3cdab118fd2b185b3e6e05e2b19a4a70c1ad
1//===- JumpThreading.cpp - Thread control through conditional blocks ------===//
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 Jump Threading pass.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "jump-threading"
15#include "llvm/Transforms/Scalar.h"
16#include "llvm/IntrinsicInst.h"
17#include "llvm/Pass.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/Analysis/ConstantFolding.h"
22#include "llvm/Transforms/Utils/BasicBlockUtils.h"
23#include "llvm/Transforms/Utils/Local.h"
24#include "llvm/Target/TargetData.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Compiler.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/ADT/SmallPtrSet.h"
29using namespace llvm;
30
31STATISTIC(NumThreads, "Number of jumps threaded");
32STATISTIC(NumFolds,   "Number of terminators folded");
33
34static cl::opt<unsigned>
35Threshold("jump-threading-threshold",
36          cl::desc("Max block size to duplicate for jump threading"),
37          cl::init(6), cl::Hidden);
38
39static cl::opt<int>
40DebugIterations("jump-threading-debug",
41                cl::desc("Stop jump threading after N iterations"),
42                cl::init(-1), cl::Hidden);
43
44namespace {
45  /// This pass performs 'jump threading', which looks at blocks that have
46  /// multiple predecessors and multiple successors.  If one or more of the
47  /// predecessors of the block can be proven to always jump to one of the
48  /// successors, we forward the edge from the predecessor to the successor by
49  /// duplicating the contents of this block.
50  ///
51  /// An example of when this can occur is code like this:
52  ///
53  ///   if () { ...
54  ///     X = 4;
55  ///   }
56  ///   if (X < 3) {
57  ///
58  /// In this case, the unconditional branch at the end of the first if can be
59  /// revectored to the false side of the second if.
60  ///
61  class VISIBILITY_HIDDEN JumpThreading : public FunctionPass {
62    TargetData *TD;
63  public:
64    static char ID; // Pass identification
65    JumpThreading() : FunctionPass(&ID) {}
66
67    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68      AU.addRequired<TargetData>();
69    }
70
71    bool runOnFunction(Function &F);
72    bool ProcessBlock(BasicBlock *BB);
73    void ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
74    BasicBlock *FactorCommonPHIPreds(PHINode *PN, Constant *CstVal);
75    bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
76    bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
77
78    bool ProcessJumpOnPHI(PHINode *PN);
79    bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
80    bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB);
81
82    bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
83  };
84}
85
86char JumpThreading::ID = 0;
87static RegisterPass<JumpThreading>
88X("jump-threading", "Jump Threading");
89
90// Public interface to the Jump Threading pass
91FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
92
93/// runOnFunction - Top level algorithm.
94///
95bool JumpThreading::runOnFunction(Function &F) {
96  DOUT << "Jump threading on function '" << F.getNameStart() << "'\n";
97  TD = &getAnalysis<TargetData>();
98
99  bool AnotherIteration = true, EverChanged = false;
100  while (AnotherIteration) {
101    AnotherIteration = false;
102    bool Changed = false;
103    for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
104      BasicBlock *BB = I;
105      while (ProcessBlock(BB))
106        Changed = true;
107
108      ++I;
109
110      // If the block is trivially dead, zap it.  This eliminates the successor
111      // edges which simplifies the CFG.
112      if (pred_begin(BB) == pred_end(BB) &&
113          BB != &BB->getParent()->getEntryBlock() &&
114          DebugIterations != 0) {
115        DOUT << "  JT: Deleting dead block '" << BB->getNameStart()
116             << "' with terminator: " << *BB->getTerminator();
117        DeleteDeadBlock(BB);
118        Changed = true;
119
120        if (DebugIterations != -1)
121          DebugIterations = DebugIterations-1;
122      }
123    }
124    AnotherIteration = Changed;
125    EverChanged |= Changed;
126  }
127  return EverChanged;
128}
129
130/// FactorCommonPHIPreds - If there are multiple preds with the same incoming
131/// value for the PHI, factor them together so we get one block to thread for
132/// the whole group.
133/// This is important for things like "phi i1 [true, true, false, true, x]"
134/// where we only need to clone the block for the true blocks once.
135///
136BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Constant *CstVal) {
137  SmallVector<BasicBlock*, 16> CommonPreds;
138  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
139    if (PN->getIncomingValue(i) == CstVal)
140      CommonPreds.push_back(PN->getIncomingBlock(i));
141
142  if (CommonPreds.size() == 1)
143    return CommonPreds[0];
144
145  DOUT << "  Factoring out " << CommonPreds.size()
146       << " common predecessors.\n";
147  return SplitBlockPredecessors(PN->getParent(),
148                                &CommonPreds[0], CommonPreds.size(),
149                                ".thr_comm", this);
150}
151
152
153/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
154/// thread across it.
155static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
156  /// Ignore PHI nodes, these will be flattened when duplication happens.
157  BasicBlock::const_iterator I = BB->getFirstNonPHI();
158
159  // Sum up the cost of each instruction until we get to the terminator.  Don't
160  // include the terminator because the copy won't include it.
161  unsigned Size = 0;
162  for (; !isa<TerminatorInst>(I); ++I) {
163    // Debugger intrinsics don't incur code size.
164    if (isa<DbgInfoIntrinsic>(I)) continue;
165
166    // If this is a pointer->pointer bitcast, it is free.
167    if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
168      continue;
169
170    // All other instructions count for at least one unit.
171    ++Size;
172
173    // Calls are more expensive.  If they are non-intrinsic calls, we model them
174    // as having cost of 4.  If they are a non-vector intrinsic, we model them
175    // as having cost of 2 total, and if they are a vector intrinsic, we model
176    // them as having cost 1.
177    if (const CallInst *CI = dyn_cast<CallInst>(I)) {
178      if (!isa<IntrinsicInst>(CI))
179        Size += 3;
180      else if (isa<VectorType>(CI->getType()))
181        Size += 1;
182    }
183  }
184
185  // Threading through a switch statement is particularly profitable.  If this
186  // block ends in a switch, decrease its cost to make it more likely to happen.
187  if (isa<SwitchInst>(I))
188    Size = Size > 6 ? Size-6 : 0;
189
190  return Size;
191}
192
193/// ProcessBlock - If there are any predecessors whose control can be threaded
194/// through to a successor, transform them now.
195bool JumpThreading::ProcessBlock(BasicBlock *BB) {
196  if (DebugIterations == 0) return false;
197  if (DebugIterations != -1)
198    DebugIterations = DebugIterations-1;
199
200  // If this block has a single predecessor, and if that pred has a single
201  // successor, merge the blocks.  This encourages recursive jump threading
202  // because now the condition in this block can be threaded through
203  // predecessors of our predecessor block.
204  if (BasicBlock *SinglePred = BB->getSinglePredecessor())
205    if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
206        SinglePred != BB) {
207      // Remember if SinglePred was the entry block of the function.  If so, we
208      // will need to move BB back to the entry position.
209      bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
210      MergeBasicBlockIntoOnlyPred(BB);
211
212      if (isEntry && BB != &BB->getParent()->getEntryBlock())
213        BB->moveBefore(&BB->getParent()->getEntryBlock());
214      return true;
215    }
216
217  // See if this block ends with a branch or switch.  If so, see if the
218  // condition is a phi node.  If so, and if an entry of the phi node is a
219  // constant, we can thread the block.
220  Value *Condition;
221  if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
222    // Can't thread an unconditional jump.
223    if (BI->isUnconditional()) return false;
224    Condition = BI->getCondition();
225  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
226    Condition = SI->getCondition();
227  else
228    return false; // Must be an invoke.
229
230  // If the terminator of this block is branching on a constant, simplify the
231  // terminator to an unconditional branch.  This can occur due to threading in
232  // other blocks.
233  if (isa<ConstantInt>(Condition)) {
234    DOUT << "  In block '" << BB->getNameStart()
235         << "' folding terminator: " << *BB->getTerminator();
236    ++NumFolds;
237    ConstantFoldTerminator(BB);
238    return true;
239  }
240
241  // If the terminator is branching on an undef, we can pick any of the
242  // successors to branch to.  Since this is arbitrary, we pick the successor
243  // with the fewest predecessors.  This should reduce the in-degree of the
244  // others.
245  if (isa<UndefValue>(Condition)) {
246    TerminatorInst *BBTerm = BB->getTerminator();
247    unsigned MinSucc = 0;
248    BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
249    // Compute the successor with the minimum number of predecessors.
250    unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
251    for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
252      TestBB = BBTerm->getSuccessor(i);
253      unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
254      if (NumPreds < MinNumPreds)
255        MinSucc = i;
256    }
257
258    // Fold the branch/switch.
259    for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
260      if (i == MinSucc) continue;
261      BBTerm->getSuccessor(i)->removePredecessor(BB);
262    }
263
264    DOUT << "  In block '" << BB->getNameStart()
265         << "' folding undef terminator: " << *BBTerm;
266    BranchInst::Create(BBTerm->getSuccessor(MinSucc), BBTerm);
267    BBTerm->eraseFromParent();
268    return true;
269  }
270
271  Instruction *CondInst = dyn_cast<Instruction>(Condition);
272
273  // If the condition is an instruction defined in another block, see if a
274  // predecessor has the same condition:
275  //     br COND, BBX, BBY
276  //  BBX:
277  //     br COND, BBZ, BBW
278  if (!Condition->hasOneUse() && // Multiple uses.
279      (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
280    pred_iterator PI = pred_begin(BB), E = pred_end(BB);
281    if (isa<BranchInst>(BB->getTerminator())) {
282      for (; PI != E; ++PI)
283        if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
284          if (PBI->isConditional() && PBI->getCondition() == Condition &&
285              ProcessBranchOnDuplicateCond(*PI, BB))
286            return true;
287    } else {
288      assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
289      for (; PI != E; ++PI)
290        if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
291          if (PSI->getCondition() == Condition &&
292              ProcessSwitchOnDuplicateCond(*PI, BB))
293            return true;
294    }
295  }
296
297  // If there is only a single predecessor of this block, nothing to fold.
298  if (BB->getSinglePredecessor())
299    return false;
300
301  // All the rest of our checks depend on the condition being an instruction.
302  if (CondInst == 0)
303    return false;
304
305  // See if this is a phi node in the current block.
306  if (PHINode *PN = dyn_cast<PHINode>(CondInst))
307    if (PN->getParent() == BB)
308      return ProcessJumpOnPHI(PN);
309
310  // If this is a conditional branch whose condition is and/or of a phi, try to
311  // simplify it.
312  if ((CondInst->getOpcode() == Instruction::And ||
313       CondInst->getOpcode() == Instruction::Or) &&
314      isa<BranchInst>(BB->getTerminator()) &&
315      ProcessBranchOnLogical(CondInst, BB,
316                             CondInst->getOpcode() == Instruction::And))
317    return true;
318
319  // If we have "br (phi != 42)" and the phi node has any constant values as
320  // operands, we can thread through this block.
321  if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst))
322    if (isa<PHINode>(CondCmp->getOperand(0)) &&
323        isa<Constant>(CondCmp->getOperand(1)) &&
324        ProcessBranchOnCompare(CondCmp, BB))
325      return true;
326
327  // Check for some cases that are worth simplifying.  Right now we want to look
328  // for loads that are used by a switch or by the condition for the branch.  If
329  // we see one, check to see if it's partially redundant.  If so, insert a PHI
330  // which can then be used to thread the values.
331  //
332  // This is particularly important because reg2mem inserts loads and stores all
333  // over the place, and this blocks jump threading if we don't zap them.
334  Value *SimplifyValue = CondInst;
335  if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
336    if (isa<Constant>(CondCmp->getOperand(1)))
337      SimplifyValue = CondCmp->getOperand(0);
338
339  if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
340    if (SimplifyPartiallyRedundantLoad(LI))
341      return true;
342
343  // TODO: If we have: "br (X > 0)"  and we have a predecessor where we know
344  // "(X == 4)" thread through this block.
345
346  return false;
347}
348
349/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
350/// block that jump on exactly the same condition.  This means that we almost
351/// always know the direction of the edge in the DESTBB:
352///  PREDBB:
353///     br COND, DESTBB, BBY
354///  DESTBB:
355///     br COND, BBZ, BBW
356///
357/// If DESTBB has multiple predecessors, we can't just constant fold the branch
358/// in DESTBB, we have to thread over it.
359bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
360                                                 BasicBlock *BB) {
361  BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
362
363  // If both successors of PredBB go to DESTBB, we don't know anything.  We can
364  // fold the branch to an unconditional one, which allows other recursive
365  // simplifications.
366  bool BranchDir;
367  if (PredBI->getSuccessor(1) != BB)
368    BranchDir = true;
369  else if (PredBI->getSuccessor(0) != BB)
370    BranchDir = false;
371  else {
372    DOUT << "  In block '" << PredBB->getNameStart()
373         << "' folding terminator: " << *PredBB->getTerminator();
374    ++NumFolds;
375    ConstantFoldTerminator(PredBB);
376    return true;
377  }
378
379  BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
380
381  // If the dest block has one predecessor, just fix the branch condition to a
382  // constant and fold it.
383  if (BB->getSinglePredecessor()) {
384    DOUT << "  In block '" << BB->getNameStart()
385         << "' folding condition to '" << BranchDir << "': "
386         << *BB->getTerminator();
387    ++NumFolds;
388    DestBI->setCondition(ConstantInt::get(Type::Int1Ty, BranchDir));
389    ConstantFoldTerminator(BB);
390    return true;
391  }
392
393  // Otherwise we need to thread from PredBB to DestBB's successor which
394  // involves code duplication.  Check to see if it is worth it.
395  unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
396  if (JumpThreadCost > Threshold) {
397    DOUT << "  Not threading BB '" << BB->getNameStart()
398         << "' - Cost is too high: " << JumpThreadCost << "\n";
399    return false;
400  }
401
402  // Next, figure out which successor we are threading to.
403  BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
404
405  // If threading to the same block as we come from, we would infinite loop.
406  if (SuccBB == BB) {
407    DOUT << "  Not threading BB '" << BB->getNameStart()
408         << "' - would thread to self!\n";
409    return false;
410  }
411
412  // And finally, do it!
413  DOUT << "  Threading edge from '" << PredBB->getNameStart() << "' to '"
414       << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
415       << ", across block:\n    "
416       << *BB << "\n";
417
418  ThreadEdge(BB, PredBB, SuccBB);
419  ++NumThreads;
420  return true;
421}
422
423/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
424/// block that switch on exactly the same condition.  This means that we almost
425/// always know the direction of the edge in the DESTBB:
426///  PREDBB:
427///     switch COND [... DESTBB, BBY ... ]
428///  DESTBB:
429///     switch COND [... BBZ, BBW ]
430///
431/// Optimizing switches like this is very important, because simplifycfg builds
432/// switches out of repeated 'if' conditions.
433bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
434                                                 BasicBlock *DestBB) {
435  SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
436  SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
437
438  // There are a variety of optimizations that we can potentially do on these
439  // blocks: we order them from most to least preferable.
440
441  // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
442  // directly to their destination.  This does not introduce *any* code size
443  // growth.
444
445  // FIXME: Thread if it just contains a PHI.
446  if (isa<SwitchInst>(DestBB->begin())) {
447    bool MadeChange = false;
448    // Ignore the default edge for now.
449    for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
450      ConstantInt *DestVal = DestSI->getCaseValue(i);
451      BasicBlock *DestSucc = DestSI->getSuccessor(i);
452
453      // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'.  See if
454      // PredSI has an explicit case for it.  If so, forward.  If it is covered
455      // by the default case, we can't update PredSI.
456      unsigned PredCase = PredSI->findCaseValue(DestVal);
457      if (PredCase == 0) continue;
458
459      // If PredSI doesn't go to DestBB on this value, then it won't reach the
460      // case on this condition.
461      if (PredSI->getSuccessor(PredCase) != DestBB &&
462          DestSI->getSuccessor(i) != DestBB)
463        continue;
464
465      // Otherwise, we're safe to make the change.  Make sure that the edge from
466      // DestSI to DestSucc is not critical and has no PHI nodes.
467      DOUT << "FORWARDING EDGE " << *DestVal << "   FROM: " << *PredSI;
468      DOUT << "THROUGH: " << *DestSI;
469
470      // If the destination has PHI nodes, just split the edge for updating
471      // simplicity.
472      if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
473        SplitCriticalEdge(DestSI, i, this);
474        DestSucc = DestSI->getSuccessor(i);
475      }
476      FoldSingleEntryPHINodes(DestSucc);
477      PredSI->setSuccessor(PredCase, DestSucc);
478      MadeChange = true;
479    }
480
481    if (MadeChange)
482      return true;
483  }
484
485  return false;
486}
487
488
489/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
490/// load instruction, eliminate it by replacing it with a PHI node.  This is an
491/// important optimization that encourages jump threading, and needs to be run
492/// interlaced with other jump threading tasks.
493bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
494  // Don't hack volatile loads.
495  if (LI->isVolatile()) return false;
496
497  // If the load is defined in a block with exactly one predecessor, it can't be
498  // partially redundant.
499  BasicBlock *LoadBB = LI->getParent();
500  if (LoadBB->getSinglePredecessor())
501    return false;
502
503  Value *LoadedPtr = LI->getOperand(0);
504
505  // If the loaded operand is defined in the LoadBB, it can't be available.
506  // FIXME: Could do PHI translation, that would be fun :)
507  if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
508    if (PtrOp->getParent() == LoadBB)
509      return false;
510
511  // Scan a few instructions up from the load, to see if it is obviously live at
512  // the entry to its block.
513  BasicBlock::iterator BBIt = LI;
514
515  if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
516                                                     BBIt, 6)) {
517    // If the value if the load is locally available within the block, just use
518    // it.  This frequently occurs for reg2mem'd allocas.
519    //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
520    LI->replaceAllUsesWith(AvailableVal);
521    LI->eraseFromParent();
522    return true;
523  }
524
525  // Otherwise, if we scanned the whole block and got to the top of the block,
526  // we know the block is locally transparent to the load.  If not, something
527  // might clobber its value.
528  if (BBIt != LoadBB->begin())
529    return false;
530
531
532  SmallPtrSet<BasicBlock*, 8> PredsScanned;
533  typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
534  AvailablePredsTy AvailablePreds;
535  BasicBlock *OneUnavailablePred = 0;
536
537  // If we got here, the loaded value is transparent through to the start of the
538  // block.  Check to see if it is available in any of the predecessor blocks.
539  for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
540       PI != PE; ++PI) {
541    BasicBlock *PredBB = *PI;
542
543    // If we already scanned this predecessor, skip it.
544    if (!PredsScanned.insert(PredBB))
545      continue;
546
547    // Scan the predecessor to see if the value is available in the pred.
548    BBIt = PredBB->end();
549    Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
550    if (!PredAvailable) {
551      OneUnavailablePred = PredBB;
552      continue;
553    }
554
555    // If so, this load is partially redundant.  Remember this info so that we
556    // can create a PHI node.
557    AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
558  }
559
560  // If the loaded value isn't available in any predecessor, it isn't partially
561  // redundant.
562  if (AvailablePreds.empty()) return false;
563
564  // Okay, the loaded value is available in at least one (and maybe all!)
565  // predecessors.  If the value is unavailable in more than one unique
566  // predecessor, we want to insert a merge block for those common predecessors.
567  // This ensures that we only have to insert one reload, thus not increasing
568  // code size.
569  BasicBlock *UnavailablePred = 0;
570
571  // If there is exactly one predecessor where the value is unavailable, the
572  // already computed 'OneUnavailablePred' block is it.  If it ends in an
573  // unconditional branch, we know that it isn't a critical edge.
574  if (PredsScanned.size() == AvailablePreds.size()+1 &&
575      OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
576    UnavailablePred = OneUnavailablePred;
577  } else if (PredsScanned.size() != AvailablePreds.size()) {
578    // Otherwise, we had multiple unavailable predecessors or we had a critical
579    // edge from the one.
580    SmallVector<BasicBlock*, 8> PredsToSplit;
581    SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
582
583    for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
584      AvailablePredSet.insert(AvailablePreds[i].first);
585
586    // Add all the unavailable predecessors to the PredsToSplit list.
587    for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
588         PI != PE; ++PI)
589      if (!AvailablePredSet.count(*PI))
590        PredsToSplit.push_back(*PI);
591
592    // Split them out to their own block.
593    UnavailablePred =
594      SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
595                             "thread-split", this);
596  }
597
598  // If the value isn't available in all predecessors, then there will be
599  // exactly one where it isn't available.  Insert a load on that edge and add
600  // it to the AvailablePreds list.
601  if (UnavailablePred) {
602    assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
603           "Can't handle critical edge here!");
604    Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
605                                 UnavailablePred->getTerminator());
606    AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
607  }
608
609  // Now we know that each predecessor of this block has a value in
610  // AvailablePreds, sort them for efficient access as we're walking the preds.
611  array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
612
613  // Create a PHI node at the start of the block for the PRE'd load value.
614  PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
615  PN->takeName(LI);
616
617  // Insert new entries into the PHI for each predecessor.  A single block may
618  // have multiple entries here.
619  for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
620       ++PI) {
621    AvailablePredsTy::iterator I =
622      std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
623                       std::make_pair(*PI, (Value*)0));
624
625    assert(I != AvailablePreds.end() && I->first == *PI &&
626           "Didn't find entry for predecessor!");
627
628    PN->addIncoming(I->second, I->first);
629  }
630
631  //cerr << "PRE: " << *LI << *PN << "\n";
632
633  LI->replaceAllUsesWith(PN);
634  LI->eraseFromParent();
635
636  return true;
637}
638
639
640/// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
641/// the current block.  See if there are any simplifications we can do based on
642/// inputs to the phi node.
643///
644bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
645  // See if the phi node has any constant values.  If so, we can determine where
646  // the corresponding predecessor will branch.
647  ConstantInt *PredCst = 0;
648  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
649    if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i))))
650      break;
651
652  // If no incoming value has a constant, we don't know the destination of any
653  // predecessors.
654  if (PredCst == 0)
655    return false;
656
657  // See if the cost of duplicating this block is low enough.
658  BasicBlock *BB = PN->getParent();
659  unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
660  if (JumpThreadCost > Threshold) {
661    DOUT << "  Not threading BB '" << BB->getNameStart()
662         << "' - Cost is too high: " << JumpThreadCost << "\n";
663    return false;
664  }
665
666  // If so, we can actually do this threading.  Merge any common predecessors
667  // that will act the same.
668  BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
669
670  // Next, figure out which successor we are threading to.
671  BasicBlock *SuccBB;
672  if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
673    SuccBB = BI->getSuccessor(PredCst == ConstantInt::getFalse());
674  else {
675    SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
676    SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
677  }
678
679  // If threading to the same block as we come from, we would infinite loop.
680  if (SuccBB == BB) {
681    DOUT << "  Not threading BB '" << BB->getNameStart()
682         << "' - would thread to self!\n";
683    return false;
684  }
685
686  // And finally, do it!
687  DOUT << "  Threading edge from '" << PredBB->getNameStart() << "' to '"
688       << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
689       << ", across block:\n    "
690       << *BB << "\n";
691
692  ThreadEdge(BB, PredBB, SuccBB);
693  ++NumThreads;
694  return true;
695}
696
697/// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
698/// whose condition is an AND/OR where one side is PN.  If PN has constant
699/// operands that permit us to evaluate the condition for some operand, thread
700/// through the block.  For example with:
701///   br (and X, phi(Y, Z, false))
702/// the predecessor corresponding to the 'false' will always jump to the false
703/// destination of the branch.
704///
705bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
706                                           bool isAnd) {
707  // If this is a binary operator tree of the same AND/OR opcode, check the
708  // LHS/RHS.
709  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
710    if ((isAnd && BO->getOpcode() == Instruction::And) ||
711        (!isAnd && BO->getOpcode() == Instruction::Or)) {
712      if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
713        return true;
714      if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
715        return true;
716    }
717
718  // If this isn't a PHI node, we can't handle it.
719  PHINode *PN = dyn_cast<PHINode>(V);
720  if (!PN || PN->getParent() != BB) return false;
721
722  // We can only do the simplification for phi nodes of 'false' with AND or
723  // 'true' with OR.  See if we have any entries in the phi for this.
724  unsigned PredNo = ~0U;
725  ConstantInt *PredCst = ConstantInt::get(Type::Int1Ty, !isAnd);
726  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
727    if (PN->getIncomingValue(i) == PredCst) {
728      PredNo = i;
729      break;
730    }
731  }
732
733  // If no match, bail out.
734  if (PredNo == ~0U)
735    return false;
736
737  // See if the cost of duplicating this block is low enough.
738  unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
739  if (JumpThreadCost > Threshold) {
740    DOUT << "  Not threading BB '" << BB->getNameStart()
741         << "' - Cost is too high: " << JumpThreadCost << "\n";
742    return false;
743  }
744
745  // If so, we can actually do this threading.  Merge any common predecessors
746  // that will act the same.
747  BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
748
749  // Next, figure out which successor we are threading to.  If this was an AND,
750  // the constant must be FALSE, and we must be targeting the 'false' block.
751  // If this is an OR, the constant must be TRUE, and we must be targeting the
752  // 'true' block.
753  BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
754
755  // If threading to the same block as we come from, we would infinite loop.
756  if (SuccBB == BB) {
757    DOUT << "  Not threading BB '" << BB->getNameStart()
758    << "' - would thread to self!\n";
759    return false;
760  }
761
762  // And finally, do it!
763  DOUT << "  Threading edge through bool from '" << PredBB->getNameStart()
764       << "' to '" << SuccBB->getNameStart() << "' with cost: "
765       << JumpThreadCost << ", across block:\n    "
766       << *BB << "\n";
767
768  ThreadEdge(BB, PredBB, SuccBB);
769  ++NumThreads;
770  return true;
771}
772
773/// ProcessBranchOnCompare - We found a branch on a comparison between a phi
774/// node and a constant.  If the PHI node contains any constants as inputs, we
775/// can fold the compare for that edge and thread through it.
776bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
777  PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
778  Constant *RHS = cast<Constant>(Cmp->getOperand(1));
779
780  // If the phi isn't in the current block, an incoming edge to this block
781  // doesn't control the destination.
782  if (PN->getParent() != BB)
783    return false;
784
785  // We can do this simplification if any comparisons fold to true or false.
786  // See if any do.
787  Constant *PredCst = 0;
788  bool TrueDirection = false;
789  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
790    PredCst = dyn_cast<Constant>(PN->getIncomingValue(i));
791    if (PredCst == 0) continue;
792
793    Constant *Res;
794    if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cmp))
795      Res = ConstantExpr::getICmp(ICI->getPredicate(), PredCst, RHS);
796    else
797      Res = ConstantExpr::getFCmp(cast<FCmpInst>(Cmp)->getPredicate(),
798                                  PredCst, RHS);
799    // If this folded to a constant expr, we can't do anything.
800    if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
801      TrueDirection = ResC->getZExtValue();
802      break;
803    }
804    // If this folded to undef, just go the false way.
805    if (isa<UndefValue>(Res)) {
806      TrueDirection = false;
807      break;
808    }
809
810    // Otherwise, we can't fold this input.
811    PredCst = 0;
812  }
813
814  // If no match, bail out.
815  if (PredCst == 0)
816    return false;
817
818  // See if the cost of duplicating this block is low enough.
819  unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
820  if (JumpThreadCost > Threshold) {
821    DOUT << "  Not threading BB '" << BB->getNameStart()
822         << "' - Cost is too high: " << JumpThreadCost << "\n";
823    return false;
824  }
825
826  // If so, we can actually do this threading.  Merge any common predecessors
827  // that will act the same.
828  BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
829
830  // Next, get our successor.
831  BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
832
833  // If threading to the same block as we come from, we would infinite loop.
834  if (SuccBB == BB) {
835    DOUT << "  Not threading BB '" << BB->getNameStart()
836    << "' - would thread to self!\n";
837    return false;
838  }
839
840
841  // And finally, do it!
842  DOUT << "  Threading edge through bool from '" << PredBB->getNameStart()
843       << "' to '" << SuccBB->getNameStart() << "' with cost: "
844       << JumpThreadCost << ", across block:\n    "
845       << *BB << "\n";
846
847  ThreadEdge(BB, PredBB, SuccBB);
848  ++NumThreads;
849  return true;
850}
851
852
853/// ThreadEdge - We have decided that it is safe and profitable to thread an
854/// edge from PredBB to SuccBB across BB.  Transform the IR to reflect this
855/// change.
856void JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
857                               BasicBlock *SuccBB) {
858
859  // Jump Threading can not update SSA properties correctly if the values
860  // defined in the duplicated block are used outside of the block itself.  For
861  // this reason, we spill all values that are used outside of BB to the stack.
862  for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
863    if (!I->isUsedOutsideOfBlock(BB))
864      continue;
865
866    // We found a use of I outside of BB.  Create a new stack slot to
867    // break this inter-block usage pattern.
868    DemoteRegToStack(*I);
869  }
870
871  // We are going to have to map operands from the original BB block to the new
872  // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
873  // account for entry from PredBB.
874  DenseMap<Instruction*, Value*> ValueMapping;
875
876  BasicBlock *NewBB =
877    BasicBlock::Create(BB->getName()+".thread", BB->getParent(), BB);
878  NewBB->moveAfter(PredBB);
879
880  BasicBlock::iterator BI = BB->begin();
881  for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
882    ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
883
884  // Clone the non-phi instructions of BB into NewBB, keeping track of the
885  // mapping and using it to remap operands in the cloned instructions.
886  for (; !isa<TerminatorInst>(BI); ++BI) {
887    Instruction *New = BI->clone();
888    New->setName(BI->getNameStart());
889    NewBB->getInstList().push_back(New);
890    ValueMapping[BI] = New;
891
892    // Remap operands to patch up intra-block references.
893    for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
894      if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i)))
895        if (Value *Remapped = ValueMapping[Inst])
896          New->setOperand(i, Remapped);
897  }
898
899  // We didn't copy the terminator from BB over to NewBB, because there is now
900  // an unconditional jump to SuccBB.  Insert the unconditional jump.
901  BranchInst::Create(SuccBB, NewBB);
902
903  // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
904  // PHI nodes for NewBB now.
905  for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
906    PHINode *PN = cast<PHINode>(PNI);
907    // Ok, we have a PHI node.  Figure out what the incoming value was for the
908    // DestBlock.
909    Value *IV = PN->getIncomingValueForBlock(BB);
910
911    // Remap the value if necessary.
912    if (Instruction *Inst = dyn_cast<Instruction>(IV))
913      if (Value *MappedIV = ValueMapping[Inst])
914        IV = MappedIV;
915    PN->addIncoming(IV, NewBB);
916  }
917
918  // Ok, NewBB is good to go.  Update the terminator of PredBB to jump to
919  // NewBB instead of BB.  This eliminates predecessors from BB, which requires
920  // us to simplify any PHI nodes in BB.
921  TerminatorInst *PredTerm = PredBB->getTerminator();
922  for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
923    if (PredTerm->getSuccessor(i) == BB) {
924      BB->removePredecessor(PredBB);
925      PredTerm->setSuccessor(i, NewBB);
926    }
927
928  // At this point, the IR is fully up to date and consistent.  Do a quick scan
929  // over the new instructions and zap any that are constants or dead.  This
930  // frequently happens because of phi translation.
931  BI = NewBB->begin();
932  for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
933    Instruction *Inst = BI++;
934    if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
935      Inst->replaceAllUsesWith(C);
936      Inst->eraseFromParent();
937      continue;
938    }
939
940    RecursivelyDeleteTriviallyDeadInstructions(Inst);
941  }
942}
943