LLVM  16.0.0git
SimplifyCFG.cpp
Go to the documentation of this file.
1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
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 // Peephole optimize the CFG.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/APInt.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/MapVector.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/ScopeExit.h"
20 #include "llvm/ADT/Sequence.h"
21 #include "llvm/ADT/SetOperations.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringRef.h"
37 #include "llvm/IR/Attributes.h"
38 #include "llvm/IR/BasicBlock.h"
39 #include "llvm/IR/CFG.h"
40 #include "llvm/IR/Constant.h"
41 #include "llvm/IR/ConstantRange.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/DebugInfo.h"
45 #include "llvm/IR/DerivedTypes.h"
46 #include "llvm/IR/Function.h"
47 #include "llvm/IR/GlobalValue.h"
48 #include "llvm/IR/GlobalVariable.h"
49 #include "llvm/IR/IRBuilder.h"
50 #include "llvm/IR/InstrTypes.h"
51 #include "llvm/IR/Instruction.h"
52 #include "llvm/IR/Instructions.h"
53 #include "llvm/IR/IntrinsicInst.h"
54 #include "llvm/IR/LLVMContext.h"
55 #include "llvm/IR/MDBuilder.h"
56 #include "llvm/IR/Metadata.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/IR/NoFolder.h"
59 #include "llvm/IR/Operator.h"
60 #include "llvm/IR/PatternMatch.h"
61 #include "llvm/IR/ProfDataUtils.h"
62 #include "llvm/IR/Type.h"
63 #include "llvm/IR/Use.h"
64 #include "llvm/IR/User.h"
65 #include "llvm/IR/Value.h"
66 #include "llvm/IR/ValueHandle.h"
68 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/Debug.h"
72 #include "llvm/Support/KnownBits.h"
78 #include <algorithm>
79 #include <cassert>
80 #include <climits>
81 #include <cstddef>
82 #include <cstdint>
83 #include <iterator>
84 #include <map>
85 #include <optional>
86 #include <set>
87 #include <tuple>
88 #include <utility>
89 #include <vector>
90 
91 using namespace llvm;
92 using namespace PatternMatch;
93 
94 #define DEBUG_TYPE "simplifycfg"
95 
97  "simplifycfg-require-and-preserve-domtree", cl::Hidden,
98 
99  cl::desc("Temorary development switch used to gradually uplift SimplifyCFG "
100  "into preserving DomTree,"));
101 
102 // Chosen as 2 so as to be cheap, but still to have enough power to fold
103 // a select, so the "clamp" idiom (of a min followed by a max) will be caught.
104 // To catch this, we need to fold a compare and a select, hence '2' being the
105 // minimum reasonable default.
107  "phi-node-folding-threshold", cl::Hidden, cl::init(2),
108  cl::desc(
109  "Control the amount of phi node folding to perform (default = 2)"));
110 
112  "two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4),
113  cl::desc("Control the maximal total instruction cost that we are willing "
114  "to speculatively execute to fold a 2-entry PHI node into a "
115  "select (default = 4)"));
116 
117 static cl::opt<bool>
118  HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true),
119  cl::desc("Hoist common instructions up to the parent block"));
120 
121 static cl::opt<unsigned>
122  HoistCommonSkipLimit("simplifycfg-hoist-common-skip-limit", cl::Hidden,
123  cl::init(20),
124  cl::desc("Allow reordering across at most this many "
125  "instructions when hoisting"));
126 
127 static cl::opt<bool>
128  SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
129  cl::desc("Sink common instructions down to the end block"));
130 
132  "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
133  cl::desc("Hoist conditional stores if an unconditional store precedes"));
134 
136  "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
137  cl::desc("Hoist conditional stores even if an unconditional store does not "
138  "precede - hoist multiple conditional stores into a single "
139  "predicated store"));
140 
142  "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
143  cl::desc("When merging conditional stores, do so even if the resultant "
144  "basic blocks are unlikely to be if-converted as a result"));
145 
147  "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
148  cl::desc("Allow exactly one expensive instruction to be speculatively "
149  "executed"));
150 
152  "max-speculation-depth", cl::Hidden, cl::init(10),
153  cl::desc("Limit maximum recursion depth when calculating costs of "
154  "speculatively executed instructions"));
155 
156 static cl::opt<int>
157  MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden,
158  cl::init(10),
159  cl::desc("Max size of a block which is still considered "
160  "small enough to thread through"));
161 
162 // Two is chosen to allow one negation and a logical combine.
163 static cl::opt<unsigned>
164  BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden,
165  cl::init(2),
166  cl::desc("Maximum cost of combining conditions when "
167  "folding branches"));
168 
170  "simplifycfg-branch-fold-common-dest-vector-multiplier", cl::Hidden,
171  cl::init(2),
172  cl::desc("Multiplier to apply to threshold when determining whether or not "
173  "to fold branch to common destination when vector operations are "
174  "present"));
175 
177  "simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(true),
178  cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"));
179 
181  "max-switch-cases-per-result", cl::Hidden, cl::init(16),
182  cl::desc("Limit cases to analyze when converting a switch to select"));
183 
184 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
185 STATISTIC(NumLinearMaps,
186  "Number of switch instructions turned into linear mapping");
187 STATISTIC(NumLookupTables,
188  "Number of switch instructions turned into lookup tables");
189 STATISTIC(
190  NumLookupTablesHoles,
191  "Number of switch instructions turned into lookup tables (holes checked)");
192 STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
193 STATISTIC(NumFoldValueComparisonIntoPredecessors,
194  "Number of value comparisons folded into predecessor basic blocks");
195 STATISTIC(NumFoldBranchToCommonDest,
196  "Number of branches folded into predecessor basic block");
197 STATISTIC(
198  NumHoistCommonCode,
199  "Number of common instruction 'blocks' hoisted up to the begin block");
200 STATISTIC(NumHoistCommonInstrs,
201  "Number of common instructions hoisted up to the begin block");
202 STATISTIC(NumSinkCommonCode,
203  "Number of common instruction 'blocks' sunk down to the end block");
204 STATISTIC(NumSinkCommonInstrs,
205  "Number of common instructions sunk down to the end block");
206 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
207 STATISTIC(NumInvokes,
208  "Number of invokes with empty resume blocks simplified into calls");
209 STATISTIC(NumInvokesMerged, "Number of invokes that were merged together");
210 STATISTIC(NumInvokeSetsFormed, "Number of invoke sets that were formed");
211 
212 namespace {
213 
214 // The first field contains the value that the switch produces when a certain
215 // case group is selected, and the second field is a vector containing the
216 // cases composing the case group.
217 using SwitchCaseResultVectorTy =
219 
220 // The first field contains the phi node that generates a result of the switch
221 // and the second field contains the value generated for a certain case in the
222 // switch for that PHI.
223 using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
224 
225 /// ValueEqualityComparisonCase - Represents a case of a switch.
226 struct ValueEqualityComparisonCase {
228  BasicBlock *Dest;
229 
230  ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
231  : Value(Value), Dest(Dest) {}
232 
233  bool operator<(ValueEqualityComparisonCase RHS) const {
234  // Comparing pointers is ok as we only rely on the order for uniquing.
235  return Value < RHS.Value;
236  }
237 
238  bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
239 };
240 
241 class SimplifyCFGOpt {
242  const TargetTransformInfo &TTI;
243  DomTreeUpdater *DTU;
244  const DataLayout &DL;
245  ArrayRef<WeakVH> LoopHeaders;
247  bool Resimplify;
248 
249  Value *isValueEqualityComparison(Instruction *TI);
250  BasicBlock *GetValueEqualityComparisonCases(
251  Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
252  bool SimplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
253  BasicBlock *Pred,
255  bool PerformValueComparisonIntoPredecessorFolding(Instruction *TI, Value *&CV,
256  Instruction *PTI,
258  bool FoldValueComparisonIntoPredecessors(Instruction *TI,
260 
261  bool simplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
262  bool simplifySingleResume(ResumeInst *RI);
263  bool simplifyCommonResume(ResumeInst *RI);
264  bool simplifyCleanupReturn(CleanupReturnInst *RI);
265  bool simplifyUnreachable(UnreachableInst *UI);
266  bool simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
267  bool simplifyIndirectBr(IndirectBrInst *IBI);
268  bool simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder);
269  bool simplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
270  bool simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
271 
272  bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
274 
275  bool HoistThenElseCodeToIf(BranchInst *BI, const TargetTransformInfo &TTI,
276  bool EqTermsOnly);
277  bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
278  const TargetTransformInfo &TTI);
279  bool SimplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
280  BasicBlock *TrueBB, BasicBlock *FalseBB,
281  uint32_t TrueWeight, uint32_t FalseWeight);
282  bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
283  const DataLayout &DL);
284  bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select);
285  bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI);
286  bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder);
287 
288 public:
289  SimplifyCFGOpt(const TargetTransformInfo &TTI, DomTreeUpdater *DTU,
290  const DataLayout &DL, ArrayRef<WeakVH> LoopHeaders,
291  const SimplifyCFGOptions &Opts)
292  : TTI(TTI), DTU(DTU), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {
293  assert((!DTU || !DTU->hasPostDomTree()) &&
294  "SimplifyCFG is not yet capable of maintaining validity of a "
295  "PostDomTree, so don't ask for it.");
296  }
297 
298  bool simplifyOnce(BasicBlock *BB);
299  bool run(BasicBlock *BB);
300 
301  // Helper to set Resimplify and return change indication.
302  bool requestResimplify() {
303  Resimplify = true;
304  return true;
305  }
306 };
307 
308 } // end anonymous namespace
309 
310 /// Return true if all the PHI nodes in the basic block \p BB
311 /// receive compatible (identical) incoming values when coming from
312 /// all of the predecessor blocks that are specified in \p IncomingBlocks.
313 ///
314 /// Note that if the values aren't exactly identical, but \p EquivalenceSet
315 /// is provided, and *both* of the values are present in the set,
316 /// then they are considered equal.
318  BasicBlock *BB, ArrayRef<BasicBlock *> IncomingBlocks,
319  SmallPtrSetImpl<Value *> *EquivalenceSet = nullptr) {
320  assert(IncomingBlocks.size() == 2 &&
321  "Only for a pair of incoming blocks at the time!");
322 
323  // FIXME: it is okay if one of the incoming values is an `undef` value,
324  // iff the other incoming value is guaranteed to be a non-poison value.
325  // FIXME: it is okay if one of the incoming values is a `poison` value.
326  return all_of(BB->phis(), [IncomingBlocks, EquivalenceSet](PHINode &PN) {
327  Value *IV0 = PN.getIncomingValueForBlock(IncomingBlocks[0]);
328  Value *IV1 = PN.getIncomingValueForBlock(IncomingBlocks[1]);
329  if (IV0 == IV1)
330  return true;
331  if (EquivalenceSet && EquivalenceSet->contains(IV0) &&
332  EquivalenceSet->contains(IV1))
333  return true;
334  return false;
335  });
336 }
337 
338 /// Return true if it is safe to merge these two
339 /// terminator instructions together.
340 static bool
342  SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
343  if (SI1 == SI2)
344  return false; // Can't merge with self!
345 
346  // It is not safe to merge these two switch instructions if they have a common
347  // successor, and if that successor has a PHI node, and if *that* PHI node has
348  // conflicting incoming values from the two switch blocks.
349  BasicBlock *SI1BB = SI1->getParent();
350  BasicBlock *SI2BB = SI2->getParent();
351 
352  SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
353  bool Fail = false;
354  for (BasicBlock *Succ : successors(SI2BB)) {
355  if (!SI1Succs.count(Succ))
356  continue;
357  if (IncomingValuesAreCompatible(Succ, {SI1BB, SI2BB}))
358  continue;
359  Fail = true;
360  if (FailBlocks)
361  FailBlocks->insert(Succ);
362  else
363  break;
364  }
365 
366  return !Fail;
367 }
368 
369 /// Update PHI nodes in Succ to indicate that there will now be entries in it
370 /// from the 'NewPred' block. The values that will be flowing into the PHI nodes
371 /// will be the same as those coming in from ExistPred, an existing predecessor
372 /// of Succ.
373 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
374  BasicBlock *ExistPred,
375  MemorySSAUpdater *MSSAU = nullptr) {
376  for (PHINode &PN : Succ->phis())
377  PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
378  if (MSSAU)
379  if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ))
380  MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred);
381 }
382 
383 /// Compute an abstract "cost" of speculating the given instruction,
384 /// which is assumed to be safe to speculate. TCC_Free means cheap,
385 /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
386 /// expensive.
388  const TargetTransformInfo &TTI) {
389  assert((!isa<Instruction>(I) ||
390  isSafeToSpeculativelyExecute(cast<Instruction>(I))) &&
391  "Instruction is not safe to speculatively execute!");
393 }
394 
395 /// If we have a merge point of an "if condition" as accepted above,
396 /// return true if the specified value dominates the block. We
397 /// don't handle the true generality of domination here, just a special case
398 /// which works well enough for us.
399 ///
400 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
401 /// see if V (which must be an instruction) and its recursive operands
402 /// that do not dominate BB have a combined cost lower than Budget and
403 /// are non-trapping. If both are true, the instruction is inserted into the
404 /// set and true is returned.
405 ///
406 /// The cost for most non-trapping instructions is defined as 1 except for
407 /// Select whose cost is 2.
408 ///
409 /// After this function returns, Cost is increased by the cost of
410 /// V plus its non-dominating operands. If that cost is greater than
411 /// Budget, false is returned and Cost is undefined.
413  SmallPtrSetImpl<Instruction *> &AggressiveInsts,
414  InstructionCost &Cost,
415  InstructionCost Budget,
416  const TargetTransformInfo &TTI,
417  unsigned Depth = 0) {
418  // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
419  // so limit the recursion depth.
420  // TODO: While this recursion limit does prevent pathological behavior, it
421  // would be better to track visited instructions to avoid cycles.
422  if (Depth == MaxSpeculationDepth)
423  return false;
424 
425  Instruction *I = dyn_cast<Instruction>(V);
426  if (!I) {
427  // Non-instructions dominate all instructions and can be executed
428  // unconditionally.
429  return true;
430  }
431  BasicBlock *PBB = I->getParent();
432 
433  // We don't want to allow weird loops that might have the "if condition" in
434  // the bottom of this block.
435  if (PBB == BB)
436  return false;
437 
438  // If this instruction is defined in a block that contains an unconditional
439  // branch to BB, then it must be in the 'conditional' part of the "if
440  // statement". If not, it definitely dominates the region.
441  BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
442  if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
443  return true;
444 
445  // If we have seen this instruction before, don't count it again.
446  if (AggressiveInsts.count(I))
447  return true;
448 
449  // Okay, it looks like the instruction IS in the "condition". Check to
450  // see if it's a cheap instruction to unconditionally compute, and if it
451  // only uses stuff defined outside of the condition. If so, hoist it out.
453  return false;
454 
456 
457  // Allow exactly one instruction to be speculated regardless of its cost
458  // (as long as it is safe to do so).
459  // This is intended to flatten the CFG even if the instruction is a division
460  // or other expensive operation. The speculation of an expensive instruction
461  // is expected to be undone in CodeGenPrepare if the speculation has not
462  // enabled further IR optimizations.
463  if (Cost > Budget &&
464  (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0 ||
465  !Cost.isValid()))
466  return false;
467 
468  // Okay, we can only really hoist these out if their operands do
469  // not take us over the cost threshold.
470  for (Use &Op : I->operands())
471  if (!dominatesMergePoint(Op, BB, AggressiveInsts, Cost, Budget, TTI,
472  Depth + 1))
473  return false;
474  // Okay, it's safe to do this! Remember this instruction.
475  AggressiveInsts.insert(I);
476  return true;
477 }
478 
479 /// Extract ConstantInt from value, looking through IntToPtr
480 /// and PointerNullValue. Return NULL if value is not a constant int.
482  // Normal constant int.
483  ConstantInt *CI = dyn_cast<ConstantInt>(V);
484  if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy() ||
485  DL.isNonIntegralPointerType(V->getType()))
486  return CI;
487 
488  // This is some kind of pointer constant. Turn it into a pointer-sized
489  // ConstantInt if possible.
490  IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
491 
492  // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
493  if (isa<ConstantPointerNull>(V))
494  return ConstantInt::get(PtrTy, 0);
495 
496  // IntToPtr const int.
497  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
498  if (CE->getOpcode() == Instruction::IntToPtr)
499  if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
500  // The constant is very likely to have the right type already.
501  if (CI->getType() == PtrTy)
502  return CI;
503  else
504  return cast<ConstantInt>(
505  ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
506  }
507  return nullptr;
508 }
509 
510 namespace {
511 
512 /// Given a chain of or (||) or and (&&) comparison of a value against a
513 /// constant, this will try to recover the information required for a switch
514 /// structure.
515 /// It will depth-first traverse the chain of comparison, seeking for patterns
516 /// like %a == 12 or %a < 4 and combine them to produce a set of integer
517 /// representing the different cases for the switch.
518 /// Note that if the chain is composed of '||' it will build the set of elements
519 /// that matches the comparisons (i.e. any of this value validate the chain)
520 /// while for a chain of '&&' it will build the set elements that make the test
521 /// fail.
522 struct ConstantComparesGatherer {
523  const DataLayout &DL;
524 
525  /// Value found for the switch comparison
526  Value *CompValue = nullptr;
527 
528  /// Extra clause to be checked before the switch
529  Value *Extra = nullptr;
530 
531  /// Set of integers to match in switch
533 
534  /// Number of comparisons matched in the and/or chain
535  unsigned UsedICmps = 0;
536 
537  /// Construct and compute the result for the comparison instruction Cond
538  ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
539  gather(Cond);
540  }
541 
542  ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
543  ConstantComparesGatherer &
544  operator=(const ConstantComparesGatherer &) = delete;
545 
546 private:
547  /// Try to set the current value used for the comparison, it succeeds only if
548  /// it wasn't set before or if the new value is the same as the old one
549  bool setValueOnce(Value *NewVal) {
550  if (CompValue && CompValue != NewVal)
551  return false;
552  CompValue = NewVal;
553  return (CompValue != nullptr);
554  }
555 
556  /// Try to match Instruction "I" as a comparison against a constant and
557  /// populates the array Vals with the set of values that match (or do not
558  /// match depending on isEQ).
559  /// Return false on failure. On success, the Value the comparison matched
560  /// against is placed in CompValue.
561  /// If CompValue is already set, the function is expected to fail if a match
562  /// is found but the value compared to is different.
563  bool matchInstruction(Instruction *I, bool isEQ) {
564  // If this is an icmp against a constant, handle this as one of the cases.
565  ICmpInst *ICI;
566  ConstantInt *C;
567  if (!((ICI = dyn_cast<ICmpInst>(I)) &&
568  (C = GetConstantInt(I->getOperand(1), DL)))) {
569  return false;
570  }
571 
572  Value *RHSVal;
573  const APInt *RHSC;
574 
575  // Pattern match a special case
576  // (x & ~2^z) == y --> x == y || x == y|2^z
577  // This undoes a transformation done by instcombine to fuse 2 compares.
578  if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
579  // It's a little bit hard to see why the following transformations are
580  // correct. Here is a CVC3 program to verify them for 64-bit values:
581 
582  /*
583  ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
584  x : BITVECTOR(64);
585  y : BITVECTOR(64);
586  z : BITVECTOR(64);
587  mask : BITVECTOR(64) = BVSHL(ONE, z);
588  QUERY( (y & ~mask = y) =>
589  ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
590  );
591  QUERY( (y | mask = y) =>
592  ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
593  );
594  */
595 
596  // Please note that each pattern must be a dual implication (<--> or
597  // iff). One directional implication can create spurious matches. If the
598  // implication is only one-way, an unsatisfiable condition on the left
599  // side can imply a satisfiable condition on the right side. Dual
600  // implication ensures that satisfiable conditions are transformed to
601  // other satisfiable conditions and unsatisfiable conditions are
602  // transformed to other unsatisfiable conditions.
603 
604  // Here is a concrete example of a unsatisfiable condition on the left
605  // implying a satisfiable condition on the right:
606  //
607  // mask = (1 << z)
608  // (x & ~mask) == y --> (x == y || x == (y | mask))
609  //
610  // Substituting y = 3, z = 0 yields:
611  // (x & -2) == 3 --> (x == 3 || x == 2)
612 
613  // Pattern match a special case:
614  /*
615  QUERY( (y & ~mask = y) =>
616  ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
617  );
618  */
619  if (match(ICI->getOperand(0),
620  m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
621  APInt Mask = ~*RHSC;
622  if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
623  // If we already have a value for the switch, it has to match!
624  if (!setValueOnce(RHSVal))
625  return false;
626 
627  Vals.push_back(C);
628  Vals.push_back(
629  ConstantInt::get(C->getContext(),
630  C->getValue() | Mask));
631  UsedICmps++;
632  return true;
633  }
634  }
635 
636  // Pattern match a special case:
637  /*
638  QUERY( (y | mask = y) =>
639  ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
640  );
641  */
642  if (match(ICI->getOperand(0),
643  m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
644  APInt Mask = *RHSC;
645  if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
646  // If we already have a value for the switch, it has to match!
647  if (!setValueOnce(RHSVal))
648  return false;
649 
650  Vals.push_back(C);
651  Vals.push_back(ConstantInt::get(C->getContext(),
652  C->getValue() & ~Mask));
653  UsedICmps++;
654  return true;
655  }
656  }
657 
658  // If we already have a value for the switch, it has to match!
659  if (!setValueOnce(ICI->getOperand(0)))
660  return false;
661 
662  UsedICmps++;
663  Vals.push_back(C);
664  return ICI->getOperand(0);
665  }
666 
667  // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
668  ConstantRange Span =
670 
671  // Shift the range if the compare is fed by an add. This is the range
672  // compare idiom as emitted by instcombine.
673  Value *CandidateVal = I->getOperand(0);
674  if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
675  Span = Span.subtract(*RHSC);
676  CandidateVal = RHSVal;
677  }
678 
679  // If this is an and/!= check, then we are looking to build the set of
680  // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
681  // x != 0 && x != 1.
682  if (!isEQ)
683  Span = Span.inverse();
684 
685  // If there are a ton of values, we don't want to make a ginormous switch.
686  if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
687  return false;
688  }
689 
690  // If we already have a value for the switch, it has to match!
691  if (!setValueOnce(CandidateVal))
692  return false;
693 
694  // Add all values from the range to the set
695  for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
696  Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
697 
698  UsedICmps++;
699  return true;
700  }
701 
702  /// Given a potentially 'or'd or 'and'd together collection of icmp
703  /// eq/ne/lt/gt instructions that compare a value against a constant, extract
704  /// the value being compared, and stick the list constants into the Vals
705  /// vector.
706  /// One "Extra" case is allowed to differ from the other.
707  void gather(Value *V) {
708  bool isEQ = match(V, m_LogicalOr(m_Value(), m_Value()));
709 
710  // Keep a stack (SmallVector for efficiency) for depth-first traversal
712  SmallPtrSet<Value *, 8> Visited;
713 
714  // Initialize
715  Visited.insert(V);
716  DFT.push_back(V);
717 
718  while (!DFT.empty()) {
719  V = DFT.pop_back_val();
720 
721  if (Instruction *I = dyn_cast<Instruction>(V)) {
722  // If it is a || (or && depending on isEQ), process the operands.
723  Value *Op0, *Op1;
724  if (isEQ ? match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1)))
725  : match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
726  if (Visited.insert(Op1).second)
727  DFT.push_back(Op1);
728  if (Visited.insert(Op0).second)
729  DFT.push_back(Op0);
730 
731  continue;
732  }
733 
734  // Try to match the current instruction
735  if (matchInstruction(I, isEQ))
736  // Match succeed, continue the loop
737  continue;
738  }
739 
740  // One element of the sequence of || (or &&) could not be match as a
741  // comparison against the same value as the others.
742  // We allow only one "Extra" case to be checked before the switch
743  if (!Extra) {
744  Extra = V;
745  continue;
746  }
747  // Failed to parse a proper sequence, abort now
748  CompValue = nullptr;
749  break;
750  }
751  }
752 };
753 
754 } // end anonymous namespace
755 
757  MemorySSAUpdater *MSSAU = nullptr) {
758  Instruction *Cond = nullptr;
759  if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
760  Cond = dyn_cast<Instruction>(SI->getCondition());
761  } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
762  if (BI->isConditional())
763  Cond = dyn_cast<Instruction>(BI->getCondition());
764  } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
765  Cond = dyn_cast<Instruction>(IBI->getAddress());
766  }
767 
768  TI->eraseFromParent();
769  if (Cond)
771 }
772 
773 /// Return true if the specified terminator checks
774 /// to see if a value is equal to constant integer value.
775 Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
776  Value *CV = nullptr;
777  if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
778  // Do not permit merging of large switch instructions into their
779  // predecessors unless there is only one predecessor.
780  if (!SI->getParent()->hasNPredecessorsOrMore(128 / SI->getNumSuccessors()))
781  CV = SI->getCondition();
782  } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
783  if (BI->isConditional() && BI->getCondition()->hasOneUse())
784  if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
785  if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
786  CV = ICI->getOperand(0);
787  }
788 
789  // Unwrap any lossless ptrtoint cast.
790  if (CV) {
791  if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
792  Value *Ptr = PTII->getPointerOperand();
793  if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
794  CV = Ptr;
795  }
796  }
797  return CV;
798 }
799 
800 /// Given a value comparison instruction,
801 /// decode all of the 'cases' that it represents and return the 'default' block.
802 BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
803  Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
804  if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
805  Cases.reserve(SI->getNumCases());
806  for (auto Case : SI->cases())
807  Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
808  Case.getCaseSuccessor()));
809  return SI->getDefaultDest();
810  }
811 
812  BranchInst *BI = cast<BranchInst>(TI);
813  ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
814  BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
815  Cases.push_back(ValueEqualityComparisonCase(
816  GetConstantInt(ICI->getOperand(1), DL), Succ));
817  return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
818 }
819 
820 /// Given a vector of bb/value pairs, remove any entries
821 /// in the list that match the specified block.
822 static void
824  std::vector<ValueEqualityComparisonCase> &Cases) {
825  llvm::erase_value(Cases, BB);
826 }
827 
828 /// Return true if there are any keys in C1 that exist in C2 as well.
829 static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
830  std::vector<ValueEqualityComparisonCase> &C2) {
831  std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
832 
833  // Make V1 be smaller than V2.
834  if (V1->size() > V2->size())
835  std::swap(V1, V2);
836 
837  if (V1->empty())
838  return false;
839  if (V1->size() == 1) {
840  // Just scan V2.
841  ConstantInt *TheVal = (*V1)[0].Value;
842  for (const ValueEqualityComparisonCase &VECC : *V2)
843  if (TheVal == VECC.Value)
844  return true;
845  }
846 
847  // Otherwise, just sort both lists and compare element by element.
848  array_pod_sort(V1->begin(), V1->end());
849  array_pod_sort(V2->begin(), V2->end());
850  unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
851  while (i1 != e1 && i2 != e2) {
852  if ((*V1)[i1].Value == (*V2)[i2].Value)
853  return true;
854  if ((*V1)[i1].Value < (*V2)[i2].Value)
855  ++i1;
856  else
857  ++i2;
858  }
859  return false;
860 }
861 
862 // Set branch weights on SwitchInst. This sets the metadata if there is at
863 // least one non-zero weight.
865  // Check that there is at least one non-zero weight. Otherwise, pass
866  // nullptr to setMetadata which will erase the existing metadata.
867  MDNode *N = nullptr;
868  if (llvm::any_of(Weights, [](uint32_t W) { return W != 0; }))
869  N = MDBuilder(SI->getParent()->getContext()).createBranchWeights(Weights);
870  SI->setMetadata(LLVMContext::MD_prof, N);
871 }
872 
873 // Similar to the above, but for branch and select instructions that take
874 // exactly 2 weights.
875 static void setBranchWeights(Instruction *I, uint32_t TrueWeight,
876  uint32_t FalseWeight) {
877  assert(isa<BranchInst>(I) || isa<SelectInst>(I));
878  // Check that there is at least one non-zero weight. Otherwise, pass
879  // nullptr to setMetadata which will erase the existing metadata.
880  MDNode *N = nullptr;
881  if (TrueWeight || FalseWeight)
882  N = MDBuilder(I->getParent()->getContext())
883  .createBranchWeights(TrueWeight, FalseWeight);
884  I->setMetadata(LLVMContext::MD_prof, N);
885 }
886 
887 /// If TI is known to be a terminator instruction and its block is known to
888 /// only have a single predecessor block, check to see if that predecessor is
889 /// also a value comparison with the same value, and if that comparison
890 /// determines the outcome of this comparison. If so, simplify TI. This does a
891 /// very limited form of jump threading.
892 bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
893  Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
894  Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
895  if (!PredVal)
896  return false; // Not a value comparison in predecessor.
897 
898  Value *ThisVal = isValueEqualityComparison(TI);
899  assert(ThisVal && "This isn't a value comparison!!");
900  if (ThisVal != PredVal)
901  return false; // Different predicates.
902 
903  // TODO: Preserve branch weight metadata, similarly to how
904  // FoldValueComparisonIntoPredecessors preserves it.
905 
906  // Find out information about when control will move from Pred to TI's block.
907  std::vector<ValueEqualityComparisonCase> PredCases;
908  BasicBlock *PredDef =
909  GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
910  EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
911 
912  // Find information about how control leaves this block.
913  std::vector<ValueEqualityComparisonCase> ThisCases;
914  BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
915  EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
916 
917  // If TI's block is the default block from Pred's comparison, potentially
918  // simplify TI based on this knowledge.
919  if (PredDef == TI->getParent()) {
920  // If we are here, we know that the value is none of those cases listed in
921  // PredCases. If there are any cases in ThisCases that are in PredCases, we
922  // can simplify TI.
923  if (!ValuesOverlap(PredCases, ThisCases))
924  return false;
925 
926  if (isa<BranchInst>(TI)) {
927  // Okay, one of the successors of this condbr is dead. Convert it to a
928  // uncond br.
929  assert(ThisCases.size() == 1 && "Branch can only have one case!");
930  // Insert the new branch.
931  Instruction *NI = Builder.CreateBr(ThisDef);
932  (void)NI;
933 
934  // Remove PHI node entries for the dead edge.
935  ThisCases[0].Dest->removePredecessor(PredDef);
936 
937  LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
938  << "Through successor TI: " << *TI << "Leaving: " << *NI
939  << "\n");
940 
942 
943  if (DTU)
944  DTU->applyUpdates(
945  {{DominatorTree::Delete, PredDef, ThisCases[0].Dest}});
946 
947  return true;
948  }
949 
950  SwitchInstProfUpdateWrapper SI = *cast<SwitchInst>(TI);
951  // Okay, TI has cases that are statically dead, prune them away.
952  SmallPtrSet<Constant *, 16> DeadCases;
953  for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
954  DeadCases.insert(PredCases[i].Value);
955 
956  LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
957  << "Through successor TI: " << *TI);
958 
959  SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
960  for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
961  --i;
962  auto *Successor = i->getCaseSuccessor();
963  if (DTU)
964  ++NumPerSuccessorCases[Successor];
965  if (DeadCases.count(i->getCaseValue())) {
966  Successor->removePredecessor(PredDef);
967  SI.removeCase(i);
968  if (DTU)
969  --NumPerSuccessorCases[Successor];
970  }
971  }
972 
973  if (DTU) {
974  std::vector<DominatorTree::UpdateType> Updates;
975  for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
976  if (I.second == 0)
977  Updates.push_back({DominatorTree::Delete, PredDef, I.first});
978  DTU->applyUpdates(Updates);
979  }
980 
981  LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n");
982  return true;
983  }
984 
985  // Otherwise, TI's block must correspond to some matched value. Find out
986  // which value (or set of values) this is.
987  ConstantInt *TIV = nullptr;
988  BasicBlock *TIBB = TI->getParent();
989  for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
990  if (PredCases[i].Dest == TIBB) {
991  if (TIV)
992  return false; // Cannot handle multiple values coming to this block.
993  TIV = PredCases[i].Value;
994  }
995  assert(TIV && "No edge from pred to succ?");
996 
997  // Okay, we found the one constant that our value can be if we get into TI's
998  // BB. Find out which successor will unconditionally be branched to.
999  BasicBlock *TheRealDest = nullptr;
1000  for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
1001  if (ThisCases[i].Value == TIV) {
1002  TheRealDest = ThisCases[i].Dest;
1003  break;
1004  }
1005 
1006  // If not handled by any explicit cases, it is handled by the default case.
1007  if (!TheRealDest)
1008  TheRealDest = ThisDef;
1009 
1010  SmallPtrSet<BasicBlock *, 2> RemovedSuccs;
1011 
1012  // Remove PHI node entries for dead edges.
1013  BasicBlock *CheckEdge = TheRealDest;
1014  for (BasicBlock *Succ : successors(TIBB))
1015  if (Succ != CheckEdge) {
1016  if (Succ != TheRealDest)
1017  RemovedSuccs.insert(Succ);
1018  Succ->removePredecessor(TIBB);
1019  } else
1020  CheckEdge = nullptr;
1021 
1022  // Insert the new branch.
1023  Instruction *NI = Builder.CreateBr(TheRealDest);
1024  (void)NI;
1025 
1026  LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1027  << "Through successor TI: " << *TI << "Leaving: " << *NI
1028  << "\n");
1029 
1031  if (DTU) {
1033  Updates.reserve(RemovedSuccs.size());
1034  for (auto *RemovedSucc : RemovedSuccs)
1035  Updates.push_back({DominatorTree::Delete, TIBB, RemovedSucc});
1036  DTU->applyUpdates(Updates);
1037  }
1038  return true;
1039 }
1040 
1041 namespace {
1042 
1043 /// This class implements a stable ordering of constant
1044 /// integers that does not depend on their address. This is important for
1045 /// applications that sort ConstantInt's to ensure uniqueness.
1046 struct ConstantIntOrdering {
1047  bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1048  return LHS->getValue().ult(RHS->getValue());
1049  }
1050 };
1051 
1052 } // end anonymous namespace
1053 
1055  ConstantInt *const *P2) {
1056  const ConstantInt *LHS = *P1;
1057  const ConstantInt *RHS = *P2;
1058  if (LHS == RHS)
1059  return 0;
1060  return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
1061 }
1062 
1063 /// Get Weights of a given terminator, the default weight is at the front
1064 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
1065 /// metadata.
1067  SmallVectorImpl<uint64_t> &Weights) {
1068  MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
1069  assert(MD);
1070  for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
1071  ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
1072  Weights.push_back(CI->getValue().getZExtValue());
1073  }
1074 
1075  // If TI is a conditional eq, the default case is the false case,
1076  // and the corresponding branch-weight data is at index 2. We swap the
1077  // default weight to be the first entry.
1078  if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1079  assert(Weights.size() == 2);
1080  ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
1081  if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1082  std::swap(Weights.front(), Weights.back());
1083  }
1084 }
1085 
1086 /// Keep halving the weights until all can fit in uint32_t.
1088  uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
1089  if (Max > UINT_MAX) {
1090  unsigned Offset = 32 - countLeadingZeros(Max);
1091  for (uint64_t &I : Weights)
1092  I >>= Offset;
1093  }
1094 }
1095 
1097  BasicBlock *BB, BasicBlock *PredBlock, ValueToValueMapTy &VMap) {
1098  Instruction *PTI = PredBlock->getTerminator();
1099 
1100  // If we have bonus instructions, clone them into the predecessor block.
1101  // Note that there may be multiple predecessor blocks, so we cannot move
1102  // bonus instructions to a predecessor block.
1103  for (Instruction &BonusInst : *BB) {
1104  if (isa<DbgInfoIntrinsic>(BonusInst) || BonusInst.isTerminator())
1105  continue;
1106 
1107  Instruction *NewBonusInst = BonusInst.clone();
1108 
1109  if (PTI->getDebugLoc() != NewBonusInst->getDebugLoc()) {
1110  // Unless the instruction has the same !dbg location as the original
1111  // branch, drop it. When we fold the bonus instructions we want to make
1112  // sure we reset their debug locations in order to avoid stepping on
1113  // dead code caused by folding dead branches.
1114  NewBonusInst->setDebugLoc(DebugLoc());
1115  }
1116 
1117  RemapInstruction(NewBonusInst, VMap,
1119  VMap[&BonusInst] = NewBonusInst;
1120 
1121  // If we moved a load, we cannot any longer claim any knowledge about
1122  // its potential value. The previous information might have been valid
1123  // only given the branch precondition.
1124  // For an analogous reason, we must also drop all the metadata whose
1125  // semantics we don't understand. We *can* preserve !annotation, because
1126  // it is tied to the instruction itself, not the value or position.
1127  // Similarly strip attributes on call parameters that may cause UB in
1128  // location the call is moved to.
1130  LLVMContext::MD_annotation);
1131 
1132  PredBlock->getInstList().insert(PTI->getIterator(), NewBonusInst);
1133  NewBonusInst->takeName(&BonusInst);
1134  BonusInst.setName(NewBonusInst->getName() + ".old");
1135 
1136  // Update (liveout) uses of bonus instructions,
1137  // now that the bonus instruction has been cloned into predecessor.
1138  // Note that we expect to be in a block-closed SSA form for this to work!
1139  for (Use &U : make_early_inc_range(BonusInst.uses())) {
1140  auto *UI = cast<Instruction>(U.getUser());
1141  auto *PN = dyn_cast<PHINode>(UI);
1142  if (!PN) {
1143  assert(UI->getParent() == BB && BonusInst.comesBefore(UI) &&
1144  "If the user is not a PHI node, then it should be in the same "
1145  "block as, and come after, the original bonus instruction.");
1146  continue; // Keep using the original bonus instruction.
1147  }
1148  // Is this the block-closed SSA form PHI node?
1149  if (PN->getIncomingBlock(U) == BB)
1150  continue; // Great, keep using the original bonus instruction.
1151  // The only other alternative is an "use" when coming from
1152  // the predecessor block - here we should refer to the cloned bonus instr.
1153  assert(PN->getIncomingBlock(U) == PredBlock &&
1154  "Not in block-closed SSA form?");
1155  U.set(NewBonusInst);
1156  }
1157  }
1158 }
1159 
1160 bool SimplifyCFGOpt::PerformValueComparisonIntoPredecessorFolding(
1161  Instruction *TI, Value *&CV, Instruction *PTI, IRBuilder<> &Builder) {
1162  BasicBlock *BB = TI->getParent();
1163  BasicBlock *Pred = PTI->getParent();
1164 
1166 
1167  // Figure out which 'cases' to copy from SI to PSI.
1168  std::vector<ValueEqualityComparisonCase> BBCases;
1169  BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
1170 
1171  std::vector<ValueEqualityComparisonCase> PredCases;
1172  BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
1173 
1174  // Based on whether the default edge from PTI goes to BB or not, fill in
1175  // PredCases and PredDefault with the new switch cases we would like to
1176  // build.
1178 
1179  // Update the branch weight metadata along the way
1180  SmallVector<uint64_t, 8> Weights;
1181  bool PredHasWeights = hasBranchWeightMD(*PTI);
1182  bool SuccHasWeights = hasBranchWeightMD(*TI);
1183 
1184  if (PredHasWeights) {
1185  GetBranchWeights(PTI, Weights);
1186  // branch-weight metadata is inconsistent here.
1187  if (Weights.size() != 1 + PredCases.size())
1188  PredHasWeights = SuccHasWeights = false;
1189  } else if (SuccHasWeights)
1190  // If there are no predecessor weights but there are successor weights,
1191  // populate Weights with 1, which will later be scaled to the sum of
1192  // successor's weights
1193  Weights.assign(1 + PredCases.size(), 1);
1194 
1195  SmallVector<uint64_t, 8> SuccWeights;
1196  if (SuccHasWeights) {
1197  GetBranchWeights(TI, SuccWeights);
1198  // branch-weight metadata is inconsistent here.
1199  if (SuccWeights.size() != 1 + BBCases.size())
1200  PredHasWeights = SuccHasWeights = false;
1201  } else if (PredHasWeights)
1202  SuccWeights.assign(1 + BBCases.size(), 1);
1203 
1204  if (PredDefault == BB) {
1205  // If this is the default destination from PTI, only the edges in TI
1206  // that don't occur in PTI, or that branch to BB will be activated.
1207  std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1208  for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1209  if (PredCases[i].Dest != BB)
1210  PTIHandled.insert(PredCases[i].Value);
1211  else {
1212  // The default destination is BB, we don't need explicit targets.
1213  std::swap(PredCases[i], PredCases.back());
1214 
1215  if (PredHasWeights || SuccHasWeights) {
1216  // Increase weight for the default case.
1217  Weights[0] += Weights[i + 1];
1218  std::swap(Weights[i + 1], Weights.back());
1219  Weights.pop_back();
1220  }
1221 
1222  PredCases.pop_back();
1223  --i;
1224  --e;
1225  }
1226 
1227  // Reconstruct the new switch statement we will be building.
1228  if (PredDefault != BBDefault) {
1229  PredDefault->removePredecessor(Pred);
1230  if (DTU && PredDefault != BB)
1231  Updates.push_back({DominatorTree::Delete, Pred, PredDefault});
1232  PredDefault = BBDefault;
1233  ++NewSuccessors[BBDefault];
1234  }
1235 
1236  unsigned CasesFromPred = Weights.size();
1237  uint64_t ValidTotalSuccWeight = 0;
1238  for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1239  if (!PTIHandled.count(BBCases[i].Value) && BBCases[i].Dest != BBDefault) {
1240  PredCases.push_back(BBCases[i]);
1241  ++NewSuccessors[BBCases[i].Dest];
1242  if (SuccHasWeights || PredHasWeights) {
1243  // The default weight is at index 0, so weight for the ith case
1244  // should be at index i+1. Scale the cases from successor by
1245  // PredDefaultWeight (Weights[0]).
1246  Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1247  ValidTotalSuccWeight += SuccWeights[i + 1];
1248  }
1249  }
1250 
1251  if (SuccHasWeights || PredHasWeights) {
1252  ValidTotalSuccWeight += SuccWeights[0];
1253  // Scale the cases from predecessor by ValidTotalSuccWeight.
1254  for (unsigned i = 1; i < CasesFromPred; ++i)
1255  Weights[i] *= ValidTotalSuccWeight;
1256  // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1257  Weights[0] *= SuccWeights[0];
1258  }
1259  } else {
1260  // If this is not the default destination from PSI, only the edges
1261  // in SI that occur in PSI with a destination of BB will be
1262  // activated.
1263  std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1264  std::map<ConstantInt *, uint64_t> WeightsForHandled;
1265  for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1266  if (PredCases[i].Dest == BB) {
1267  PTIHandled.insert(PredCases[i].Value);
1268 
1269  if (PredHasWeights || SuccHasWeights) {
1270  WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1271  std::swap(Weights[i + 1], Weights.back());
1272  Weights.pop_back();
1273  }
1274 
1275  std::swap(PredCases[i], PredCases.back());
1276  PredCases.pop_back();
1277  --i;
1278  --e;
1279  }
1280 
1281  // Okay, now we know which constants were sent to BB from the
1282  // predecessor. Figure out where they will all go now.
1283  for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1284  if (PTIHandled.count(BBCases[i].Value)) {
1285  // If this is one we are capable of getting...
1286  if (PredHasWeights || SuccHasWeights)
1287  Weights.push_back(WeightsForHandled[BBCases[i].Value]);
1288  PredCases.push_back(BBCases[i]);
1289  ++NewSuccessors[BBCases[i].Dest];
1290  PTIHandled.erase(BBCases[i].Value); // This constant is taken care of
1291  }
1292 
1293  // If there are any constants vectored to BB that TI doesn't handle,
1294  // they must go to the default destination of TI.
1295  for (ConstantInt *I : PTIHandled) {
1296  if (PredHasWeights || SuccHasWeights)
1297  Weights.push_back(WeightsForHandled[I]);
1298  PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1299  ++NewSuccessors[BBDefault];
1300  }
1301  }
1302 
1303  // Okay, at this point, we know which new successor Pred will get. Make
1304  // sure we update the number of entries in the PHI nodes for these
1305  // successors.
1306  SmallPtrSet<BasicBlock *, 2> SuccsOfPred;
1307  if (DTU) {
1308  SuccsOfPred = {succ_begin(Pred), succ_end(Pred)};
1309  Updates.reserve(Updates.size() + NewSuccessors.size());
1310  }
1311  for (const std::pair<BasicBlock *, int /*Num*/> &NewSuccessor :
1312  NewSuccessors) {
1313  for (auto I : seq(0, NewSuccessor.second)) {
1314  (void)I;
1315  AddPredecessorToBlock(NewSuccessor.first, Pred, BB);
1316  }
1317  if (DTU && !SuccsOfPred.contains(NewSuccessor.first))
1318  Updates.push_back({DominatorTree::Insert, Pred, NewSuccessor.first});
1319  }
1320 
1321  Builder.SetInsertPoint(PTI);
1322  // Convert pointer to int before we switch.
1323  if (CV->getType()->isPointerTy()) {
1324  CV =
1325  Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), "magicptr");
1326  }
1327 
1328  // Now that the successors are updated, create the new Switch instruction.
1329  SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, PredCases.size());
1330  NewSI->setDebugLoc(PTI->getDebugLoc());
1331  for (ValueEqualityComparisonCase &V : PredCases)
1332  NewSI->addCase(V.Value, V.Dest);
1333 
1334  if (PredHasWeights || SuccHasWeights) {
1335  // Halve the weights if any of them cannot fit in an uint32_t
1336  FitWeights(Weights);
1337 
1338  SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1339 
1340  setBranchWeights(NewSI, MDWeights);
1341  }
1342 
1344 
1345  // Okay, last check. If BB is still a successor of PSI, then we must
1346  // have an infinite loop case. If so, add an infinitely looping block
1347  // to handle the case to preserve the behavior of the code.
1348  BasicBlock *InfLoopBlock = nullptr;
1349  for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1350  if (NewSI->getSuccessor(i) == BB) {
1351  if (!InfLoopBlock) {
1352  // Insert it at the end of the function, because it's either code,
1353  // or it won't matter if it's hot. :)
1354  InfLoopBlock =
1355  BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
1356  BranchInst::Create(InfLoopBlock, InfLoopBlock);
1357  if (DTU)
1358  Updates.push_back(
1359  {DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
1360  }
1361  NewSI->setSuccessor(i, InfLoopBlock);
1362  }
1363 
1364  if (DTU) {
1365  if (InfLoopBlock)
1366  Updates.push_back({DominatorTree::Insert, Pred, InfLoopBlock});
1367 
1368  Updates.push_back({DominatorTree::Delete, Pred, BB});
1369 
1370  DTU->applyUpdates(Updates);
1371  }
1372 
1373  ++NumFoldValueComparisonIntoPredecessors;
1374  return true;
1375 }
1376 
1377 /// The specified terminator is a value equality comparison instruction
1378 /// (either a switch or a branch on "X == c").
1379 /// See if any of the predecessors of the terminator block are value comparisons
1380 /// on the same value. If so, and if safe to do so, fold them together.
1381 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(Instruction *TI,
1382  IRBuilder<> &Builder) {
1383  BasicBlock *BB = TI->getParent();
1384  Value *CV = isValueEqualityComparison(TI); // CondVal
1385  assert(CV && "Not a comparison?");
1386 
1387  bool Changed = false;
1388 
1390  while (!Preds.empty()) {
1391  BasicBlock *Pred = Preds.pop_back_val();
1392  Instruction *PTI = Pred->getTerminator();
1393 
1394  // Don't try to fold into itself.
1395  if (Pred == BB)
1396  continue;
1397 
1398  // See if the predecessor is a comparison with the same value.
1399  Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
1400  if (PCV != CV)
1401  continue;
1402 
1404  if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
1405  for (auto *Succ : FailBlocks) {
1406  if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split", DTU))
1407  return false;
1408  }
1409  }
1410 
1411  PerformValueComparisonIntoPredecessorFolding(TI, CV, PTI, Builder);
1412  Changed = true;
1413  }
1414  return Changed;
1415 }
1416 
1417 // If we would need to insert a select that uses the value of this invoke
1418 // (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1419 // can't hoist the invoke, as there is nowhere to put the select in this case.
1421  Instruction *I1, Instruction *I2) {
1422  for (BasicBlock *Succ : successors(BB1)) {
1423  for (const PHINode &PN : Succ->phis()) {
1424  Value *BB1V = PN.getIncomingValueForBlock(BB1);
1425  Value *BB2V = PN.getIncomingValueForBlock(BB2);
1426  if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1427  return false;
1428  }
1429  }
1430  }
1431  return true;
1432 }
1433 
1434 // Get interesting characteristics of instructions that `HoistThenElseCodeToIf`
1435 // didn't hoist. They restrict what kind of instructions can be reordered
1436 // across.
1441 };
1442 
1443 static unsigned skippedInstrFlags(Instruction *I) {
1444  unsigned Flags = 0;
1445  if (I->mayReadFromMemory())
1446  Flags |= SkipReadMem;
1447  // We can't arbitrarily move around allocas, e.g. moving allocas (especially
1448  // inalloca) across stacksave/stackrestore boundaries.
1449  if (I->mayHaveSideEffects() || isa<AllocaInst>(I))
1450  Flags |= SkipSideEffect;
1452  Flags |= SkipImplicitControlFlow;
1453  return Flags;
1454 }
1455 
1456 // Returns true if it is safe to reorder an instruction across preceding
1457 // instructions in a basic block.
1458 static bool isSafeToHoistInstr(Instruction *I, unsigned Flags) {
1459  // Don't reorder a store over a load.
1460  if ((Flags & SkipReadMem) && I->mayWriteToMemory())
1461  return false;
1462 
1463  // If we have seen an instruction with side effects, it's unsafe to reorder an
1464  // instruction which reads memory or itself has side effects.
1465  if ((Flags & SkipSideEffect) &&
1466  (I->mayReadFromMemory() || I->mayHaveSideEffects()))
1467  return false;
1468 
1469  // Reordering across an instruction which does not necessarily transfer
1470  // control to the next instruction is speculation.
1472  return false;
1473 
1474  // It's also unsafe/illegal to hoist an instruction above its instruction
1475  // operands
1476  BasicBlock *BB = I->getParent();
1477  for (Value *Op : I->operands()) {
1478  if (auto *J = dyn_cast<Instruction>(Op))
1479  if (J->getParent() == BB)
1480  return false;
1481  }
1482 
1483  return true;
1484 }
1485 
1486 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified = false);
1487 
1488 /// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1489 /// in the two blocks up into the branch block. The caller of this function
1490 /// guarantees that BI's block dominates BB1 and BB2. If EqTermsOnly is given,
1491 /// only perform hoisting in case both blocks only contain a terminator. In that
1492 /// case, only the original BI will be replaced and selects for PHIs are added.
1493 bool SimplifyCFGOpt::HoistThenElseCodeToIf(BranchInst *BI,
1494  const TargetTransformInfo &TTI,
1495  bool EqTermsOnly) {
1496  // This does very trivial matching, with limited scanning, to find identical
1497  // instructions in the two blocks. In particular, we don't want to get into
1498  // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1499  // such, we currently just scan for obviously identical instructions in an
1500  // identical order, possibly separated by the same number of non-identical
1501  // instructions.
1502  BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1503  BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1504 
1505  // If either of the blocks has it's address taken, then we can't do this fold,
1506  // because the code we'd hoist would no longer run when we jump into the block
1507  // by it's address.
1508  if (BB1->hasAddressTaken() || BB2->hasAddressTaken())
1509  return false;
1510 
1511  BasicBlock::iterator BB1_Itr = BB1->begin();
1512  BasicBlock::iterator BB2_Itr = BB2->begin();
1513 
1514  Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
1515  // Skip debug info if it is not identical.
1516  DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1517  DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1518  if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1519  while (isa<DbgInfoIntrinsic>(I1))
1520  I1 = &*BB1_Itr++;
1521  while (isa<DbgInfoIntrinsic>(I2))
1522  I2 = &*BB2_Itr++;
1523  }
1524  if (isa<PHINode>(I1))
1525  return false;
1526 
1527  BasicBlock *BIParent = BI->getParent();
1528 
1529  bool Changed = false;
1530 
1531  auto _ = make_scope_exit([&]() {
1532  if (Changed)
1533  ++NumHoistCommonCode;
1534  });
1535 
1536  // Check if only hoisting terminators is allowed. This does not add new
1537  // instructions to the hoist location.
1538  if (EqTermsOnly) {
1539  // Skip any debug intrinsics, as they are free to hoist.
1540  auto *I1NonDbg = &*skipDebugIntrinsics(I1->getIterator());
1541  auto *I2NonDbg = &*skipDebugIntrinsics(I2->getIterator());
1542  if (!I1NonDbg->isIdenticalToWhenDefined(I2NonDbg))
1543  return false;
1544  if (!I1NonDbg->isTerminator())
1545  return false;
1546  // Now we know that we only need to hoist debug intrinsics and the
1547  // terminator. Let the loop below handle those 2 cases.
1548  }
1549 
1550  // Count how many instructions were not hoisted so far. There's a limit on how
1551  // many instructions we skip, serving as a compilation time control as well as
1552  // preventing excessive increase of life ranges.
1553  unsigned NumSkipped = 0;
1554 
1555  // Record any skipped instuctions that may read memory, write memory or have
1556  // side effects, or have implicit control flow.
1557  unsigned SkipFlagsBB1 = 0;
1558  unsigned SkipFlagsBB2 = 0;
1559 
1560  for (;;) {
1561  // If we are hoisting the terminator instruction, don't move one (making a
1562  // broken BB), instead clone it, and remove BI.
1563  if (I1->isTerminator() || I2->isTerminator()) {
1564  // If any instructions remain in the block, we cannot hoist terminators.
1565  if (NumSkipped || !I1->isIdenticalToWhenDefined(I2))
1566  return Changed;
1567  goto HoistTerminator;
1568  }
1569 
1570  if (I1->isIdenticalToWhenDefined(I2)) {
1571  // Even if the instructions are identical, it may not be safe to hoist
1572  // them if we have skipped over instructions with side effects or their
1573  // operands weren't hoisted.
1574  if (!isSafeToHoistInstr(I1, SkipFlagsBB1) ||
1575  !isSafeToHoistInstr(I2, SkipFlagsBB2))
1576  return Changed;
1577 
1578  // If we're going to hoist a call, make sure that the two instructions
1579  // we're commoning/hoisting are both marked with musttail, or neither of
1580  // them is marked as such. Otherwise, we might end up in a situation where
1581  // we hoist from a block where the terminator is a `ret` to a block where
1582  // the terminator is a `br`, and `musttail` calls expect to be followed by
1583  // a return.
1584  auto *C1 = dyn_cast<CallInst>(I1);
1585  auto *C2 = dyn_cast<CallInst>(I2);
1586  if (C1 && C2)
1587  if (C1->isMustTailCall() != C2->isMustTailCall())
1588  return Changed;
1589 
1591  return Changed;
1592 
1593  // If any of the two call sites has nomerge attribute, stop hoisting.
1594  if (const auto *CB1 = dyn_cast<CallBase>(I1))
1595  if (CB1->cannotMerge())
1596  return Changed;
1597  if (const auto *CB2 = dyn_cast<CallBase>(I2))
1598  if (CB2->cannotMerge())
1599  return Changed;
1600 
1601  if (isa<DbgInfoIntrinsic>(I1) || isa<DbgInfoIntrinsic>(I2)) {
1602  assert(isa<DbgInfoIntrinsic>(I1) && isa<DbgInfoIntrinsic>(I2));
1603  // The debug location is an integral part of a debug info intrinsic
1604  // and can't be separated from it or replaced. Instead of attempting
1605  // to merge locations, simply hoist both copies of the intrinsic.
1606  BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(),
1607  I1);
1608  BIParent->getInstList().splice(BI->getIterator(), BB2->getInstList(),
1609  I2);
1610  } else {
1611  // For a normal instruction, we just move one to right before the
1612  // branch, then replace all uses of the other with the first. Finally,
1613  // we remove the now redundant second instruction.
1614  BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(),
1615  I1);
1616  if (!I2->use_empty())
1617  I2->replaceAllUsesWith(I1);
1618  I1->andIRFlags(I2);
1619  unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
1620  LLVMContext::MD_range,
1621  LLVMContext::MD_fpmath,
1622  LLVMContext::MD_invariant_load,
1623  LLVMContext::MD_nonnull,
1624  LLVMContext::MD_invariant_group,
1625  LLVMContext::MD_align,
1626  LLVMContext::MD_dereferenceable,
1627  LLVMContext::MD_dereferenceable_or_null,
1628  LLVMContext::MD_mem_parallel_loop_access,
1629  LLVMContext::MD_access_group,
1630  LLVMContext::MD_preserve_access_index};
1631  combineMetadata(I1, I2, KnownIDs, true);
1632 
1633  // I1 and I2 are being combined into a single instruction. Its debug
1634  // location is the merged locations of the original instructions.
1635  I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
1636 
1637  I2->eraseFromParent();
1638  }
1639  Changed = true;
1640  ++NumHoistCommonInstrs;
1641  } else {
1642  if (NumSkipped >= HoistCommonSkipLimit)
1643  return Changed;
1644  // We are about to skip over a pair of non-identical instructions. Record
1645  // if any have characteristics that would prevent reordering instructions
1646  // across them.
1647  SkipFlagsBB1 |= skippedInstrFlags(I1);
1648  SkipFlagsBB2 |= skippedInstrFlags(I2);
1649  ++NumSkipped;
1650  }
1651 
1652  I1 = &*BB1_Itr++;
1653  I2 = &*BB2_Itr++;
1654  // Skip debug info if it is not identical.
1655  DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1656  DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1657  if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1658  while (isa<DbgInfoIntrinsic>(I1))
1659  I1 = &*BB1_Itr++;
1660  while (isa<DbgInfoIntrinsic>(I2))
1661  I2 = &*BB2_Itr++;
1662  }
1663  }
1664 
1665  return Changed;
1666 
1667 HoistTerminator:
1668  // It may not be possible to hoist an invoke.
1669  // FIXME: Can we define a safety predicate for CallBr?
1670  if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1671  return Changed;
1672 
1673  // TODO: callbr hoisting currently disabled pending further study.
1674  if (isa<CallBrInst>(I1))
1675  return Changed;
1676 
1677  for (BasicBlock *Succ : successors(BB1)) {
1678  for (PHINode &PN : Succ->phis()) {
1679  Value *BB1V = PN.getIncomingValueForBlock(BB1);
1680  Value *BB2V = PN.getIncomingValueForBlock(BB2);
1681  if (BB1V == BB2V)
1682  continue;
1683 
1684  // Check for passingValueIsAlwaysUndefined here because we would rather
1685  // eliminate undefined control flow then converting it to a select.
1686  if (passingValueIsAlwaysUndefined(BB1V, &PN) ||
1687  passingValueIsAlwaysUndefined(BB2V, &PN))
1688  return Changed;
1689  }
1690  }
1691 
1692  // Okay, it is safe to hoist the terminator.
1693  Instruction *NT = I1->clone();
1694  BIParent->getInstList().insert(BI->getIterator(), NT);
1695  if (!NT->getType()->isVoidTy()) {
1696  I1->replaceAllUsesWith(NT);
1697  I2->replaceAllUsesWith(NT);
1698  NT->takeName(I1);
1699  }
1700  Changed = true;
1701  ++NumHoistCommonInstrs;
1702 
1703  // Ensure terminator gets a debug location, even an unknown one, in case
1704  // it involves inlinable calls.
1705  NT->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
1706 
1707  // PHIs created below will adopt NT's merged DebugLoc.
1709 
1710  // Hoisting one of the terminators from our successor is a great thing.
1711  // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1712  // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1713  // nodes, so we insert select instruction to compute the final result.
1714  std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
1715  for (BasicBlock *Succ : successors(BB1)) {
1716  for (PHINode &PN : Succ->phis()) {
1717  Value *BB1V = PN.getIncomingValueForBlock(BB1);
1718  Value *BB2V = PN.getIncomingValueForBlock(BB2);
1719  if (BB1V == BB2V)
1720  continue;
1721 
1722  // These values do not agree. Insert a select instruction before NT
1723  // that determines the right value.
1724  SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1725  if (!SI) {
1726  // Propagate fast-math-flags from phi node to its replacement select.
1728  if (isa<FPMathOperator>(PN))
1729  Builder.setFastMathFlags(PN.getFastMathFlags());
1730 
1731  SI = cast<SelectInst>(
1732  Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1733  BB1V->getName() + "." + BB2V->getName(), BI));
1734  }
1735 
1736  // Make the PHI node use the select for all incoming values for BB1/BB2
1737  for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1738  if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
1739  PN.setIncomingValue(i, SI);
1740  }
1741  }
1742 
1744 
1745  // Update any PHI nodes in our new successors.
1746  for (BasicBlock *Succ : successors(BB1)) {
1747  AddPredecessorToBlock(Succ, BIParent, BB1);
1748  if (DTU)
1749  Updates.push_back({DominatorTree::Insert, BIParent, Succ});
1750  }
1751 
1752  if (DTU)
1753  for (BasicBlock *Succ : successors(BI))
1754  Updates.push_back({DominatorTree::Delete, BIParent, Succ});
1755 
1757  if (DTU)
1758  DTU->applyUpdates(Updates);
1759  return Changed;
1760 }
1761 
1762 // Check lifetime markers.
1763 static bool isLifeTimeMarker(const Instruction *I) {
1764  if (auto II = dyn_cast<IntrinsicInst>(I)) {
1765  switch (II->getIntrinsicID()) {
1766  default:
1767  break;
1768  case Intrinsic::lifetime_start:
1769  case Intrinsic::lifetime_end:
1770  return true;
1771  }
1772  }
1773  return false;
1774 }
1775 
1776 // TODO: Refine this. This should avoid cases like turning constant memcpy sizes
1777 // into variables.
1779  int OpIdx) {
1780  return !isa<IntrinsicInst>(I);
1781 }
1782 
1783 // All instructions in Insts belong to different blocks that all unconditionally
1784 // branch to a common successor. Analyze each instruction and return true if it
1785 // would be possible to sink them into their successor, creating one common
1786 // instruction instead. For every value that would be required to be provided by
1787 // PHI node (because an operand varies in each input block), add to PHIOperands.
1790  DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
1791  // Prune out obviously bad instructions to move. Each instruction must have
1792  // exactly zero or one use, and we check later that use is by a single, common
1793  // PHI instruction in the successor.
1794  bool HasUse = !Insts.front()->user_empty();
1795  for (auto *I : Insts) {
1796  // These instructions may change or break semantics if moved.
1797  if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
1798  I->getType()->isTokenTy())
1799  return false;
1800 
1801  // Do not try to sink an instruction in an infinite loop - it can cause
1802  // this algorithm to infinite loop.
1803  if (I->getParent()->getSingleSuccessor() == I->getParent())
1804  return false;
1805 
1806  // Conservatively return false if I is an inline-asm instruction. Sinking
1807  // and merging inline-asm instructions can potentially create arguments
1808  // that cannot satisfy the inline-asm constraints.
1809  // If the instruction has nomerge attribute, return false.
1810  if (const auto *C = dyn_cast<CallBase>(I))
1811  if (C->isInlineAsm() || C->cannotMerge())
1812  return false;
1813 
1814  // Each instruction must have zero or one use.
1815  if (HasUse && !I->hasOneUse())
1816  return false;
1817  if (!HasUse && !I->user_empty())
1818  return false;
1819  }
1820 
1821  const Instruction *I0 = Insts.front();
1822  for (auto *I : Insts)
1823  if (!I->isSameOperationAs(I0))
1824  return false;
1825 
1826  // All instructions in Insts are known to be the same opcode. If they have a
1827  // use, check that the only user is a PHI or in the same block as the
1828  // instruction, because if a user is in the same block as an instruction we're
1829  // contemplating sinking, it must already be determined to be sinkable.
1830  if (HasUse) {
1831  auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1832  auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
1833  if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
1834  auto *U = cast<Instruction>(*I->user_begin());
1835  return (PNUse &&
1836  PNUse->getParent() == Succ &&
1837  PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
1838  U->getParent() == I->getParent();
1839  }))
1840  return false;
1841  }
1842 
1843  // Because SROA can't handle speculating stores of selects, try not to sink
1844  // loads, stores or lifetime markers of allocas when we'd have to create a
1845  // PHI for the address operand. Also, because it is likely that loads or
1846  // stores of allocas will disappear when Mem2Reg/SROA is run, don't sink
1847  // them.
1848  // This can cause code churn which can have unintended consequences down
1849  // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244.
1850  // FIXME: This is a workaround for a deficiency in SROA - see
1851  // https://llvm.org/bugs/show_bug.cgi?id=30188
1852  if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
1853  return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
1854  }))
1855  return false;
1856  if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
1857  return isa<AllocaInst>(I->getOperand(0)->stripPointerCasts());
1858  }))
1859  return false;
1860  if (isLifeTimeMarker(I0) && any_of(Insts, [](const Instruction *I) {
1861  return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
1862  }))
1863  return false;
1864 
1865  // For calls to be sinkable, they must all be indirect, or have same callee.
1866  // I.e. if we have two direct calls to different callees, we don't want to
1867  // turn that into an indirect call. Likewise, if we have an indirect call,
1868  // and a direct call, we don't actually want to have a single indirect call.
1869  if (isa<CallBase>(I0)) {
1870  auto IsIndirectCall = [](const Instruction *I) {
1871  return cast<CallBase>(I)->isIndirectCall();
1872  };
1873  bool HaveIndirectCalls = any_of(Insts, IsIndirectCall);
1874  bool AllCallsAreIndirect = all_of(Insts, IsIndirectCall);
1875  if (HaveIndirectCalls) {
1876  if (!AllCallsAreIndirect)
1877  return false;
1878  } else {
1879  // All callees must be identical.
1880  Value *Callee = nullptr;
1881  for (const Instruction *I : Insts) {
1882  Value *CurrCallee = cast<CallBase>(I)->getCalledOperand();
1883  if (!Callee)
1884  Callee = CurrCallee;
1885  else if (Callee != CurrCallee)
1886  return false;
1887  }
1888  }
1889  }
1890 
1891  for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
1892  Value *Op = I0->getOperand(OI);
1893  if (Op->getType()->isTokenTy())
1894  // Don't touch any operand of token type.
1895  return false;
1896 
1897  auto SameAsI0 = [&I0, OI](const Instruction *I) {
1898  assert(I->getNumOperands() == I0->getNumOperands());
1899  return I->getOperand(OI) == I0->getOperand(OI);
1900  };
1901  if (!all_of(Insts, SameAsI0)) {
1902  if ((isa<Constant>(Op) && !replacingOperandWithVariableIsCheap(I0, OI)) ||
1904  // We can't create a PHI from this GEP.
1905  return false;
1906  for (auto *I : Insts)
1907  PHIOperands[I].push_back(I->getOperand(OI));
1908  }
1909  }
1910  return true;
1911 }
1912 
1913 // Assuming canSinkInstructions(Blocks) has returned true, sink the last
1914 // instruction of every block in Blocks to their common successor, commoning
1915 // into one instruction.
1917  auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1918 
1919  // canSinkInstructions returning true guarantees that every block has at
1920  // least one non-terminator instruction.
1922  for (auto *BB : Blocks) {
1923  Instruction *I = BB->getTerminator();
1924  do {
1925  I = I->getPrevNode();
1926  } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
1927  if (!isa<DbgInfoIntrinsic>(I))
1928  Insts.push_back(I);
1929  }
1930 
1931  // The only checking we need to do now is that all users of all instructions
1932  // are the same PHI node. canSinkInstructions should have checked this but
1933  // it is slightly over-aggressive - it gets confused by commutative
1934  // instructions so double-check it here.
1935  Instruction *I0 = Insts.front();
1936  if (!I0->user_empty()) {
1937  auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1938  if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
1939  auto *U = cast<Instruction>(*I->user_begin());
1940  return U == PNUse;
1941  }))
1942  return false;
1943  }
1944 
1945  // We don't need to do any more checking here; canSinkInstructions should
1946  // have done it all for us.
1947  SmallVector<Value*, 4> NewOperands;
1948  for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
1949  // This check is different to that in canSinkInstructions. There, we
1950  // cared about the global view once simplifycfg (and instcombine) have
1951  // completed - it takes into account PHIs that become trivially
1952  // simplifiable. However here we need a more local view; if an operand
1953  // differs we create a PHI and rely on instcombine to clean up the very
1954  // small mess we may make.
1955  bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
1956  return I->getOperand(O) != I0->getOperand(O);
1957  });
1958  if (!NeedPHI) {
1959  NewOperands.push_back(I0->getOperand(O));
1960  continue;
1961  }
1962 
1963  // Create a new PHI in the successor block and populate it.
1964  auto *Op = I0->getOperand(O);
1965  assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
1966  auto *PN = PHINode::Create(Op->getType(), Insts.size(),
1967  Op->getName() + ".sink", &BBEnd->front());
1968  for (auto *I : Insts)
1969  PN->addIncoming(I->getOperand(O), I->getParent());
1970  NewOperands.push_back(PN);
1971  }
1972 
1973  // Arbitrarily use I0 as the new "common" instruction; remap its operands
1974  // and move it to the start of the successor block.
1975  for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
1976  I0->getOperandUse(O).set(NewOperands[O]);
1977  I0->moveBefore(&*BBEnd->getFirstInsertionPt());
1978 
1979  // Update metadata and IR flags, and merge debug locations.
1980  for (auto *I : Insts)
1981  if (I != I0) {
1982  // The debug location for the "common" instruction is the merged locations
1983  // of all the commoned instructions. We start with the original location
1984  // of the "common" instruction and iteratively merge each location in the
1985  // loop below.
1986  // This is an N-way merge, which will be inefficient if I0 is a CallInst.
1987  // However, as N-way merge for CallInst is rare, so we use simplified API
1988  // instead of using complex API for N-way merge.
1989  I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
1990  combineMetadataForCSE(I0, I, true);
1991  I0->andIRFlags(I);
1992  }
1993 
1994  if (!I0->user_empty()) {
1995  // canSinkLastInstruction checked that all instructions were used by
1996  // one and only one PHI node. Find that now, RAUW it to our common
1997  // instruction and nuke it.
1998  auto *PN = cast<PHINode>(*I0->user_begin());
1999  PN->replaceAllUsesWith(I0);
2000  PN->eraseFromParent();
2001  }
2002 
2003  // Finally nuke all instructions apart from the common instruction.
2004  for (auto *I : Insts) {
2005  if (I == I0)
2006  continue;
2007  // The remaining uses are debug users, replace those with the common inst.
2008  // In most (all?) cases this just introduces a use-before-def.
2009  assert(I->user_empty() && "Inst unexpectedly still has non-dbg users");
2010  I->replaceAllUsesWith(I0);
2011  I->eraseFromParent();
2012  }
2013 
2014  return true;
2015 }
2016 
2017 namespace {
2018 
2019  // LockstepReverseIterator - Iterates through instructions
2020  // in a set of blocks in reverse order from the first non-terminator.
2021  // For example (assume all blocks have size n):
2022  // LockstepReverseIterator I([B1, B2, B3]);
2023  // *I-- = [B1[n], B2[n], B3[n]];
2024  // *I-- = [B1[n-1], B2[n-1], B3[n-1]];
2025  // *I-- = [B1[n-2], B2[n-2], B3[n-2]];
2026  // ...
2027  class LockstepReverseIterator {
2028  ArrayRef<BasicBlock*> Blocks;
2030  bool Fail;
2031 
2032  public:
2033  LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) {
2034  reset();
2035  }
2036 
2037  void reset() {
2038  Fail = false;
2039  Insts.clear();
2040  for (auto *BB : Blocks) {
2041  Instruction *Inst = BB->getTerminator();
2042  for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
2043  Inst = Inst->getPrevNode();
2044  if (!Inst) {
2045  // Block wasn't big enough.
2046  Fail = true;
2047  return;
2048  }
2049  Insts.push_back(Inst);
2050  }
2051  }
2052 
2053  bool isValid() const {
2054  return !Fail;
2055  }
2056 
2057  void operator--() {
2058  if (Fail)
2059  return;
2060  for (auto *&Inst : Insts) {
2061  for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
2062  Inst = Inst->getPrevNode();
2063  // Already at beginning of block.
2064  if (!Inst) {
2065  Fail = true;
2066  return;
2067  }
2068  }
2069  }
2070 
2071  void operator++() {
2072  if (Fail)
2073  return;
2074  for (auto *&Inst : Insts) {
2075  for (Inst = Inst->getNextNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
2076  Inst = Inst->getNextNode();
2077  // Already at end of block.
2078  if (!Inst) {
2079  Fail = true;
2080  return;
2081  }
2082  }
2083  }
2084 
2086  return Insts;
2087  }
2088  };
2089 
2090 } // end anonymous namespace
2091 
2092 /// Check whether BB's predecessors end with unconditional branches. If it is
2093 /// true, sink any common code from the predecessors to BB.
2095  DomTreeUpdater *DTU) {
2096  // We support two situations:
2097  // (1) all incoming arcs are unconditional
2098  // (2) there are non-unconditional incoming arcs
2099  //
2100  // (2) is very common in switch defaults and
2101  // else-if patterns;
2102  //
2103  // if (a) f(1);
2104  // else if (b) f(2);
2105  //
2106  // produces:
2107  //
2108  // [if]
2109  // / \
2110  // [f(1)] [if]
2111  // | | \
2112  // | | |
2113  // | [f(2)]|
2114  // \ | /
2115  // [ end ]
2116  //
2117  // [end] has two unconditional predecessor arcs and one conditional. The
2118  // conditional refers to the implicit empty 'else' arc. This conditional
2119  // arc can also be caused by an empty default block in a switch.
2120  //
2121  // In this case, we attempt to sink code from all *unconditional* arcs.
2122  // If we can sink instructions from these arcs (determined during the scan
2123  // phase below) we insert a common successor for all unconditional arcs and
2124  // connect that to [end], to enable sinking:
2125  //
2126  // [if]
2127  // / \
2128  // [x(1)] [if]
2129  // | | \
2130  // | | \
2131  // | [x(2)] |
2132  // \ / |
2133  // [sink.split] |
2134  // \ /
2135  // [ end ]
2136  //
2137  SmallVector<BasicBlock*,4> UnconditionalPreds;
2138  bool HaveNonUnconditionalPredecessors = false;
2139  for (auto *PredBB : predecessors(BB)) {
2140  auto *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
2141  if (PredBr && PredBr->isUnconditional())
2142  UnconditionalPreds.push_back(PredBB);
2143  else
2144  HaveNonUnconditionalPredecessors = true;
2145  }
2146  if (UnconditionalPreds.size() < 2)
2147  return false;
2148 
2149  // We take a two-step approach to tail sinking. First we scan from the end of
2150  // each block upwards in lockstep. If the n'th instruction from the end of each
2151  // block can be sunk, those instructions are added to ValuesToSink and we
2152  // carry on. If we can sink an instruction but need to PHI-merge some operands
2153  // (because they're not identical in each instruction) we add these to
2154  // PHIOperands.
2155  int ScanIdx = 0;
2156  SmallPtrSet<Value*,4> InstructionsToSink;
2158  LockstepReverseIterator LRI(UnconditionalPreds);
2159  while (LRI.isValid() &&
2160  canSinkInstructions(*LRI, PHIOperands)) {
2161  LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
2162  << "\n");
2163  InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
2164  ++ScanIdx;
2165  --LRI;
2166  }
2167 
2168  // If no instructions can be sunk, early-return.
2169  if (ScanIdx == 0)
2170  return false;
2171 
2172  bool followedByDeoptOrUnreachable = IsBlockFollowedByDeoptOrUnreachable(BB);
2173 
2174  if (!followedByDeoptOrUnreachable) {
2175  // Okay, we *could* sink last ScanIdx instructions. But how many can we
2176  // actually sink before encountering instruction that is unprofitable to
2177  // sink?
2178  auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
2179  unsigned NumPHIdValues = 0;
2180  for (auto *I : *LRI)
2181  for (auto *V : PHIOperands[I]) {
2182  if (!InstructionsToSink.contains(V))
2183  ++NumPHIdValues;
2184  // FIXME: this check is overly optimistic. We may end up not sinking
2185  // said instruction, due to the very same profitability check.
2186  // See @creating_too_many_phis in sink-common-code.ll.
2187  }
2188  LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
2189  unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
2190  if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
2191  NumPHIInsts++;
2192 
2193  return NumPHIInsts <= 1;
2194  };
2195 
2196  // We've determined that we are going to sink last ScanIdx instructions,
2197  // and recorded them in InstructionsToSink. Now, some instructions may be
2198  // unprofitable to sink. But that determination depends on the instructions
2199  // that we are going to sink.
2200 
2201  // First, forward scan: find the first instruction unprofitable to sink,
2202  // recording all the ones that are profitable to sink.
2203  // FIXME: would it be better, after we detect that not all are profitable.
2204  // to either record the profitable ones, or erase the unprofitable ones?
2205  // Maybe we need to choose (at runtime) the one that will touch least
2206  // instrs?
2207  LRI.reset();
2208  int Idx = 0;
2209  SmallPtrSet<Value *, 4> InstructionsProfitableToSink;
2210  while (Idx < ScanIdx) {
2211  if (!ProfitableToSinkInstruction(LRI)) {
2212  // Too many PHIs would be created.
2213  LLVM_DEBUG(
2214  dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
2215  break;
2216  }
2217  InstructionsProfitableToSink.insert((*LRI).begin(), (*LRI).end());
2218  --LRI;
2219  ++Idx;
2220  }
2221 
2222  // If no instructions can be sunk, early-return.
2223  if (Idx == 0)
2224  return false;
2225 
2226  // Did we determine that (only) some instructions are unprofitable to sink?
2227  if (Idx < ScanIdx) {
2228  // Okay, some instructions are unprofitable.
2229  ScanIdx = Idx;
2230  InstructionsToSink = InstructionsProfitableToSink;
2231 
2232  // But, that may make other instructions unprofitable, too.
2233  // So, do a backward scan, do any earlier instructions become
2234  // unprofitable?
2235  assert(
2236  !ProfitableToSinkInstruction(LRI) &&
2237  "We already know that the last instruction is unprofitable to sink");
2238  ++LRI;
2239  --Idx;
2240  while (Idx >= 0) {
2241  // If we detect that an instruction becomes unprofitable to sink,
2242  // all earlier instructions won't be sunk either,
2243  // so preemptively keep InstructionsProfitableToSink in sync.
2244  // FIXME: is this the most performant approach?
2245  for (auto *I : *LRI)
2246  InstructionsProfitableToSink.erase(I);
2247  if (!ProfitableToSinkInstruction(LRI)) {
2248  // Everything starting with this instruction won't be sunk.
2249  ScanIdx = Idx;
2250  InstructionsToSink = InstructionsProfitableToSink;
2251  }
2252  ++LRI;
2253  --Idx;
2254  }
2255  }
2256 
2257  // If no instructions can be sunk, early-return.
2258  if (ScanIdx == 0)
2259  return false;
2260  }
2261 
2262  bool Changed = false;
2263 
2264  if (HaveNonUnconditionalPredecessors) {
2265  if (!followedByDeoptOrUnreachable) {
2266  // It is always legal to sink common instructions from unconditional
2267  // predecessors. However, if not all predecessors are unconditional,
2268  // this transformation might be pessimizing. So as a rule of thumb,
2269  // don't do it unless we'd sink at least one non-speculatable instruction.
2270  // See https://bugs.llvm.org/show_bug.cgi?id=30244
2271  LRI.reset();
2272  int Idx = 0;
2273  bool Profitable = false;
2274  while (Idx < ScanIdx) {
2275  if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
2276  Profitable = true;
2277  break;
2278  }
2279  --LRI;
2280  ++Idx;
2281  }
2282  if (!Profitable)
2283  return false;
2284  }
2285 
2286  LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
2287  // We have a conditional edge and we're going to sink some instructions.
2288  // Insert a new block postdominating all blocks we're going to sink from.
2289  if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split", DTU))
2290  // Edges couldn't be split.
2291  return false;
2292  Changed = true;
2293  }
2294 
2295  // Now that we've analyzed all potential sinking candidates, perform the
2296  // actual sink. We iteratively sink the last non-terminator of the source
2297  // blocks into their common successor unless doing so would require too
2298  // many PHI instructions to be generated (currently only one PHI is allowed
2299  // per sunk instruction).
2300  //
2301  // We can use InstructionsToSink to discount values needing PHI-merging that will
2302  // actually be sunk in a later iteration. This allows us to be more
2303  // aggressive in what we sink. This does allow a false positive where we
2304  // sink presuming a later value will also be sunk, but stop half way through
2305  // and never actually sink it which means we produce more PHIs than intended.
2306  // This is unlikely in practice though.
2307  int SinkIdx = 0;
2308  for (; SinkIdx != ScanIdx; ++SinkIdx) {
2309  LLVM_DEBUG(dbgs() << "SINK: Sink: "
2310  << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
2311  << "\n");
2312 
2313  // Because we've sunk every instruction in turn, the current instruction to
2314  // sink is always at index 0.
2315  LRI.reset();
2316 
2317  if (!sinkLastInstruction(UnconditionalPreds)) {
2318  LLVM_DEBUG(
2319  dbgs()
2320  << "SINK: stopping here, failed to actually sink instruction!\n");
2321  break;
2322  }
2323 
2324  NumSinkCommonInstrs++;
2325  Changed = true;
2326  }
2327  if (SinkIdx != 0)
2328  ++NumSinkCommonCode;
2329  return Changed;
2330 }
2331 
2332 namespace {
2333 
2334 struct CompatibleSets {
2335  using SetTy = SmallVector<InvokeInst *, 2>;
2336 
2337  SmallVector<SetTy, 1> Sets;
2338 
2339  static bool shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes);
2340 
2341  SetTy &getCompatibleSet(InvokeInst *II);
2342 
2343  void insert(InvokeInst *II);
2344 };
2345 
2346 CompatibleSets::SetTy &CompatibleSets::getCompatibleSet(InvokeInst *II) {
2347  // Perform a linear scan over all the existing sets, see if the new `invoke`
2348  // is compatible with any particular set. Since we know that all the `invokes`
2349  // within a set are compatible, only check the first `invoke` in each set.
2350  // WARNING: at worst, this has quadratic complexity.
2351  for (CompatibleSets::SetTy &Set : Sets) {
2352  if (CompatibleSets::shouldBelongToSameSet({Set.front(), II}))
2353  return Set;
2354  }
2355 
2356  // Otherwise, we either had no sets yet, or this invoke forms a new set.
2357  return Sets.emplace_back();
2358 }
2359 
2360 void CompatibleSets::insert(InvokeInst *II) {
2361  getCompatibleSet(II).emplace_back(II);
2362 }
2363 
2364 bool CompatibleSets::shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes) {
2365  assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2366 
2367  // Can we theoretically merge these `invoke`s?
2368  auto IsIllegalToMerge = [](InvokeInst *II) {
2369  return II->cannotMerge() || II->isInlineAsm();
2370  };
2371  if (any_of(Invokes, IsIllegalToMerge))
2372  return false;
2373 
2374  // Either both `invoke`s must be direct,
2375  // or both `invoke`s must be indirect.
2376  auto IsIndirectCall = [](InvokeInst *II) { return II->isIndirectCall(); };
2377  bool HaveIndirectCalls = any_of(Invokes, IsIndirectCall);
2378  bool AllCallsAreIndirect = all_of(Invokes, IsIndirectCall);
2379  if (HaveIndirectCalls) {
2380  if (!AllCallsAreIndirect)
2381  return false;
2382  } else {
2383  // All callees must be identical.
2384  Value *Callee = nullptr;
2385  for (InvokeInst *II : Invokes) {
2386  Value *CurrCallee = II->getCalledOperand();
2387  assert(CurrCallee && "There is always a called operand.");
2388  if (!Callee)
2389  Callee = CurrCallee;
2390  else if (Callee != CurrCallee)
2391  return false;
2392  }
2393  }
2394 
2395  // Either both `invoke`s must not have a normal destination,
2396  // or both `invoke`s must have a normal destination,
2397  auto HasNormalDest = [](InvokeInst *II) {
2398  return !isa<UnreachableInst>(II->getNormalDest()->getFirstNonPHIOrDbg());
2399  };
2400  if (any_of(Invokes, HasNormalDest)) {
2401  // Do not merge `invoke` that does not have a normal destination with one
2402  // that does have a normal destination, even though doing so would be legal.
2403  if (!all_of(Invokes, HasNormalDest))
2404  return false;
2405 
2406  // All normal destinations must be identical.
2407  BasicBlock *NormalBB = nullptr;
2408  for (InvokeInst *II : Invokes) {
2409  BasicBlock *CurrNormalBB = II->getNormalDest();
2410  assert(CurrNormalBB && "There is always a 'continue to' basic block.");
2411  if (!NormalBB)
2412  NormalBB = CurrNormalBB;
2413  else if (NormalBB != CurrNormalBB)
2414  return false;
2415  }
2416 
2417  // In the normal destination, the incoming values for these two `invoke`s
2418  // must be compatible.
2419  SmallPtrSet<Value *, 16> EquivalenceSet(Invokes.begin(), Invokes.end());
2421  NormalBB, {Invokes[0]->getParent(), Invokes[1]->getParent()},
2422  &EquivalenceSet))
2423  return false;
2424  }
2425 
2426 #ifndef NDEBUG
2427  // All unwind destinations must be identical.
2428  // We know that because we have started from said unwind destination.
2429  BasicBlock *UnwindBB = nullptr;
2430  for (InvokeInst *II : Invokes) {
2431  BasicBlock *CurrUnwindBB = II->getUnwindDest();
2432  assert(CurrUnwindBB && "There is always an 'unwind to' basic block.");
2433  if (!UnwindBB)
2434  UnwindBB = CurrUnwindBB;
2435  else
2436  assert(UnwindBB == CurrUnwindBB && "Unexpected unwind destination.");
2437  }
2438 #endif
2439 
2440  // In the unwind destination, the incoming values for these two `invoke`s
2441  // must be compatible.
2443  Invokes.front()->getUnwindDest(),
2444  {Invokes[0]->getParent(), Invokes[1]->getParent()}))
2445  return false;
2446 
2447  // Ignoring arguments, these `invoke`s must be identical,
2448  // including operand bundles.
2449  const InvokeInst *II0 = Invokes.front();
2450  for (auto *II : Invokes.drop_front())
2451  if (!II->isSameOperationAs(II0))
2452  return false;
2453 
2454  // Can we theoretically form the data operands for the merged `invoke`?
2455  auto IsIllegalToMergeArguments = [](auto Ops) {
2456  Type *Ty = std::get<0>(Ops)->getType();
2457  assert(Ty == std::get<1>(Ops)->getType() && "Incompatible types?");
2458  return Ty->isTokenTy() && std::get<0>(Ops) != std::get<1>(Ops);
2459  };
2460  assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2461  if (any_of(zip(Invokes[0]->data_ops(), Invokes[1]->data_ops()),
2462  IsIllegalToMergeArguments))
2463  return false;
2464 
2465  return true;
2466 }
2467 
2468 } // namespace
2469 
2470 // Merge all invokes in the provided set, all of which are compatible
2471 // as per the `CompatibleSets::shouldBelongToSameSet()`.
2473  DomTreeUpdater *DTU) {
2474  assert(Invokes.size() >= 2 && "Must have at least two invokes to merge.");
2475 
2477  if (DTU)
2478  Updates.reserve(2 + 3 * Invokes.size());
2479 
2480  bool HasNormalDest =
2481  !isa<UnreachableInst>(Invokes[0]->getNormalDest()->getFirstNonPHIOrDbg());
2482 
2483  // Clone one of the invokes into a new basic block.
2484  // Since they are all compatible, it doesn't matter which invoke is cloned.
2485  InvokeInst *MergedInvoke = [&Invokes, HasNormalDest]() {
2486  InvokeInst *II0 = Invokes.front();
2487  BasicBlock *II0BB = II0->getParent();
2488  BasicBlock *InsertBeforeBlock =
2489  II0->getParent()->getIterator()->getNextNode();
2490  Function *Func = II0BB->getParent();
2491  LLVMContext &Ctx = II0->getContext();
2492 
2493  BasicBlock *MergedInvokeBB = BasicBlock::Create(
2494  Ctx, II0BB->getName() + ".invoke", Func, InsertBeforeBlock);
2495 
2496  auto *MergedInvoke = cast<InvokeInst>(II0->clone());
2497  // NOTE: all invokes have the same attributes, so no handling needed.
2498  MergedInvokeBB->getInstList().push_back(MergedInvoke);
2499 
2500  if (!HasNormalDest) {
2501  // This set does not have a normal destination,
2502  // so just form a new block with unreachable terminator.
2503  BasicBlock *MergedNormalDest = BasicBlock::Create(
2504  Ctx, II0BB->getName() + ".cont", Func, InsertBeforeBlock);
2505  new UnreachableInst(Ctx, MergedNormalDest);
2506  MergedInvoke->setNormalDest(MergedNormalDest);
2507  }
2508 
2509  // The unwind destination, however, remainds identical for all invokes here.
2510 
2511  return MergedInvoke;
2512  }();
2513 
2514  if (DTU) {
2515  // Predecessor blocks that contained these invokes will now branch to
2516  // the new block that contains the merged invoke, ...
2517  for (InvokeInst *II : Invokes)
2518  Updates.push_back(
2519  {DominatorTree::Insert, II->getParent(), MergedInvoke->getParent()});
2520 
2521  // ... which has the new `unreachable` block as normal destination,
2522  // or unwinds to the (same for all `invoke`s in this set) `landingpad`,
2523  for (BasicBlock *SuccBBOfMergedInvoke : successors(MergedInvoke))
2524  Updates.push_back({DominatorTree::Insert, MergedInvoke->getParent(),
2525  SuccBBOfMergedInvoke});
2526 
2527  // Since predecessor blocks now unconditionally branch to a new block,
2528  // they no longer branch to their original successors.
2529  for (InvokeInst *II : Invokes)
2530  for (BasicBlock *SuccOfPredBB : successors(II->getParent()))
2531  Updates.push_back(
2532  {DominatorTree::Delete, II->getParent(), SuccOfPredBB});
2533  }
2534 
2535  bool IsIndirectCall = Invokes[0]->isIndirectCall();
2536 
2537  // Form the merged operands for the merged invoke.
2538  for (Use &U : MergedInvoke->operands()) {
2539  // Only PHI together the indirect callees and data operands.
2540  if (MergedInvoke->isCallee(&U)) {
2541  if (!IsIndirectCall)
2542  continue;
2543  } else if (!MergedInvoke->isDataOperand(&U))
2544  continue;
2545 
2546  // Don't create trivial PHI's with all-identical incoming values.
2547  bool NeedPHI = any_of(Invokes, [&U](InvokeInst *II) {
2548  return II->getOperand(U.getOperandNo()) != U.get();
2549  });
2550  if (!NeedPHI)
2551  continue;
2552 
2553  // Form a PHI out of all the data ops under this index.
2554  PHINode *PN = PHINode::Create(
2555  U->getType(), /*NumReservedValues=*/Invokes.size(), "", MergedInvoke);
2556  for (InvokeInst *II : Invokes)
2557  PN->addIncoming(II->getOperand(U.getOperandNo()), II->getParent());
2558 
2559  U.set(PN);
2560  }
2561 
2562  // We've ensured that each PHI node has compatible (identical) incoming values
2563  // when coming from each of the `invoke`s in the current merge set,
2564  // so update the PHI nodes accordingly.
2565  for (BasicBlock *Succ : successors(MergedInvoke))
2566  AddPredecessorToBlock(Succ, /*NewPred=*/MergedInvoke->getParent(),
2567  /*ExistPred=*/Invokes.front()->getParent());
2568 
2569  // And finally, replace the original `invoke`s with an unconditional branch
2570  // to the block with the merged `invoke`. Also, give that merged `invoke`
2571  // the merged debugloc of all the original `invoke`s.
2572  const DILocation *MergedDebugLoc = nullptr;
2573  for (InvokeInst *II : Invokes) {
2574  // Compute the debug location common to all the original `invoke`s.
2575  if (!MergedDebugLoc)
2576  MergedDebugLoc = II->getDebugLoc();
2577  else
2578  MergedDebugLoc =
2579  DILocation::getMergedLocation(MergedDebugLoc, II->getDebugLoc());
2580 
2581  // And replace the old `invoke` with an unconditionally branch
2582  // to the block with the merged `invoke`.
2583  for (BasicBlock *OrigSuccBB : successors(II->getParent()))
2584  OrigSuccBB->removePredecessor(II->getParent());
2585  BranchInst::Create(MergedInvoke->getParent(), II->getParent());
2586  II->replaceAllUsesWith(MergedInvoke);
2587  II->eraseFromParent();
2588  ++NumInvokesMerged;
2589  }
2590  MergedInvoke->setDebugLoc(MergedDebugLoc);
2591  ++NumInvokeSetsFormed;
2592 
2593  if (DTU)
2594  DTU->applyUpdates(Updates);
2595 }
2596 
2597 /// If this block is a `landingpad` exception handling block, categorize all
2598 /// the predecessor `invoke`s into sets, with all `invoke`s in each set
2599 /// being "mergeable" together, and then merge invokes in each set together.
2600 ///
2601 /// This is a weird mix of hoisting and sinking. Visually, it goes from:
2602 /// [...] [...]
2603 /// | |
2604 /// [invoke0] [invoke1]
2605 /// / \ / \
2606 /// [cont0] [landingpad] [cont1]
2607 /// to:
2608 /// [...] [...]
2609 /// \ /
2610 /// [invoke]
2611 /// / \
2612 /// [cont] [landingpad]
2613 ///
2614 /// But of course we can only do that if the invokes share the `landingpad`,
2615 /// edges invoke0->cont0 and invoke1->cont1 are "compatible",
2616 /// and the invoked functions are "compatible".
2619  return false;
2620 
2621  bool Changed = false;
2622 
2623  // FIXME: generalize to all exception handling blocks?
2624  if (!BB->isLandingPad())
2625  return Changed;
2626 
2627  CompatibleSets Grouper;
2628 
2629  // Record all the predecessors of this `landingpad`. As per verifier,
2630  // the only allowed predecessor is the unwind edge of an `invoke`.
2631  // We want to group "compatible" `invokes` into the same set to be merged.
2632  for (BasicBlock *PredBB : predecessors(BB))
2633  Grouper.insert(cast<InvokeInst>(PredBB->getTerminator()));
2634 
2635  // And now, merge `invoke`s that were grouped togeter.
2636  for (ArrayRef<InvokeInst *> Invokes : Grouper.Sets) {
2637  if (Invokes.size() < 2)
2638  continue;
2639  Changed = true;
2640  MergeCompatibleInvokesImpl(Invokes, DTU);
2641  }
2642 
2643  return Changed;
2644 }
2645 
2646 namespace {
2647 /// Track ephemeral values, which should be ignored for cost-modelling
2648 /// purposes. Requires walking instructions in reverse order.
2649 class EphemeralValueTracker {
2651 
2652  bool isEphemeral(const Instruction *I) {
2653  if (isa<AssumeInst>(I))
2654  return true;
2655  return !I->mayHaveSideEffects() && !I->isTerminator() &&
2656  all_of(I->users(), [&](const User *U) {
2657  return EphValues.count(cast<Instruction>(U));
2658  });
2659  }
2660 
2661 public:
2662  bool track(const Instruction *I) {
2663  if (isEphemeral(I)) {
2664  EphValues.insert(I);
2665  return true;
2666  }
2667  return false;
2668  }
2669 
2670  bool contains(const Instruction *I) const { return EphValues.contains(I); }
2671 };
2672 } // namespace
2673 
2674 /// Determine if we can hoist sink a sole store instruction out of a
2675 /// conditional block.
2676 ///
2677 /// We are looking for code like the following:
2678 /// BrBB:
2679 /// store i32 %add, i32* %arrayidx2
2680 /// ... // No other stores or function calls (we could be calling a memory
2681 /// ... // function).
2682 /// %cmp = icmp ult %x, %y
2683 /// br i1 %cmp, label %EndBB, label %ThenBB
2684 /// ThenBB:
2685 /// store i32 %add5, i32* %arrayidx2
2686 /// br label EndBB
2687 /// EndBB:
2688 /// ...
2689 /// We are going to transform this into:
2690 /// BrBB:
2691 /// store i32 %add, i32* %arrayidx2
2692 /// ... //
2693 /// %cmp = icmp ult %x, %y
2694 /// %add.add5 = select i1 %cmp, i32 %add, %add5
2695 /// store i32 %add.add5, i32* %arrayidx2
2696 /// ...
2697 ///
2698 /// \return The pointer to the value of the previous store if the store can be
2699 /// hoisted into the predecessor block. 0 otherwise.
2701  BasicBlock *StoreBB, BasicBlock *EndBB) {
2702  StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
2703  if (!StoreToHoist)
2704  return nullptr;
2705 
2706  // Volatile or atomic.
2707  if (!StoreToHoist->isSimple())
2708  return nullptr;
2709 
2710  Value *StorePtr = StoreToHoist->getPointerOperand();
2711  Type *StoreTy = StoreToHoist->getValueOperand()->getType();
2712 
2713  // Look for a store to the same pointer in BrBB.
2714  unsigned MaxNumInstToLookAt = 9;
2715  // Skip pseudo probe intrinsic calls which are not really killing any memory
2716  // accesses.
2717  for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug(true))) {
2718  if (!MaxNumInstToLookAt)
2719  break;
2720  --MaxNumInstToLookAt;
2721 
2722  // Could be calling an instruction that affects memory like free().
2723  if (CurI.mayWriteToMemory() && !isa<StoreInst>(CurI))
2724  return nullptr;
2725 
2726  if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
2727  // Found the previous store to same location and type. Make sure it is
2728  // simple, to avoid introducing a spurious non-atomic write after an
2729  // atomic write.
2730  if (SI->getPointerOperand() == StorePtr &&
2731  SI->getValueOperand()->getType() == StoreTy && SI->isSimple())
2732  // Found the previous store, return its value operand.
2733  return SI->getValueOperand();
2734  return nullptr; // Unknown store.
2735  }
2736 
2737  if (auto *LI = dyn_cast<LoadInst>(&CurI)) {
2738  if (LI->getPointerOperand() == StorePtr && LI->getType() == StoreTy &&
2739  LI->isSimple()) {
2740  // Local objects (created by an `alloca` instruction) are always
2741  // writable, so once we are past a read from a location it is valid to
2742  // also write to that same location.
2743  // If the address of the local object never escapes the function, that
2744  // means it's never concurrently read or written, hence moving the store
2745  // from under the condition will not introduce a data race.
2746  auto *AI = dyn_cast<AllocaInst>(getUnderlyingObject(StorePtr));
2747  if (AI && !PointerMayBeCaptured(AI, false, true))
2748  // Found a previous load, return it.
2749  return LI;
2750  }
2751  // The load didn't work out, but we may still find a store.
2752  }
2753  }
2754 
2755  return nullptr;
2756 }
2757 
2758 /// Estimate the cost of the insertion(s) and check that the PHI nodes can be
2759 /// converted to selects.
2761  BasicBlock *EndBB,
2762  unsigned &SpeculatedInstructions,
2763  InstructionCost &Cost,
2764  const TargetTransformInfo &TTI) {
2766  BB->getParent()->hasMinSize()
2767  ? TargetTransformInfo::TCK_CodeSize
2768  : TargetTransformInfo::TCK_SizeAndLatency;
2769 
2770  bool HaveRewritablePHIs = false;
2771  for (PHINode &PN : EndBB->phis()) {
2772  Value *OrigV = PN.getIncomingValueForBlock(BB);
2773  Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
2774 
2775  // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
2776  // Skip PHIs which are trivial.
2777  if (ThenV == OrigV)
2778  continue;
2779 
2781  CmpInst::BAD_ICMP_PREDICATE, CostKind);
2782 
2783  // Don't convert to selects if we could remove undefined behavior instead.
2784  if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
2785  passingValueIsAlwaysUndefined(ThenV, &PN))
2786  return false;
2787 
2788  HaveRewritablePHIs = true;
2789  ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
2790  ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
2791  if (!OrigCE && !ThenCE)
2792  continue; // Known cheap (FIXME: Maybe not true for aggregates).
2793 
2794  InstructionCost OrigCost = OrigCE ? computeSpeculationCost(OrigCE, TTI) : 0;
2795  InstructionCost ThenCost = ThenCE ? computeSpeculationCost(ThenCE, TTI) : 0;
2796  InstructionCost MaxCost =
2797  2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
2798  if (OrigCost + ThenCost > MaxCost)
2799  return false;
2800 
2801  // Account for the cost of an unfolded ConstantExpr which could end up
2802  // getting expanded into Instructions.
2803  // FIXME: This doesn't account for how many operations are combined in the
2804  // constant expression.
2805  ++SpeculatedInstructions;
2806  if (SpeculatedInstructions > 1)
2807  return false;
2808  }
2809 
2810  return HaveRewritablePHIs;
2811 }
2812 
2813 /// Speculate a conditional basic block flattening the CFG.
2814 ///
2815 /// Note that this is a very risky transform currently. Speculating
2816 /// instructions like this is most often not desirable. Instead, there is an MI
2817 /// pass which can do it with full awareness of the resource constraints.
2818 /// However, some cases are "obvious" and we should do directly. An example of
2819 /// this is speculating a single, reasonably cheap instruction.
2820 ///
2821 /// There is only one distinct advantage to flattening the CFG at the IR level:
2822 /// it makes very common but simplistic optimizations such as are common in
2823 /// instcombine and the DAG combiner more powerful by removing CFG edges and
2824 /// modeling their effects with easier to reason about SSA value graphs.
2825 ///
2826 ///
2827 /// An illustration of this transform is turning this IR:
2828 /// \code
2829 /// BB:
2830 /// %cmp = icmp ult %x, %y
2831 /// br i1 %cmp, label %EndBB, label %ThenBB
2832 /// ThenBB:
2833 /// %sub = sub %x, %y
2834 /// br label BB2
2835 /// EndBB:
2836 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
2837 /// ...
2838 /// \endcode
2839 ///
2840 /// Into this IR:
2841 /// \code
2842 /// BB:
2843 /// %cmp = icmp ult %x, %y
2844 /// %sub = sub %x, %y
2845 /// %cond = select i1 %cmp, 0, %sub
2846 /// ...
2847 /// \endcode
2848 ///
2849 /// \returns true if the conditional block is removed.
2850 bool SimplifyCFGOpt::SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
2851  const TargetTransformInfo &TTI) {
2852  // Be conservative for now. FP select instruction can often be expensive.
2853  Value *BrCond = BI->getCondition();
2854  if (isa<FCmpInst>(BrCond))
2855  return false;
2856 
2857  BasicBlock *BB = BI->getParent();
2858  BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
2859  InstructionCost Budget =
2860  PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
2861 
2862  // If ThenBB is actually on the false edge of the conditional branch, remember
2863  // to swap the select operands later.
2864  bool Invert = false;
2865  if (ThenBB != BI->getSuccessor(0)) {
2866  assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
2867  Invert = true;
2868  }
2869  assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
2870 
2871  // If the branch is non-unpredictable, and is predicted to *not* branch to
2872  // the `then` block, then avoid speculating it.
2873  if (!BI->getMetadata(LLVMContext::MD_unpredictable)) {
2874  uint64_t TWeight, FWeight;
2875  if (extractBranchWeights(*BI, TWeight, FWeight) &&
2876  (TWeight + FWeight) != 0) {
2877  uint64_t EndWeight = Invert ? TWeight : FWeight;
2878  BranchProbability BIEndProb =
2879  BranchProbability::getBranchProbability(EndWeight, TWeight + FWeight);
2881  if (BIEndProb >= Likely)
2882  return false;
2883  }
2884  }
2885 
2886  // Keep a count of how many times instructions are used within ThenBB when
2887  // they are candidates for sinking into ThenBB. Specifically:
2888  // - They are defined in BB, and
2889  // - They have no side effects, and
2890  // - All of their uses are in ThenBB.
2891  SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
2892 
2893  SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics;
2894 
2895  unsigned SpeculatedInstructions = 0;
2896  Value *SpeculatedStoreValue = nullptr;
2897  StoreInst *SpeculatedStore = nullptr;
2898  EphemeralValueTracker EphTracker;
2899  for (Instruction &I : reverse(drop_end(*ThenBB))) {
2900  // Skip debug info.
2901  if (isa<DbgInfoIntrinsic>(I)) {
2902  SpeculatedDbgIntrinsics.push_back(&I);
2903  continue;
2904  }
2905 
2906  // Skip pseudo probes. The consequence is we lose track of the branch
2907  // probability for ThenBB, which is fine since the optimization here takes
2908  // place regardless of the branch probability.
2909  if (isa<PseudoProbeInst>(I)) {
2910  // The probe should be deleted so that it will not be over-counted when
2911  // the samples collected on the non-conditional path are counted towards
2912  // the conditional path. We leave it for the counts inference algorithm to
2913  // figure out a proper count for an unknown probe.
2914  SpeculatedDbgIntrinsics.push_back(&I);
2915  continue;
2916  }
2917 
2918  // Ignore ephemeral values, they will be dropped by the transform.
2919  if (EphTracker.track(&I))
2920  continue;
2921 
2922  // Only speculatively execute a single instruction (not counting the
2923  // terminator) for now.
2924  ++SpeculatedInstructions;
2925  if (SpeculatedInstructions > 1)
2926  return false;
2927 
2928  // Don't hoist the instruction if it's unsafe or expensive.
2930  !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
2931  &I, BB, ThenBB, EndBB))))
2932  return false;
2933  if (!SpeculatedStoreValue &&
2935  PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
2936  return false;
2937 
2938  // Store the store speculation candidate.
2939  if (SpeculatedStoreValue)
2940  SpeculatedStore = cast<StoreInst>(&I);
2941 
2942  // Do not hoist the instruction if any of its operands are defined but not
2943  // used in BB. The transformation will prevent the operand from
2944  // being sunk into the use block.
2945  for (Use &Op : I.operands()) {
2946  Instruction *OpI = dyn_cast<Instruction>(Op);
2947  if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
2948  continue; // Not a candidate for sinking.
2949 
2950  ++SinkCandidateUseCounts[OpI];
2951  }
2952  }
2953 
2954  // Consider any sink candidates which are only used in ThenBB as costs for
2955  // speculation. Note, while we iterate over a DenseMap here, we are summing
2956  // and so iteration order isn't significant.
2957  for (const auto &[Inst, Count] : SinkCandidateUseCounts)
2958  if (Inst->hasNUses(Count)) {
2959  ++SpeculatedInstructions;
2960  if (SpeculatedInstructions > 1)
2961  return false;
2962  }
2963 
2964  // Check that we can insert the selects and that it's not too expensive to do
2965  // so.
2966  bool Convert = SpeculatedStore != nullptr;
2967  InstructionCost Cost = 0;
2968  Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB,
2969  SpeculatedInstructions,
2970  Cost, TTI);
2971  if (!Convert || Cost > Budget)
2972  return false;
2973 
2974  // If we get here, we can hoist the instruction and if-convert.
2975  LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
2976 
2977  // Insert a select of the value of the speculated store.
2978  if (SpeculatedStoreValue) {
2980  Value *OrigV = SpeculatedStore->getValueOperand();
2981  Value *TrueV = SpeculatedStore->getValueOperand();
2982  Value *FalseV = SpeculatedStoreValue;
2983  if (Invert)
2984  std::swap(TrueV, FalseV);
2985  Value *S = Builder.CreateSelect(
2986  BrCond, TrueV, FalseV, "spec.store.select", BI);
2987  SpeculatedStore->setOperand(0, S);
2988  SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
2989  SpeculatedStore->getDebugLoc());
2990  // The value stored is still conditional, but the store itself is now
2991  // unconditonally executed, so we must be sure that any linked dbg.assign
2992  // intrinsics are tracking the new stored value (the result of the
2993  // select). If we don't, and the store were to be removed by another pass
2994  // (e.g. DSE), then we'd eventually end up emitting a location describing
2995  // the conditional value, unconditionally.
2996  //
2997  // === Before this transformation ===
2998  // pred:
2999  // store %one, %x.dest, !DIAssignID !1
3000  // dbg.assign %one, "x", ..., !1, ...
3001  // br %cond if.then
3002  //
3003  // if.then:
3004  // store %two, %x.dest, !DIAssignID !2
3005  // dbg.assign %two, "x", ..., !2, ...
3006  //
3007  // === After this transformation ===
3008  // pred:
3009  // store %one, %x.dest, !DIAssignID !1
3010  // dbg.assign %one, "x", ..., !1
3011  /// ...
3012  // %merge = select %cond, %two, %one
3013  // store %merge, %x.dest, !DIAssignID !2
3014  // dbg.assign %merge, "x", ..., !2
3015  for (auto *DAI : at::getAssignmentMarkers(SpeculatedStore)) {
3016  if (any_of(DAI->location_ops(), [&](Value *V) { return V == OrigV; }))
3017  DAI->replaceVariableLocationOp(OrigV, S);
3018  }
3019  }
3020 
3021  // Metadata can be dependent on the condition we are hoisting above.
3022  // Conservatively strip all metadata on the instruction. Drop the debug loc
3023  // to avoid making it appear as if the condition is a constant, which would
3024  // be misleading while debugging.
3025  // Similarly strip attributes that maybe dependent on condition we are
3026  // hoisting above.
3027  for (auto &I : make_early_inc_range(*ThenBB)) {
3028  if (!SpeculatedStoreValue || &I != SpeculatedStore) {
3029  // Don't update the DILocation of dbg.assign intrinsics.
3030  if (!isa<DbgAssignIntrinsic>(&I))
3031  I.setDebugLoc(DebugLoc());
3032  }
3033  I.dropUndefImplyingAttrsAndUnknownMetadata();
3034 
3035  // Drop ephemeral values.
3036  if (EphTracker.contains(&I)) {
3037  I.replaceAllUsesWith(PoisonValue::get(I.getType()));
3038  I.eraseFromParent();
3039  }
3040  }
3041 
3042  // Hoist the instructions.
3043  BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
3044  ThenBB->begin(), std::prev(ThenBB->end()));
3045 
3046  // Insert selects and rewrite the PHI operands.
3048  for (PHINode &PN : EndBB->phis()) {
3049  unsigned OrigI = PN.getBasicBlockIndex(BB);
3050  unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
3051  Value *OrigV = PN.getIncomingValue(OrigI);
3052  Value *ThenV = PN.getIncomingValue(ThenI);
3053 
3054  // Skip PHIs which are trivial.
3055  if (OrigV == ThenV)
3056  continue;
3057 
3058  // Create a select whose true value is the speculatively executed value and
3059  // false value is the pre-existing value. Swap them if the branch
3060  // destinations were inverted.
3061  Value *TrueV = ThenV, *FalseV = OrigV;
3062  if (Invert)
3063  std::swap(TrueV, FalseV);
3064  Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV, "spec.select", BI);
3065  PN.setIncomingValue(OrigI, V);
3066  PN.setIncomingValue(ThenI, V);
3067  }
3068 
3069  // Remove speculated dbg intrinsics.
3070  // FIXME: Is it possible to do this in a more elegant way? Moving/merging the
3071  // dbg value for the different flows and inserting it after the select.
3072  for (Instruction *I : SpeculatedDbgIntrinsics) {
3073  // We still want to know that an assignment took place so don't remove
3074  // dbg.assign intrinsics.
3075  if (!isa<DbgAssignIntrinsic>(I))
3076  I->eraseFromParent();
3077  }
3078 
3079  ++NumSpeculations;
3080  return true;
3081 }
3082 
3083 /// Return true if we can thread a branch across this block.
3085  int Size = 0;
3086  EphemeralValueTracker EphTracker;
3087 
3088  // Walk the loop in reverse so that we can identify ephemeral values properly
3089  // (values only feeding assumes).
3090  for (Instruction &I : reverse(BB->instructionsWithoutDebug(false))) {
3091  // Can't fold blocks that contain noduplicate or convergent calls.
3092  if (CallInst *CI = dyn_cast<CallInst>(&I))
3093  if (CI->cannotDuplicate() || CI->isConvergent())
3094  return false;
3095 
3096  // Ignore ephemeral values which are deleted during codegen.
3097  // We will delete Phis while threading, so Phis should not be accounted in
3098  // block's size.
3099  if (!EphTracker.track(&I) && !isa<PHINode>(I)) {
3100  if (Size++ > MaxSmallBlockSize)
3101  return false; // Don't clone large BB's.
3102  }
3103 
3104  // We can only support instructions that do not define values that are
3105  // live outside of the current basic block.
3106  for (User *U : I.users()) {
3107  Instruction *UI = cast<Instruction>(U);
3108  if (UI->getParent() != BB || isa<PHINode>(UI))
3109  return false;
3110  }
3111 
3112  // Looks ok, continue checking.
3113  }
3114 
3115  return true;
3116 }
3117 
3119  BasicBlock *To) {
3120  // Don't look past the block defining the value, we might get the value from
3121  // a previous loop iteration.
3122  auto *I = dyn_cast<Instruction>(V);
3123  if (I && I->getParent() == To)
3124  return nullptr;
3125 
3126  // We know the value if the From block branches on it.
3127  auto *BI = dyn_cast<BranchInst>(From->getTerminator());
3128  if (BI && BI->isConditional() && BI->getCondition() == V &&
3129  BI->getSuccessor(0) != BI->getSuccessor(1))
3130  return BI->getSuccessor(0) == To ? ConstantInt::getTrue(BI->getContext())
3132 
3133  return nullptr;
3134 }
3135 
3136 /// If we have a conditional branch on something for which we know the constant
3137 /// value in predecessors (e.g. a phi node in the current block), thread edges
3138 /// from the predecessor to their ultimate destination.
3139 static Optional<bool>
3141  const DataLayout &DL,
3142  AssumptionCache *AC) {
3144  BasicBlock *BB = BI->getParent();
3145  Value *Cond = BI->getCondition();
3146  PHINode *PN = dyn_cast<PHINode>(Cond);
3147  if (PN && PN->getParent() == BB) {
3148  // Degenerate case of a single entry PHI.
3149  if (PN->getNumIncomingValues() == 1) {
3151  return true;
3152  }
3153 
3154  for (Use &U : PN->incoming_values())
3155  if (auto *CB = dyn_cast<ConstantInt>(U))
3156  KnownValues[CB].insert(PN->getIncomingBlock(U));
3157  } else {
3158  for (BasicBlock *Pred : predecessors(BB)) {
3159  if (ConstantInt *CB = getKnownValueOnEdge(Cond, Pred, BB))
3160  KnownValues[CB].insert(Pred);
3161  }
3162  }
3163 
3164  if (KnownValues.empty())
3165  return false;
3166 
3167  // Now we know that this block has multiple preds and two succs.
3168  // Check that the block is small enough and values defined in the block are
3169  // not used outside of it.
3171  return false;
3172 
3173  for (const auto &Pair : KnownValues) {
3174  // Okay, we now know that all edges from PredBB should be revectored to
3175  // branch to RealDest.
3176  ConstantInt *CB = Pair.first;
3177  ArrayRef<BasicBlock *> PredBBs = Pair.second.getArrayRef();
3178  BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
3179 
3180  if (RealDest == BB)
3181  continue; // Skip self loops.
3182 
3183  // Skip if the predecessor's terminator is an indirect branch.
3184  if (any_of(PredBBs, [](BasicBlock *PredBB) {
3185  return isa<IndirectBrInst>(PredBB->getTerminator());
3186  }))
3187  continue;
3188 
3189  LLVM_DEBUG({
3190  dbgs() << "Condition " << *Cond << " in " << BB->getName()
3191  << " has value " << *Pair.first << " in predecessors:\n";
3192  for (const BasicBlock *PredBB : Pair.second)
3193  dbgs() << " " << PredBB->getName() << "\n";
3194  dbgs() << "Threading to destination " << RealDest->getName() << ".\n";
3195  });
3196 
3197  // Split the predecessors we are threading into a new edge block. We'll
3198  // clone the instructions into this block, and then redirect it to RealDest.
3199  BasicBlock *EdgeBB = SplitBlockPredecessors(BB, PredBBs, ".critedge", DTU);
3200 
3201  // TODO: These just exist to reduce test diff, we can drop them if we like.
3202  EdgeBB->setName(RealDest->getName() + ".critedge");
3203  EdgeBB->moveBefore(RealDest);
3204 
3205  // Update PHI nodes.
3206  AddPredecessorToBlock(RealDest, EdgeBB, BB);
3207 
3208  // BB may have instructions that are being threaded over. Clone these
3209  // instructions into EdgeBB. We know that there will be no uses of the
3210  // cloned instructions outside of EdgeBB.
3211  BasicBlock::iterator InsertPt = EdgeBB->getFirstInsertionPt();
3212  DenseMap<Value *, Value *> TranslateMap; // Track translated values.
3213  TranslateMap[Cond] = CB;
3214  for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
3215  if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
3216  TranslateMap[PN] = PN->getIncomingValueForBlock(EdgeBB);
3217  continue;
3218  }
3219  // Clone the instruction.
3220  Instruction *N = BBI->clone();
3221  if (BBI->hasName())
3222  N->setName(BBI->getName() + ".c");
3223 
3224  // Update operands due to translation.
3225  for (Use &Op : N->operands()) {
3226  DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(Op);
3227  if (PI != TranslateMap.end())
3228  Op = PI->second;
3229  }
3230 
3231  // Check for trivial simplification.
3232  if (Value *V = simplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
3233  if (!BBI->use_empty())
3234  TranslateMap[&*BBI] = V;
3235  if (!N->mayHaveSideEffects()) {
3236  N->deleteValue(); // Instruction folded away, don't need actual inst
3237  N = nullptr;
3238  }
3239  } else {
3240  if (!BBI->use_empty())
3241  TranslateMap[&*BBI] = N;
3242  }
3243  if (N) {
3244  // Insert the new instruction into its new home.
3245  EdgeBB->getInstList().insert(InsertPt, N);
3246 
3247  // Register the new instruction with the assumption cache if necessary.
3248  if (auto *Assume = dyn_cast<AssumeInst>(N))
3249  if (AC)
3250  AC->registerAssumption(Assume);
3251  }
3252  }
3253 
3254  BB->removePredecessor(EdgeBB);
3255  BranchInst *EdgeBI = cast<BranchInst>(EdgeBB->getTerminator());
3256  EdgeBI->setSuccessor(0, RealDest);
3257  EdgeBI->setDebugLoc(BI->getDebugLoc());
3258 
3259  if (DTU) {
3261  Updates.push_back({DominatorTree::Delete, EdgeBB, BB});
3262  Updates.push_back({DominatorTree::Insert, EdgeBB, RealDest});
3263  DTU->applyUpdates(Updates);
3264  }
3265 
3266  // For simplicity, we created a separate basic block for the edge. Merge
3267  // it back into the predecessor if possible. This not only avoids
3268  // unnecessary SimplifyCFG iterations, but also makes sure that we don't
3269  // bypass the check for trivial cycles above.
3270  MergeBlockIntoPredecessor(EdgeBB, DTU);
3271 
3272  // Signal repeat, simplifying any other constants.
3273  return None;
3274  }
3275 
3276  return false;
3277 }
3278 
3280  DomTreeUpdater *DTU,
3281  const DataLayout &DL,
3282  AssumptionCache *AC) {
3283  Optional<bool> Result;
3284  bool EverChanged = false;
3285  do {
3286  // Note that None means "we changed things, but recurse further."
3287  Result = FoldCondBranchOnValueKnownInPredecessorImpl(BI, DTU, DL, AC);
3288  EverChanged |= Result == None || *Result;
3289  } while (Result == None);
3290  return EverChanged;
3291 }
3292 
3293 /// Given a BB that starts with the specified two-entry PHI node,
3294 /// see if we can eliminate it.
3296  DomTreeUpdater *DTU, const DataLayout &DL) {
3297  // Ok, this is a two entry PHI node. Check to see if this is a simple "if
3298  // statement", which has a very simple dominance structure. Basically, we
3299  // are trying to find the condition that is being branched on, which
3300  // subsequently causes this merge to happen. We really want control
3301  // dependence information for this check, but simplifycfg can't keep it up
3302  // to date, and this catches most of the cases we care about anyway.
3303  BasicBlock *BB = PN->getParent();
3304 
3305  BasicBlock *IfTrue, *IfFalse;
3306  BranchInst *DomBI = GetIfCondition(BB, IfTrue, IfFalse);
3307  if (!DomBI)
3308  return false;
3309  Value *IfCond = DomBI->getCondition();
3310  // Don't bother if the branch will be constant folded trivially.
3311  if (isa<ConstantInt>(IfCond))
3312  return false;
3313 
3314  BasicBlock *DomBlock = DomBI->getParent();
3316  llvm::copy_if(
3317  PN->blocks(), std::back_inserter(IfBlocks), [](BasicBlock *IfBlock) {
3318  return cast<BranchInst>(IfBlock->getTerminator())->isUnconditional();
3319  });
3320  assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) &&
3321  "Will have either one or two blocks to speculate.");
3322 
3323  // If the branch is non-unpredictable, see if we either predictably jump to
3324  // the merge bb (if we have only a single 'then' block), or if we predictably
3325  // jump to one specific 'then' block (if we have two of them).
3326  // It isn't beneficial to speculatively execute the code
3327  // from the block that we know is predictably not entered.
3328  if (!DomBI->getMetadata(LLVMContext::MD_unpredictable)) {
3329  uint64_t TWeight, FWeight;
3330  if (extractBranchWeights(*DomBI, TWeight, FWeight) &&
3331  (TWeight + FWeight) != 0) {
3332  BranchProbability BITrueProb =
3333  BranchProbability::getBranchProbability(TWeight, TWeight + FWeight);
3335  BranchProbability BIFalseProb = BITrueProb.getCompl();
3336  if (IfBlocks.size() == 1) {
3337  BranchProbability BIBBProb =
3338  DomBI->getSuccessor(0) == BB ? BITrueProb : BIFalseProb;
3339  if (BIBBProb >= Likely)
3340  return false;
3341  } else {
3342  if (BITrueProb >= Likely || BIFalseProb >= Likely)
3343  return false;
3344  }
3345  }
3346  }
3347 
3348  // Don't try to fold an unreachable block. For example, the phi node itself
3349  // can't be the candidate if-condition for a select that we want to form.
3350  if (auto *IfCondPhiInst = dyn_cast<PHINode>(IfCond))
3351  if (IfCondPhiInst->getParent() == BB)
3352  return false;
3353 
3354  // Okay, we found that we can merge this two-entry phi node into a select.
3355  // Doing so would require us to fold *all* two entry phi nodes in this block.
3356  // At some point this becomes non-profitable (particularly if the target
3357  // doesn't support cmov's). Only do this transformation if there are two or
3358  // fewer PHI nodes in this block.
3359  unsigned NumPhis = 0;
3360  for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
3361  if (NumPhis > 2)
3362  return false;
3363 
3364  // Loop over the PHI's seeing if we can promote them all to select
3365  // instructions. While we are at it, keep track of the instructions
3366  // that need to be moved to the dominating block.
3367  SmallPtrSet<Instruction *, 4> AggressiveInsts;
3368  InstructionCost Cost = 0;
3369  InstructionCost Budget =
3370  TwoEntryPHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
3371 
3372  bool Changed = false;
3373  for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
3374  PHINode *PN = cast<PHINode>(II++);
3375  if (Value *V = simplifyInstruction(PN, {DL, PN})) {
3376  PN->replaceAllUsesWith(V);
3377  PN->eraseFromParent();
3378  Changed = true;
3379  continue;
3380  }
3381 
3382  if (!dominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts,
3383  Cost, Budget, TTI) ||
3384  !dominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts,
3385  Cost, Budget, TTI))
3386  return Changed;
3387  }
3388 
3389  // If we folded the first phi, PN dangles at this point. Refresh it. If
3390  // we ran out of PHIs then we simplified them all.
3391  PN = dyn_cast<PHINode>(BB->begin());
3392  if (!PN)
3393  return true;
3394 
3395  // Return true if at least one of these is a 'not', and another is either
3396  // a 'not' too, or a constant.
3397  auto CanHoistNotFromBothValues = [](Value *V0, Value *V1) {
3398  if (!match(V0, m_Not(m_Value())))
3399  std::swap(V0, V1);
3400  auto Invertible = m_CombineOr(m_Not(m_Value()), m_AnyIntegralConstant());
3401  return match(V0, m_Not(m_Value())) && match(V1, Invertible);
3402  };
3403 
3404  // Don't fold i1 branches on PHIs which contain binary operators or
3405  // (possibly inverted) select form of or/ands, unless one of
3406  // the incoming values is an 'not' and another one is freely invertible.
3407  // These can often be turned into switches and other things.
3408  auto IsBinOpOrAnd = [](Value *V) {
3409  return match(
3410  V, m_CombineOr(
3411  m_BinOp(),
3413  m_Select(m_Value(), m_Value(), m_ImmConstant()))));
3414  };
3415  if (PN->getType()->isIntegerTy(1) &&
3416  (IsBinOpOrAnd(PN->getIncomingValue(0)) ||
3417  IsBinOpOrAnd(PN->getIncomingValue(1)) || IsBinOpOrAnd(IfCond)) &&
3418  !CanHoistNotFromBothValues(PN->getIncomingValue(0),
3419  PN->getIncomingValue(1)))
3420  return Changed;
3421 
3422  // If all PHI nodes are promotable, check to make sure that all instructions
3423  // in the predecessor blocks can be promoted as well. If not, we won't be able
3424  // to get rid of the control flow, so it's not worth promoting to select
3425  // instructions.
3426  for (BasicBlock *IfBlock : IfBlocks)
3427  for (BasicBlock::iterator I = IfBlock->begin(); !I->isTerminator(); ++I)
3428  if (!AggressiveInsts.count(&*I) && !I->isDebugOrPseudoInst()) {
3429  // This is not an aggressive instruction that we can promote.
3430  // Because of this, we won't be able to get rid of the control flow, so
3431  // the xform is not worth it.
3432  return Changed;
3433  }
3434 
3435  // If either of the blocks has it's address taken, we can't do this fold.
3436  if (any_of(IfBlocks,
3437  [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); }))
3438  return Changed;
3439 
3440  LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond
3441  << " T: " << IfTrue->getName()
3442  << " F: " << IfFalse->getName() << "\n");
3443 
3444  // If we can still promote the PHI nodes after this gauntlet of tests,
3445  // do all of the PHI's now.
3446 
3447  // Move all 'aggressive' instructions, which are defined in the
3448  // conditional parts of the if's up to the dominating block.
3449  for (BasicBlock *IfBlock : IfBlocks)
3450  hoistAllInstructionsInto(DomBlock, DomBI, IfBlock);
3451 
3453  // Propagate fast-math-flags from phi nodes to replacement selects.
3455  while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
3456  if (isa<FPMathOperator>(PN))
3457  Builder.setFastMathFlags(PN->getFastMathFlags());
3458 
3459  // Change the PHI node into a select instruction.
3460  Value *TrueVal = PN->getIncomingValueForBlock(IfTrue);
3461  Value *FalseVal = PN->getIncomingValueForBlock(IfFalse);
3462 
3463  Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", DomBI);
3464  PN->replaceAllUsesWith(Sel);
3465  Sel->takeName(PN);
3466  PN->eraseFromParent();
3467  }
3468 
3469  // At this point, all IfBlocks are empty, so our if statement
3470  // has been flattened. Change DomBlock to jump directly to our new block to
3471  // avoid other simplifycfg's kicking in on the diamond.
3472  Builder.CreateBr(BB);
3473 
3475  if (DTU) {
3476  Updates.push_back({DominatorTree::Insert, DomBlock, BB});
3477  for (auto *Successor : successors(DomBlock))
3478  Updates.push_back({DominatorTree::Delete, DomBlock, Successor});
3479  }
3480 
3481  DomBI->eraseFromParent();
3482  if (DTU)
3483  DTU->applyUpdates(Updates);
3484 
3485  return true;
3486 }
3487 
3490  Value *RHS, const Twine &Name = "") {
3491  // Try to relax logical op to binary op.
3492  if (impliesPoison(RHS, LHS))
3493  return Builder.CreateBinOp(Opc, LHS, RHS, Name);
3494  if (Opc == Instruction::And)
3495  return Builder.CreateLogicalAnd(LHS, RHS, Name);
3496  if (Opc == Instruction::Or)
3497  return Builder.CreateLogicalOr(LHS, RHS, Name);
3498  llvm_unreachable("Invalid logical opcode");
3499 }
3500 
3501 /// Return true if either PBI or BI has branch weight available, and store
3502 /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
3503 /// not have branch weight, use 1:1 as its weight.
3505  uint64_t &PredTrueWeight,
3506  uint64_t &PredFalseWeight,
3507  uint64_t &SuccTrueWeight,
3508  uint64_t &SuccFalseWeight) {
3509  bool PredHasWeights =
3510  extractBranchWeights(*PBI, PredTrueWeight, PredFalseWeight);
3511  bool SuccHasWeights =
3512  extractBranchWeights(*BI, SuccTrueWeight, SuccFalseWeight);
3513  if (PredHasWeights || SuccHasWeights) {
3514  if (!PredHasWeights)
3515  PredTrueWeight = PredFalseWeight = 1;
3516  if (!SuccHasWeights)
3517  SuccTrueWeight = SuccFalseWeight = 1;
3518  return true;
3519  } else {
3520  return false;
3521  }
3522 }
3523 
3524 /// Determine if the two branches share a common destination and deduce a glue
3525 /// that joins the branches' conditions to arrive at the common destination if
3526 /// that would be profitable.
3527 static std::optional<std::pair<Instruction::BinaryOps, bool>>
3529  const TargetTransformInfo *TTI) {
3530  assert(BI && PBI && BI->isConditional() && PBI->isConditional() &&
3531  "Both blocks must end with a conditional branches.");
3533  "PredBB must be a predecessor of BB.");
3534 
3535  // We have the potential to fold the conditions together, but if the
3536  // predecessor branch is predictable, we may not want to merge them.
3537  uint64_t PTWeight, PFWeight;
3538  BranchProbability PBITrueProb, Likely;
3539  if (TTI && !PBI->getMetadata(LLVMContext::MD_unpredictable) &&
3540  extractBranchWeights(*PBI, PTWeight, PFWeight) &&
3541  (PTWeight + PFWeight) != 0) {
3542  PBITrueProb =
3543  BranchProbability::getBranchProbability(PTWeight, PTWeight + PFWeight);
3544  Likely = TTI->getPredictableBranchThreshold();
3545  }
3546 
3547  if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3548  // Speculate the 2nd condition unless the 1st is probably true.
3549  if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
3550  return {{Instruction::Or, false}};
3551  } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3552  // Speculate the 2nd condition unless the 1st is probably false.
3553  if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
3554  return {{Instruction::And, false}};
3555  } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3556  // Speculate the 2nd condition unless the 1st is probably true.
3557  if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
3558  return {{Instruction::And, true}};
3559  } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3560  // Speculate the 2nd condition unless the 1st is probably false.
3561  if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
3562  return {{Instruction::Or, true}};
3563  }
3564  return None;
3565 }
3566 
3568  DomTreeUpdater *DTU,
3569  MemorySSAUpdater *MSSAU,
3570  const TargetTransformInfo *TTI) {
3571  BasicBlock *BB = BI->getParent();
3572  BasicBlock *PredBlock = PBI->getParent();
3573 
3574  // Determine if the two branches share a common destination.
3576  bool InvertPredCond;
3577  std::tie(Opc, InvertPredCond) =
3579 
3580  LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
3581 
3582  IRBuilder<> Builder(PBI);
3583  // The builder is used to create instructions to eliminate the branch in BB.
3584  // If BB's terminator has !annotation metadata, add it to the new
3585  // instructions.
3586  Builder.CollectMetadataToCopy(BB->getTerminator(),
3587  {LLVMContext::MD_annotation});
3588 
3589  // If we need to invert the condition in the pred block to match, do so now.
3590  if (InvertPredCond) {
3591  Value *NewCond = PBI->getCondition();
3592  if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
3593  CmpInst *CI = cast<CmpInst>(NewCond);
3594  CI->setPredicate(CI->getInversePredicate());
3595  } else {
3596  NewCond =
3597  Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
3598  }
3599 
3600  PBI->setCondition(NewCond);
3601  PBI->swapSuccessors();
3602  }
3603 
3604  BasicBlock *UniqueSucc =
3605  PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1);
3606 
3607  // Before cloning instructions, notify the successor basic block that it
3608  // is about to have a new predecessor. This will update PHI nodes,
3609  // which will allow us to update live-out uses of bonus instructions.
3610  AddPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU);
3611 
3612  // Try to update branch weights.
3613  uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3614  if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3615  SuccTrueWeight, SuccFalseWeight)) {
3616  SmallVector<uint64_t, 8> NewWeights;
3617 
3618  if (PBI->getSuccessor(0) == BB) {
3619  // PBI: br i1 %x, BB, FalseDest
3620  // BI: br i1 %y, UniqueSucc, FalseDest
3621  // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
3622  NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
3623  // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
3624  // TrueWeight for PBI * FalseWeight for BI.
3625  // We assume that total weights of a BranchInst can fit into 32 bits.
3626  // Therefore, we will not have overflow using 64-bit arithmetic.
3627  NewWeights.push_back(PredFalseWeight *
3628  (SuccFalseWeight + SuccTrueWeight) +
3629  PredTrueWeight * SuccFalseWeight);
3630  } else {
3631  // PBI: br i1 %x, TrueDest, BB
3632  // BI: br i1 %y, TrueDest, UniqueSucc
3633  // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
3634  // FalseWeight for PBI * TrueWeight for BI.
3635  NewWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) +
3636  PredFalseWeight * SuccTrueWeight);
3637  // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
3638  NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
3639  }
3640 
3641  // Halve the weights if any of them cannot fit in an uint32_t
3642  FitWeights(NewWeights);
3643 
3644  SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), NewWeights.end());
3645  setBranchWeights(PBI, MDWeights[0], MDWeights[1]);
3646 
3647  // TODO: If BB is reachable from all paths through PredBlock, then we
3648  // could replace PBI's branch probabilities with BI's.
3649  } else
3650  PBI->setMetadata(LLVMContext::MD_prof, nullptr);
3651 
3652  // Now, update the CFG.
3653  PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc);
3654 
3655  if (DTU)
3656  DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc},
3657  {DominatorTree::Delete, PredBlock, BB}});
3658 
3659  // If BI was a loop latch, it may have had associated loop metadata.
3660  // We need to copy it to the new latch, that is, PBI.
3661  if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
3662  PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
3663 
3664  ValueToValueMapTy VMap; // maps original values to cloned values
3666 
3667  // Now that the Cond was cloned into the predecessor basic block,
3668  // or/and the two conditions together.
3669  Value *BICond = VMap[BI->getCondition()];
3670  PBI->setCondition(
3671  createLogicalOp(Builder, Opc, PBI->getCondition(), BICond, "or.cond"));
3672 
3673  // Copy any debug value intrinsics into the end of PredBlock.
3674  for (Instruction &I : *BB) {
3675  if (isa<DbgInfoIntrinsic>(I)) {
3676  Instruction *NewI = I.clone();
3677  RemapInstruction(NewI, VMap,
3679  NewI->insertBefore(PBI);
3680  }
3681  }
3682 
3683  ++NumFoldBranchToCommonDest;
3684  return true;
3685 }
3686 
3687 /// Return if an instruction's type or any of its operands' types are a vector
3688 /// type.
3689 static bool isVectorOp(Instruction &I) {
3690  return I.getType()->isVectorTy() || any_of(I.operands(), [](Use &U) {
3691  return U->getType()->isVectorTy();
3692  });
3693 }
3694 
3695 /// If this basic block is simple enough, and if a predecessor branches to us
3696 /// and one of our successors, fold the block into the predecessor and use
3697 /// logical operations to pick the right destination.
3699  MemorySSAUpdater *MSSAU,
3700  const TargetTransformInfo *TTI,
3701  unsigned BonusInstThreshold) {
3702  // If this block ends with an unconditional branch,
3703  // let SpeculativelyExecuteBB() deal with it.
3704  if (!BI->isConditional())
3705  return false;
3706 
3707  BasicBlock *BB = BI->getParent();
3709  BB->getParent()->hasMinSize() ? TargetTransformInfo::TCK_CodeSize
3710  : TargetTransformInfo::TCK_SizeAndLatency;
3711 
3712  Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
3713 
3714  if (!Cond ||
3715  (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond) &&
3716  !isa<SelectInst>(Cond)) ||
3717  Cond->getParent() != BB || !Cond->hasOneUse())
3718  return false;
3719 
3720  // Finally, don't infinitely unroll conditional loops.
3721  if (is_contained(successors(BB), BB))
3722  return false;
3723 
3724  // With which predecessors will we want to deal with?
3726  for (BasicBlock *PredBlock : predecessors(BB)) {
3727  BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
3728 
3729  // Check that we have two conditional branches. If there is a PHI node in
3730  // the common successor, verify that the same value flows in from both
3731  // blocks.
3732  if (!PBI || PBI->isUnconditional() || !SafeToMergeTerminators(BI, PBI))
3733  continue;
3734 
3735  // Determine if the two branches share a common destination.
3737  bool InvertPredCond;
3738  if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI))
3739  std::tie(Opc, InvertPredCond) = *Recipe;
3740  else
3741  continue;
3742 
3743  // Check the cost of inserting the necessary logic before performing the
3744  // transformation.
3745  if (TTI) {
3746  Type *Ty = BI->getCondition()->getType();
3748  if (InvertPredCond && (!PBI->getCondition()->hasOneUse() ||
3749  !isa<CmpInst>(PBI->getCondition())))
3750  Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind);
3751 
3752  if (Cost > BranchFoldThreshold)
3753  continue;
3754  }
3755 
3756  // Ok, we do want to deal with this predecessor. Record it.
3757  Preds.emplace_back(PredBlock);
3758  }
3759 
3760  // If there aren't any predecessors into which we can fold,
3761  // don't bother checking the cost.
3762  if (Preds.empty())
3763  return false;
3764 
3765  // Only allow this transformation if computing the condition doesn't involve
3766  // too many instructions and these involved instructions can be executed
3767  // unconditionally. We denote all involved instructions except the condition
3768  // as "bonus instructions", and only allow this transformation when the
3769  // number of the bonus instructions we'll need to create when cloning into
3770  // each predecessor does not exceed a certain threshold.
3771  unsigned NumBonusInsts = 0;
3772  bool SawVectorOp = false;
3773  const unsigned PredCount = Preds.size();
3774  for (Instruction &I : *BB) {
3775  // Don't check the branch condition comparison itself.
3776  if (&I == Cond)
3777  continue;
3778  // Ignore dbg intrinsics, and the terminator.
3779  if (isa<DbgInfoIntrinsic>(I) || isa<BranchInst>(I))
3780  continue;
3781  // I must be safe to execute unconditionally.
3783  return false;
3784  SawVectorOp |= isVectorOp(I);
3785 
3786  // Account for the cost of duplicating this instruction into each
3787  // predecessor. Ignore free instructions.
3788  if (!TTI || TTI->getInstructionCost(&I, CostKind) !=
3789  TargetTransformInfo::TCC_Free) {
3790  NumBonusInsts += PredCount;
3791 
3792  // Early exits once we reach the limit.
3793  if (NumBonusInsts >
3794  BonusInstThreshold * BranchFoldToCommonDestVectorMultiplier)
3795  return false;
3796  }
3797 
3798  auto IsBCSSAUse = [BB, &I](Use &U) {
3799  auto *UI = cast<Instruction>(U.getUser());
3800  if (auto *PN = dyn_cast<PHINode>(UI))
3801  return PN->getIncomingBlock(U) == BB;
3802  return UI->getParent() == BB && I.comesBefore(UI);
3803  };
3804 
3805  // Does this instruction require rewriting of uses?
3806  if (!all_of(I.uses(), IsBCSSAUse))
3807  return false;
3808  }
3809  if (NumBonusInsts >
3810  BonusInstThreshold *
3811  (SawVectorOp ? BranchFoldToCommonDestVectorMultiplier : 1))
3812  return false;
3813 
3814  // Ok, we have the budget. Perform the transformation.
3815  for (BasicBlock *PredBlock : Preds) {
3816  auto *PBI = cast<BranchInst>(PredBlock->getTerminator());
3817  return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI);
3818  }
3819  return false;
3820 }
3821 
3822 // If there is only one store in BB1 and BB2, return it, otherwise return
3823 // nullptr.
3825  StoreInst *S = nullptr;
3826  for (auto *BB : {BB1, BB2}) {
3827  if (!BB)
3828  continue;
3829  for (auto &I : *BB)
3830  if (auto *SI = dyn_cast<StoreInst>(&I)) {
3831  if (S)
3832  // Multiple stores seen.
3833  return nullptr;
3834  else
3835  S = SI;
3836  }
3837  }
3838  return S;
3839 }
3840 
3842  Value *AlternativeV = nullptr) {
3843  // PHI is going to be a PHI node that allows the value V that is defined in
3844  // BB to be referenced in BB's only successor.
3845  //
3846  // If AlternativeV is nullptr, the only value we care about in PHI is V. It
3847  // doesn't matter to us what the other operand is (it'll never get used). We
3848  // could just create a new PHI with an undef incoming value, but that could
3849  // increase register pressure if EarlyCSE/InstCombine can't fold it with some
3850  // other PHI. So here we directly look for some PHI in BB's successor with V
3851  // as an incoming operand. If we find one, we use it, else we create a new
3852  // one.
3853  //
3854  // If AlternativeV is not nullptr, we care about both incoming values in PHI.
3855  // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
3856  // where OtherBB is the single other predecessor of BB's only successor.
3857  PHINode *PHI = nullptr;
3858  BasicBlock *Succ = BB->getSingleSuccessor();
3859 
3860  for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
3861  if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
3862  PHI = cast<PHINode>(I);
3863  if (!AlternativeV)
3864  break;
3865 
3866  assert(Succ->hasNPredecessors(2));
3867  auto PredI = pred_begin(Succ);
3868  BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
3869  if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
3870  break;
3871  PHI = nullptr;
3872  }
3873  if (PHI)
3874  return PHI;
3875 
3876  // If V is not an instruction defined in BB, just return it.
3877  if (!AlternativeV &&
3878  (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
3879  return V;
3880 
3881  PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
3882  PHI->addIncoming(V, BB);
3883  for (BasicBlock *PredBB : predecessors(Succ))
3884  if (PredBB != BB)
3885  PHI->addIncoming(
3886  AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
3887  return PHI;
3888 }
3889 
3891  BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB,
3892  BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond,
3893  DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) {
3894  // For every pointer, there must be exactly two stores, one coming from
3895  // PTB or PFB, and the other from QTB or QFB. We don't support more than one
3896  // store (to any address) in PTB,PFB or QTB,QFB.
3897  // FIXME: We could relax this restriction with a bit more work and performance
3898  // testing.
3899  StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
3900  StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
3901  if (!PStore || !QStore)
3902  return false;
3903 
3904  // Now check the stores are compatible.
3905  if (!QStore->isUnordered() || !PStore->isUnordered() ||
3906  PStore->getValueOperand()->getType() !=
3907  QStore->getValueOperand()->getType())
3908  return false;
3909 
3910  // Check that sinking the store won't cause program behavior changes. Sinking
3911  // the store out of the Q blocks won't change any behavior as we're sinking
3912  // from a block to its unconditional successor. But we're moving a store from
3913  // the P blocks down through the middle block (QBI) and past both QFB and QTB.
3914  // So we need to check that there are no aliasing loads or stores in
3915  // QBI, QTB and QFB. We also need to check there are no conflicting memory
3916  // operations between PStore and the end of its parent block.
3917  //
3918  // The ideal way to do this is to query AliasAnalysis, but we don't
3919  // preserve AA currently so that is dangerous. Be super safe and just
3920  // check there are no other memory operations at all.
3921  for (auto &I : *QFB->getSinglePredecessor())
3922  if (I.mayReadOrWriteMemory())
3923  return false;
3924  for (auto &I : *QFB)
3925  if (&I != QStore && I.mayReadOrWriteMemory())
3926  return false;
3927  if (QTB)
3928  for (auto &I : *QTB)
3929  if (&I != QStore && I.mayReadOrWriteMemory())
3930  return false;
3931  for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
3932  I != E; ++I)
3933  if (&*I != PStore && I->mayReadOrWriteMemory())
3934  return false;
3935 
3936  // If we're not in aggressive mode, we only optimize if we have some
3937  // confidence that by optimizing we'll allow P and/or Q to be if-converted.
3938  auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
3939  if (!BB)
3940  return true;
3941  // Heuristic: if the block can be if-converted/phi-folded and the
3942  // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
3943  // thread this store.
3944  InstructionCost Cost = 0;
3945  InstructionCost Budget =
3946  PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
3947  for (auto &I : BB->instructionsWithoutDebug(false)) {
3948  // Consider terminator instruction to be free.
3949  if (I.isTerminator())
3950  continue;
3951  // If this is one the stores that we want to speculate out of this BB,
3952  // then don't count it's cost, consider it to be free.
3953  if (auto *S = dyn_cast<StoreInst>(&I))
3954  if (llvm::find(FreeStores, S))
3955  continue;
3956  // Else, we have a white-list of instructions that we are ak speculating.
3957  if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I))
3958  return false; // Not in white-list - not worthwhile folding.
3959  // And finally, if this is a non-free instruction that we are okay
3960  // speculating, ensure that we consider the speculation budget.
3961  Cost +=
3962  TTI.getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
3963  if (Cost > Budget)
3964  return false; // Eagerly refuse to fold as soon as we're out of budget.
3965  }
3966  assert(Cost <= Budget &&
3967  "When we run out of budget we will eagerly return from within the "
3968  "per-instruction loop.");
3969  return true;
3970  };
3971 
3972  const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
3974  (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
3975  !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
3976  return false;
3977 
3978  // If PostBB has more than two predecessors, we need to split it so we can
3979  // sink the store.
3980  if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
3981  // We know that QFB's only successor is PostBB. And QFB has a single
3982  // predecessor. If QTB exists, then its only successor is also PostBB.
3983  // If QTB does not exist, then QFB's only predecessor has a conditional
3984  // branch to QFB and PostBB.
3985  BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
3986  BasicBlock *NewBB =
3987  SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU);
3988  if (!NewBB)
3989  return false;
3990  PostBB = NewBB;
3991  }
3992 
3993  // OK, we're going to sink the stores to PostBB. The store has to be
3994  // conditional though, so first create the predicate.
3995  Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
3996  ->getCondition();
3997  Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
3998  ->getCondition();
3999 
4001  PStore->getParent());
4003  QStore->getParent(), PPHI);
4004 
4005  IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
4006 
4007  Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
4008  Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
4009 
4010  if (InvertPCond)
4011  PPred = QB.CreateNot(PPred);
4012  if (InvertQCond)
4013  QPred = QB.CreateNot(QPred);
4014  Value *CombinedPred = QB.CreateOr(PPred, QPred);
4015 
4016  auto *T = SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(),
4017  /*Unreachable=*/false,
4018  /*BranchWeights=*/nullptr, DTU);
4019  QB.SetInsertPoint(T);
4020  StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
4021  SI->setAAMetadata(PStore->getAAMetadata().merge(QStore->getAAMetadata()));
4022  // Choose the minimum alignment. If we could prove both stores execute, we
4023  // could use biggest one. In this case, though, we only know that one of the
4024  // stores executes. And we don't know it's safe to take the alignment from a
4025  // store that doesn't execute.
4026  SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign()));
4027 
4028  QStore->eraseFromParent();
4029  PStore->eraseFromParent();
4030 
4031  return true;
4032 }
4033 
4035  DomTreeUpdater *DTU, const DataLayout &DL,
4036  const TargetTransformInfo &TTI) {
4037  // The intention here is to find diamonds or triangles (see below) where each
4038  // conditional block contains a store to the same address. Both of these
4039  // stores are conditional, so they can't be unconditionally sunk. But it may
4040  // be profitable to speculatively sink the stores into one merged store at the
4041  // end, and predicate the merged store on the union of the two conditions of
4042  // PBI and QBI.
4043  //
4044  // This can reduce the number of stores executed if both of the conditions are
4045  // true, and can allow the blocks to become small enough to be if-converted.
4046  // This optimization will also chain, so that ladders of test-and-set
4047  // sequences can be if-converted away.
4048  //
4049  // We only deal with simple diamonds or triangles:
4050  //
4051  // PBI or PBI or a combination of the two
4052  // / \ | \
4053  // PTB PFB | PFB
4054  // \ / | /
4055  // QBI QBI
4056  // / \ | \
4057  // QTB QFB | QFB
4058  // \ / | /
4059  // PostBB PostBB
4060  //
4061  // We model triangles as a type of diamond with a nullptr "true" block.
4062  // Triangles are canonicalized so that the fallthrough edge is represented by
4063  // a true condition, as in the diagram above.
4064  BasicBlock *PTB = PBI->getSuccessor(0);
4065  BasicBlock *PFB = PBI->getSuccessor(1);
4066  BasicBlock *QTB = QBI->getSuccessor(0);
4067  BasicBlock *QFB = QBI->getSuccessor(1);
4068  BasicBlock *PostBB = QFB->getSingleSuccessor();
4069 
4070  // Make sure we have a good guess for PostBB. If QTB's only successor is
4071  // QFB, then QFB is a better PostBB.
4072  if (QTB->getSingleSuccessor() == QFB)
4073  PostBB = QFB;
4074 
4075  // If we couldn't find a good PostBB, stop.
4076  if (!PostBB)
4077  return false;
4078 
4079  bool InvertPCond = false, InvertQCond = false;
4080  // Canonicalize fallthroughs to the true branches.
4081  if (PFB == QBI->getParent()) {
4082  std::swap(PFB, PTB);
4083  InvertPCond = true;
4084  }
4085  if (QFB == PostBB) {
4086  std::swap(QFB, QTB);
4087  InvertQCond = true;
4088  }
4089 
4090  // From this point on we can assume PTB or QTB may be fallthroughs but PFB
4091  // and QFB may not. Model fallthroughs as a nullptr block.
4092  if (PTB == QBI->getParent())
4093  PTB = nullptr;
4094  if (QTB == PostBB)
4095  QTB = nullptr;
4096 
4097  // Legality bailouts. We must have at least the non-fallthrough blocks and
4098  // the post-dominating block, and the non-fallthroughs must only have one
4099  // predecessor.
4100  auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
4101  return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
4102  };
4103  if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
4104  !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
4105  return false;
4106  if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
4107  (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
4108  return false;
4109  if (!QBI->getParent()->hasNUses(2))
4110  return false;
4111 
4112  // OK, this is a sequence of two diamonds or triangles.
4113  // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
4114  SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
4115  for (auto *BB : {PTB, PFB}) {
4116  if (!BB)
4117  continue;
4118  for (auto &I : *BB)
4119  if (StoreInst *SI = dyn_cast<StoreInst>(&I))
4120  PStoreAddresses.insert(SI->getPointerOperand());
4121  }
4122  for (auto *BB : {QTB, QFB}) {
4123  if (!BB)
4124  continue;
4125  for (auto &I : *BB)
4126  if (StoreInst *SI = dyn_cast<StoreInst>(&I))
4127  QStoreAddresses.insert(SI->getPointerOperand());
4128  }
4129 
4130  set_intersect(PStoreAddresses, QStoreAddresses);
4131  // set_intersect mutates PStoreAddresses in place. Rename it here to make it
4132  // clear what it contains.
4133  auto &CommonAddresses = PStoreAddresses;
4134 
4135  bool Changed = false;
4136  for (auto *Address : CommonAddresses)
4137  Changed |=
4138  mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address,
4139  InvertPCond, InvertQCond, DTU, DL, TTI);
4140  return Changed;
4141 }
4142 
4143 /// If the previous block ended with a widenable branch, determine if reusing
4144 /// the target block is profitable and legal. This will have the effect of
4145 /// "widening" PBI, but doesn't require us to reason about hosting safety.
4147  DomTreeUpdater *DTU) {
4148  // TODO: This can be generalized in two important ways:
4149  // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
4150  // values from the PBI edge.
4151  // 2) We can sink side effecting instructions into BI's fallthrough
4152  // successor provided they doesn't contribute to computation of
4153  // BI's condition.
4154  Value *CondWB, *WC;
4155  BasicBlock *IfTrueBB, *IfFalseBB;
4156  if (!parseWidenableBranch(PBI, CondWB, WC, IfTrueBB, IfFalseBB) ||
4157  IfTrueBB != BI->getParent() || !BI->getParent()->getSinglePredecessor())
4158  return false;
4159  if (!IfFalseBB->phis().empty())
4160  return false; // TODO
4161  // This helps avoid infinite loop with SimplifyCondBranchToCondBranch which
4162  // may undo the transform done here.
4163  // TODO: There might be a more fine-grained solution to this.
4164  if (!llvm::succ_empty(IfFalseBB))
4165  return false;
4166  // Use lambda to lazily compute expensive condition after cheap ones.
4167  auto NoSideEffects = [](BasicBlock &BB) {
4168  return llvm::none_of(BB, [](const Instruction &I) {
4169  return I.mayWriteToMemory() || I.mayHaveSideEffects();
4170  });
4171  };
4172  if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
4173  BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
4174  NoSideEffects(*BI->getParent())) {
4175  auto *OldSuccessor = BI->getSuccessor(1);
4176  OldSuccessor->removePredecessor(BI->getParent());
4177  BI->setSuccessor(1, IfFalseBB);
4178  if (DTU)
4179  DTU->applyUpdates(
4180  {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4181  {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4182  return true;
4183  }
4184  if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
4185  BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
4186  NoSideEffects(*BI->getParent())) {
4187  auto *OldSuccessor = BI->getSuccessor(0);
4188  OldSuccessor->removePredecessor(BI->getParent());
4189  BI->setSuccessor(0, IfFalseBB);
4190  if (DTU)
4191  DTU->applyUpdates(
4192  {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4193  {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4194  return true;
4195  }
4196  return false;
4197 }
4198 
4199 /// If we have a conditional branch as a predecessor of another block,
4200 /// this function tries to simplify it. We know
4201 /// that PBI and BI are both conditional branches, and BI is in one of the
4202 /// successor blocks of PBI - PBI branches to BI.
4204  DomTreeUpdater *DTU,
4205  const DataLayout &DL,
4206  const TargetTransformInfo &TTI) {
4207  assert(PBI->isConditional() && BI->isConditional());
4208  BasicBlock *BB = BI->getParent();
4209 
4210  // If this block ends with a branch instruction, and if there is a
4211  // predecessor that ends on a branch of the same condition, make
4212  // this conditional branch redundant.
4213  if (PBI->getCondition() == BI->getCondition() &&
4214  PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
4215  // Okay, the outcome of this conditional branch is statically
4216  // knowable. If this block had a single pred, handle specially, otherwise
4217  // FoldCondBranchOnValueKnownInPredecessor() will handle it.
4218  if (BB->getSinglePredecessor()) {
4219  // Turn this into a branch on constant.
4220  bool CondIsTrue = PBI->getSuccessor(0) == BB;
4221  BI->setCondition(
4222  ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
4223  return true; // Nuke the branch on constant.
4224  }
4225  }
4226 
4227  // If the previous block ended with a widenable branch, determine if reusing
4228  // the target block is profitable and legal. This will have the effect of
4229  // "widening" PBI, but doesn't require us to reason about hosting safety.
4230  if (tryWidenCondBranchToCondBranch(PBI, BI, DTU))
4231  return true;
4232 
4233  // If both branches are conditional and both contain stores to the same
4234  // address, remove the stores from the conditionals and create a conditional
4235  // merged store at the end.
4236  if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI))
4237  return true;
4238 
4239  // If this is a conditional branch in an empty block, and if any
4240  // predecessors are a conditional branch to one of our destinations,
4241  // fold the conditions into logical ops and one cond br.
4242 
4243  // Ignore dbg intrinsics.
4244  if (&*BB->instructionsWithoutDebug(false).begin() != BI)
4245  return false;
4246 
4247  int PBIOp, BIOp;
4248  if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4249  PBIOp = 0;
4250  BIOp = 0;
4251  } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4252  PBIOp = 0;
4253  BIOp = 1;
4254  } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4255  PBIOp = 1;
4256  BIOp = 0;
4257  } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4258  PBIOp = 1;
4259  BIOp = 1;
4260  } else {
4261  return false;
4262  }
4263 
4264  // Check to make sure that the other destination of this branch
4265  // isn't BB itself. If so, this is an infinite loop that will
4266  // keep getting unwound.
4267  if (PBI->getSuccessor(PBIOp) == BB)
4268  return false;
4269 
4270  // Do not perform this transformation if it would require
4271  // insertion of a large number of select instructions. For targets
4272  // without predication/cmovs, this is a big pessimization.
4273 
4274  BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
4275  BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1);
4276  unsigned NumPhis = 0;
4277  for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
4278  ++II, ++NumPhis) {
4279  if (NumPhis > 2) // Disable this xform.
4280  return false;
4281  }
4282 
4283  // Finally, if everything is ok, fold the branches to logical ops.
4284  BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
4285 
4286  LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
4287  << "AND: " << *BI->getParent());
4288 
4290 
4291  // If OtherDest *is* BB, then BB is a basic block with a single conditional
4292  // branch in it, where one edge (OtherDest) goes back to itself but the other
4293  // exits. We don't *know* that the program avoids the infinite loop
4294  // (even though that seems likely). If we do this xform naively, we'll end up
4295  // recursively unpeeling the loop. Since we know that (after the xform is
4296  // done) that the block *is* infinite if reached, we just make it an obviously
4297  // infinite loop with no cond branch.
4298  if (OtherDest == BB) {
4299  // Insert it at the end of the function, because it's either code,
4300  // or it won't matter if it's hot. :)
4301  BasicBlock *InfLoopBlock =
4302  BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
4303  BranchInst::Create(InfLoopBlock, InfLoopBlock);
4304  if (DTU)
4305  Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
4306  OtherDest = InfLoopBlock;
4307  }
4308 
4309  LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4310 
4311  // BI may have other predecessors. Because of this, we leave
4312  // it alone, but modify PBI.
4313 
4314  // Make sure we get to CommonDest on True&True directions.
4315  Value *PBICond = PBI->getCondition();
4317  if (PBIOp)
4318  PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
4319 
4320  Value *BICond = BI->getCondition();
4321  if (BIOp)
4322  BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
4323 
4324  // Merge the conditions.
4325  Value *Cond =
4326  createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge");
4327 
4328  // Modify PBI to branch on the new condition to the new dests.
4329  PBI->setCondition(Cond);
4330  PBI->setSuccessor(0, CommonDest);
4331  PBI->setSuccessor(1, OtherDest);
4332 
4333  if (DTU) {
4334  Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest});
4335  Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest});
4336 
4337  DTU->applyUpdates(Updates);
4338  }
4339 
4340  // Update branch weight for PBI.
4341  uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4342  uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
4343  bool HasWeights =
4344  extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4345  SuccTrueWeight, SuccFalseWeight);
4346  if (HasWeights) {
4347  PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4348  PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4349  SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4350  SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4351  // The weight to CommonDest should be PredCommon * SuccTotal +
4352  // PredOther * SuccCommon.
4353  // The weight to OtherDest should be PredOther * SuccOther.
4354  uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
4355  PredOther * SuccCommon,
4356  PredOther * SuccOther};
4357  // Halve the weights if any of them cannot fit in an uint32_t
4358  FitWeights(NewWeights);
4359 
4360  setBranchWeights(PBI, NewWeights[0], NewWeights[1]);
4361  }
4362 
4363  // OtherDest may have phi nodes. If so, add an entry from PBI's
4364  // block that are identical to the entries for BI's block.
4365  AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
4366 
4367  // We know that the CommonDest already had an edge from PBI to
4368  // it. If it has PHIs though, the PHIs may have different
4369  // entries for BB and PBI's BB. If so, insert a select to make
4370  // them agree.
4371  for (PHINode &PN : CommonDest->phis()) {
4372  Value *BIV = PN.getIncomingValueForBlock(BB);
4373  unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
4374  Value *PBIV = PN.getIncomingValue(PBBIdx);
4375  if (BIV != PBIV) {
4376  // Insert a select in PBI to pick the right value.
4377  SelectInst *NV = cast<SelectInst>(
4378  Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
4379  PN.setIncomingValue(PBBIdx, NV);
4380  // Although the select has the same condition as PBI, the original branch
4381  // weights for PBI do not apply to the new select because the select's
4382  // 'logical' edges are incoming edges of the phi that is eliminated, not
4383  // the outgoing edges of PBI.
4384  if (HasWeights) {
4385  uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4386  uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4387  uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4388  uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4389  // The weight to PredCommonDest should be PredCommon * SuccTotal.
4390  // The weight to PredOtherDest should be PredOther * SuccCommon.
4391  uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
4392  PredOther * SuccCommon};
4393 
4394  FitWeights(NewWeights);
4395 
4396  setBranchWeights(NV, NewWeights[0], NewWeights[1]);
4397  }
4398  }
4399  }
4400 
4401  LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
4402  LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4403 
4404  // This basic block is probably dead. We know it has at least
4405  // one fewer predecessor.
4406  return true;
4407 }
4408 
4409 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
4410 // true or to FalseBB if Cond is false.
4411 // Takes care of updating the successors and removing the old terminator.
4412 // Also makes sure not to introduce new successors by assuming that edges to
4413 // non-successor TrueBBs and FalseBBs aren't reachable.
4414 bool SimplifyCFGOpt::SimplifyTerminatorOnSelect(Instruction *OldTerm,
4415  Value *Cond, BasicBlock *TrueBB,
4416  BasicBlock *FalseBB,
4417  uint32_t TrueWeight,
4418  uint32_t FalseWeight) {
4419  auto *BB = OldTerm->getParent();
4420  // Remove any superfluous successor edges from the CFG.
4421  // First, figure out which successors to preserve.
4422  // If TrueBB and FalseBB are equal, only try to preserve one copy of that
4423  // successor.
4424  BasicBlock *KeepEdge1 = TrueBB;
4425  BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
4426 
4427  SmallSetVector<BasicBlock *, 2> RemovedSuccessors;
4428 
4429  // Then remove the rest.
4430  for (BasicBlock *Succ : successors(OldTerm)) {
4431  // Make sure only to keep exactly one copy of each edge.
4432  if (Succ == KeepEdge1)
4433  KeepEdge1 = nullptr;
4434  else if (Succ == KeepEdge2)
4435  KeepEdge2 = nullptr;
4436  else {
4437  Succ->removePredecessor(BB,
4438  /*KeepOneInputPHIs=*/true);
4439 
4440  if (Succ != TrueBB && Succ != FalseBB)
4441  RemovedSuccessors.insert(Succ);
4442  }
4443  }
4444 
4445  IRBuilder<> Builder(OldTerm);
4446  Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
4447 
4448  // Insert an appropriate new terminator.
4449  if (!KeepEdge1 && !KeepEdge2) {
4450  if (TrueBB == FalseBB) {
4451  // We were only looking for one successor, and it was present.
4452  // Create an unconditional branch to it.
4453  Builder.CreateBr(TrueBB);
4454  } else {
4455  // We found both of the successors we were looking for.
4456  // Create a conditional branch sharing the condition of the select.
4457  BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
4458  if (TrueWeight != FalseWeight)
4459  setBranchWeights(NewBI, TrueWeight, FalseWeight);
4460  }
4461  } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
4462  // Neither of the selected blocks were successors, so this
4463  // terminator must be unreachable.
4464  new UnreachableInst(OldTerm->getContext(), OldTerm);
4465  } else {
4466  // One of the selected values was a successor, but the other wasn't.
4467  // Insert an unconditional branch to the one that was found;
4468  // the edge to the one that wasn't must be unreachable.
4469  if (!KeepEdge1) {
4470  // Only TrueBB was found.
4471  Builder.CreateBr(TrueBB);
4472  } else {
4473  // Only FalseBB was found.
4474  Builder.CreateBr(FalseBB);
4475  }
4476  }
4477 
4478  EraseTerminatorAndDCECond(OldTerm);
4479 
4480  if (DTU) {
4482  Updates.reserve(RemovedSuccessors.size());
4483  for (auto *RemovedSuccessor : RemovedSuccessors)
4484  Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
4485  DTU->applyUpdates(Updates);
4486  }
4487 
4488  return true;
4489 }
4490 
4491 // Replaces
4492 // (switch (select cond, X, Y)) on constant X, Y
4493 // with a branch - conditional if X and Y lead to distinct BBs,
4494 // unconditional otherwise.
4495 bool SimplifyCFGOpt::SimplifySwitchOnSelect(SwitchInst *SI,
4496  SelectInst *Select) {
4497  // Check for constant integer values in the select.
4498  ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
4499  ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
4500  if (!TrueVal || !FalseVal)
4501  return false;
4502 
4503  // Find the relevant condition and destinations.
4504  Value *Condition = Select->getCondition();
4505  BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
4506  BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
4507 
4508  // Get weight for TrueBB and FalseBB.
4509  uint32_t TrueWeight = 0, FalseWeight = 0;
4510  SmallVector<uint64_t, 8> Weights;
4511  bool HasWeights = hasBranchWeightMD(*SI);
4512  if (HasWeights) {
4513  GetBranchWeights(SI, Weights);
4514  if (Weights.size() == 1 + SI->getNumCases()) {
4515  TrueWeight =
4516  (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
4517  FalseWeight =
4518  (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
4519  }
4520  }
4521 
4522  // Perform the actual simplification.
4523  return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
4524  FalseWeight);
4525 }
4526 
4527 // Replaces
4528 // (indirectbr (select cond, blockaddress(@fn, BlockA),
4529 // blockaddress(@fn, BlockB)))
4530 // with
4531 // (br cond, BlockA, BlockB).
4532 bool SimplifyCFGOpt::SimplifyIndirectBrOnSelect(IndirectBrInst *IBI,
4533  SelectInst *SI) {
4534  // Check that both operands of the select are block addresses.
4535  BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
4536  BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
4537  if (!TBA || !FBA)
4538  return false;
4539 
4540  // Extract the actual blocks.
4541  BasicBlock *TrueBB = TBA->getBasicBlock();
4542  BasicBlock *FalseBB = FBA->getBasicBlock();
4543 
4544  // Perform the actual simplification.
4545  return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
4546  0);
4547 }
4548 
4549 /// This is called when we find an icmp instruction
4550 /// (a seteq/setne with a constant) as the only instruction in a
4551 /// block that ends with an uncond branch. We are looking for a very specific
4552 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
4553 /// this case, we merge the first two "or's of icmp" into a switch, but then the
4554 /// default value goes to an uncond block with a seteq in it, we get something
4555 /// like:
4556 ///
4557 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
4558 /// DEFAULT:
4559 /// %tmp = icmp eq i8 %A, 92
4560 /// br label %end
4561 /// end:
4562 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
4563 ///
4564 /// We prefer to split the edge to 'end' so that there is a true/false entry to
4565 /// the PHI, merging the third icmp into the switch.
4566 bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
4567  ICmpInst *ICI, IRBuilder<> &Builder) {
4568  BasicBlock *BB = ICI->getParent();
4569 
4570  // If the block has any PHIs in it or the icmp has multiple uses, it is too
4571  // complex.
4572  if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
4573  return false;
4574 
4575  Value *V = ICI->getOperand(0);
4576  ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
4577 
4578  // The pattern we're looking for is where our only predecessor is a switch on
4579  // 'V' and this block is the default case for the switch. In this case we can
4580  // fold the compared value into the switch to simplify things.
4581  BasicBlock *Pred = BB->getSinglePredecessor();
4582  if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
4583  return false;
4584 
4585  SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
4586  if (SI->getCondition() != V)
4587  return false;
4588 
4589  // If BB is reachable on a non-default case, then we simply know the value of
4590  // V in this block. Substitute it and constant fold the icmp instruction
4591  // away.
4592  if (SI->getDefaultDest() != BB) {
4593  ConstantInt *VVal = SI->findCaseDest(BB);
4594  assert(VVal && "Should have a unique destination value");
4595  ICI->setOperand(0, VVal);
4596 
4597  if (Value *V = simplifyInstruction(ICI, {DL, ICI})) {
4598  ICI->replaceAllUsesWith(V);
4599  ICI->eraseFromParent();
4600  }
4601  // BB is now empty, so it is likely to simplify away.
4602  return requestResimplify();
4603  }
4604 
4605  // Ok, the block is reachable from the default dest. If the constant we're
4606  // comparing exists in one of the other edges, then we can constant fold ICI
4607  // and zap it.
4608  if (SI->findCaseValue(Cst) != SI->case_default()) {
4609  Value *V;
4610  if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
4611  V = ConstantInt::getFalse(BB->getContext());
4612  else
4613  V = ConstantInt::getTrue(BB->getContext());
4614 
4615  ICI->replaceAllUsesWith(V);
4616  ICI->eraseFromParent();
4617  // BB is now empty, so it is likely to simplify away.
4618  return requestResimplify();
4619  }
4620 
4621  // The use of the icmp has to be in the 'end' block, by the only PHI node in
4622  // the block.
4623  BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
4624  PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
4625  if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
4626  isa<PHINode>(++BasicBlock::iterator(PHIUse)))
4627  return false;
4628 
4629  // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
4630  // true in the PHI.
4631  Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
4632  Constant *NewCst = ConstantInt::getFalse(BB->getContext());
4633 
4634  if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
4635  std::swap(DefaultCst, NewCst);
4636 
4637  // Replace ICI (which is used by the PHI for the default value) with true or
4638  // false depending on if it is EQ or NE.
4639  ICI->replaceAllUsesWith(DefaultCst);
4640  ICI->eraseFromParent();
4641 
4643 
4644  // Okay, the switch goes to this block on a default value. Add an edge from
4645  // the switch to the merge point on the compared value.
4646  BasicBlock *NewBB =
4647  BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
4648  {
4650  auto W0 = SIW.getSuccessorWeight(0);
4652  if (W0) {
4653  NewW = ((uint64_t(*W0) + 1) >> 1);
4654  SIW.setSuccessorWeight(0, *NewW);
4655  }
4656  SIW.addCase(Cst, NewBB, NewW);
4657  if (DTU)
4658  Updates.push_back({DominatorTree::Insert, Pred, NewBB});
4659  }
4660 
4661  // NewBB branches to the phi block, add the uncond branch and the phi entry.
4662  Builder.SetInsertPoint(NewBB);
4663  Builder.SetCurrentDebugLocation(SI->getDebugLoc());
4664  Builder.CreateBr(SuccBlock);
4665  PHIUse->addIncoming(NewCst, NewBB);
4666  if (DTU) {
4667  Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock});
4668  DTU->applyUpdates(Updates);
4669  }
4670  return true;
4671 }
4672 
4673 /// The specified branch is a conditional branch.
4674 /// Check to see if it is branching on an or/and chain of icmp instructions, and
4675 /// fold it into a switch instruction if so.
4676 bool SimplifyCFGOpt::SimplifyBranchOnICmpChain(BranchInst *BI,
4678  const DataLayout &DL) {
4679  Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
4680  if (!Cond)
4681  return false;
4682 
4683  // Change br (X == 0 | X == 1), T, F into a switch instruction.
4684  // If this is a bunch of seteq's or'd together, or if it's a bunch of
4685  // 'setne's and'ed together, collect them.
4686 
4687  // Try to gather values from a chain of and/or to be turned into a switch
4688  ConstantComparesGatherer ConstantCompare(Cond, DL);
4689  // Unpack the result
4690  SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
4691  Value *CompVal = ConstantCompare.CompValue;
4692  unsigned UsedICmps = ConstantCompare.UsedICmps;
4693  Value *ExtraCase = ConstantCompare.Extra;
4694 
4695  // If we didn't have a multiply compared value, fail.
4696  if (!CompVal)
4697  return false;
4698 
4699  // Avoid turning single icmps into a switch.
4700  if (UsedICmps <= 1)
4701  return false;
4702 
4703  bool TrueWhenEqual = match(Cond, m_LogicalOr(m_Value(), m_Value()));
4704 
4705  // There might be duplicate constants in the list, which the switch
4706  // instruction can't handle, remove them now.
4707  array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
4708  Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
4709 
4710  // If Extra was used, we require at least two switch values to do the
4711  // transformation. A switch with one value is just a conditional branch.
4712  if (ExtraCase && Values.size() < 2)
4713  return false;
4714 
4715  // TODO: Preserve branch weight metadata, similarly to how
4716  // FoldValueComparisonIntoPredecessors preserves it.
4717 
4718  // Figure out which block is which destination.
4719  BasicBlock *DefaultBB = BI->getSuccessor(1);
4720  BasicBlock *EdgeBB = BI->getSuccessor(0);
4721  if (!TrueWhenEqual)
4722  std::swap(DefaultBB, EdgeBB);
4723 
4724  BasicBlock *BB = BI->getParent();
4725 
4726  LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
4727  << " cases into SWITCH. BB is:\n"
4728  << *BB);
4729 
4731 
4732  // If there are any extra values that couldn't be folded into the switch
4733  // then we evaluate them with an explicit branch first. Split the block
4734  // right before the condbr to handle it.
4735  if (ExtraCase) {
4736  BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr,
4737  /*MSSAU=*/nullptr, "switch.early.test");
4738 
4739  // Remove the uncond branch added to the old block.
4740  Instruction *OldTI = BB->getTerminator();
4741  Builder.SetInsertPoint(OldTI);
4742 
4743  // There can be an unintended UB if extra values are Poison. Before the
4744  // transformation, extra values may not be evaluated according to the
4745  // condition, and it will not raise UB. But after transformation, we are
4746  // evaluating extra values before checking the condition, and it will raise
4747  // UB. It can be solved by adding freeze instruction to extra values.
4748  AssumptionCache *AC = Options.AC;
4749 
4750  if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr))
4751  ExtraCase = Builder.CreateFreeze(ExtraCase);
4752 
4753  if (TrueWhenEqual)
4754  Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
4755  else
4756  Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
4757 
4758  OldTI->eraseFromParent();
4759 
4760  if (DTU)
4761  Updates.push_back({DominatorTree::Insert, BB, EdgeBB});
4762 
4763  // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
4764  // for the edge we just added.
4765  AddPredecessorToBlock(EdgeBB, BB, NewBB);
4766 
4767  LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
4768  << "\nEXTRABB = " << *BB);
4769  BB = NewBB;
4770  }
4771 
4772  Builder.SetInsertPoint(BI);
4773  // Convert pointer to int before we switch.
4774  if (CompVal->getType()->isPointerTy()) {
4775  CompVal = Builder.CreatePtrToInt(
4776  CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
4777  }
4778 
4779  // Create the new switch instruction now.
4780  SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
4781 
4782  // Add all of the 'cases' to the switch instruction.
4783  for (unsigned i = 0, e = Values.size(); i != e; ++i)
4784  New->addCase(Values[i], EdgeBB);
4785 
4786  // We added edges from PI to the EdgeBB. As such, if there were any
4787  // PHI nodes in EdgeBB, they need entries to be added corresponding to
4788  // the number of edges added.
4789  for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
4790  PHINode *PN = cast<PHINode>(BBI);
4791  Value *InVal = PN->getIncomingValueForBlock(BB);
4792  for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
4793  PN->addIncoming(InVal, BB);
4794  }
4795 
4796  // Erase the old branch instruction.
4798  if (DTU)
4799  DTU->applyUpdates(Updates);
4800 
4801  LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
4802  return true;
4803 }
4804 
4805 bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
4806  if (isa<PHINode>(RI->getValue()))
4807  return simplifyCommonResume(RI);
4808  else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
4809  RI->getValue() == RI->getParent()->getFirstNonPHI())
4810  // The resume must unwind the exception that caused control to branch here.
4811  return simplifySingleResume(RI);
4812 
4813  return false;
4814 }
4815 
4816 // Check if cleanup block is empty
4818  for (Instruction &I : R) {
4819  auto *II = dyn_cast<IntrinsicInst>(&I);
4820  if (!II)
4821  return false;
4822 
4823  Intrinsic::ID IntrinsicID = II->getIntrinsicID();
4824  switch (IntrinsicID) {
4825  case Intrinsic::dbg_declare:
4826  case Intrinsic::dbg_value:
4827  case Intrinsic::dbg_label:
4828  case Intrinsic::lifetime_end:
4829  break;
4830  default:
4831  return false;
4832  }
4833  }
4834  return true;
4835 }
4836 
4837 // Simplify resume that is shared by several landing pads (phi of landing pad).
4838 bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
4839  BasicBlock *BB = RI->getParent();
4840 
4841  // Check that there are no other instructions except for debug and lifetime
4842  // intrinsics between the phi's and resume instruction.
4843  if (!isCleanupBlockEmpty(
4844  make_range(RI->getParent()->getFirstNonPHI(), BB->getTerminator())))
4845  return false;
4846 
4847  SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
4848  auto *PhiLPInst = cast<PHINode>(RI->getValue());
4849 
4850  // Check incoming blocks to see if any of them are trivial.
4851  for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
4852  Idx++) {
4853  auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
4854  auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
4855 
4856  // If the block has other successors, we can not delete it because
4857  // it has other dependents.
4858  if (IncomingBB->getUniqueSuccessor() != BB)
4859  continue;
4860 
4861  auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
4862  // Not the landing pad that caused the control to branch here.
4863  if (IncomingValue != LandingPad)
4864  continue;
4865 
4866  if (isCleanupBlockEmpty(
4867  make_range(LandingPad->getNextNode(), IncomingBB->getTerminator())))
4868  TrivialUnwindBlocks.insert(IncomingBB);
4869  }
4870 
4871  // If no trivial unwind blocks, don't do any simplifications.
4872  if (TrivialUnwindBlocks.empty())
4873  return false;
4874 
4875  // Turn all invokes that unwind here into calls.
4876  for (auto *TrivialBB : TrivialUnwindBlocks) {
4877  // Blocks that will be simplified should be removed from the phi node.
4878  // Note there could be multiple edges to the resume block, and we need
4879  // to remove them all.
4880  while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
4881  BB->removePredecessor(TrivialBB, true);
4882 
4883  for (BasicBlock *Pred :
4885  removeUnwindEdge(Pred, DTU);
4886  ++NumInvokes;
4887  }
4888 
4889  // In each SimplifyCFG run, only the current processed block can be erased.
4890  // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
4891  // of erasing TrivialBB, we only remove the branch to the common resume
4892  // block so that we can later erase the resume block since it has no
4893  // predecessors.
4894  TrivialBB->getTerminator()->eraseFromParent();
4895  new UnreachableInst(RI->getContext(), TrivialBB);
4896  if (DTU)
4897  DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}});
4898  }
4899 
4900  // Delete the resume block if all its predecessors have been removed.
4901  if (pred_empty(BB))
4902  DeleteDeadBlock(BB, DTU);
4903 
4904  return !TrivialUnwindBlocks.empty();
4905 }
4906 
4907 // Simplify resume that is only used by a single (non-phi) landing pad.
4908 bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
4909  BasicBlock *BB = RI->getParent();
4910  auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI());
4911  assert(RI->getValue() == LPInst &&
4912  "Resume must unwind the exception that caused control to here");
4913 
4914  // Check that there are no other instructions except for debug intrinsics.
4915  if (!isCleanupBlockEmpty(
4916  make_range<Instruction *>(LPInst->getNextNode(), RI)))
4917  return false;
4918 
4919  // Turn all invokes that unwind here into calls and delete the basic block.
4921  removeUnwindEdge(Pred, DTU);
4922  ++NumInvokes;
4923  }
4924 
4925  // The landingpad is now unreachable. Zap it.
4926  DeleteDeadBlock(BB, DTU);
4927  return true;
4928 }
4929 
4931  // If this is a trivial cleanup pad that executes no instructions, it can be
4932  // eliminated. If the cleanup pad continues to the caller, any predecessor
4933  // that is an EH pad will be updated to continue to the caller and any
4934  // predecessor that terminates with an invoke instruction will have its invoke
4935  // instruction converted to a call instruction. If the cleanup pad being
4936  // simplified does not continue to the caller, each predecessor will be
4937  // updated to continue to the unwind destination of the cleanup pad being
4938  // simplified.
4939  BasicBlock *BB = RI->getParent();
4940  CleanupPadInst *CPInst = RI->getCleanupPad();
4941  if (CPInst->getParent() != BB)
4942  // This isn't an empty cleanup.
4943  return false;
4944 
4945  // We cannot kill the pad if it has multiple uses. This typically arises
4946  // from unreachable basic blocks.
4947  if (!CPInst->hasOneUse())
4948  return false;
4949 
4950  // Check that there are no other instructions except for benign intrinsics.
4951  if (!isCleanupBlockEmpty(
4952  make_range<Instruction *>(CPInst->getNextNode(), RI)))
4953  return false;
4954 
4955  // If the cleanup return we are simplifying unwinds to the caller, this will
4956  // set UnwindDest to nullptr.
4957  BasicBlock *UnwindDest = RI->getUnwindDest();
4958  Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
4959 
4960  // We're about to remove BB from the control flow. Before we do, sink any
4961  // PHINodes into the unwind destination. Doing this before changing the
4962  // control flow avoids some potentially slow checks, since we can currently
4963  // be certain that UnwindDest and BB have no common predecessors (since they
4964  // are both EH pads).
4965  if (UnwindDest) {
4966  // First, go through the PHI nodes in UnwindDest and update any nodes that
4967  // reference the block we are removing
4968  for (PHINode &DestPN : UnwindDest->phis()) {
4969  int Idx = DestPN.getBasicBlockIndex(BB);
4970  // Since BB unwinds to UnwindDest, it has to be in the PHI node.
4971  assert(Idx != -1);
4972  // This PHI node has an incoming value that corresponds to a control
4973  // path through the cleanup pad we are removing. If the incoming
4974  // value is in the cleanup pad, it must be a PHINode (because we
4975  // verified above that the block is otherwise empty). Otherwise, the
4976  // value is either a constant or a value that dominates the cleanup
4977  // pad being removed.
4978  //
4979  // Because BB and UnwindDest are both EH pads, all of their
4980  // predecessors must unwind to these blocks, and since no instruction
4981  // can have multiple unwind destinations, there will be no overlap in
4982  // incoming blocks between SrcPN and DestPN.
4983  Value *SrcVal = DestPN.getIncomingValue(Idx);
4984  PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
4985 
4986  bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB;
4987  for (auto *Pred : predecessors(BB)) {
4988  Value *Incoming =
4989  NeedPHITranslation ? SrcPN->getIncomingValueForBlock(Pred) : SrcVal;
4990  DestPN.addIncoming(Incoming, Pred);
4991  }
4992  }
4993 
4994  // Sink any remaining PHI nodes directly into UnwindDest.
4995  Instruction *InsertPt = DestEHPad;
4996  for (PHINode &PN : make_early_inc_range(BB->phis())) {
4997  if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB))
4998  // If the PHI node has no uses or all of its uses are in this basic
4999  // block (meaning they are debug or lifetime intrinsics), just leave
5000  // it. It will be erased when we erase BB below.
5001  continue;
5002 
5003  // Otherwise, sink this PHI node into UnwindDest.
5004  // Any predecessors to UnwindDest which are not already represented
5005  // must be back edges which inherit the value from the path through
5006  // BB. In this case, the PHI value must reference itself.
5007  for (auto *pred : predecessors(UnwindDest))
5008  if (pred != BB)
5009  PN.addIncoming(&PN, pred);
5010  PN.moveBefore(InsertPt);
5011  // Also, add a dummy incoming value for the original BB itself,
5012  // so that the PHI is well-formed until we drop said predecessor.
5014  }
5015  }
5016 
5017  std::vector<DominatorTree::UpdateType> Updates;
5018 
5019  // We use make_early_inc_range here because we will remove all predecessors.
5021  if (UnwindDest == nullptr) {
5022  if (DTU) {
5023  DTU->applyUpdates(Updates);
5024  Updates.clear();
5025  }
5026  removeUnwindEdge(PredBB, DTU);
5027  ++NumInvokes;
5028  } else {
5029  BB->removePredecessor(PredBB);
5030  Instruction *TI = PredBB->getTerminator();
5031  TI->replaceUsesOfWith(BB, UnwindDest);
5032  if (DTU) {
5033  Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest});
5034  Updates.push_back({DominatorTree::Delete, PredBB, BB});
5035  }
5036  }
5037  }
5038 
5039  if (DTU)
5040  DTU->applyUpdates(Updates);
5041 
5042  DeleteDeadBlock(BB, DTU);
5043 
5044  return true;
5045 }
5046 
5047 // Try to merge two cleanuppads together.
5049  // Skip any cleanuprets which unwind to caller, there is nothing to merge
5050  // with.
5051  BasicBlock *UnwindDest = RI->getUnwindDest();
5052  if (!UnwindDest)
5053  return false;
5054 
5055  // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
5056  // be safe to merge without code duplication.
5057  if (UnwindDest->getSinglePredecessor() != RI->getParent())
5058  return false;
5059 
5060  // Verify that our cleanuppad's unwind destination is another cleanuppad.
5061  auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
5062  if (!SuccessorCleanupPad)
5063  return false;
5064 
5065  CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
5066  // Replace any uses of the successor cleanupad with the predecessor pad
5067  // The only cleanuppad uses should be this cleanupret, it's cleanupret and
5068  // funclet bundle operands.
5069  SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
5070  // Remove the old cleanuppad.
5071  SuccessorCleanupPad->eraseFromParent();
5072  // Now, we simply replace the cleanupret with a branch to the unwind
5073  // destination.
5074  BranchInst::Create(UnwindDest, RI->getParent());
5075  RI->eraseFromParent();
5076 
5077  return true;
5078 }
5079 
5080 bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
5081  // It is possible to transiantly have an undef cleanuppad operand because we
5082  // have deleted some, but not all, dead blocks.
5083  // Eventually, this block will be deleted.
5084  if (isa<UndefValue>(RI->getOperand(0)))
5085  return false;
5086 
5087  if (mergeCleanupPad(RI))
5088  return true;
5089 
5090  if (removeEmptyCleanup(RI, DTU))
5091  return true;
5092 
5093  return false;
5094 }
5095 
5096 // WARNING: keep in sync with InstCombinerImpl::visitUnreachableInst()!
5097 bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
5098  BasicBlock *BB = UI->getParent();
5099 
5100  bool Changed = false;
5101 
5102  // If there are any instructions immediately before the unreachable that can
5103  // be removed, do so.
5104  while (UI->getIterator() != BB->begin()) {
5105  BasicBlock::iterator BBI = UI->getIterator();
5106  --BBI;
5107 
5109  break; // Can not drop any more instructions. We're done here.
5110  // Otherwise, this instruction can be freely erased,
5111  // even if it is not side-effect free.
5112 
5113  // Note that deleting EH's here is in fact okay, although it involves a bit
5114  // of subtle reasoning. If this inst is an EH, all the predecessors of this
5115  // block will be the unwind edges of Invoke/CatchSwitch/CleanupReturn,
5116  // and we can therefore guarantee this block will be erased.
5117 
5118  // Delete this instruction (any uses are guaranteed to be dead)
5119  BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
5120  BBI->eraseFromParent();
5121  Changed = true;
5122  }
5123 
5124  // If the unreachable instruction is the first in the block, take a gander
5125  // at all of the predecessors of this instruction, and simplify them.
5126  if (&BB->front() != UI)
5127  return Changed;
5128 
5129  std::vector<DominatorTree::UpdateType> Updates;
5130 
5132  for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
5133  auto *Predecessor = Preds[i];
5134  Instruction *TI = Predecessor->getTerminator();
5135  IRBuilder<> Builder(TI);
5136  if (auto *BI = dyn_cast<BranchInst>(TI)) {
5137  // We could either have a proper unconditional branch,
5138  // or a degenerate conditional branch with matching destinations.
5139  if (all_of(BI->successors(),
5140  [BB](auto *Successor) { return Successor == BB; })) {
5141  new UnreachableInst(TI->getContext(), TI);
5142  TI->eraseFromParent();
5143  Changed = true;
5144  } else {
5145  assert(BI->isConditional() && "Can't get here with an uncond branch.");
5146  Value* Cond = BI->getCondition();
5147  assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
5148  "The destinations are guaranteed to be different here.");
5149  if (BI->getSuccessor(0) == BB) {
5150  Builder.CreateAssumption(Builder.CreateNot(Cond));
5151  Builder.CreateBr(BI->getSuccessor(1));
5152  } else {
5153  assert(BI->getSuccessor(1) == BB && "Incorrect CFG");
5154  Builder.CreateAssumption(Cond);
5155  Builder.CreateBr(BI->getSuccessor(0));
5156  }
5158  Changed = true;
5159  }
5160  if (DTU)
5161  Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5162  } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
5164  for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
5165  if (i->getCaseSuccessor() != BB) {
5166  ++i;
5167  continue;
5168  }
5169  BB->removePredecessor(SU->getParent());
5170  i = SU.removeCase(i);
5171  e = SU->case_end();
5172  Changed = true;
5173  }
5174  // Note that the default destination can't be removed!
5175  if (DTU && SI->getDefaultDest() != BB)
5176  Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5177  } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
5178  if (II->getUnwindDest() == BB) {
5179  if (DTU) {
5180  DTU->applyUpdates(Updates);
5181  Updates.clear();
5182  }
5183  removeUnwindEdge(TI->getParent(), DTU);
5184  Changed = true;
5185  }
5186  } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
5187  if (CSI->getUnwindDest() == BB) {
5188  if (DTU) {
5189  DTU->applyUpdates(Updates);
5190  Updates.clear();
5191  }
5192  removeUnwindEdge(TI->getParent(), DTU);
5193  Changed = true;
5194  continue;
5195  }
5196 
5197  for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
5198  E = CSI->handler_end();
5199  I != E; ++I) {
5200  if (*I == BB) {
5201  CSI->removeHandler(I);
5202  --I;
5203  --E;
5204  Changed = true;
5205  }
5206  }
5207  if (DTU)
5208  Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5209  if (CSI->getNumHandlers() == 0) {
5210  if (CSI->hasUnwindDest()) {
5211  // Redirect all predecessors of the block containing CatchSwitchInst
5212  // to instead branch to the CatchSwitchInst's unwind destination.
5213  if (DTU) {
5214  for (auto *PredecessorOfPredecessor : predecessors(Predecessor)) {
5215  Updates.push_back({DominatorTree::Insert,
5216  PredecessorOfPredecessor,
5217  CSI->getUnwindDest()});
5218  Updates.push_back({DominatorTree::Delete,
5219  PredecessorOfPredecessor, Predecessor});
5220  }
5221  }
5222  Predecessor->replaceAllUsesWith(CSI->getUnwindDest());
5223  } else {
5224  // Rewrite all preds to unwind to caller (or from invoke to call).
5225  if (DTU) {
5226  DTU->applyUpdates(Updates);
5227  Updates.clear();
5228  }
5229  SmallVector<BasicBlock *, 8> EHPreds(predecessors(Predecessor));
5230  for (BasicBlock *EHPred : EHPreds)
5231  removeUnwindEdge(EHPred, DTU);
5232  }
5233  // The catchswitch is no longer reachable.
5234  new UnreachableInst(CSI->getContext(), CSI);
5235  CSI->eraseFromParent();
5236  Changed = true;
5237  }
5238  } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
5239  (void)CRI;
5240  assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB &&
5241  "Expected to always have an unwind to BB.");
5242  if (DTU)
5243  Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5244  new UnreachableInst(TI->getContext(), TI);
5245  TI->eraseFromParent();
5246  Changed = true;
5247  }
5248  }
5249 
5250  if (DTU)
5251  DTU->applyUpdates(Updates);
5252 
5253  // If this block is now dead, remove it.
5254  if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
5255  DeleteDeadBlock(BB, DTU);
5256  return true;
5257  }
5258 
5259  return Changed;
5260 }
5261 
5263  assert(Cases.size() >= 1);
5264 
5265  array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
5266  for (size_t I = 1, E = Cases.size(); I != E; ++I) {
5267  if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
5268  return false;
5269  }
5270  return true;
5271 }
5272 
5274  DomTreeUpdater *DTU) {
5275  LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
5276  auto *BB = Switch->getParent();
5277  auto *OrigDefaultBlock = Switch->getDefaultDest();
5278  OrigDefaultBlock->removePredecessor(BB);
5279  BasicBlock *NewDefaultBlock = BasicBlock::Create(
5280  BB->getContext(), BB->getName() + ".unreachabledefault", BB->getParent(),
5281  OrigDefaultBlock);
5282  new UnreachableInst(Switch->getContext(), NewDefaultBlock);
5283  Switch->setDefaultDest(&*NewDefaultBlock);
5284  if (DTU) {
5286  Updates.push_back({DominatorTree::Insert, BB, &*NewDefaultBlock});
5287  if (!is_contained(successors(BB), OrigDefaultBlock))
5288  Updates.push_back({DominatorTree::Delete, BB, &*OrigDefaultBlock});
5289  DTU->applyUpdates(Updates);
5290  }
5291 }
5292 
5293 /// Turn a switch into an integer range comparison and branch.
5294 /// Switches with more than 2 destinations are ignored.
5295 /// Switches with 1 destination are also ignored.
5296 bool SimplifyCFGOpt::TurnSwitchRangeIntoICmp(SwitchInst *SI,
5297  IRBuilder<> &Builder) {
5298  assert(SI->getNumCases() > 1 && "Degenerate switch?");
5299 
5300  bool HasDefault =
5301  !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5302 
5303  auto *BB = SI->getParent();
5304 
5305  // Partition the cases into two sets with different destinations.
5306  BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
5307  BasicBlock *DestB = nullptr;
5310 
5311  for (auto Case : SI->cases()) {
5312  BasicBlock *Dest = Case.getCaseSuccessor();
5313  if (!DestA)
5314  DestA = Dest;
5315  if (Dest == DestA) {
5316  CasesA.push_back(Case.getCaseValue());
5317  continue;
5318  }
5319  if (!DestB)
5320  DestB = Dest;
5321  if (Dest == DestB) {
5322  CasesB.push_back(Case.getCaseValue());
5323  continue;
5324  }
5325  return false; // More than two destinations.
5326  }
5327  if (!DestB)
5328  return false; // All destinations are the same and the default is unreachable
5329 
5330  assert(DestA && DestB &&
5331  "Single-destination switch should have been folded.");
5332  assert(DestA != DestB);
5333  assert(DestB != SI->getDefaultDest());
5334  assert(!CasesB.empty() && "There must be non-default cases.");
5335  assert(!CasesA.empty() || HasDefault);
5336 
5337  // Figure out if one of the sets of cases form a contiguous range.
5338  SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
5339  BasicBlock *ContiguousDest = nullptr;
5340  BasicBlock *OtherDest = nullptr;
5341  if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
5342  ContiguousCases = &CasesA;
5343  ContiguousDest = DestA;
5344  OtherDest = DestB;
5345  } else if (CasesAreContiguous(CasesB)) {
5346  ContiguousCases = &CasesB;
5347  ContiguousDest = DestB;
5348  OtherDest = DestA;
5349  } else
5350  return false;
5351 
5352  // Start building the compare and branch.
5353 
5354  Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
5355