LLVM 18.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/STLExtras.h"
18#include "llvm/ADT/ScopeExit.h"
19#include "llvm/ADT/Sequence.h"
21#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/ADT/StringRef.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/CFG.h"
39#include "llvm/IR/Constant.h"
41#include "llvm/IR/Constants.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/DebugInfo.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/GlobalValue.h"
48#include "llvm/IR/IRBuilder.h"
49#include "llvm/IR/InstrTypes.h"
50#include "llvm/IR/Instruction.h"
53#include "llvm/IR/LLVMContext.h"
54#include "llvm/IR/MDBuilder.h"
55#include "llvm/IR/Metadata.h"
56#include "llvm/IR/Module.h"
57#include "llvm/IR/NoFolder.h"
58#include "llvm/IR/Operator.h"
61#include "llvm/IR/Type.h"
62#include "llvm/IR/Use.h"
63#include "llvm/IR/User.h"
64#include "llvm/IR/Value.h"
65#include "llvm/IR/ValueHandle.h"
69#include "llvm/Support/Debug.h"
77#include <algorithm>
78#include <cassert>
79#include <climits>
80#include <cstddef>
81#include <cstdint>
82#include <iterator>
83#include <map>
84#include <optional>
85#include <set>
86#include <tuple>
87#include <utility>
88#include <vector>
89
90using namespace llvm;
91using namespace PatternMatch;
92
93#define DEBUG_TYPE "simplifycfg"
94
96 "simplifycfg-require-and-preserve-domtree", cl::Hidden,
97
98 cl::desc("Temorary development switch used to gradually uplift SimplifyCFG "
99 "into preserving DomTree,"));
100
101// Chosen as 2 so as to be cheap, but still to have enough power to fold
102// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
103// To catch this, we need to fold a compare and a select, hence '2' being the
104// minimum reasonable default.
106 "phi-node-folding-threshold", cl::Hidden, cl::init(2),
107 cl::desc(
108 "Control the amount of phi node folding to perform (default = 2)"));
109
111 "two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4),
112 cl::desc("Control the maximal total instruction cost that we are willing "
113 "to speculatively execute to fold a 2-entry PHI node into a "
114 "select (default = 4)"));
115
116static cl::opt<bool>
117 HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true),
118 cl::desc("Hoist common instructions up to the parent block"));
119
121 HoistCommonSkipLimit("simplifycfg-hoist-common-skip-limit", cl::Hidden,
122 cl::init(20),
123 cl::desc("Allow reordering across at most this many "
124 "instructions when hoisting"));
125
126static cl::opt<bool>
127 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
128 cl::desc("Sink common instructions down to the end block"));
129
131 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
132 cl::desc("Hoist conditional stores if an unconditional store precedes"));
133
135 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
136 cl::desc("Hoist conditional stores even if an unconditional store does not "
137 "precede - hoist multiple conditional stores into a single "
138 "predicated store"));
139
141 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
142 cl::desc("When merging conditional stores, do so even if the resultant "
143 "basic blocks are unlikely to be if-converted as a result"));
144
146 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
147 cl::desc("Allow exactly one expensive instruction to be speculatively "
148 "executed"));
149
151 "max-speculation-depth", cl::Hidden, cl::init(10),
152 cl::desc("Limit maximum recursion depth when calculating costs of "
153 "speculatively executed instructions"));
154
155static cl::opt<int>
156 MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden,
157 cl::init(10),
158 cl::desc("Max size of a block which is still considered "
159 "small enough to thread through"));
160
161// Two is chosen to allow one negation and a logical combine.
163 BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden,
164 cl::init(2),
165 cl::desc("Maximum cost of combining conditions when "
166 "folding branches"));
167
169 "simplifycfg-branch-fold-common-dest-vector-multiplier", cl::Hidden,
170 cl::init(2),
171 cl::desc("Multiplier to apply to threshold when determining whether or not "
172 "to fold branch to common destination when vector operations are "
173 "present"));
174
176 "simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(true),
177 cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"));
178
180 "max-switch-cases-per-result", cl::Hidden, cl::init(16),
181 cl::desc("Limit cases to analyze when converting a switch to select"));
182
183STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
184STATISTIC(NumLinearMaps,
185 "Number of switch instructions turned into linear mapping");
186STATISTIC(NumLookupTables,
187 "Number of switch instructions turned into lookup tables");
189 NumLookupTablesHoles,
190 "Number of switch instructions turned into lookup tables (holes checked)");
191STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
192STATISTIC(NumFoldValueComparisonIntoPredecessors,
193 "Number of value comparisons folded into predecessor basic blocks");
194STATISTIC(NumFoldBranchToCommonDest,
195 "Number of branches folded into predecessor basic block");
197 NumHoistCommonCode,
198 "Number of common instruction 'blocks' hoisted up to the begin block");
199STATISTIC(NumHoistCommonInstrs,
200 "Number of common instructions hoisted up to the begin block");
201STATISTIC(NumSinkCommonCode,
202 "Number of common instruction 'blocks' sunk down to the end block");
203STATISTIC(NumSinkCommonInstrs,
204 "Number of common instructions sunk down to the end block");
205STATISTIC(NumSpeculations, "Number of speculative executed instructions");
206STATISTIC(NumInvokes,
207 "Number of invokes with empty resume blocks simplified into calls");
208STATISTIC(NumInvokesMerged, "Number of invokes that were merged together");
209STATISTIC(NumInvokeSetsFormed, "Number of invoke sets that were formed");
210
211namespace {
212
213// The first field contains the value that the switch produces when a certain
214// case group is selected, and the second field is a vector containing the
215// cases composing the case group.
216using SwitchCaseResultVectorTy =
218
219// The first field contains the phi node that generates a result of the switch
220// and the second field contains the value generated for a certain case in the
221// switch for that PHI.
222using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
223
224/// ValueEqualityComparisonCase - Represents a case of a switch.
225struct ValueEqualityComparisonCase {
227 BasicBlock *Dest;
228
229 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
230 : Value(Value), Dest(Dest) {}
231
232 bool operator<(ValueEqualityComparisonCase RHS) const {
233 // Comparing pointers is ok as we only rely on the order for uniquing.
234 return Value < RHS.Value;
235 }
236
237 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
238};
239
240class SimplifyCFGOpt {
242 DomTreeUpdater *DTU;
243 const DataLayout &DL;
244 ArrayRef<WeakVH> LoopHeaders;
246 bool Resimplify;
247
248 Value *isValueEqualityComparison(Instruction *TI);
249 BasicBlock *GetValueEqualityComparisonCases(
250 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
251 bool SimplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
252 BasicBlock *Pred,
253 IRBuilder<> &Builder);
254 bool PerformValueComparisonIntoPredecessorFolding(Instruction *TI, Value *&CV,
255 Instruction *PTI,
256 IRBuilder<> &Builder);
257 bool FoldValueComparisonIntoPredecessors(Instruction *TI,
258 IRBuilder<> &Builder);
259
260 bool simplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
261 bool simplifySingleResume(ResumeInst *RI);
262 bool simplifyCommonResume(ResumeInst *RI);
263 bool simplifyCleanupReturn(CleanupReturnInst *RI);
264 bool simplifyUnreachable(UnreachableInst *UI);
265 bool simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
266 bool simplifyIndirectBr(IndirectBrInst *IBI);
267 bool simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder);
268 bool simplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
269 bool simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
270
271 bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
272 IRBuilder<> &Builder);
273
274 bool hoistCommonCodeFromSuccessors(BasicBlock *BB, bool EqTermsOnly);
275 bool hoistSuccIdenticalTerminatorToSwitchOrIf(
276 Instruction *TI, Instruction *I1,
277 SmallVectorImpl<Instruction *> &OtherSuccTIs);
278 bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB);
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
288public:
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.
340static 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.
373static 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,
415 InstructionCost Budget,
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.
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
510namespace {
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.
522struct 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
546private:
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
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.
775Value *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.
802BasicBlock *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.
822static 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.
829static 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.
875static 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.
892bool 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.
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
1041namespace {
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.
1046struct 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 - llvm::countl_zero(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 speculated an instruction, we need to drop any metadata that may
1122 // result in undefined behavior, as the metadata might have been valid
1123 // only given the branch precondition.
1124 // Similarly strip attributes on call parameters that may cause UB in
1125 // location the call is moved to.
1126 NewBonusInst->dropUBImplyingAttrsAndMetadata();
1127
1128 NewBonusInst->insertInto(PredBlock, PTI->getIterator());
1129 NewBonusInst->takeName(&BonusInst);
1130 BonusInst.setName(NewBonusInst->getName() + ".old");
1131
1132 // Update (liveout) uses of bonus instructions,
1133 // now that the bonus instruction has been cloned into predecessor.
1134 // Note that we expect to be in a block-closed SSA form for this to work!
1135 for (Use &U : make_early_inc_range(BonusInst.uses())) {
1136 auto *UI = cast<Instruction>(U.getUser());
1137 auto *PN = dyn_cast<PHINode>(UI);
1138 if (!PN) {
1139 assert(UI->getParent() == BB && BonusInst.comesBefore(UI) &&
1140 "If the user is not a PHI node, then it should be in the same "
1141 "block as, and come after, the original bonus instruction.");
1142 continue; // Keep using the original bonus instruction.
1143 }
1144 // Is this the block-closed SSA form PHI node?
1145 if (PN->getIncomingBlock(U) == BB)
1146 continue; // Great, keep using the original bonus instruction.
1147 // The only other alternative is an "use" when coming from
1148 // the predecessor block - here we should refer to the cloned bonus instr.
1149 assert(PN->getIncomingBlock(U) == PredBlock &&
1150 "Not in block-closed SSA form?");
1151 U.set(NewBonusInst);
1152 }
1153 }
1154}
1155
1156bool SimplifyCFGOpt::PerformValueComparisonIntoPredecessorFolding(
1157 Instruction *TI, Value *&CV, Instruction *PTI, IRBuilder<> &Builder) {
1158 BasicBlock *BB = TI->getParent();
1159 BasicBlock *Pred = PTI->getParent();
1160
1162
1163 // Figure out which 'cases' to copy from SI to PSI.
1164 std::vector<ValueEqualityComparisonCase> BBCases;
1165 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
1166
1167 std::vector<ValueEqualityComparisonCase> PredCases;
1168 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
1169
1170 // Based on whether the default edge from PTI goes to BB or not, fill in
1171 // PredCases and PredDefault with the new switch cases we would like to
1172 // build.
1174
1175 // Update the branch weight metadata along the way
1177 bool PredHasWeights = hasBranchWeightMD(*PTI);
1178 bool SuccHasWeights = hasBranchWeightMD(*TI);
1179
1180 if (PredHasWeights) {
1181 GetBranchWeights(PTI, Weights);
1182 // branch-weight metadata is inconsistent here.
1183 if (Weights.size() != 1 + PredCases.size())
1184 PredHasWeights = SuccHasWeights = false;
1185 } else if (SuccHasWeights)
1186 // If there are no predecessor weights but there are successor weights,
1187 // populate Weights with 1, which will later be scaled to the sum of
1188 // successor's weights
1189 Weights.assign(1 + PredCases.size(), 1);
1190
1191 SmallVector<uint64_t, 8> SuccWeights;
1192 if (SuccHasWeights) {
1193 GetBranchWeights(TI, SuccWeights);
1194 // branch-weight metadata is inconsistent here.
1195 if (SuccWeights.size() != 1 + BBCases.size())
1196 PredHasWeights = SuccHasWeights = false;
1197 } else if (PredHasWeights)
1198 SuccWeights.assign(1 + BBCases.size(), 1);
1199
1200 if (PredDefault == BB) {
1201 // If this is the default destination from PTI, only the edges in TI
1202 // that don't occur in PTI, or that branch to BB will be activated.
1203 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1204 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1205 if (PredCases[i].Dest != BB)
1206 PTIHandled.insert(PredCases[i].Value);
1207 else {
1208 // The default destination is BB, we don't need explicit targets.
1209 std::swap(PredCases[i], PredCases.back());
1210
1211 if (PredHasWeights || SuccHasWeights) {
1212 // Increase weight for the default case.
1213 Weights[0] += Weights[i + 1];
1214 std::swap(Weights[i + 1], Weights.back());
1215 Weights.pop_back();
1216 }
1217
1218 PredCases.pop_back();
1219 --i;
1220 --e;
1221 }
1222
1223 // Reconstruct the new switch statement we will be building.
1224 if (PredDefault != BBDefault) {
1225 PredDefault->removePredecessor(Pred);
1226 if (DTU && PredDefault != BB)
1227 Updates.push_back({DominatorTree::Delete, Pred, PredDefault});
1228 PredDefault = BBDefault;
1229 ++NewSuccessors[BBDefault];
1230 }
1231
1232 unsigned CasesFromPred = Weights.size();
1233 uint64_t ValidTotalSuccWeight = 0;
1234 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1235 if (!PTIHandled.count(BBCases[i].Value) && BBCases[i].Dest != BBDefault) {
1236 PredCases.push_back(BBCases[i]);
1237 ++NewSuccessors[BBCases[i].Dest];
1238 if (SuccHasWeights || PredHasWeights) {
1239 // The default weight is at index 0, so weight for the ith case
1240 // should be at index i+1. Scale the cases from successor by
1241 // PredDefaultWeight (Weights[0]).
1242 Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1243 ValidTotalSuccWeight += SuccWeights[i + 1];
1244 }
1245 }
1246
1247 if (SuccHasWeights || PredHasWeights) {
1248 ValidTotalSuccWeight += SuccWeights[0];
1249 // Scale the cases from predecessor by ValidTotalSuccWeight.
1250 for (unsigned i = 1; i < CasesFromPred; ++i)
1251 Weights[i] *= ValidTotalSuccWeight;
1252 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1253 Weights[0] *= SuccWeights[0];
1254 }
1255 } else {
1256 // If this is not the default destination from PSI, only the edges
1257 // in SI that occur in PSI with a destination of BB will be
1258 // activated.
1259 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1260 std::map<ConstantInt *, uint64_t> WeightsForHandled;
1261 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1262 if (PredCases[i].Dest == BB) {
1263 PTIHandled.insert(PredCases[i].Value);
1264
1265 if (PredHasWeights || SuccHasWeights) {
1266 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1267 std::swap(Weights[i + 1], Weights.back());
1268 Weights.pop_back();
1269 }
1270
1271 std::swap(PredCases[i], PredCases.back());
1272 PredCases.pop_back();
1273 --i;
1274 --e;
1275 }
1276
1277 // Okay, now we know which constants were sent to BB from the
1278 // predecessor. Figure out where they will all go now.
1279 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1280 if (PTIHandled.count(BBCases[i].Value)) {
1281 // If this is one we are capable of getting...
1282 if (PredHasWeights || SuccHasWeights)
1283 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
1284 PredCases.push_back(BBCases[i]);
1285 ++NewSuccessors[BBCases[i].Dest];
1286 PTIHandled.erase(BBCases[i].Value); // This constant is taken care of
1287 }
1288
1289 // If there are any constants vectored to BB that TI doesn't handle,
1290 // they must go to the default destination of TI.
1291 for (ConstantInt *I : PTIHandled) {
1292 if (PredHasWeights || SuccHasWeights)
1293 Weights.push_back(WeightsForHandled[I]);
1294 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1295 ++NewSuccessors[BBDefault];
1296 }
1297 }
1298
1299 // Okay, at this point, we know which new successor Pred will get. Make
1300 // sure we update the number of entries in the PHI nodes for these
1301 // successors.
1302 SmallPtrSet<BasicBlock *, 2> SuccsOfPred;
1303 if (DTU) {
1304 SuccsOfPred = {succ_begin(Pred), succ_end(Pred)};
1305 Updates.reserve(Updates.size() + NewSuccessors.size());
1306 }
1307 for (const std::pair<BasicBlock *, int /*Num*/> &NewSuccessor :
1308 NewSuccessors) {
1309 for (auto I : seq(NewSuccessor.second)) {
1310 (void)I;
1311 AddPredecessorToBlock(NewSuccessor.first, Pred, BB);
1312 }
1313 if (DTU && !SuccsOfPred.contains(NewSuccessor.first))
1314 Updates.push_back({DominatorTree::Insert, Pred, NewSuccessor.first});
1315 }
1316
1317 Builder.SetInsertPoint(PTI);
1318 // Convert pointer to int before we switch.
1319 if (CV->getType()->isPointerTy()) {
1320 CV =
1321 Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), "magicptr");
1322 }
1323
1324 // Now that the successors are updated, create the new Switch instruction.
1325 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, PredCases.size());
1326 NewSI->setDebugLoc(PTI->getDebugLoc());
1327 for (ValueEqualityComparisonCase &V : PredCases)
1328 NewSI->addCase(V.Value, V.Dest);
1329
1330 if (PredHasWeights || SuccHasWeights) {
1331 // Halve the weights if any of them cannot fit in an uint32_t
1332 FitWeights(Weights);
1333
1334 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1335
1336 setBranchWeights(NewSI, MDWeights);
1337 }
1338
1340
1341 // Okay, last check. If BB is still a successor of PSI, then we must
1342 // have an infinite loop case. If so, add an infinitely looping block
1343 // to handle the case to preserve the behavior of the code.
1344 BasicBlock *InfLoopBlock = nullptr;
1345 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1346 if (NewSI->getSuccessor(i) == BB) {
1347 if (!InfLoopBlock) {
1348 // Insert it at the end of the function, because it's either code,
1349 // or it won't matter if it's hot. :)
1350 InfLoopBlock =
1351 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
1352 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1353 if (DTU)
1354 Updates.push_back(
1355 {DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
1356 }
1357 NewSI->setSuccessor(i, InfLoopBlock);
1358 }
1359
1360 if (DTU) {
1361 if (InfLoopBlock)
1362 Updates.push_back({DominatorTree::Insert, Pred, InfLoopBlock});
1363
1364 Updates.push_back({DominatorTree::Delete, Pred, BB});
1365
1366 DTU->applyUpdates(Updates);
1367 }
1368
1369 ++NumFoldValueComparisonIntoPredecessors;
1370 return true;
1371}
1372
1373/// The specified terminator is a value equality comparison instruction
1374/// (either a switch or a branch on "X == c").
1375/// See if any of the predecessors of the terminator block are value comparisons
1376/// on the same value. If so, and if safe to do so, fold them together.
1377bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(Instruction *TI,
1378 IRBuilder<> &Builder) {
1379 BasicBlock *BB = TI->getParent();
1380 Value *CV = isValueEqualityComparison(TI); // CondVal
1381 assert(CV && "Not a comparison?");
1382
1383 bool Changed = false;
1384
1386 while (!Preds.empty()) {
1387 BasicBlock *Pred = Preds.pop_back_val();
1388 Instruction *PTI = Pred->getTerminator();
1389
1390 // Don't try to fold into itself.
1391 if (Pred == BB)
1392 continue;
1393
1394 // See if the predecessor is a comparison with the same value.
1395 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
1396 if (PCV != CV)
1397 continue;
1398
1400 if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
1401 for (auto *Succ : FailBlocks) {
1402 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split", DTU))
1403 return false;
1404 }
1405 }
1406
1407 PerformValueComparisonIntoPredecessorFolding(TI, CV, PTI, Builder);
1408 Changed = true;
1409 }
1410 return Changed;
1411}
1412
1413// If we would need to insert a select that uses the value of this invoke
1414// (comments in hoistSuccIdenticalTerminatorToSwitchOrIf explain why we would
1415// need to do this), we can't hoist the invoke, as there is nowhere to put the
1416// select in this case.
1418 Instruction *I1, Instruction *I2) {
1419 for (BasicBlock *Succ : successors(BB1)) {
1420 for (const PHINode &PN : Succ->phis()) {
1421 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1422 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1423 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1424 return false;
1425 }
1426 }
1427 }
1428 return true;
1429}
1430
1431// Get interesting characteristics of instructions that
1432// `hoistCommonCodeFromSuccessors` didn't hoist. They restrict what kind of
1433// instructions can be reordered across.
1439
1441 unsigned Flags = 0;
1442 if (I->mayReadFromMemory())
1443 Flags |= SkipReadMem;
1444 // We can't arbitrarily move around allocas, e.g. moving allocas (especially
1445 // inalloca) across stacksave/stackrestore boundaries.
1446 if (I->mayHaveSideEffects() || isa<AllocaInst>(I))
1447 Flags |= SkipSideEffect;
1449 Flags |= SkipImplicitControlFlow;
1450 return Flags;
1451}
1452
1453// Returns true if it is safe to reorder an instruction across preceding
1454// instructions in a basic block.
1455static bool isSafeToHoistInstr(Instruction *I, unsigned Flags) {
1456 // Don't reorder a store over a load.
1457 if ((Flags & SkipReadMem) && I->mayWriteToMemory())
1458 return false;
1459
1460 // If we have seen an instruction with side effects, it's unsafe to reorder an
1461 // instruction which reads memory or itself has side effects.
1462 if ((Flags & SkipSideEffect) &&
1463 (I->mayReadFromMemory() || I->mayHaveSideEffects() || isa<AllocaInst>(I)))
1464 return false;
1465
1466 // Reordering across an instruction which does not necessarily transfer
1467 // control to the next instruction is speculation.
1469 return false;
1470
1471 // Hoisting of llvm.deoptimize is only legal together with the next return
1472 // instruction, which this pass is not always able to do.
1473 if (auto *CB = dyn_cast<CallBase>(I))
1474 if (CB->getIntrinsicID() == Intrinsic::experimental_deoptimize)
1475 return false;
1476
1477 // It's also unsafe/illegal to hoist an instruction above its instruction
1478 // operands
1479 BasicBlock *BB = I->getParent();
1480 for (Value *Op : I->operands()) {
1481 if (auto *J = dyn_cast<Instruction>(Op))
1482 if (J->getParent() == BB)
1483 return false;
1484 }
1485
1486 return true;
1487}
1488
1489static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified = false);
1490
1491/// Helper function for hoistCommonCodeFromSuccessors. Return true if identical
1492/// instructions \p I1 and \p I2 can and should be hoisted.
1494 const TargetTransformInfo &TTI) {
1495 // If we're going to hoist a call, make sure that the two instructions
1496 // we're commoning/hoisting are both marked with musttail, or neither of
1497 // them is marked as such. Otherwise, we might end up in a situation where
1498 // we hoist from a block where the terminator is a `ret` to a block where
1499 // the terminator is a `br`, and `musttail` calls expect to be followed by
1500 // a return.
1501 auto *C1 = dyn_cast<CallInst>(I1);
1502 auto *C2 = dyn_cast<CallInst>(I2);
1503 if (C1 && C2)
1504 if (C1->isMustTailCall() != C2->isMustTailCall())
1505 return false;
1506
1508 return false;
1509
1510 // If any of the two call sites has nomerge or convergent attribute, stop
1511 // hoisting.
1512 if (const auto *CB1 = dyn_cast<CallBase>(I1))
1513 if (CB1->cannotMerge() || CB1->isConvergent())
1514 return false;
1515 if (const auto *CB2 = dyn_cast<CallBase>(I2))
1516 if (CB2->cannotMerge() || CB2->isConvergent())
1517 return false;
1518
1519 return true;
1520}
1521
1522/// Hoist any common code in the successor blocks up into the block. This
1523/// function guarantees that BB dominates all successors. If EqTermsOnly is
1524/// given, only perform hoisting in case both blocks only contain a terminator.
1525/// In that case, only the original BI will be replaced and selects for PHIs are
1526/// added.
1527bool SimplifyCFGOpt::hoistCommonCodeFromSuccessors(BasicBlock *BB,
1528 bool EqTermsOnly) {
1529 // This does very trivial matching, with limited scanning, to find identical
1530 // instructions in the two blocks. In particular, we don't want to get into
1531 // O(N1*N2*...) situations here where Ni are the sizes of these successors. As
1532 // such, we currently just scan for obviously identical instructions in an
1533 // identical order, possibly separated by the same number of non-identical
1534 // instructions.
1535 unsigned int SuccSize = succ_size(BB);
1536 if (SuccSize < 2)
1537 return false;
1538
1539 // If either of the blocks has it's address taken, then we can't do this fold,
1540 // because the code we'd hoist would no longer run when we jump into the block
1541 // by it's address.
1542 for (auto *Succ : successors(BB))
1543 if (Succ->hasAddressTaken() || !Succ->getSinglePredecessor())
1544 return false;
1545
1546 auto *TI = BB->getTerminator();
1547
1548 // The second of pair is a SkipFlags bitmask.
1549 using SuccIterPair = std::pair<BasicBlock::iterator, unsigned>;
1550 SmallVector<SuccIterPair, 8> SuccIterPairs;
1551 for (auto *Succ : successors(BB)) {
1552 BasicBlock::iterator SuccItr = Succ->begin();
1553 if (isa<PHINode>(*SuccItr))
1554 return false;
1555 SuccIterPairs.push_back(SuccIterPair(SuccItr, 0));
1556 }
1557
1558 // Check if only hoisting terminators is allowed. This does not add new
1559 // instructions to the hoist location.
1560 if (EqTermsOnly) {
1561 // Skip any debug intrinsics, as they are free to hoist.
1562 for (auto &SuccIter : make_first_range(SuccIterPairs)) {
1563 auto *INonDbg = &*skipDebugIntrinsics(SuccIter);
1564 if (!INonDbg->isTerminator())
1565 return false;
1566 }
1567 // Now we know that we only need to hoist debug intrinsics and the
1568 // terminator. Let the loop below handle those 2 cases.
1569 }
1570
1571 // Count how many instructions were not hoisted so far. There's a limit on how
1572 // many instructions we skip, serving as a compilation time control as well as
1573 // preventing excessive increase of life ranges.
1574 unsigned NumSkipped = 0;
1575 // If we find an unreachable instruction at the beginning of a basic block, we
1576 // can still hoist instructions from the rest of the basic blocks.
1577 if (SuccIterPairs.size() > 2) {
1578 erase_if(SuccIterPairs,
1579 [](const auto &Pair) { return isa<UnreachableInst>(Pair.first); });
1580 if (SuccIterPairs.size() < 2)
1581 return false;
1582 }
1583
1584 bool Changed = false;
1585
1586 for (;;) {
1587 auto *SuccIterPairBegin = SuccIterPairs.begin();
1588 auto &BB1ItrPair = *SuccIterPairBegin++;
1589 auto OtherSuccIterPairRange =
1590 iterator_range(SuccIterPairBegin, SuccIterPairs.end());
1591 auto OtherSuccIterRange = make_first_range(OtherSuccIterPairRange);
1592
1593 Instruction *I1 = &*BB1ItrPair.first;
1594 auto *BB1 = I1->getParent();
1595
1596 // Skip debug info if it is not identical.
1597 bool AllDbgInstsAreIdentical = all_of(OtherSuccIterRange, [I1](auto &Iter) {
1598 Instruction *I2 = &*Iter;
1599 return I1->isIdenticalToWhenDefined(I2);
1600 });
1601 if (!AllDbgInstsAreIdentical) {
1602 while (isa<DbgInfoIntrinsic>(I1))
1603 I1 = &*++BB1ItrPair.first;
1604 for (auto &SuccIter : OtherSuccIterRange) {
1605 Instruction *I2 = &*SuccIter;
1606 while (isa<DbgInfoIntrinsic>(I2))
1607 I2 = &*++SuccIter;
1608 }
1609 }
1610
1611 bool AllInstsAreIdentical = true;
1612 bool HasTerminator = I1->isTerminator();
1613 for (auto &SuccIter : OtherSuccIterRange) {
1614 Instruction *I2 = &*SuccIter;
1615 HasTerminator |= I2->isTerminator();
1616 if (AllInstsAreIdentical && !I1->isIdenticalToWhenDefined(I2))
1617 AllInstsAreIdentical = false;
1618 }
1619
1620 // If we are hoisting the terminator instruction, don't move one (making a
1621 // broken BB), instead clone it, and remove BI.
1622 if (HasTerminator) {
1623 // Even if BB, which contains only one unreachable instruction, is ignored
1624 // at the beginning of the loop, we can hoist the terminator instruction.
1625 // If any instructions remain in the block, we cannot hoist terminators.
1626 if (NumSkipped || !AllInstsAreIdentical)
1627 return Changed;
1629 for (auto &SuccIter : OtherSuccIterRange)
1630 Insts.push_back(&*SuccIter);
1631 return hoistSuccIdenticalTerminatorToSwitchOrIf(TI, I1, Insts) || Changed;
1632 }
1633
1634 if (AllInstsAreIdentical) {
1635 unsigned SkipFlagsBB1 = BB1ItrPair.second;
1636 AllInstsAreIdentical =
1637 isSafeToHoistInstr(I1, SkipFlagsBB1) &&
1638 all_of(OtherSuccIterPairRange, [=](const auto &Pair) {
1639 Instruction *I2 = &*Pair.first;
1640 unsigned SkipFlagsBB2 = Pair.second;
1641 // Even if the instructions are identical, it may not
1642 // be safe to hoist them if we have skipped over
1643 // instructions with side effects or their operands
1644 // weren't hoisted.
1645 return isSafeToHoistInstr(I2, SkipFlagsBB2) &&
1647 });
1648 }
1649
1650 if (AllInstsAreIdentical) {
1651 BB1ItrPair.first++;
1652 if (isa<DbgInfoIntrinsic>(I1)) {
1653 // The debug location is an integral part of a debug info intrinsic
1654 // and can't be separated from it or replaced. Instead of attempting
1655 // to merge locations, simply hoist both copies of the intrinsic.
1656 I1->moveBeforePreserving(TI);
1657 for (auto &SuccIter : OtherSuccIterRange) {
1658 auto *I2 = &*SuccIter++;
1659 assert(isa<DbgInfoIntrinsic>(I2));
1660 I2->moveBeforePreserving(TI);
1661 }
1662 } else {
1663 // For a normal instruction, we just move one to right before the
1664 // branch, then replace all uses of the other with the first. Finally,
1665 // we remove the now redundant second instruction.
1666 I1->moveBeforePreserving(TI);
1667 BB->splice(TI->getIterator(), BB1, I1->getIterator());
1668 for (auto &SuccIter : OtherSuccIterRange) {
1669 Instruction *I2 = &*SuccIter++;
1670 assert(I2 != I1);
1671 if (!I2->use_empty())
1672 I2->replaceAllUsesWith(I1);
1673 I1->andIRFlags(I2);
1674 combineMetadataForCSE(I1, I2, true);
1675 // I1 and I2 are being combined into a single instruction. Its debug
1676 // location is the merged locations of the original instructions.
1677 I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
1678 I2->eraseFromParent();
1679 }
1680 }
1681 if (!Changed)
1682 NumHoistCommonCode += SuccIterPairs.size();
1683 Changed = true;
1684 NumHoistCommonInstrs += SuccIterPairs.size();
1685 } else {
1686 if (NumSkipped >= HoistCommonSkipLimit)
1687 return Changed;
1688 // We are about to skip over a pair of non-identical instructions. Record
1689 // if any have characteristics that would prevent reordering instructions
1690 // across them.
1691 for (auto &SuccIterPair : SuccIterPairs) {
1692 Instruction *I = &*SuccIterPair.first++;
1693 SuccIterPair.second |= skippedInstrFlags(I);
1694 }
1695 ++NumSkipped;
1696 }
1697 }
1698}
1699
1700bool SimplifyCFGOpt::hoistSuccIdenticalTerminatorToSwitchOrIf(
1701 Instruction *TI, Instruction *I1,
1702 SmallVectorImpl<Instruction *> &OtherSuccTIs) {
1703
1704 auto *BI = dyn_cast<BranchInst>(TI);
1705
1706 bool Changed = false;
1707 BasicBlock *TIParent = TI->getParent();
1708 BasicBlock *BB1 = I1->getParent();
1709
1710 // Use only for an if statement.
1711 auto *I2 = *OtherSuccTIs.begin();
1712 auto *BB2 = I2->getParent();
1713 if (BI) {
1714 assert(OtherSuccTIs.size() == 1);
1715 assert(BI->getSuccessor(0) == I1->getParent());
1716 assert(BI->getSuccessor(1) == I2->getParent());
1717 }
1718
1719 // In the case of an if statement, we try to hoist an invoke.
1720 // FIXME: Can we define a safety predicate for CallBr?
1721 // FIXME: Test case llvm/test/Transforms/SimplifyCFG/2009-06-15-InvokeCrash.ll
1722 // removed in 4c923b3b3fd0ac1edebf0603265ca3ba51724937 commit?
1723 if (isa<InvokeInst>(I1) && (!BI || !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
1724 return false;
1725
1726 // TODO: callbr hoisting currently disabled pending further study.
1727 if (isa<CallBrInst>(I1))
1728 return false;
1729
1730 for (BasicBlock *Succ : successors(BB1)) {
1731 for (PHINode &PN : Succ->phis()) {
1732 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1733 for (Instruction *OtherSuccTI : OtherSuccTIs) {
1734 Value *BB2V = PN.getIncomingValueForBlock(OtherSuccTI->getParent());
1735 if (BB1V == BB2V)
1736 continue;
1737
1738 // In the case of an if statement, check for
1739 // passingValueIsAlwaysUndefined here because we would rather eliminate
1740 // undefined control flow then converting it to a select.
1741 if (!BI || passingValueIsAlwaysUndefined(BB1V, &PN) ||
1743 return false;
1744 }
1745 }
1746 }
1747
1748 // Okay, it is safe to hoist the terminator.
1749 Instruction *NT = I1->clone();
1750 NT->insertInto(TIParent, TI->getIterator());
1751 if (!NT->getType()->isVoidTy()) {
1752 I1->replaceAllUsesWith(NT);
1753 for (Instruction *OtherSuccTI : OtherSuccTIs)
1754 OtherSuccTI->replaceAllUsesWith(NT);
1755 NT->takeName(I1);
1756 }
1757 Changed = true;
1758 NumHoistCommonInstrs += OtherSuccTIs.size() + 1;
1759
1760 // Ensure terminator gets a debug location, even an unknown one, in case
1761 // it involves inlinable calls.
1763 Locs.push_back(I1->getDebugLoc());
1764 for (auto *OtherSuccTI : OtherSuccTIs)
1765 Locs.push_back(OtherSuccTI->getDebugLoc());
1766 NT->setDebugLoc(DILocation::getMergedLocations(Locs));
1767
1768 // PHIs created below will adopt NT's merged DebugLoc.
1770
1771 // In the case of an if statement, hoisting one of the terminators from our
1772 // successor is a great thing. Unfortunately, the successors of the if/else
1773 // blocks may have PHI nodes in them. If they do, all PHI entries for BB1/BB2
1774 // must agree for all PHI nodes, so we insert select instruction to compute
1775 // the final result.
1776 if (BI) {
1777 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
1778 for (BasicBlock *Succ : successors(BB1)) {
1779 for (PHINode &PN : Succ->phis()) {
1780 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1781 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1782 if (BB1V == BB2V)
1783 continue;
1784
1785 // These values do not agree. Insert a select instruction before NT
1786 // that determines the right value.
1787 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1788 if (!SI) {
1789 // Propagate fast-math-flags from phi node to its replacement select.
1790 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
1791 if (isa<FPMathOperator>(PN))
1792 Builder.setFastMathFlags(PN.getFastMathFlags());
1793
1794 SI = cast<SelectInst>(Builder.CreateSelect(
1795 BI->getCondition(), BB1V, BB2V,
1796 BB1V->getName() + "." + BB2V->getName(), BI));
1797 }
1798
1799 // Make the PHI node use the select for all incoming values for BB1/BB2
1800 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1801 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
1802 PN.setIncomingValue(i, SI);
1803 }
1804 }
1805 }
1806
1808
1809 // Update any PHI nodes in our new successors.
1810 for (BasicBlock *Succ : successors(BB1)) {
1811 AddPredecessorToBlock(Succ, TIParent, BB1);
1812 if (DTU)
1813 Updates.push_back({DominatorTree::Insert, TIParent, Succ});
1814 }
1815
1816 if (DTU)
1817 for (BasicBlock *Succ : successors(TI))
1818 Updates.push_back({DominatorTree::Delete, TIParent, Succ});
1819
1821 if (DTU)
1822 DTU->applyUpdates(Updates);
1823 return Changed;
1824}
1825
1826// Check lifetime markers.
1827static bool isLifeTimeMarker(const Instruction *I) {
1828 if (auto II = dyn_cast<IntrinsicInst>(I)) {
1829 switch (II->getIntrinsicID()) {
1830 default:
1831 break;
1832 case Intrinsic::lifetime_start:
1833 case Intrinsic::lifetime_end:
1834 return true;
1835 }
1836 }
1837 return false;
1838}
1839
1840// TODO: Refine this. This should avoid cases like turning constant memcpy sizes
1841// into variables.
1843 int OpIdx) {
1844 return !isa<IntrinsicInst>(I);
1845}
1846
1847// All instructions in Insts belong to different blocks that all unconditionally
1848// branch to a common successor. Analyze each instruction and return true if it
1849// would be possible to sink them into their successor, creating one common
1850// instruction instead. For every value that would be required to be provided by
1851// PHI node (because an operand varies in each input block), add to PHIOperands.
1854 DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
1855 // Prune out obviously bad instructions to move. Each instruction must have
1856 // exactly zero or one use, and we check later that use is by a single, common
1857 // PHI instruction in the successor.
1858 bool HasUse = !Insts.front()->user_empty();
1859 for (auto *I : Insts) {
1860 // These instructions may change or break semantics if moved.
1861 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
1862 I->getType()->isTokenTy())
1863 return false;
1864
1865 // Do not try to sink an instruction in an infinite loop - it can cause
1866 // this algorithm to infinite loop.
1867 if (I->getParent()->getSingleSuccessor() == I->getParent())
1868 return false;
1869
1870 // Conservatively return false if I is an inline-asm instruction. Sinking
1871 // and merging inline-asm instructions can potentially create arguments
1872 // that cannot satisfy the inline-asm constraints.
1873 // If the instruction has nomerge or convergent attribute, return false.
1874 if (const auto *C = dyn_cast<CallBase>(I))
1875 if (C->isInlineAsm() || C->cannotMerge() || C->isConvergent())
1876 return false;
1877
1878 // Each instruction must have zero or one use.
1879 if (HasUse && !I->hasOneUse())
1880 return false;
1881 if (!HasUse && !I->user_empty())
1882 return false;
1883 }
1884
1885 const Instruction *I0 = Insts.front();
1886 for (auto *I : Insts) {
1887 if (!I->isSameOperationAs(I0))
1888 return false;
1889
1890 // swifterror pointers can only be used by a load or store; sinking a load
1891 // or store would require introducing a select for the pointer operand,
1892 // which isn't allowed for swifterror pointers.
1893 if (isa<StoreInst>(I) && I->getOperand(1)->isSwiftError())
1894 return false;
1895 if (isa<LoadInst>(I) && I->getOperand(0)->isSwiftError())
1896 return false;
1897 }
1898
1899 // All instructions in Insts are known to be the same opcode. If they have a
1900 // use, check that the only user is a PHI or in the same block as the
1901 // instruction, because if a user is in the same block as an instruction we're
1902 // contemplating sinking, it must already be determined to be sinkable.
1903 if (HasUse) {
1904 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1905 auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
1906 if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
1907 auto *U = cast<Instruction>(*I->user_begin());
1908 return (PNUse &&
1909 PNUse->getParent() == Succ &&
1910 PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
1911 U->getParent() == I->getParent();
1912 }))
1913 return false;
1914 }
1915
1916 // Because SROA can't handle speculating stores of selects, try not to sink
1917 // loads, stores or lifetime markers of allocas when we'd have to create a
1918 // PHI for the address operand. Also, because it is likely that loads or
1919 // stores of allocas will disappear when Mem2Reg/SROA is run, don't sink
1920 // them.
1921 // This can cause code churn which can have unintended consequences down
1922 // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244.
1923 // FIXME: This is a workaround for a deficiency in SROA - see
1924 // https://llvm.org/bugs/show_bug.cgi?id=30188
1925 if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
1926 return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
1927 }))
1928 return false;
1929 if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
1930 return isa<AllocaInst>(I->getOperand(0)->stripPointerCasts());
1931 }))
1932 return false;
1933 if (isLifeTimeMarker(I0) && any_of(Insts, [](const Instruction *I) {
1934 return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
1935 }))
1936 return false;
1937
1938 // For calls to be sinkable, they must all be indirect, or have same callee.
1939 // I.e. if we have two direct calls to different callees, we don't want to
1940 // turn that into an indirect call. Likewise, if we have an indirect call,
1941 // and a direct call, we don't actually want to have a single indirect call.
1942 if (isa<CallBase>(I0)) {
1943 auto IsIndirectCall = [](const Instruction *I) {
1944 return cast<CallBase>(I)->isIndirectCall();
1945 };
1946 bool HaveIndirectCalls = any_of(Insts, IsIndirectCall);
1947 bool AllCallsAreIndirect = all_of(Insts, IsIndirectCall);
1948 if (HaveIndirectCalls) {
1949 if (!AllCallsAreIndirect)
1950 return false;
1951 } else {
1952 // All callees must be identical.
1953 Value *Callee = nullptr;
1954 for (const Instruction *I : Insts) {
1955 Value *CurrCallee = cast<CallBase>(I)->getCalledOperand();
1956 if (!Callee)
1957 Callee = CurrCallee;
1958 else if (Callee != CurrCallee)
1959 return false;
1960 }
1961 }
1962 }
1963
1964 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
1965 Value *Op = I0->getOperand(OI);
1966 if (Op->getType()->isTokenTy())
1967 // Don't touch any operand of token type.
1968 return false;
1969
1970 auto SameAsI0 = [&I0, OI](const Instruction *I) {
1971 assert(I->getNumOperands() == I0->getNumOperands());
1972 return I->getOperand(OI) == I0->getOperand(OI);
1973 };
1974 if (!all_of(Insts, SameAsI0)) {
1975 if ((isa<Constant>(Op) && !replacingOperandWithVariableIsCheap(I0, OI)) ||
1977 // We can't create a PHI from this GEP.
1978 return false;
1979 for (auto *I : Insts)
1980 PHIOperands[I].push_back(I->getOperand(OI));
1981 }
1982 }
1983 return true;
1984}
1985
1986// Assuming canSinkInstructions(Blocks) has returned true, sink the last
1987// instruction of every block in Blocks to their common successor, commoning
1988// into one instruction.
1990 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1991
1992 // canSinkInstructions returning true guarantees that every block has at
1993 // least one non-terminator instruction.
1995 for (auto *BB : Blocks) {
1996 Instruction *I = BB->getTerminator();
1997 do {
1998 I = I->getPrevNode();
1999 } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
2000 if (!isa<DbgInfoIntrinsic>(I))
2001 Insts.push_back(I);
2002 }
2003
2004 // The only checking we need to do now is that all users of all instructions
2005 // are the same PHI node. canSinkInstructions should have checked this but
2006 // it is slightly over-aggressive - it gets confused by commutative
2007 // instructions so double-check it here.
2008 Instruction *I0 = Insts.front();
2009 if (!I0->user_empty()) {
2010 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
2011 if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
2012 auto *U = cast<Instruction>(*I->user_begin());
2013 return U == PNUse;
2014 }))
2015 return false;
2016 }
2017
2018 // We don't need to do any more checking here; canSinkInstructions should
2019 // have done it all for us.
2020 SmallVector<Value*, 4> NewOperands;
2021 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
2022 // This check is different to that in canSinkInstructions. There, we
2023 // cared about the global view once simplifycfg (and instcombine) have
2024 // completed - it takes into account PHIs that become trivially
2025 // simplifiable. However here we need a more local view; if an operand
2026 // differs we create a PHI and rely on instcombine to clean up the very
2027 // small mess we may make.
2028 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
2029 return I->getOperand(O) != I0->getOperand(O);
2030 });
2031 if (!NeedPHI) {
2032 NewOperands.push_back(I0->getOperand(O));
2033 continue;
2034 }
2035
2036 // Create a new PHI in the successor block and populate it.
2037 auto *Op = I0->getOperand(O);
2038 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
2039 auto *PN =
2040 PHINode::Create(Op->getType(), Insts.size(), Op->getName() + ".sink");
2041 PN->insertBefore(BBEnd->begin());
2042 for (auto *I : Insts)
2043 PN->addIncoming(I->getOperand(O), I->getParent());
2044 NewOperands.push_back(PN);
2045 }
2046
2047 // Arbitrarily use I0 as the new "common" instruction; remap its operands
2048 // and move it to the start of the successor block.
2049 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
2050 I0->getOperandUse(O).set(NewOperands[O]);
2051
2052 I0->moveBefore(*BBEnd, BBEnd->getFirstInsertionPt());
2053
2054 // Update metadata and IR flags, and merge debug locations.
2055 for (auto *I : Insts)
2056 if (I != I0) {
2057 // The debug location for the "common" instruction is the merged locations
2058 // of all the commoned instructions. We start with the original location
2059 // of the "common" instruction and iteratively merge each location in the
2060 // loop below.
2061 // This is an N-way merge, which will be inefficient if I0 is a CallInst.
2062 // However, as N-way merge for CallInst is rare, so we use simplified API
2063 // instead of using complex API for N-way merge.
2064 I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
2065 combineMetadataForCSE(I0, I, true);
2066 I0->andIRFlags(I);
2067 }
2068
2069 if (!I0->user_empty()) {
2070 // canSinkLastInstruction checked that all instructions were used by
2071 // one and only one PHI node. Find that now, RAUW it to our common
2072 // instruction and nuke it.
2073 auto *PN = cast<PHINode>(*I0->user_begin());
2074 PN->replaceAllUsesWith(I0);
2075 PN->eraseFromParent();
2076 }
2077
2078 // Finally nuke all instructions apart from the common instruction.
2079 for (auto *I : Insts) {
2080 if (I == I0)
2081 continue;
2082 // The remaining uses are debug users, replace those with the common inst.
2083 // In most (all?) cases this just introduces a use-before-def.
2084 assert(I->user_empty() && "Inst unexpectedly still has non-dbg users");
2085 I->replaceAllUsesWith(I0);
2086 I->eraseFromParent();
2087 }
2088
2089 return true;
2090}
2091
2092namespace {
2093
2094 // LockstepReverseIterator - Iterates through instructions
2095 // in a set of blocks in reverse order from the first non-terminator.
2096 // For example (assume all blocks have size n):
2097 // LockstepReverseIterator I([B1, B2, B3]);
2098 // *I-- = [B1[n], B2[n], B3[n]];
2099 // *I-- = [B1[n-1], B2[n-1], B3[n-1]];
2100 // *I-- = [B1[n-2], B2[n-2], B3[n-2]];
2101 // ...
2102 class LockstepReverseIterator {
2105 bool Fail;
2106
2107 public:
2108 LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) {
2109 reset();
2110 }
2111
2112 void reset() {
2113 Fail = false;
2114 Insts.clear();
2115 for (auto *BB : Blocks) {
2116 Instruction *Inst = BB->getTerminator();
2117 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
2118 Inst = Inst->getPrevNode();
2119 if (!Inst) {
2120 // Block wasn't big enough.
2121 Fail = true;
2122 return;
2123 }
2124 Insts.push_back(Inst);
2125 }
2126 }
2127
2128 bool isValid() const {
2129 return !Fail;
2130 }
2131
2132 void operator--() {
2133 if (Fail)
2134 return;
2135 for (auto *&Inst : Insts) {
2136 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
2137 Inst = Inst->getPrevNode();
2138 // Already at beginning of block.
2139 if (!Inst) {
2140 Fail = true;
2141 return;
2142 }
2143 }
2144 }
2145
2146 void operator++() {
2147 if (Fail)
2148 return;
2149 for (auto *&Inst : Insts) {
2150 for (Inst = Inst->getNextNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
2151 Inst = Inst->getNextNode();
2152 // Already at end of block.
2153 if (!Inst) {
2154 Fail = true;
2155 return;
2156 }
2157 }
2158 }
2159
2161 return Insts;
2162 }
2163 };
2164
2165} // end anonymous namespace
2166
2167/// Check whether BB's predecessors end with unconditional branches. If it is
2168/// true, sink any common code from the predecessors to BB.
2170 DomTreeUpdater *DTU) {
2171 // We support two situations:
2172 // (1) all incoming arcs are unconditional
2173 // (2) there are non-unconditional incoming arcs
2174 //
2175 // (2) is very common in switch defaults and
2176 // else-if patterns;
2177 //
2178 // if (a) f(1);
2179 // else if (b) f(2);
2180 //
2181 // produces:
2182 //
2183 // [if]
2184 // / \
2185 // [f(1)] [if]
2186 // | | \
2187 // | | |
2188 // | [f(2)]|
2189 // \ | /
2190 // [ end ]
2191 //
2192 // [end] has two unconditional predecessor arcs and one conditional. The
2193 // conditional refers to the implicit empty 'else' arc. This conditional
2194 // arc can also be caused by an empty default block in a switch.
2195 //
2196 // In this case, we attempt to sink code from all *unconditional* arcs.
2197 // If we can sink instructions from these arcs (determined during the scan
2198 // phase below) we insert a common successor for all unconditional arcs and
2199 // connect that to [end], to enable sinking:
2200 //
2201 // [if]
2202 // / \
2203 // [x(1)] [if]
2204 // | | \
2205 // | | \
2206 // | [x(2)] |
2207 // \ / |
2208 // [sink.split] |
2209 // \ /
2210 // [ end ]
2211 //
2212 SmallVector<BasicBlock*,4> UnconditionalPreds;
2213 bool HaveNonUnconditionalPredecessors = false;
2214 for (auto *PredBB : predecessors(BB)) {
2215 auto *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
2216 if (PredBr && PredBr->isUnconditional())
2217 UnconditionalPreds.push_back(PredBB);
2218 else
2219 HaveNonUnconditionalPredecessors = true;
2220 }
2221 if (UnconditionalPreds.size() < 2)
2222 return false;
2223
2224 // We take a two-step approach to tail sinking. First we scan from the end of
2225 // each block upwards in lockstep. If the n'th instruction from the end of each
2226 // block can be sunk, those instructions are added to ValuesToSink and we
2227 // carry on. If we can sink an instruction but need to PHI-merge some operands
2228 // (because they're not identical in each instruction) we add these to
2229 // PHIOperands.
2230 int ScanIdx = 0;
2231 SmallPtrSet<Value*,4> InstructionsToSink;
2233 LockstepReverseIterator LRI(UnconditionalPreds);
2234 while (LRI.isValid() &&
2235 canSinkInstructions(*LRI, PHIOperands)) {
2236 LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
2237 << "\n");
2238 InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
2239 ++ScanIdx;
2240 --LRI;
2241 }
2242
2243 // If no instructions can be sunk, early-return.
2244 if (ScanIdx == 0)
2245 return false;
2246
2247 bool followedByDeoptOrUnreachable = IsBlockFollowedByDeoptOrUnreachable(BB);
2248
2249 if (!followedByDeoptOrUnreachable) {
2250 // Okay, we *could* sink last ScanIdx instructions. But how many can we
2251 // actually sink before encountering instruction that is unprofitable to
2252 // sink?
2253 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
2254 unsigned NumPHIdValues = 0;
2255 for (auto *I : *LRI)
2256 for (auto *V : PHIOperands[I]) {
2257 if (!InstructionsToSink.contains(V))
2258 ++NumPHIdValues;
2259 // FIXME: this check is overly optimistic. We may end up not sinking
2260 // said instruction, due to the very same profitability check.
2261 // See @creating_too_many_phis in sink-common-code.ll.
2262 }
2263 LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
2264 unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
2265 if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
2266 NumPHIInsts++;
2267
2268 return NumPHIInsts <= 1;
2269 };
2270
2271 // We've determined that we are going to sink last ScanIdx instructions,
2272 // and recorded them in InstructionsToSink. Now, some instructions may be
2273 // unprofitable to sink. But that determination depends on the instructions
2274 // that we are going to sink.
2275
2276 // First, forward scan: find the first instruction unprofitable to sink,
2277 // recording all the ones that are profitable to sink.
2278 // FIXME: would it be better, after we detect that not all are profitable.
2279 // to either record the profitable ones, or erase the unprofitable ones?
2280 // Maybe we need to choose (at runtime) the one that will touch least
2281 // instrs?
2282 LRI.reset();
2283 int Idx = 0;
2284 SmallPtrSet<Value *, 4> InstructionsProfitableToSink;
2285 while (Idx < ScanIdx) {
2286 if (!ProfitableToSinkInstruction(LRI)) {
2287 // Too many PHIs would be created.
2288 LLVM_DEBUG(
2289 dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
2290 break;
2291 }
2292 InstructionsProfitableToSink.insert((*LRI).begin(), (*LRI).end());
2293 --LRI;
2294 ++Idx;
2295 }
2296
2297 // If no instructions can be sunk, early-return.
2298 if (Idx == 0)
2299 return false;
2300
2301 // Did we determine that (only) some instructions are unprofitable to sink?
2302 if (Idx < ScanIdx) {
2303 // Okay, some instructions are unprofitable.
2304 ScanIdx = Idx;
2305 InstructionsToSink = InstructionsProfitableToSink;
2306
2307 // But, that may make other instructions unprofitable, too.
2308 // So, do a backward scan, do any earlier instructions become
2309 // unprofitable?
2310 assert(
2311 !ProfitableToSinkInstruction(LRI) &&
2312 "We already know that the last instruction is unprofitable to sink");
2313 ++LRI;
2314 --Idx;
2315 while (Idx >= 0) {
2316 // If we detect that an instruction becomes unprofitable to sink,
2317 // all earlier instructions won't be sunk either,
2318 // so preemptively keep InstructionsProfitableToSink in sync.
2319 // FIXME: is this the most performant approach?
2320 for (auto *I : *LRI)
2321 InstructionsProfitableToSink.erase(I);
2322 if (!ProfitableToSinkInstruction(LRI)) {
2323 // Everything starting with this instruction won't be sunk.
2324 ScanIdx = Idx;
2325 InstructionsToSink = InstructionsProfitableToSink;
2326 }
2327 ++LRI;
2328 --Idx;
2329 }
2330 }
2331
2332 // If no instructions can be sunk, early-return.
2333 if (ScanIdx == 0)
2334 return false;
2335 }
2336
2337 bool Changed = false;
2338
2339 if (HaveNonUnconditionalPredecessors) {
2340 if (!followedByDeoptOrUnreachable) {
2341 // It is always legal to sink common instructions from unconditional
2342 // predecessors. However, if not all predecessors are unconditional,
2343 // this transformation might be pessimizing. So as a rule of thumb,
2344 // don't do it unless we'd sink at least one non-speculatable instruction.
2345 // See https://bugs.llvm.org/show_bug.cgi?id=30244
2346 LRI.reset();
2347 int Idx = 0;
2348 bool Profitable = false;
2349 while (Idx < ScanIdx) {
2350 if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
2351 Profitable = true;
2352 break;
2353 }
2354 --LRI;
2355 ++Idx;
2356 }
2357 if (!Profitable)
2358 return false;
2359 }
2360
2361 LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
2362 // We have a conditional edge and we're going to sink some instructions.
2363 // Insert a new block postdominating all blocks we're going to sink from.
2364 if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split", DTU))
2365 // Edges couldn't be split.
2366 return false;
2367 Changed = true;
2368 }
2369
2370 // Now that we've analyzed all potential sinking candidates, perform the
2371 // actual sink. We iteratively sink the last non-terminator of the source
2372 // blocks into their common successor unless doing so would require too
2373 // many PHI instructions to be generated (currently only one PHI is allowed
2374 // per sunk instruction).
2375 //
2376 // We can use InstructionsToSink to discount values needing PHI-merging that will
2377 // actually be sunk in a later iteration. This allows us to be more
2378 // aggressive in what we sink. This does allow a false positive where we
2379 // sink presuming a later value will also be sunk, but stop half way through
2380 // and never actually sink it which means we produce more PHIs than intended.
2381 // This is unlikely in practice though.
2382 int SinkIdx = 0;
2383 for (; SinkIdx != ScanIdx; ++SinkIdx) {
2384 LLVM_DEBUG(dbgs() << "SINK: Sink: "
2385 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
2386 << "\n");
2387
2388 // Because we've sunk every instruction in turn, the current instruction to
2389 // sink is always at index 0.
2390 LRI.reset();
2391
2392 if (!sinkLastInstruction(UnconditionalPreds)) {
2393 LLVM_DEBUG(
2394 dbgs()
2395 << "SINK: stopping here, failed to actually sink instruction!\n");
2396 break;
2397 }
2398
2399 NumSinkCommonInstrs++;
2400 Changed = true;
2401 }
2402 if (SinkIdx != 0)
2403 ++NumSinkCommonCode;
2404 return Changed;
2405}
2406
2407namespace {
2408
2409struct CompatibleSets {
2410 using SetTy = SmallVector<InvokeInst *, 2>;
2411
2413
2414 static bool shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes);
2415
2416 SetTy &getCompatibleSet(InvokeInst *II);
2417
2418 void insert(InvokeInst *II);
2419};
2420
2421CompatibleSets::SetTy &CompatibleSets::getCompatibleSet(InvokeInst *II) {
2422 // Perform a linear scan over all the existing sets, see if the new `invoke`
2423 // is compatible with any particular set. Since we know that all the `invokes`
2424 // within a set are compatible, only check the first `invoke` in each set.
2425 // WARNING: at worst, this has quadratic complexity.
2426 for (CompatibleSets::SetTy &Set : Sets) {
2427 if (CompatibleSets::shouldBelongToSameSet({Set.front(), II}))
2428 return Set;
2429 }
2430
2431 // Otherwise, we either had no sets yet, or this invoke forms a new set.
2432 return Sets.emplace_back();
2433}
2434
2435void CompatibleSets::insert(InvokeInst *II) {
2436 getCompatibleSet(II).emplace_back(II);
2437}
2438
2439bool CompatibleSets::shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes) {
2440 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2441
2442 // Can we theoretically merge these `invoke`s?
2443 auto IsIllegalToMerge = [](InvokeInst *II) {
2444 return II->cannotMerge() || II->isInlineAsm();
2445 };
2446 if (any_of(Invokes, IsIllegalToMerge))
2447 return false;
2448
2449 // Either both `invoke`s must be direct,
2450 // or both `invoke`s must be indirect.
2451 auto IsIndirectCall = [](InvokeInst *II) { return II->isIndirectCall(); };
2452 bool HaveIndirectCalls = any_of(Invokes, IsIndirectCall);
2453 bool AllCallsAreIndirect = all_of(Invokes, IsIndirectCall);
2454 if (HaveIndirectCalls) {
2455 if (!AllCallsAreIndirect)
2456 return false;
2457 } else {
2458 // All callees must be identical.
2459 Value *Callee = nullptr;
2460 for (InvokeInst *II : Invokes) {
2461 Value *CurrCallee = II->getCalledOperand();
2462 assert(CurrCallee && "There is always a called operand.");
2463 if (!Callee)
2464 Callee = CurrCallee;
2465 else if (Callee != CurrCallee)
2466 return false;
2467 }
2468 }
2469
2470 // Either both `invoke`s must not have a normal destination,
2471 // or both `invoke`s must have a normal destination,
2472 auto HasNormalDest = [](InvokeInst *II) {
2473 return !isa<UnreachableInst>(II->getNormalDest()->getFirstNonPHIOrDbg());
2474 };
2475 if (any_of(Invokes, HasNormalDest)) {
2476 // Do not merge `invoke` that does not have a normal destination with one
2477 // that does have a normal destination, even though doing so would be legal.
2478 if (!all_of(Invokes, HasNormalDest))
2479 return false;
2480
2481 // All normal destinations must be identical.
2482 BasicBlock *NormalBB = nullptr;
2483 for (InvokeInst *II : Invokes) {
2484 BasicBlock *CurrNormalBB = II->getNormalDest();
2485 assert(CurrNormalBB && "There is always a 'continue to' basic block.");
2486 if (!NormalBB)
2487 NormalBB = CurrNormalBB;
2488 else if (NormalBB != CurrNormalBB)
2489 return false;
2490 }
2491
2492 // In the normal destination, the incoming values for these two `invoke`s
2493 // must be compatible.
2494 SmallPtrSet<Value *, 16> EquivalenceSet(Invokes.begin(), Invokes.end());
2496 NormalBB, {Invokes[0]->getParent(), Invokes[1]->getParent()},
2497 &EquivalenceSet))
2498 return false;
2499 }
2500
2501#ifndef NDEBUG
2502 // All unwind destinations must be identical.
2503 // We know that because we have started from said unwind destination.
2504 BasicBlock *UnwindBB = nullptr;
2505 for (InvokeInst *II : Invokes) {
2506 BasicBlock *CurrUnwindBB = II->getUnwindDest();
2507 assert(CurrUnwindBB && "There is always an 'unwind to' basic block.");
2508 if (!UnwindBB)
2509 UnwindBB = CurrUnwindBB;
2510 else
2511 assert(UnwindBB == CurrUnwindBB && "Unexpected unwind destination.");
2512 }
2513#endif
2514
2515 // In the unwind destination, the incoming values for these two `invoke`s
2516 // must be compatible.
2518 Invokes.front()->getUnwindDest(),
2519 {Invokes[0]->getParent(), Invokes[1]->getParent()}))
2520 return false;
2521
2522 // Ignoring arguments, these `invoke`s must be identical,
2523 // including operand bundles.
2524 const InvokeInst *II0 = Invokes.front();
2525 for (auto *II : Invokes.drop_front())
2526 if (!II->isSameOperationAs(II0))
2527 return false;
2528
2529 // Can we theoretically form the data operands for the merged `invoke`?
2530 auto IsIllegalToMergeArguments = [](auto Ops) {
2531 Use &U0 = std::get<0>(Ops);
2532 Use &U1 = std::get<1>(Ops);
2533 if (U0 == U1)
2534 return false;
2535 return U0->getType()->isTokenTy() ||
2536 !canReplaceOperandWithVariable(cast<Instruction>(U0.getUser()),
2537 U0.getOperandNo());
2538 };
2539 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2540 if (any_of(zip(Invokes[0]->data_ops(), Invokes[1]->data_ops()),
2541 IsIllegalToMergeArguments))
2542 return false;
2543
2544 return true;
2545}
2546
2547} // namespace
2548
2549// Merge all invokes in the provided set, all of which are compatible
2550// as per the `CompatibleSets::shouldBelongToSameSet()`.
2552 DomTreeUpdater *DTU) {
2553 assert(Invokes.size() >= 2 && "Must have at least two invokes to merge.");
2554
2556 if (DTU)
2557 Updates.reserve(2 + 3 * Invokes.size());
2558
2559 bool HasNormalDest =
2560 !isa<UnreachableInst>(Invokes[0]->getNormalDest()->getFirstNonPHIOrDbg());
2561
2562 // Clone one of the invokes into a new basic block.
2563 // Since they are all compatible, it doesn't matter which invoke is cloned.
2564 InvokeInst *MergedInvoke = [&Invokes, HasNormalDest]() {
2565 InvokeInst *II0 = Invokes.front();
2566 BasicBlock *II0BB = II0->getParent();
2567 BasicBlock *InsertBeforeBlock =
2568 II0->getParent()->getIterator()->getNextNode();
2569 Function *Func = II0BB->getParent();
2570 LLVMContext &Ctx = II0->getContext();
2571
2572 BasicBlock *MergedInvokeBB = BasicBlock::Create(
2573 Ctx, II0BB->getName() + ".invoke", Func, InsertBeforeBlock);
2574
2575 auto *MergedInvoke = cast<InvokeInst>(II0->clone());
2576 // NOTE: all invokes have the same attributes, so no handling needed.
2577 MergedInvoke->insertInto(MergedInvokeBB, MergedInvokeBB->end());
2578
2579 if (!HasNormalDest) {
2580 // This set does not have a normal destination,
2581 // so just form a new block with unreachable terminator.
2582 BasicBlock *MergedNormalDest = BasicBlock::Create(
2583 Ctx, II0BB->getName() + ".cont", Func, InsertBeforeBlock);
2584 new UnreachableInst(Ctx, MergedNormalDest);
2585 MergedInvoke->setNormalDest(MergedNormalDest);
2586 }
2587
2588 // The unwind destination, however, remainds identical for all invokes here.
2589
2590 return MergedInvoke;
2591 }();
2592
2593 if (DTU) {
2594 // Predecessor blocks that contained these invokes will now branch to
2595 // the new block that contains the merged invoke, ...
2596 for (InvokeInst *II : Invokes)
2597 Updates.push_back(
2598 {DominatorTree::Insert, II->getParent(), MergedInvoke->getParent()});
2599
2600 // ... which has the new `unreachable` block as normal destination,
2601 // or unwinds to the (same for all `invoke`s in this set) `landingpad`,
2602 for (BasicBlock *SuccBBOfMergedInvoke : successors(MergedInvoke))
2603 Updates.push_back({DominatorTree::Insert, MergedInvoke->getParent(),
2604 SuccBBOfMergedInvoke});
2605
2606 // Since predecessor blocks now unconditionally branch to a new block,
2607 // they no longer branch to their original successors.
2608 for (InvokeInst *II : Invokes)
2609 for (BasicBlock *SuccOfPredBB : successors(II->getParent()))
2610 Updates.push_back(
2611 {DominatorTree::Delete, II->getParent(), SuccOfPredBB});
2612 }
2613
2614 bool IsIndirectCall = Invokes[0]->isIndirectCall();
2615
2616 // Form the merged operands for the merged invoke.
2617 for (Use &U : MergedInvoke->operands()) {
2618 // Only PHI together the indirect callees and data operands.
2619 if (MergedInvoke->isCallee(&U)) {
2620 if (!IsIndirectCall)
2621 continue;
2622 } else if (!MergedInvoke->isDataOperand(&U))
2623 continue;
2624
2625 // Don't create trivial PHI's with all-identical incoming values.
2626 bool NeedPHI = any_of(Invokes, [&U](InvokeInst *II) {
2627 return II->getOperand(U.getOperandNo()) != U.get();
2628 });
2629 if (!NeedPHI)
2630 continue;
2631
2632 // Form a PHI out of all the data ops under this index.
2634 U->getType(), /*NumReservedValues=*/Invokes.size(), "", MergedInvoke);
2635 for (InvokeInst *II : Invokes)
2636 PN->addIncoming(II->getOperand(U.getOperandNo()), II->getParent());
2637
2638 U.set(PN);
2639 }
2640
2641 // We've ensured that each PHI node has compatible (identical) incoming values
2642 // when coming from each of the `invoke`s in the current merge set,
2643 // so update the PHI nodes accordingly.
2644 for (BasicBlock *Succ : successors(MergedInvoke))
2645 AddPredecessorToBlock(Succ, /*NewPred=*/MergedInvoke->getParent(),
2646 /*ExistPred=*/Invokes.front()->getParent());
2647
2648 // And finally, replace the original `invoke`s with an unconditional branch
2649 // to the block with the merged `invoke`. Also, give that merged `invoke`
2650 // the merged debugloc of all the original `invoke`s.
2651 DILocation *MergedDebugLoc = nullptr;
2652 for (InvokeInst *II : Invokes) {
2653 // Compute the debug location common to all the original `invoke`s.
2654 if (!MergedDebugLoc)
2655 MergedDebugLoc = II->getDebugLoc();
2656 else
2657 MergedDebugLoc =
2658 DILocation::getMergedLocation(MergedDebugLoc, II->getDebugLoc());
2659
2660 // And replace the old `invoke` with an unconditionally branch
2661 // to the block with the merged `invoke`.
2662 for (BasicBlock *OrigSuccBB : successors(II->getParent()))
2663 OrigSuccBB->removePredecessor(II->getParent());
2664 BranchInst::Create(MergedInvoke->getParent(), II->getParent());
2665 II->replaceAllUsesWith(MergedInvoke);
2666 II->eraseFromParent();
2667 ++NumInvokesMerged;
2668 }
2669 MergedInvoke->setDebugLoc(MergedDebugLoc);
2670 ++NumInvokeSetsFormed;
2671
2672 if (DTU)
2673 DTU->applyUpdates(Updates);
2674}
2675
2676/// If this block is a `landingpad` exception handling block, categorize all
2677/// the predecessor `invoke`s into sets, with all `invoke`s in each set
2678/// being "mergeable" together, and then merge invokes in each set together.
2679///
2680/// This is a weird mix of hoisting and sinking. Visually, it goes from:
2681/// [...] [...]
2682/// | |
2683/// [invoke0] [invoke1]
2684/// / \ / \
2685/// [cont0] [landingpad] [cont1]
2686/// to:
2687/// [...] [...]
2688/// \ /
2689/// [invoke]
2690/// / \
2691/// [cont] [landingpad]
2692///
2693/// But of course we can only do that if the invokes share the `landingpad`,
2694/// edges invoke0->cont0 and invoke1->cont1 are "compatible",
2695/// and the invoked functions are "compatible".
2698 return false;
2699
2700 bool Changed = false;
2701
2702 // FIXME: generalize to all exception handling blocks?
2703 if (!BB->isLandingPad())
2704 return Changed;
2705
2706 CompatibleSets Grouper;
2707
2708 // Record all the predecessors of this `landingpad`. As per verifier,
2709 // the only allowed predecessor is the unwind edge of an `invoke`.
2710 // We want to group "compatible" `invokes` into the same set to be merged.
2711 for (BasicBlock *PredBB : predecessors(BB))
2712 Grouper.insert(cast<InvokeInst>(PredBB->getTerminator()));
2713
2714 // And now, merge `invoke`s that were grouped togeter.
2715 for (ArrayRef<InvokeInst *> Invokes : Grouper.Sets) {
2716 if (Invokes.size() < 2)
2717 continue;
2718 Changed = true;
2719 MergeCompatibleInvokesImpl(Invokes, DTU);
2720 }
2721
2722 return Changed;
2723}
2724
2725namespace {
2726/// Track ephemeral values, which should be ignored for cost-modelling
2727/// purposes. Requires walking instructions in reverse order.
2728class EphemeralValueTracker {
2730
2731 bool isEphemeral(const Instruction *I) {
2732 if (isa<AssumeInst>(I))
2733 return true;
2734 return !I->mayHaveSideEffects() && !I->isTerminator() &&
2735 all_of(I->users(), [&](const User *U) {
2736 return EphValues.count(cast<Instruction>(U));
2737 });
2738 }
2739
2740public:
2741 bool track(const Instruction *I) {
2742 if (isEphemeral(I)) {
2743 EphValues.insert(I);
2744 return true;
2745 }
2746 return false;
2747 }
2748
2749 bool contains(const Instruction *I) const { return EphValues.contains(I); }
2750};
2751} // namespace
2752
2753/// Determine if we can hoist sink a sole store instruction out of a
2754/// conditional block.
2755///
2756/// We are looking for code like the following:
2757/// BrBB:
2758/// store i32 %add, i32* %arrayidx2
2759/// ... // No other stores or function calls (we could be calling a memory
2760/// ... // function).
2761/// %cmp = icmp ult %x, %y
2762/// br i1 %cmp, label %EndBB, label %ThenBB
2763/// ThenBB:
2764/// store i32 %add5, i32* %arrayidx2
2765/// br label EndBB
2766/// EndBB:
2767/// ...
2768/// We are going to transform this into:
2769/// BrBB:
2770/// store i32 %add, i32* %arrayidx2
2771/// ... //
2772/// %cmp = icmp ult %x, %y
2773/// %add.add5 = select i1 %cmp, i32 %add, %add5
2774/// store i32 %add.add5, i32* %arrayidx2
2775/// ...
2776///
2777/// \return The pointer to the value of the previous store if the store can be
2778/// hoisted into the predecessor block. 0 otherwise.
2780 BasicBlock *StoreBB, BasicBlock *EndBB) {
2781 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
2782 if (!StoreToHoist)
2783 return nullptr;
2784
2785 // Volatile or atomic.
2786 if (!StoreToHoist->isSimple())
2787 return nullptr;
2788
2789 Value *StorePtr = StoreToHoist->getPointerOperand();
2790 Type *StoreTy = StoreToHoist->getValueOperand()->getType();
2791
2792 // Look for a store to the same pointer in BrBB.
2793 unsigned MaxNumInstToLookAt = 9;
2794 // Skip pseudo probe intrinsic calls which are not really killing any memory
2795 // accesses.
2796 for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug(true))) {
2797 if (!MaxNumInstToLookAt)
2798 break;
2799 --MaxNumInstToLookAt;
2800
2801 // Could be calling an instruction that affects memory like free().
2802 if (CurI.mayWriteToMemory() && !isa<StoreInst>(CurI))
2803 return nullptr;
2804
2805 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
2806 // Found the previous store to same location and type. Make sure it is
2807 // simple, to avoid introducing a spurious non-atomic write after an
2808 // atomic write.
2809 if (SI->getPointerOperand() == StorePtr &&
2810 SI->getValueOperand()->getType() == StoreTy && SI->isSimple())
2811 // Found the previous store, return its value operand.
2812 return SI->getValueOperand();
2813 return nullptr; // Unknown store.
2814 }
2815
2816 if (auto *LI = dyn_cast<LoadInst>(&CurI)) {
2817 if (LI->getPointerOperand() == StorePtr && LI->getType() == StoreTy &&
2818 LI->isSimple()) {
2819 // Local objects (created by an `alloca` instruction) are always
2820 // writable, so once we are past a read from a location it is valid to
2821 // also write to that same location.
2822 // If the address of the local object never escapes the function, that
2823 // means it's never concurrently read or written, hence moving the store
2824 // from under the condition will not introduce a data race.
2825 auto *AI = dyn_cast<AllocaInst>(getUnderlyingObject(StorePtr));
2826 if (AI && !PointerMayBeCaptured(AI, false, true))
2827 // Found a previous load, return it.
2828 return LI;
2829 }
2830 // The load didn't work out, but we may still find a store.
2831 }
2832 }
2833
2834 return nullptr;
2835}
2836
2837/// Estimate the cost of the insertion(s) and check that the PHI nodes can be
2838/// converted to selects.
2840 BasicBlock *EndBB,
2841 unsigned &SpeculatedInstructions,
2843 const TargetTransformInfo &TTI) {
2845 BB->getParent()->hasMinSize()
2848
2849 bool HaveRewritablePHIs = false;
2850 for (PHINode &PN : EndBB->phis()) {
2851 Value *OrigV = PN.getIncomingValueForBlock(BB);
2852 Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
2853
2854 // FIXME: Try to remove some of the duplication with
2855 // hoistCommonCodeFromSuccessors. Skip PHIs which are trivial.
2856 if (ThenV == OrigV)
2857 continue;
2858
2859 Cost += TTI.getCmpSelInstrCost(Instruction::Select, PN.getType(), nullptr,
2861
2862 // Don't convert to selects if we could remove undefined behavior instead.
2863 if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
2865 return false;
2866
2867 HaveRewritablePHIs = true;
2868 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
2869 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
2870 if (!OrigCE && !ThenCE)
2871 continue; // Known cheap (FIXME: Maybe not true for aggregates).
2872
2873 InstructionCost OrigCost = OrigCE ? computeSpeculationCost(OrigCE, TTI) : 0;
2874 InstructionCost ThenCost = ThenCE ? computeSpeculationCost(ThenCE, TTI) : 0;
2875 InstructionCost MaxCost =
2877 if (OrigCost + ThenCost > MaxCost)
2878 return false;
2879
2880 // Account for the cost of an unfolded ConstantExpr which could end up
2881 // getting expanded into Instructions.
2882 // FIXME: This doesn't account for how many operations are combined in the
2883 // constant expression.
2884 ++SpeculatedInstructions;
2885 if (SpeculatedInstructions > 1)
2886 return false;
2887 }
2888
2889 return HaveRewritablePHIs;
2890}
2891
2892/// Speculate a conditional basic block flattening the CFG.
2893///
2894/// Note that this is a very risky transform currently. Speculating
2895/// instructions like this is most often not desirable. Instead, there is an MI
2896/// pass which can do it with full awareness of the resource constraints.
2897/// However, some cases are "obvious" and we should do directly. An example of
2898/// this is speculating a single, reasonably cheap instruction.
2899///
2900/// There is only one distinct advantage to flattening the CFG at the IR level:
2901/// it makes very common but simplistic optimizations such as are common in
2902/// instcombine and the DAG combiner more powerful by removing CFG edges and
2903/// modeling their effects with easier to reason about SSA value graphs.
2904///
2905///
2906/// An illustration of this transform is turning this IR:
2907/// \code
2908/// BB:
2909/// %cmp = icmp ult %x, %y
2910/// br i1 %cmp, label %EndBB, label %ThenBB
2911/// ThenBB:
2912/// %sub = sub %x, %y
2913/// br label BB2
2914/// EndBB:
2915/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
2916/// ...
2917/// \endcode
2918///
2919/// Into this IR:
2920/// \code
2921/// BB:
2922/// %cmp = icmp ult %x, %y
2923/// %sub = sub %x, %y
2924/// %cond = select i1 %cmp, 0, %sub
2925/// ...
2926/// \endcode
2927///
2928/// \returns true if the conditional block is removed.
2929bool SimplifyCFGOpt::SpeculativelyExecuteBB(BranchInst *BI,
2930 BasicBlock *ThenBB) {
2931 if (!Options.SpeculateBlocks)
2932 return false;
2933
2934 // Be conservative for now. FP select instruction can often be expensive.
2935 Value *BrCond = BI->getCondition();
2936 if (isa<FCmpInst>(BrCond))
2937 return false;
2938
2939 BasicBlock *BB = BI->getParent();
2940 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
2941 InstructionCost Budget =
2943
2944 // If ThenBB is actually on the false edge of the conditional branch, remember
2945 // to swap the select operands later.
2946 bool Invert = false;
2947 if (ThenBB != BI->getSuccessor(0)) {
2948 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
2949 Invert = true;
2950 }
2951 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
2952
2953 // If the branch is non-unpredictable, and is predicted to *not* branch to
2954 // the `then` block, then avoid speculating it.
2955 if (!BI->getMetadata(LLVMContext::MD_unpredictable)) {
2956 uint64_t TWeight, FWeight;
2957 if (extractBranchWeights(*BI, TWeight, FWeight) &&
2958 (TWeight + FWeight) != 0) {
2959 uint64_t EndWeight = Invert ? TWeight : FWeight;
2960 BranchProbability BIEndProb =
2961 BranchProbability::getBranchProbability(EndWeight, TWeight + FWeight);
2963 if (BIEndProb >= Likely)
2964 return false;
2965 }
2966 }
2967
2968 // Keep a count of how many times instructions are used within ThenBB when
2969 // they are candidates for sinking into ThenBB. Specifically:
2970 // - They are defined in BB, and
2971 // - They have no side effects, and
2972 // - All of their uses are in ThenBB.
2973 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
2974
2975 SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics;
2976
2977 unsigned SpeculatedInstructions = 0;
2978 Value *SpeculatedStoreValue = nullptr;
2979 StoreInst *SpeculatedStore = nullptr;
2980 EphemeralValueTracker EphTracker;
2981 for (Instruction &I : reverse(drop_end(*ThenBB))) {
2982 // Skip debug info.
2983 if (isa<DbgInfoIntrinsic>(I)) {
2984 SpeculatedDbgIntrinsics.push_back(&I);
2985 continue;
2986 }
2987
2988 // Skip pseudo probes. The consequence is we lose track of the branch
2989 // probability for ThenBB, which is fine since the optimization here takes
2990 // place regardless of the branch probability.
2991 if (isa<PseudoProbeInst>(I)) {
2992 // The probe should be deleted so that it will not be over-counted when
2993 // the samples collected on the non-conditional path are counted towards
2994 // the conditional path. We leave it for the counts inference algorithm to
2995 // figure out a proper count for an unknown probe.
2996 SpeculatedDbgIntrinsics.push_back(&I);
2997 continue;
2998 }
2999
3000 // Ignore ephemeral values, they will be dropped by the transform.
3001 if (EphTracker.track(&I))
3002 continue;
3003
3004 // Only speculatively execute a single instruction (not counting the
3005 // terminator) for now.
3006 ++SpeculatedInstructions;
3007 if (SpeculatedInstructions > 1)
3008 return false;
3009
3010 // Don't hoist the instruction if it's unsafe or expensive.
3012 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
3013 &I, BB, ThenBB, EndBB))))
3014 return false;
3015 if (!SpeculatedStoreValue &&
3018 return false;
3019
3020 // Store the store speculation candidate.
3021 if (SpeculatedStoreValue)
3022 SpeculatedStore = cast<StoreInst>(&I);
3023
3024 // Do not hoist the instruction if any of its operands are defined but not
3025 // used in BB. The transformation will prevent the operand from
3026 // being sunk into the use block.
3027 for (Use &Op : I.operands()) {
3028 Instruction *OpI = dyn_cast<Instruction>(Op);
3029 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
3030 continue; // Not a candidate for sinking.
3031
3032 ++SinkCandidateUseCounts[OpI];
3033 }
3034 }
3035
3036 // Consider any sink candidates which are only used in ThenBB as costs for
3037 // speculation. Note, while we iterate over a DenseMap here, we are summing
3038 // and so iteration order isn't significant.
3039 for (const auto &[Inst, Count] : SinkCandidateUseCounts)
3040 if (Inst->hasNUses(Count)) {
3041 ++SpeculatedInstructions;
3042 if (SpeculatedInstructions > 1)
3043 return false;
3044 }
3045
3046 // Check that we can insert the selects and that it's not too expensive to do
3047 // so.
3048 bool Convert = SpeculatedStore != nullptr;
3050 Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB,
3051 SpeculatedInstructions,
3052 Cost, TTI);
3053 if (!Convert || Cost > Budget)
3054 return false;
3055
3056 // If we get here, we can hoist the instruction and if-convert.
3057 LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
3058
3059 // Insert a select of the value of the speculated store.
3060 if (SpeculatedStoreValue) {
3062 Value *OrigV = SpeculatedStore->getValueOperand();
3063 Value *TrueV = SpeculatedStore->getValueOperand();
3064 Value *FalseV = SpeculatedStoreValue;
3065 if (Invert)
3066 std::swap(TrueV, FalseV);
3067 Value *S = Builder.CreateSelect(
3068 BrCond, TrueV, FalseV, "spec.store.select", BI);
3069 SpeculatedStore->setOperand(0, S);
3070 SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
3071 SpeculatedStore->getDebugLoc());
3072 // The value stored is still conditional, but the store itself is now
3073 // unconditonally executed, so we must be sure that any linked dbg.assign
3074 // intrinsics are tracking the new stored value (the result of the
3075 // select). If we don't, and the store were to be removed by another pass
3076 // (e.g. DSE), then we'd eventually end up emitting a location describing
3077 // the conditional value, unconditionally.
3078 //
3079 // === Before this transformation ===
3080 // pred:
3081 // store %one, %x.dest, !DIAssignID !1
3082 // dbg.assign %one, "x", ..., !1, ...
3083 // br %cond if.then
3084 //
3085 // if.then:
3086 // store %two, %x.dest, !DIAssignID !2
3087 // dbg.assign %two, "x", ..., !2, ...
3088 //
3089 // === After this transformation ===
3090 // pred:
3091 // store %one, %x.dest, !DIAssignID !1
3092 // dbg.assign %one, "x", ..., !1
3093 /// ...
3094 // %merge = select %cond, %two, %one
3095 // store %merge, %x.dest, !DIAssignID !2
3096 // dbg.assign %merge, "x", ..., !2
3097 for (auto *DAI : at::getAssignmentMarkers(SpeculatedStore)) {
3098 if (llvm::is_contained(DAI->location_ops(), OrigV))
3099 DAI->replaceVariableLocationOp(OrigV, S);
3100 }
3101 }
3102
3103 // Metadata can be dependent on the condition we are hoisting above.
3104 // Strip all UB-implying metadata on the instruction. Drop the debug loc
3105 // to avoid making it appear as if the condition is a constant, which would
3106 // be misleading while debugging.
3107 // Similarly strip attributes that maybe dependent on condition we are
3108 // hoisting above.
3109 for (auto &I : make_early_inc_range(*ThenBB)) {
3110 if (!SpeculatedStoreValue || &I != SpeculatedStore) {
3111 // Don't update the DILocation of dbg.assign intrinsics.
3112 if (!isa<DbgAssignIntrinsic>(&I))
3113 I.setDebugLoc(DebugLoc());
3114 }
3115 I.dropUBImplyingAttrsAndMetadata();
3116
3117 // Drop ephemeral values.
3118 if (EphTracker.contains(&I)) {
3119 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
3120 I.eraseFromParent();
3121 }
3122 }
3123
3124 // Hoist the instructions.
3125 BB->splice(BI->getIterator(), ThenBB, ThenBB->begin(),
3126 std::prev(ThenBB->end()));
3127
3128 // Insert selects and rewrite the PHI operands.
3130 for (PHINode &PN : EndBB->phis()) {
3131 unsigned OrigI = PN.getBasicBlockIndex(BB);
3132 unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
3133 Value *OrigV = PN.getIncomingValue(OrigI);
3134 Value *ThenV = PN.getIncomingValue(ThenI);
3135
3136 // Skip PHIs which are trivial.
3137 if (OrigV == ThenV)
3138 continue;
3139
3140 // Create a select whose true value is the speculatively executed value and
3141 // false value is the pre-existing value. Swap them if the branch
3142 // destinations were inverted.
3143 Value *TrueV = ThenV, *FalseV = OrigV;
3144 if (Invert)
3145 std::swap(TrueV, FalseV);
3146 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV, "spec.select", BI);
3147 PN.setIncomingValue(OrigI, V);
3148 PN.setIncomingValue(ThenI, V);
3149 }
3150
3151 // Remove speculated dbg intrinsics.
3152 // FIXME: Is it possible to do this in a more elegant way? Moving/merging the
3153 // dbg value for the different flows and inserting it after the select.
3154 for (Instruction *I : SpeculatedDbgIntrinsics) {
3155 // We still want to know that an assignment took place so don't remove
3156 // dbg.assign intrinsics.
3157 if (!isa<DbgAssignIntrinsic>(I))
3158 I->eraseFromParent();
3159 }
3160
3161 ++NumSpeculations;
3162 return true;
3163}
3164
3165/// Return true if we can thread a branch across this block.
3167 int Size = 0;
3168 EphemeralValueTracker EphTracker;
3169
3170 // Walk the loop in reverse so that we can identify ephemeral values properly
3171 // (values only feeding assumes).
3172 for (Instruction &I : reverse(BB->instructionsWithoutDebug(false))) {
3173 // Can't fold blocks that contain noduplicate or convergent calls.
3174 if (CallInst *CI = dyn_cast<CallInst>(&I))
3175 if (CI->cannotDuplicate() || CI->isConvergent())
3176 return false;
3177
3178 // Ignore ephemeral values which are deleted during codegen.
3179 // We will delete Phis while threading, so Phis should not be accounted in
3180 // block's size.
3181 if (!EphTracker.track(&I) && !isa<PHINode>(I)) {
3182 if (Size++ > MaxSmallBlockSize)
3183 return false; // Don't clone large BB's.
3184 }
3185
3186 // We can only support instructions that do not define values that are
3187 // live outside of the current basic block.
3188 for (User *U : I.users()) {
3189 Instruction *UI = cast<Instruction>(U);
3190 if (UI->getParent() != BB || isa<PHINode>(UI))
3191 return false;
3192 }
3193
3194 // Looks ok, continue checking.
3195 }
3196
3197 return true;
3198}
3199
3201 BasicBlock *To) {
3202 // Don't look past the block defining the value, we might get the value from
3203 // a previous loop iteration.
3204 auto *I = dyn_cast<Instruction>(V);
3205 if (I && I->getParent() == To)
3206 return nullptr;
3207
3208 // We know the value if the From block branches on it.
3209 auto *BI = dyn_cast<BranchInst>(From->getTerminator());
3210 if (BI && BI->isConditional() && BI->getCondition() == V &&
3211 BI->getSuccessor(0) != BI->getSuccessor(1))
3212 return BI->getSuccessor(0) == To ? ConstantInt::getTrue(BI->getContext())
3214
3215 return nullptr;
3216}
3217
3218/// If we have a conditional branch on something for which we know the constant
3219/// value in predecessors (e.g. a phi node in the current block), thread edges
3220/// from the predecessor to their ultimate destination.
3221static std::optional<bool>
3223 const DataLayout &DL,
3224 AssumptionCache *AC) {
3226 BasicBlock *BB = BI->getParent();
3227 Value *Cond = BI->getCondition();
3228 PHINode *PN = dyn_cast<PHINode>(Cond);
3229 if (PN && PN->getParent() == BB) {
3230 // Degenerate case of a single entry PHI.
3231 if (PN->getNumIncomingValues() == 1) {
3233 return true;
3234 }
3235
3236 for (Use &U : PN->incoming_values())
3237 if (auto *CB = dyn_cast<ConstantInt>(U))
3238 KnownValues[CB].insert(PN->getIncomingBlock(U));
3239 } else {
3240 for (BasicBlock *Pred : predecessors(BB)) {
3241 if (ConstantInt *CB = getKnownValueOnEdge(Cond, Pred, BB))
3242 KnownValues[CB].insert(Pred);
3243 }
3244 }
3245
3246 if (KnownValues.empty())
3247 return false;
3248
3249 // Now we know that this block has multiple preds and two succs.
3250 // Check that the block is small enough and values defined in the block are
3251 // not used outside of it.
3253 return false;
3254
3255 for (const auto &Pair : KnownValues) {
3256 // Okay, we now know that all edges from PredBB should be revectored to
3257 // branch to RealDest.
3258 ConstantInt *CB = Pair.first;
3259 ArrayRef<BasicBlock *> PredBBs = Pair.second.getArrayRef();
3260 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
3261
3262 if (RealDest == BB)
3263 continue; // Skip self loops.
3264
3265 // Skip if the predecessor's terminator is an indirect branch.
3266 if (any_of(PredBBs, [](BasicBlock *PredBB) {
3267 return isa<IndirectBrInst>(PredBB->getTerminator());
3268 }))
3269 continue;
3270
3271 LLVM_DEBUG({
3272 dbgs() << "Condition " << *Cond << " in " << BB->getName()
3273 << " has value " << *Pair.first << " in predecessors:\n";
3274 for (const BasicBlock *PredBB : Pair.second)
3275 dbgs() << " " << PredBB->getName() << "\n";
3276 dbgs() << "Threading to destination " << RealDest->getName() << ".\n";
3277 });
3278
3279 // Split the predecessors we are threading into a new edge block. We'll
3280 // clone the instructions into this block, and then redirect it to RealDest.
3281 BasicBlock *EdgeBB = SplitBlockPredecessors(BB, PredBBs, ".critedge", DTU);
3282
3283 // TODO: These just exist to reduce test diff, we can drop them if we like.
3284 EdgeBB->setName(RealDest->getName() + ".critedge");
3285 EdgeBB->moveBefore(RealDest);
3286
3287 // Update PHI nodes.
3288 AddPredecessorToBlock(RealDest, EdgeBB, BB);
3289
3290 // BB may have instructions that are being threaded over. Clone these
3291 // instructions into EdgeBB. We know that there will be no uses of the
3292 // cloned instructions outside of EdgeBB.
3293 BasicBlock::iterator InsertPt = EdgeBB->getFirstInsertionPt();
3294 DenseMap<Value *, Value *> TranslateMap; // Track translated values.
3295 TranslateMap[Cond] = CB;
3296 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
3297 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
3298 TranslateMap[PN] = PN->getIncomingValueForBlock(EdgeBB);
3299 continue;
3300 }
3301 // Clone the instruction.
3302 Instruction *N = BBI->clone();
3303 // Insert the new instruction into its new home.
3304 N->insertInto(EdgeBB, InsertPt);
3305
3306 if (BBI->hasName())
3307 N->setName(BBI->getName() + ".c");
3308
3309 // Update operands due to translation.
3310 for (Use &Op : N->operands()) {
3311 DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(Op);
3312 if (PI != TranslateMap.end())
3313 Op = PI->second;
3314 }
3315
3316 // Check for trivial simplification.
3317 if (Value *V = simplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
3318 if (!BBI->use_empty())
3319 TranslateMap[&*BBI] = V;
3320 if (!N->mayHaveSideEffects()) {
3321 N->eraseFromParent(); // Instruction folded away, don't need actual
3322 // inst
3323 N = nullptr;
3324 }
3325 } else {
3326 if (!BBI->use_empty())
3327 TranslateMap[&*BBI] = N;
3328 }
3329 if (N) {
3330 // Register the new instruction with the assumption cache if necessary.
3331 if (auto *Assume = dyn_cast<AssumeInst>(N))
3332 if (AC)
3333 AC->registerAssumption(Assume);
3334 }
3335 }
3336
3337 BB->removePredecessor(EdgeBB);
3338 BranchInst *EdgeBI = cast<BranchInst>(EdgeBB->getTerminator());
3339 EdgeBI->setSuccessor(0, RealDest);
3340 EdgeBI->setDebugLoc(BI->getDebugLoc());
3341
3342 if (DTU) {
3344 Updates.push_back({DominatorTree::Delete, EdgeBB, BB});
3345 Updates.push_back({DominatorTree::Insert, EdgeBB, RealDest});
3346 DTU->applyUpdates(Updates);
3347 }
3348
3349 // For simplicity, we created a separate basic block for the edge. Merge
3350 // it back into the predecessor if possible. This not only avoids
3351 // unnecessary SimplifyCFG iterations, but also makes sure that we don't
3352 // bypass the check for trivial cycles above.
3353 MergeBlockIntoPredecessor(EdgeBB, DTU);
3354
3355 // Signal repeat, simplifying any other constants.
3356 return std::nullopt;
3357 }
3358
3359 return false;
3360}
3361
3363 DomTreeUpdater *DTU,
3364 const DataLayout &DL,
3365 AssumptionCache *AC) {
3366 std::optional<bool> Result;
3367 bool EverChanged = false;
3368 do {
3369 // Note that None means "we changed things, but recurse further."
3370 Result = FoldCondBranchOnValueKnownInPredecessorImpl(BI, DTU, DL, AC);
3371 EverChanged |= Result == std::nullopt || *Result;
3372 } while (Result == std::nullopt);
3373 return EverChanged;
3374}
3375
3376/// Given a BB that starts with the specified two-entry PHI node,
3377/// see if we can eliminate it.
3379 DomTreeUpdater *DTU, const DataLayout &DL) {
3380 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
3381 // statement", which has a very simple dominance structure. Basically, we
3382 // are trying to find the condition that is being branched on, which
3383 // subsequently causes this merge to happen. We really want control
3384 // dependence information for this check, but simplifycfg can't keep it up
3385 // to date, and this catches most of the cases we care about anyway.
3386 BasicBlock *BB = PN->getParent();
3387
3388 BasicBlock *IfTrue, *IfFalse;
3389 BranchInst *DomBI = GetIfCondition(BB, IfTrue, IfFalse);
3390 if (!DomBI)
3391 return false;
3392 Value *IfCond = DomBI->getCondition();
3393 // Don't bother if the branch will be constant folded trivially.
3394 if (isa<ConstantInt>(IfCond))
3395 return false;
3396
3397 BasicBlock *DomBlock = DomBI->getParent();
3400 PN->blocks(), std::back_inserter(IfBlocks), [](BasicBlock *IfBlock) {
3401 return cast<BranchInst>(IfBlock->getTerminator())->isUnconditional();
3402 });
3403 assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) &&
3404 "Will have either one or two blocks to speculate.");
3405
3406 // If the branch is non-unpredictable, see if we either predictably jump to
3407 // the merge bb (if we have only a single 'then' block), or if we predictably
3408 // jump to one specific 'then' block (if we have two of them).
3409 // It isn't beneficial to speculatively execute the code
3410 // from the block that we know is predictably not entered.
3411 if (!DomBI->getMetadata(LLVMContext::MD_unpredictable)) {
3412 uint64_t TWeight, FWeight;
3413 if (extractBranchWeights(*DomBI, TWeight, FWeight) &&
3414 (TWeight + FWeight) != 0) {
3415 BranchProbability BITrueProb =
3416 BranchProbability::getBranchProbability(TWeight, TWeight + FWeight);
3418 BranchProbability BIFalseProb = BITrueProb.getCompl();
3419 if (IfBlocks.size() == 1) {
3420 BranchProbability BIBBProb =
3421 DomBI->getSuccessor(0) == BB ? BITrueProb : BIFalseProb;
3422 if (BIBBProb >= Likely)
3423 return false;
3424 } else {
3425 if (BITrueProb >= Likely || BIFalseProb >= Likely)
3426 return false;
3427 }
3428 }
3429 }
3430
3431 // Don't try to fold an unreachable block. For example, the phi node itself
3432 // can't be the candidate if-condition for a select that we want to form.
3433 if (auto *IfCondPhiInst = dyn_cast<PHINode>(IfCond))
3434 if (IfCondPhiInst->getParent() == BB)
3435 return false;
3436
3437 // Okay, we found that we can merge this two-entry phi node into a select.
3438 // Doing so would require us to fold *all* two entry phi nodes in this block.
3439 // At some point this becomes non-profitable (particularly if the target
3440 // doesn't support cmov's). Only do this transformation if there are two or
3441 // fewer PHI nodes in this block.
3442 unsigned NumPhis = 0;
3443 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
3444 if (NumPhis > 2)
3445 return false;
3446
3447 // Loop over the PHI's seeing if we can promote them all to select
3448 // instructions. While we are at it, keep track of the instructions
3449 // that need to be moved to the dominating block.
3450 SmallPtrSet<Instruction *, 4> AggressiveInsts;
3452 InstructionCost Budget =
3454
3455 bool Changed = false;
3456 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
3457 PHINode *PN = cast<PHINode>(II++);
3458 if (Value *V = simplifyInstruction(PN, {DL, PN})) {
3459 PN->replaceAllUsesWith(V);
3460 PN->eraseFromParent();
3461 Changed = true;
3462 continue;
3463 }
3464
3465 if (!dominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts,
3466 Cost, Budget, TTI) ||
3467 !dominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts,
3468 Cost, Budget, TTI))
3469 return Changed;
3470 }
3471
3472 // If we folded the first phi, PN dangles at this point. Refresh it. If
3473 // we ran out of PHIs then we simplified them all.
3474 PN = dyn_cast<PHINode>(BB->begin());
3475 if (!PN)
3476 return true;
3477
3478 // Return true if at least one of these is a 'not', and another is either
3479 // a 'not' too, or a constant.
3480 auto CanHoistNotFromBothValues = [](Value *V0, Value *V1) {
3481 if (!match(V0, m_Not(m_Value())))
3482 std::swap(V0, V1);
3483 auto Invertible = m_CombineOr(m_Not(m_Value()), m_AnyIntegralConstant());
3484 return match(V0, m_Not(m_Value())) && match(V1, Invertible);
3485 };
3486
3487 // Don't fold i1 branches on PHIs which contain binary operators or
3488 // (possibly inverted) select form of or/ands, unless one of
3489 // the incoming values is an 'not' and another one is freely invertible.
3490 // These can often be turned into switches and other things.
3491 auto IsBinOpOrAnd = [](Value *V) {
3492 return match(
3493 V, m_CombineOr(
3494 m_BinOp(),
3497 };
3498 if (PN->getType()->isIntegerTy(1) &&
3499 (IsBinOpOrAnd(PN->getIncomingValue(0)) ||
3500 IsBinOpOrAnd(PN->getIncomingValue(1)) || IsBinOpOrAnd(IfCond)) &&
3501 !CanHoistNotFromBothValues(PN->getIncomingValue(0),
3502 PN->getIncomingValue(1)))
3503 return Changed;
3504
3505 // If all PHI nodes are promotable, check to make sure that all instructions
3506 // in the predecessor blocks can be promoted as well. If not, we won't be able
3507 // to get rid of the control flow, so it's not worth promoting to select
3508 // instructions.
3509 for (BasicBlock *IfBlock : IfBlocks)
3510 for (BasicBlock::iterator I = IfBlock->begin(); !I->isTerminator(); ++I)
3511 if (!AggressiveInsts.count(&*I) && !I->isDebugOrPseudoInst()) {
3512 // This is not an aggressive instruction that we can promote.
3513 // Because of this, we won't be able to get rid of the control flow, so
3514 // the xform is not worth it.
3515 return Changed;
3516 }
3517
3518 // If either of the blocks has it's address taken, we can't do this fold.
3519 if (any_of(IfBlocks,
3520 [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); }))
3521 return Changed;
3522
3523 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond
3524 << " T: " << IfTrue->getName()
3525 << " F: " << IfFalse->getName() << "\n");
3526
3527 // If we can still promote the PHI nodes after this gauntlet of tests,
3528 // do all of the PHI's now.
3529
3530 // Move all 'aggressive' instructions, which are defined in the
3531 // conditional parts of the if's up to the dominating block.
3532 for (BasicBlock *IfBlock : IfBlocks)
3533 hoistAllInstructionsInto(DomBlock, DomBI, IfBlock);
3534
3536 // Propagate fast-math-flags from phi nodes to replacement selects.
3538 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
3539 if (isa<FPMathOperator>(PN))
3540 Builder.setFastMathFlags(PN->getFastMathFlags());
3541
3542 // Change the PHI node into a select instruction.
3543 Value *TrueVal = PN->getIncomingValueForBlock(IfTrue);
3544 Value *FalseVal = PN->getIncomingValueForBlock(IfFalse);
3545
3546 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", DomBI);
3547 PN->replaceAllUsesWith(Sel);
3548 Sel->takeName(PN);
3549 PN->eraseFromParent();
3550 }
3551
3552 // At this point, all IfBlocks are empty, so our if statement
3553 // has been flattened. Change DomBlock to jump directly to our new block to
3554 // avoid other simplifycfg's kicking in on the diamond.
3555 Builder.CreateBr(BB);
3556
3558 if (DTU) {
3559 Updates.push_back({DominatorTree::Insert, DomBlock, BB});
3560 for (auto *Successor : successors(DomBlock))
3561 Updates.push_back({DominatorTree::Delete, DomBlock, Successor});
3562 }
3563
3564 DomBI->eraseFromParent();
3565 if (DTU)
3566 DTU->applyUpdates(Updates);
3567
3568 return true;
3569}
3570
3572 Instruction::BinaryOps Opc, Value *LHS,
3573 Value *RHS, const Twine &Name = "") {
3574 // Try to relax logical op to binary op.
3575 if (impliesPoison(RHS, LHS))
3576 return Builder.CreateBinOp(Opc, LHS, RHS, Name);
3577 if (Opc == Instruction::And)
3578 return Builder.CreateLogicalAnd(LHS, RHS, Name);
3579 if (Opc == Instruction::Or)
3580 return Builder.CreateLogicalOr(LHS, RHS, Name);
3581 llvm_unreachable("Invalid logical opcode");
3582}
3583
3584/// Return true if either PBI or BI has branch weight available, and store
3585/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
3586/// not have branch weight, use 1:1 as its weight.
3588 uint64_t &PredTrueWeight,
3589 uint64_t &PredFalseWeight,
3590 uint64_t &SuccTrueWeight,
3591 uint64_t &SuccFalseWeight) {
3592 bool PredHasWeights =
3593 extractBranchWeights(*PBI, PredTrueWeight, PredFalseWeight);
3594 bool SuccHasWeights =
3595 extractBranchWeights(*BI, SuccTrueWeight, SuccFalseWeight);
3596 if (PredHasWeights || SuccHasWeights) {
3597 if (!PredHasWeights)
3598 PredTrueWeight = PredFalseWeight = 1;
3599 if (!SuccHasWeights)
3600 SuccTrueWeight = SuccFalseWeight = 1;
3601 return true;
3602 } else {
3603 return false;
3604 }
3605}
3606
3607/// Determine if the two branches share a common destination and deduce a glue
3608/// that joins the branches' conditions to arrive at the common destination if
3609/// that would be profitable.
3610static std::optional<std::tuple<BasicBlock *, Instruction::BinaryOps, bool>>
3612 const TargetTransformInfo *TTI) {
3613 assert(BI && PBI && BI->isConditional() && PBI->isConditional() &&
3614 "Both blocks must end with a conditional branches.");
3616 "PredBB must be a predecessor of BB.");
3617
3618 // We have the potential to fold the conditions together, but if the
3619 // predecessor branch is predictable, we may not want to merge them.
3620 uint64_t PTWeight, PFWeight;
3621 BranchProbability PBITrueProb, Likely;
3622 if (TTI && !PBI->getMetadata(LLVMContext::MD_unpredictable) &&
3623 extractBranchWeights(*PBI, PTWeight, PFWeight) &&
3624 (PTWeight + PFWeight) != 0) {
3625 PBITrueProb =
3626 BranchProbability::getBranchProbability(PTWeight, PTWeight + PFWeight);
3628 }
3629
3630 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3631 // Speculate the 2nd condition unless the 1st is probably true.
3632 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
3633 return {{BI->getSuccessor(0), Instruction::Or, false}};
3634 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3635 // Speculate the 2nd condition unless the 1st is probably false.
3636 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
3637 return {{BI->getSuccessor(1), Instruction::And, false}};
3638 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3639 // Speculate the 2nd condition unless the 1st is probably true.
3640 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
3641 return {{BI->getSuccessor(1), Instruction::And, true}};
3642 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3643 // Speculate the 2nd condition unless the 1st is probably false.
3644 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
3645 return {{BI->getSuccessor(0), Instruction::Or, true}};
3646 }
3647 return std::nullopt;
3648}
3649
3651 DomTreeUpdater *DTU,
3652 MemorySSAUpdater *MSSAU,
3653 const TargetTransformInfo *TTI) {
3654 BasicBlock *BB = BI->getParent();
3655 BasicBlock *PredBlock = PBI->getParent();
3656
3657 // Determine if the two branches share a common destination.
3658 BasicBlock *CommonSucc;
3660 bool InvertPredCond;
3661 std::tie(CommonSucc, Opc, InvertPredCond) =
3663
3664 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
3665
3666 IRBuilder<> Builder(PBI);
3667 // The builder is used to create instructions to eliminate the branch in BB.
3668 // If BB's terminator has !annotation metadata, add it to the new
3669 // instructions.
3670 Builder.CollectMetadataToCopy(BB->getTerminator(),
3671 {LLVMContext::MD_annotation});
3672
3673 // If we need to invert the condition in the pred block to match, do so now.
3674 if (InvertPredCond) {
3675 InvertBranch(PBI, Builder);
3676 }
3677
3678 BasicBlock *UniqueSucc =
3679 PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1);
3680
3681 // Before cloning instructions, notify the successor basic block that it
3682 // is about to have a new predecessor. This will update PHI nodes,
3683 // which will allow us to update live-out uses of bonus instructions.
3684 AddPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU);
3685
3686 // Try to update branch weights.
3687 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3688 if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3689 SuccTrueWeight, SuccFalseWeight)) {
3690 SmallVector<uint64_t, 8> NewWeights;
3691
3692 if (PBI->getSuccessor(0) == BB) {
3693 // PBI: br i1 %x, BB, FalseDest
3694 // BI: br i1 %y, UniqueSucc, FalseDest
3695 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
3696 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
3697 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
3698 // TrueWeight for PBI * FalseWeight for BI.
3699 // We assume that total weights of a BranchInst can fit into 32 bits.
3700 // Therefore, we will not have overflow using 64-bit arithmetic.
3701 NewWeights.push_back(PredFalseWeight *
3702 (SuccFalseWeight + SuccTrueWeight) +
3703 PredTrueWeight * SuccFalseWeight);
3704 } else {
3705 // PBI: br i1 %x, TrueDest, BB
3706 // BI: br i1 %y, TrueDest, UniqueSucc
3707 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
3708 // FalseWeight for PBI * TrueWeight for BI.
3709 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) +
3710 PredFalseWeight * SuccTrueWeight);
3711 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
3712 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
3713 }
3714
3715 // Halve the weights if any of them cannot fit in an uint32_t
3716 FitWeights(NewWeights);
3717
3718 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), NewWeights.end());
3719 setBranchWeights(PBI, MDWeights[0], MDWeights[1]);
3720
3721 // TODO: If BB is reachable from all paths through PredBlock, then we
3722 // could replace PBI's branch probabilities with BI's.
3723 } else
3724 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
3725
3726 // Now, update the CFG.
3727 PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc);
3728
3729 if (DTU)
3730 DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc},
3731 {DominatorTree::Delete, PredBlock, BB}});
3732
3733 // If BI was a loop latch, it may have had associated loop metadata.
3734 // We need to copy it to the new latch, that is, PBI.
3735 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
3736 PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
3737
3738 ValueToValueMapTy VMap; // maps original values to cloned values
3740
3741 // Now that the Cond was cloned into the predecessor basic block,
3742 // or/and the two conditions together.
3743 Value *BICond = VMap[BI->getCondition()];
3744 PBI->setCondition(
3745 createLogicalOp(Builder, Opc, PBI->getCondition(), BICond, "or.cond"));
3746
3747 // Copy any debug value intrinsics into the end of PredBlock.
3748 for (Instruction &I : *BB) {
3749 if (isa<DbgInfoIntrinsic>(I)) {
3750 Instruction *NewI = I.clone();
3751 RemapInstruction(NewI, VMap,
3753 NewI->insertBefore(PBI);
3754 }
3755 }
3756
3757 ++NumFoldBranchToCommonDest;
3758 return true;
3759}
3760
3761/// Return if an instruction's type or any of its operands' types are a vector
3762/// type.
3763static bool isVectorOp(Instruction &I) {
3764 return I.getType()->isVectorTy() || any_of(I.operands(), [](Use &U) {
3765 return U->getType()->isVectorTy();
3766 });
3767}
3768
3769/// If this basic block is simple enough, and if a predecessor branches to us
3770/// and one of our successors, fold the block into the predecessor and use
3771/// logical operations to pick the right destination.
3773 MemorySSAUpdater *MSSAU,
3774 const TargetTransformInfo *TTI,
3775 unsigned BonusInstThreshold) {
3776 // If this block ends with an unconditional branch,
3777 // let SpeculativelyExecuteBB() deal with it.
3778 if (!BI->isConditional())
3779 return false;
3780
3781 BasicBlock *BB = BI->getParent();
3785
3786 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
3787
3788 if (!Cond ||
3789 (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond) &&
3790 !isa<SelectInst>(Cond)) ||
3791 Cond->getParent() != BB || !Cond->hasOneUse())
3792 return false;
3793
3794 // Finally, don't infinitely unroll conditional loops.
3795 if (is_contained(successors(BB), BB))
3796 return false;
3797
3798 // With which predecessors will we want to deal with?
3800 for (BasicBlock *PredBlock : predecessors(BB)) {
3801 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
3802
3803 // Check that we have two conditional branches. If there is a PHI node in
3804 // the common successor, verify that the same value flows in from both
3805 // blocks.
3806 if (!PBI || PBI->isUnconditional() || !SafeToMergeTerminators(BI, PBI))
3807 continue;
3808
3809 // Determine if the two branches share a common destination.
3810 BasicBlock *CommonSucc;
3812 bool InvertPredCond;
3813 if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI))
3814 std::tie(CommonSucc, Opc, InvertPredCond) = *Recipe;
3815 else
3816 continue;
3817
3818 // Check the cost of inserting the necessary logic before performing the
3819 // transformation.
3820 if (TTI) {
3821 Type *Ty = BI->getCondition()->getType();
3823 if (InvertPredCond && (!PBI->getCondition()->hasOneUse() ||
3824 !isa<CmpInst>(PBI->getCondition())))
3825 Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind);
3826
3828 continue;
3829 }
3830
3831 // Ok, we do want to deal with this predecessor. Record it.
3832 Preds.emplace_back(PredBlock);
3833 }
3834
3835 // If there aren't any predecessors into which we can fold,
3836 // don't bother checking the cost.
3837 if (Preds.empty())
3838 return false;
3839
3840 // Only allow this transformation if computing the condition doesn't involve
3841 // too many instructions and these involved instructions can be executed
3842 // unconditionally. We denote all involved instructions except the condition
3843 // as "bonus instructions", and only allow this transformation when the
3844 // number of the bonus instructions we'll need to create when cloning into
3845 // each predecessor does not exceed a certain threshold.
3846 unsigned NumBonusInsts = 0;
3847 bool SawVectorOp = false;
3848 const unsigned PredCount = Preds.size();
3849 for (Instruction &I : *BB) {
3850 // Don't check the branch condition comparison itself.
3851 if (&I == Cond)
3852 continue;
3853 // Ignore dbg intrinsics, and the terminator.
3854 if (isa<DbgInfoIntrinsic>(I) || isa<BranchInst>(I))
3855 continue;
3856 // I must be safe to execute unconditionally.
3858 return false;
3859 SawVectorOp |= isVectorOp(I);
3860
3861 // Account for the cost of duplicating this instruction into each
3862 // predecessor. Ignore free instructions.
3863 if (!TTI || TTI->getInstructionCost(&I, CostKind) !=
3865 NumBonusInsts += PredCount;
3866
3867 // Early exits once we reach the limit.
3868 if (NumBonusInsts >
3869 BonusInstThreshold * BranchFoldToCommonDestVectorMultiplier)
3870 return false;
3871 }
3872
3873 auto IsBCSSAUse = [BB, &I](Use &U) {
3874 auto *UI = cast<Instruction>(U.getUser());
3875 if (auto *PN = dyn_cast<PHINode>(UI))
3876 return PN->getIncomingBlock(U) == BB;
3877 return UI->getParent() == BB && I.comesBefore(UI);
3878 };
3879
3880 // Does this instruction require rewriting of uses?
3881 if (!all_of(I.uses(), IsBCSSAUse))
3882 return false;
3883 }
3884 if (NumBonusInsts >
3885 BonusInstThreshold *
3886 (SawVectorOp ? BranchFoldToCommonDestVectorMultiplier : 1))
3887 return false;
3888
3889 // Ok, we have the budget. Perform the transformation.
3890 for (BasicBlock *PredBlock : Preds) {
3891 auto *PBI = cast<BranchInst>(PredBlock->getTerminator());
3892 return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI);
3893 }
3894 return false;
3895}
3896
3897// If there is only one store in BB1 and BB2, return it, otherwise return
3898// nullptr.
3900 StoreInst *S = nullptr;
3901 for (auto *BB : {BB1, BB2}) {
3902 if (!BB)
3903 continue;
3904 for (auto &I : *BB)
3905 if (auto *SI = dyn_cast<StoreInst>(&I)) {
3906 if (S)
3907 // Multiple stores seen.
3908 return nullptr;
3909 else
3910 S = SI;
3911 }
3912 }
3913 return S;
3914}
3915
3917 Value *AlternativeV = nullptr) {
3918 // PHI is going to be a PHI node that allows the value V that is defined in
3919 // BB to be referenced in BB's only successor.
3920 //
3921 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
3922 // doesn't matter to us what the other operand is (it'll never get used). We
3923 // could just create a new PHI with an undef incoming value, but that could
3924 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
3925 // other PHI. So here we directly look for some PHI in BB's successor with V
3926 // as an incoming operand. If we find one, we use it, else we create a new
3927 // one.
3928 //
3929 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
3930 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
3931 // where OtherBB is the single other predecessor of BB's only successor.
3932 PHINode *PHI = nullptr;
3933 BasicBlock *Succ = BB->getSingleSuccessor();
3934
3935 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
3936 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
3937 PHI = cast<PHINode>(I);
3938 if (!AlternativeV)
3939 break;
3940
3941 assert(Succ->hasNPredecessors(2));
3942 auto PredI = pred_begin(Succ);
3943 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
3944 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
3945 break;
3946 PHI = nullptr;
3947 }
3948 if (PHI)
3949 return PHI;
3950
3951 // If V is not an instruction defined in BB, just return it.
3952 if (!AlternativeV &&
3953 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
3954 return V;
3955
3956 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge");
3957 PHI->insertBefore(Succ->begin());
3958 PHI->addIncoming(V, BB);
3959 for (BasicBlock *PredBB : predecessors(Succ))
3960 if (PredBB != BB)
3961 PHI->addIncoming(
3962 AlternativeV ? AlternativeV : PoisonValue::get(V->getType()), PredBB);
3963 return PHI;
3964}
3965
3967 BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB,
3968 BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond,
3969 DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) {
3970 // For every pointer, there must be exactly two stores, one coming from
3971 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
3972 // store (to any address) in PTB,PFB or QTB,QFB.
3973 // FIXME: We could relax this restriction with a bit more work and performance
3974 // testing.
3975 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
3976 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
3977 if (!PStore || !QStore)
3978 return false;
3979
3980 // Now check the stores are compatible.
3981 if (!QStore->isUnordered() || !PStore->isUnordered() ||
3982 PStore->getValueOperand()->getType() !=
3983 QStore->getValueOperand()->getType())
3984 return false;
3985
3986 // Check that sinking the store won't cause program behavior changes. Sinking
3987 // the store out of the Q blocks won't change any behavior as we're sinking
3988 // from a block to its unconditional successor. But we're moving a store from
3989 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
3990 // So we need to check that there are no aliasing loads or stores in
3991 // QBI, QTB and QFB. We also need to check there are no conflicting memory
3992 // operations between PStore and the end of its parent block.
3993 //
3994 // The ideal way to do this is to query AliasAnalysis, but we don't
3995 // preserve AA currently so that is dangerous. Be super safe and just
3996 // check there are no other memory operations at all.
3997 for (auto &I : *QFB->getSinglePredecessor())
3998 if (I.mayReadOrWriteMemory())
3999 return false;
4000 for (auto &I : *QFB)
4001 if (&I != QStore && I.mayReadOrWriteMemory())
4002 return false;
4003 if (QTB)
4004 for (auto &I : *QTB)
4005 if (&I != QStore && I.mayReadOrWriteMemory())
4006 return false;
4007 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
4008 I != E; ++I)
4009 if (&*I != PStore && I->mayReadOrWriteMemory())
4010 return false;
4011
4012 // If we're not in aggressive mode, we only optimize if we have some
4013 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
4014 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
4015 if (!BB)
4016 return true;
4017 // Heuristic: if the block can be if-converted/phi-folded and the
4018 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
4019 // thread this store.
4021 InstructionCost Budget =
4023 for (auto &I : BB->instructionsWithoutDebug(false)) {
4024 // Consider terminator instruction to be free.
4025 if (I.isTerminator())
4026 continue;
4027 // If this is one the stores that we want to speculate out of this BB,
4028 // then don't count it's cost, consider it to be free.
4029 if (auto *S = dyn_cast<StoreInst>(&I))
4030 if (llvm::find(FreeStores, S))
4031 continue;
4032 // Else, we have a white-list of instructions that we are ak speculating.
4033 if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I))
4034 return false; // Not in white-list - not worthwhile folding.
4035 // And finally, if this is a non-free instruction that we are okay
4036 // speculating, ensure that we consider the speculation budget.
4037 Cost +=
4039 if (Cost > Budget)
4040 return false; // Eagerly refuse to fold as soon as we're out of budget.
4041 }
4042 assert(Cost <= Budget &&
4043 "When we run out of budget we will eagerly return from within the "
4044 "per-instruction loop.");
4045 return true;
4046 };
4047
4048 const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
4050 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
4051 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
4052 return false;
4053
4054 // If PostBB has more than two predecessors, we need to split it so we can
4055 // sink the store.
4056 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
4057 // We know that QFB's only successor is PostBB. And QFB has a single
4058 // predecessor. If QTB exists, then its only successor is also PostBB.
4059 // If QTB does not exist, then QFB's only predecessor has a conditional
4060 // branch to QFB and PostBB.
4061 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
4062 BasicBlock *NewBB =
4063 SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU);
4064 if (!NewBB)
4065 return false;
4066 PostBB = NewBB;
4067 }
4068
4069 // OK, we're going to sink the stores to PostBB. The store has to be
4070 // conditional though, so first create the predicate.
4071 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
4072 ->getCondition();
4073 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
4074 ->getCondition();
4075
4077 PStore->getParent());
4079 QStore->getParent(), PPHI);
4080
4081 BasicBlock::iterator PostBBFirst = PostBB->getFirstInsertionPt();
4082 IRBuilder<> QB(PostBB, PostBBFirst);
4083 QB.SetCurrentDebugLocation(PostBBFirst->getStableDebugLoc());
4084
4085 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
4086 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
4087
4088 if (InvertPCond)
4089 PPred = QB.CreateNot(PPred);
4090 if (InvertQCond)
4091 QPred = QB.CreateNot(QPred);
4092 Value *CombinedPred = QB.CreateOr(PPred, QPred);
4093
4094 BasicBlock::iterator InsertPt = QB.GetInsertPoint();
4095 auto *T = SplitBlockAndInsertIfThen(CombinedPred, InsertPt,
4096 /*Unreachable=*/false,
4097 /*BranchWeights=*/nullptr, DTU);
4098
4099 QB.SetInsertPoint(T);
4100 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
4101 SI->setAAMetadata(PStore->getAAMetadata().merge(QStore->getAAMetadata()));
4102 // Choose the minimum alignment. If we could prove both stores execute, we
4103 // could use biggest one. In this case, though, we only know that one of the
4104 // stores executes. And we don't know it's safe to take the alignment from a
4105 // store that doesn't execute.
4106 SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign()));
4107
4108 QStore->eraseFromParent();
4109 PStore->eraseFromParent();
4110
4111 return true;
4112}
4113
4115 DomTreeUpdater *DTU, const DataLayout &DL,
4116 const TargetTransformInfo &TTI) {
4117 // The intention here is to find diamonds or triangles (see below) where each
4118 // conditional block contains a store to the same address. Both of these
4119 // stores are conditional, so they can't be unconditionally sunk. But it may
4120 // be profitable to speculatively sink the stores into one merged store at the
4121 // end, and predicate the merged store on the union of the two conditions of
4122 // PBI and QBI.
4123 //
4124 // This can reduce the number of stores executed if both of the conditions are
4125 // true, and can allow the blocks to become small enough to be if-converted.
4126 // This optimization will also chain, so that ladders of test-and-set
4127 // sequences can be if-converted away.
4128 //
4129 // We only deal with simple diamonds or triangles:
4130 //
4131 // PBI or PBI or a combination of the two
4132 // / \ | \
4133 // PTB PFB | PFB
4134 // \ / | /
4135 // QBI QBI
4136 // / \ | \
4137 // QTB QFB | QFB
4138 // \ / | /
4139 // PostBB PostBB
4140 //
4141 // We model triangles as a type of diamond with a nullptr "true" block.
4142 // Triangles are canonicalized so that the fallthrough edge is represented by
4143 // a true condition, as in the diagram above.
4144 BasicBlock *PTB = PBI->getSuccessor(0);
4145 BasicBlock *PFB = PBI->getSuccessor(1);
4146 BasicBlock *QTB = QBI->getSuccessor(0);
4147 BasicBlock *QFB = QBI->getSuccessor(1);
4148 BasicBlock *PostBB = QFB->getSingleSuccessor();
4149
4150 // Make sure we have a good guess for PostBB. If QTB's only successor is
4151 // QFB, then QFB is a better PostBB.
4152 if (QTB->getSingleSuccessor() == QFB)
4153 PostBB = QFB;
4154
4155 // If we couldn't find a good PostBB, stop.
4156 if (!PostBB)
4157 return false;
4158
4159 bool InvertPCond = false, InvertQCond = false;
4160 // Canonicalize fallthroughs to the true branches.
4161 if (PFB == QBI->getParent()) {
4162 std::swap(PFB, PTB);
4163 InvertPCond = true;
4164 }
4165 if (QFB == PostBB) {
4166 std::swap(QFB, QTB);
4167 InvertQCond = true;
4168 }
4169
4170 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
4171 // and QFB may not. Model fallthroughs as a nullptr block.
4172 if (PTB == QBI->getParent())
4173 PTB = nullptr;
4174 if (QTB == PostBB)
4175 QTB = nullptr;
4176
4177 // Legality bailouts. We must have at least the non-fallthrough blocks and
4178 // the post-dominating block, and the non-fallthroughs must only have one
4179 // predecessor.
4180 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
4181 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
4182 };
4183 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
4184 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
4185 return false;
4186 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
4187 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
4188 return false;
4189 if (!QBI->getParent()->hasNUses(2))
4190 return false;
4191
4192 // OK, this is a sequence of two diamonds or triangles.
4193 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
4194 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
4195 for (auto *BB : {PTB, PFB}) {
4196 if (!BB)
4197 continue;
4198 for (auto &I : *BB)
4199 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
4200 PStoreAddresses.insert(SI->getPointerOperand());
4201 }
4202 for (auto *BB : {QTB, QFB}) {
4203 if (!BB)
4204 continue;
4205 for (auto &I : *BB)
4206 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
4207 QStoreAddresses.insert(SI->getPointerOperand());
4208 }
4209
4210 set_intersect(PStoreAddresses, QStoreAddresses);
4211 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
4212 // clear what it contains.
4213 auto &CommonAddresses = PStoreAddresses;
4214
4215 bool Changed = false;
4216 for (auto *Address : CommonAddresses)
4217 Changed |=
4218 mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address,
4219 InvertPCond, InvertQCond, DTU, DL, TTI);
4220 return Changed;
4221}
4222
4223/// If the previous block ended with a widenable branch, determine if reusing
4224/// the target block is profitable and legal. This will have the effect of
4225/// "widening" PBI, but doesn't require us to reason about hosting safety.
4227 DomTreeUpdater *DTU) {
4228 // TODO: This can be generalized in two important ways:
4229 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
4230 // values from the PBI edge.
4231 // 2) We can sink side effecting instructions into BI's fallthrough
4232 // successor provided they doesn't contribute to computation of
4233 // BI's condition.
4234 BasicBlock *IfTrueBB = PBI->getSuccessor(0);
4235 BasicBlock *IfFalseBB = PBI->getSuccessor(1);
4236 if (!isWidenableBranch(PBI) || IfTrueBB != BI->getParent() ||
4238 return false;
4239 if (!IfFalseBB->phis().empty())
4240 return false; // TODO
4241 // This helps avoid infinite loop with SimplifyCondBranchToCondBranch which
4242 // may undo the transform done here.
4243 // TODO: There might be a more fine-grained solution to this.
4244 if (!llvm::succ_empty(IfFalseBB))
4245 return false;
4246 // Use lambda to lazily compute expensive condition after cheap ones.
4247 auto NoSideEffects = [](BasicBlock &BB) {
4248 return llvm::none_of(BB, [](const Instruction &I) {
4249 return I.mayWriteToMemory() || I.mayHaveSideEffects();
4250 });
4251 };
4252 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
4253 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
4254 NoSideEffects(*BI->getParent())) {
4255 auto *OldSuccessor = BI->getSuccessor(1);
4256 OldSuccessor->removePredecessor(BI->getParent());
4257 BI->setSuccessor(1, IfFalseBB);
4258 if (DTU)
4259 DTU->applyUpdates(
4260 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4261 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4262 return true;
4263 }
4264 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
4265 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
4266 NoSideEffects(*BI->getParent())) {
4267 auto *OldSuccessor = BI->getSuccessor(0);
4268 OldSuccessor->removePredecessor(BI->getParent());
4269 BI->setSuccessor(0, IfFalseBB);
4270 if (DTU)
4271 DTU->applyUpdates(
4272 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4273 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4274 return true;
4275 }
4276 return false;
4277}
4278
4279/// If we have a conditional branch as a predecessor of another block,
4280/// this function tries to simplify it. We know
4281/// that PBI and BI are both conditional branches, and BI is in one of the
4282/// successor blocks of PBI - PBI branches to BI.
4284 DomTreeUpdater *DTU,
4285 const DataLayout &DL,
4286 const TargetTransformInfo &TTI) {
4287 assert(PBI->isConditional() && BI->isConditional());
4288 BasicBlock *BB = BI->getParent();
4289
4290 // If this block ends with a branch instruction, and if there is a
4291 // predecessor that ends on a branch of the same condition, make
4292 // this conditional branch redundant.
4293 if (PBI->getCondition() == BI->getCondition() &&
4294 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
4295 // Okay, the outcome of this conditional branch is statically
4296 // knowable. If this block had a single pred, handle specially, otherwise
4297 // FoldCondBranchOnValueKnownInPredecessor() will handle it.
4298 if (BB->getSinglePredecessor()) {
4299 // Turn this into a branch on constant.
4300 bool CondIsTrue = PBI->getSuccessor(0) == BB;
4301 BI->setCondition(
4302 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
4303 return true; // Nuke the branch on constant.
4304 }
4305 }
4306
4307 // If the previous block ended with a widenable branch, determine if reusing
4308 // the target block is profitable and legal. This will have the effect of
4309 // "widening" PBI, but doesn't require us to reason about hosting safety.
4310 if (tryWidenCondBranchToCondBranch(PBI, BI, DTU))
4311 return true;
4312
4313 // If both branches are conditional and both contain stores to the same
4314 // address, remove the stores from the conditionals and create a conditional
4315 // merged store at the end.
4316 if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI))
4317 return true;
4318
4319 // If this is a conditional branch in an empty block, and if any
4320 // predecessors are a conditional branch to one of our destinations,
4321 // fold the conditions into logical ops and one cond br.
4322
4323 // Ignore dbg intrinsics.
4324 if (&*BB->instructionsWithoutDebug(false).begin() != BI)
4325 return false;
4326
4327 int PBIOp, BIOp;
4328 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4329 PBIOp = 0;
4330 BIOp = 0;
4331 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4332 PBIOp = 0;
4333 BIOp = 1;
4334 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4335 PBIOp = 1;
4336 BIOp = 0;
4337 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4338 PBIOp = 1;
4339 BIOp = 1;
4340 } else {
4341 return false;
4342 }
4343
4344 // Check to make sure that the other destination of this branch
4345 // isn't BB itself. If so, this is an infinite loop that will
4346 // keep getting unwound.
4347 if (PBI->getSuccessor(PBIOp) == BB)
4348 return false;
4349
4350 // Do not perform this transformation if it would require
4351 // insertion of a large number of select instructions. For targets
4352 // without predication/cmovs, this is a big pessimization.
4353
4354 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
4355 BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1);
4356 unsigned NumPhis = 0;
4357 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
4358 ++II, ++NumPhis) {
4359 if (NumPhis > 2) // Disable this xform.
4360 return false;
4361 }
4362
4363 // Finally, if everything is ok, fold the branches to logical ops.
4364 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
4365
4366 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
4367 << "AND: " << *BI->getParent());
4368
4370
4371 // If OtherDest *is* BB, then BB is a basic block with a single conditional
4372 // branch in it, where one edge (OtherDest) goes back to itself but the other
4373 // exits. We don't *know* that the program avoids the infinite loop
4374 // (even though that seems likely). If we do this xform naively, we'll end up
4375 // recursively unpeeling the loop. Since we know that (after the xform is
4376 // done) that the block *is* infinite if reached, we just make it an obviously
4377 // infinite loop with no cond branch.
4378 if (OtherDest == BB) {
4379 // Insert it at the end of the function, because it's either code,
4380 // or it won't matter if it's hot. :)
4381 BasicBlock *InfLoopBlock =
4382 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
4383 BranchInst::Create(InfLoopBlock, InfLoopBlock);
4384 if (DTU)
4385 Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
4386 OtherDest = InfLoopBlock;
4387 }
4388
4389 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4390
4391 // BI may have other predecessors. Because of this, we leave
4392 // it alone, but modify PBI.
4393
4394 // Make sure we get to CommonDest on True&True directions.
4395 Value *PBICond = PBI->getCondition();
4397 if (PBIOp)
4398 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
4399
4400 Value *BICond = BI->getCondition();
4401 if (BIOp)
4402 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
4403
4404 // Merge the conditions.
4405 Value *Cond =
4406 createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge");
4407
4408 // Modify PBI to branch on the new condition to the new dests.
4409 PBI->setCondition(Cond);
4410 PBI->setSuccessor(0, CommonDest);
4411 PBI->setSuccessor(1, OtherDest);
4412
4413 if (DTU) {
4414 Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest});
4415 Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest});
4416
4417 DTU->applyUpdates(Updates);
4418 }
4419
4420 // Update branch weight for PBI.
4421 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4422 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
4423 bool HasWeights =
4424 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4425 SuccTrueWeight, SuccFalseWeight);
4426 if (HasWeights) {
4427 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4428 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4429 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4430 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4431 // The weight to CommonDest should be PredCommon * SuccTotal +
4432 // PredOther * SuccCommon.
4433 // The weight to OtherDest should be PredOther * SuccOther.
4434 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
4435 PredOther * SuccCommon,
4436 PredOther * SuccOther};
4437 // Halve the weights if any of them cannot fit in an uint32_t
4438 FitWeights(NewWeights);
4439
4440 setBranchWeights(PBI, NewWeights[0], NewWeights[1]);
4441 }
4442
4443 // OtherDest may have phi nodes. If so, add an entry from PBI's
4444 // block that are identical to the entries for BI's block.
4445 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
4446
4447 // We know that the CommonDest already had an edge from PBI to
4448 // it. If it has PHIs though, the PHIs may have different
4449 // entries for BB and PBI's BB. If so, insert a select to make
4450 // them agree.
4451 for (PHINode &PN : CommonDest->phis()) {
4452 Value *BIV = PN.getIncomingValueForBlock(BB);
4453 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
4454 Value *PBIV = PN.getIncomingValue(PBBIdx);
4455 if (BIV != PBIV) {
4456 // Insert a select in PBI to pick the right value.
4457 SelectInst *NV = cast<SelectInst>(
4458 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
4459 PN.setIncomingValue(PBBIdx, NV);
4460 // Although the select has the same condition as PBI, the original branch
4461 // weights for PBI do not apply to the new select because the select's
4462 // 'logical' edges are incoming edges of the phi that is eliminated, not
4463 // the outgoing edges of PBI.
4464 if (HasWeights) {
4465 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4466 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4467 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4468 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4469 // The weight to PredCommonDest should be PredCommon * SuccTotal.
4470 // The weight to PredOtherDest should be PredOther * SuccCommon.
4471 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
4472 PredOther * SuccCommon};
4473
4474 FitWeights(NewWeights);
4475
4476 setBranchWeights(NV, NewWeights[0], NewWeights[1]);
4477 }
4478 }
4479 }
4480
4481 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
4482 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4483
4484 // This basic block is probably dead. We know it has at least
4485 // one fewer predecessor.
4486 return true;
4487}
4488
4489// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
4490// true or to FalseBB if Cond is false.
4491// Takes care of updating the successors and removing the old terminator.
4492// Also makes sure not to introduce new successors by assuming that edges to
4493// non-successor TrueBBs and FalseBBs aren't reachable.
4494bool SimplifyCFGOpt::SimplifyTerminatorOnSelect(Instruction *OldTerm,
4495 Value *Cond, BasicBlock *TrueBB,
4496 BasicBlock *FalseBB,
4497 uint32_t TrueWeight,
4498 uint32_t FalseWeight) {
4499 auto *BB = OldTerm->getParent();
4500 // Remove any superfluous successor edges from the CFG.
4501 // First, figure out which successors to preserve.
4502 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
4503 // successor.
4504 BasicBlock *KeepEdge1 = TrueBB;
4505 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
4506
4507 SmallSetVector<BasicBlock *, 2> RemovedSuccessors;
4508
4509 // Then remove the rest.
4510 for (BasicBlock *Succ : successors(OldTerm)) {
4511 // Make sure only to keep exactly one copy of each edge.
4512 if (Succ == KeepEdge1)
4513 KeepEdge1 = nullptr;
4514 else if (Succ == KeepEdge2)
4515 KeepEdge2 = nullptr;
4516 else {
4517 Succ->removePredecessor(BB,
4518 /*KeepOneInputPHIs=*/true);
4519
4520 if (Succ != TrueBB && Succ != FalseBB)
4521 RemovedSuccessors.insert(Succ);
4522 }
4523 }
4524
4525 IRBuilder<> Builder(OldTerm);
4526 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
4527
4528 // Insert an appropriate new terminator.
4529 if (!KeepEdge1 && !KeepEdge2) {
4530 if (TrueBB == FalseBB) {
4531 // We were only looking for one successor, and it was present.
4532 // Create an unconditional branch to it.
4533 Builder.CreateBr(TrueBB);
4534 } else {
4535 // We found both of the successors we were looking for.
4536 // Create a conditional branch sharing the condition of the select.
4537 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
4538 if (TrueWeight != FalseWeight)
4539 setBranchWeights(NewBI, TrueWeight, FalseWeight);
4540 }
4541 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
4542 // Neither of the selected blocks were successors, so this
4543 // terminator must be unreachable.
4544 new UnreachableInst(OldTerm->getContext(), OldTerm);
4545 } else {
4546 // One of the selected values was a successor, but the other wasn't.
4547 // Insert an unconditional branch to the one that was found;
4548 // the edge to the one that wasn't must be unreachable.
4549 if (!KeepEdge1) {
4550 // Only TrueBB was found.
4551 Builder.CreateBr(TrueBB);
4552 } else {
4553 // Only FalseBB was found.
4554 Builder.CreateBr(FalseBB);
4555 }
4556 }
4557
4559
4560 if (DTU) {
4562 Updates.reserve(RemovedSuccessors.size());
4563 for (auto *RemovedSuccessor : RemovedSuccessors)
4564 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
4565 DTU->applyUpdates(Updates);
4566 }
4567
4568 return true;
4569}
4570
4571// Replaces
4572// (switch (select cond, X, Y)) on constant X, Y
4573// with a branch - conditional if X and Y lead to distinct BBs,
4574// unconditional otherwise.
4575bool SimplifyCFGOpt::SimplifySwitchOnSelect(SwitchInst *SI,
4576 SelectInst *Select) {
4577 // Check for constant integer values in the select.
4578 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
4579 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
4580 if (!TrueVal || !FalseVal)
4581 return false;
4582
4583 // Find the relevant condition and destinations.
4584 Value *Condition = Select->getCondition();
4585 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
4586 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
4587
4588 // Get weight for TrueBB and FalseBB.
4589 uint32_t TrueWeight = 0, FalseWeight = 0;
4591 bool HasWeights = hasBranchWeightMD(*SI);
4592 if (HasWeights) {
4593 GetBranchWeights(SI, Weights);
4594 if (Weights.size() == 1 + SI->getNumCases()) {
4595 TrueWeight =
4596 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
4597 FalseWeight =
4598 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
4599 }
4600 }
4601
4602 // Perform the actual simplification.
4603 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
4604 FalseWeight);
4605}
4606
4607// Replaces
4608// (indirectbr (select cond, blockaddress(@fn, BlockA),
4609// blockaddress(@fn, BlockB)))
4610// with
4611// (br cond, BlockA, BlockB).
4612bool SimplifyCFGOpt::SimplifyIndirectBrOnSelect(IndirectBrInst *IBI,
4613 SelectInst *SI) {
4614 // Check that both operands of the select are block addresses.
4615 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
4616 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
4617 if (!TBA || !FBA)
4618 return false;
4619
4620 // Extract the actual blocks.
4621 BasicBlock *TrueBB = TBA->getBasicBlock();
4622 BasicBlock *FalseBB = FBA->getBasicBlock();
4623
4624 // Perform the actual simplification.
4625 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
4626 0);
4627}
4628
4629/// This is called when we find an icmp instruction
4630/// (a seteq/setne with a constant) as the only instruction in a
4631/// block that ends with an uncond branch. We are looking for a very specific
4632/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
4633/// this case, we merge the first two "or's of icmp" into a switch, but then the
4634/// default value goes to an uncond block with a seteq in it, we get something
4635/// like:
4636///
4637/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
4638/// DEFAULT:
4639/// %tmp = icmp eq i8 %A, 92
4640/// br label %end
4641/// end:
4642/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
4643///
4644/// We prefer to split the edge to 'end' so that there is a true/false entry to
4645/// the PHI, merging the third icmp into the switch.
4646bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
4647 ICmpInst *ICI, IRBuilder<> &Builder) {
4648 BasicBlock *BB = ICI->getParent();
4649
4650 // If the block has any PHIs in it or the icmp has multiple uses, it is too
4651 // complex.
4652 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
4653 return false;
4654
4655 Value *V = ICI->getOperand(0);
4656 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
4657
4658 // The pattern we're looking for is where our only predecessor is a switch on
4659 // 'V' and this block is the default case for the switch. In this case we can
4660 // fold the compared value into the switch to simplify things.
4661 BasicBlock *Pred = BB->getSinglePredecessor();
4662 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
4663 return false;
4664
4665 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
4666 if (SI->getCondition() != V)
4667 return false;
4668
4669 // If BB is reachable on a non-default case, then we simply know the value of
4670 // V in this block. Substitute it and constant fold the icmp instruction
4671 // away.
4672 if (SI->getDefaultDest() != BB) {
4673 ConstantInt *VVal = SI->findCaseDest(BB);
4674 assert(VVal && "Should have a unique destination value");
4675 ICI->setOperand(0, VVal);
4676
4677 if (Value *V = simplifyInstruction(ICI, {DL, ICI})) {
4678 ICI->replaceAllUsesWith(V);
4679 ICI->eraseFromParent();
4680 }
4681 // BB is now empty, so it is likely to simplify away.
4682 return requestResimplify();
4683 }
4684
4685 // Ok, the block is reachable from the default dest. If the constant we're
4686 // comparing exists in one of the other edges, then we can constant fold ICI
4687 // and zap it.
4688 if (SI->findCaseValue(Cst) != SI->case_default()) {
4689 Value *V;
4690 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
4692 else
4694
4695 ICI->replaceAllUsesWith(V);
4696 ICI->eraseFromParent();
4697 // BB is now empty, so it is likely to simplify away.
4698 return requestResimplify();
4699 }
4700
4701 // The use of the icmp has to be in the 'end' block, by the only PHI node in
4702 // the block.
4703 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
4704 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
4705 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
4706 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
4707 return false;
4708
4709 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
4710 // true in the PHI.
4711 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
4712 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
4713
4714 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
4715 std::swap(DefaultCst, NewCst);
4716
4717 // Replace ICI (which is used by the PHI for the default value) with true or
4718 // false depending on if it is EQ or NE.
4719 ICI->replaceAllUsesWith(DefaultCst);
4720 ICI->eraseFromParent();
4721
4723
4724 // Okay, the switch goes to this block on a default value. Add an edge from
4725 // the switch to the merge point on the compared value.
4726 BasicBlock *NewBB =
4727 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
4728 {
4730 auto W0 = SIW.getSuccessorWeight(0);
4732 if (W0) {
4733 NewW = ((uint64_t(*W0) + 1) >> 1);
4734 SIW.setSuccessorWeight(0, *NewW);
4735 }
4736 SIW.addCase(Cst, NewBB, NewW);
4737 if (DTU)
4738 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
4739 }
4740
4741 // NewBB branches to the phi block, add the uncond branch and the phi entry.
4742 Builder.SetInsertPoint(NewBB);
4743 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
4744 Builder.CreateBr(SuccBlock);
4745 PHIUse->addIncoming(NewCst, NewBB);
4746 if (DTU) {
4747 Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock});
4748 DTU->applyUpdates(Updates);
4749 }
4750 return true;
4751}
4752
4753/// The specified branch is a conditional branch.
4754/// Check to see if it is branching on an or/and chain of icmp instructions, and
4755/// fold it into a switch instruction if so.
4756bool SimplifyCFGOpt::SimplifyBranchOnICmpChain(BranchInst *BI,
4757 IRBuilder<> &Builder,
4758 const DataLayout &DL) {
4759 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
4760 if (!Cond)
4761 return false;
4762
4763 // Change br (X == 0 | X == 1), T, F into a switch instruction.
4764 // If this is a bunch of seteq's or'd together, or if it's a bunch of
4765 // 'setne's and'ed together, collect them.
4766
4767 // Try to gather values from a chain of and/or to be turned into a switch
4768 ConstantComparesGatherer ConstantCompare(Cond, DL);
4769 // Unpack the result
4770 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
4771 Value *CompVal = ConstantCompare.CompValue;
4772 unsigned UsedICmps = ConstantCompare.UsedICmps;
4773 Value *ExtraCase = ConstantCompare.Extra;
4774
4775 // If we didn't have a multiply compared value, fail.
4776 if (!CompVal)
4777 return false;
4778
4779 // Avoid turning single icmps into a switch.
4780 if (UsedICmps <= 1)
4781 return false;
4782
4783 bool TrueWhenEqual = match(Cond, m_LogicalOr(m_Value(), m_Value()));
4784
4785 // There might be duplicate constants in the list, which the switch
4786 // instruction can't handle, remove them now.
4787 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
4788 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
4789
4790 // If Extra was used, we require at least two switch values to do the
4791 // transformation. A switch with one value is just a conditional branch.
4792 if (ExtraCase && Values.size() < 2)
4793 return false;
4794
4795 // TODO: Preserve branch weight metadata, similarly to how
4796 // FoldValueComparisonIntoPredecessors preserves it.
4797
4798 // Figure out which block is which destination.
4799 BasicBlock *DefaultBB = BI->getSuccessor(1);
4800 BasicBlock *EdgeBB = BI->getSuccessor(0);
4801 if (!TrueWhenEqual)
4802 std::swap(DefaultBB, EdgeBB);
4803
4804 BasicBlock *BB = BI->getParent();
4805
4806 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
4807 << " cases into SWITCH. BB is:\n"
4808 << *BB);
4809
4811
4812 // If there are any extra values that couldn't be folded into the switch
4813 // then we evaluate them with an explicit branch first. Split the block
4814 // right before the condbr to handle it.
4815 if (ExtraCase) {
4816 BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr,
4817 /*MSSAU=*/nullptr, "switch.early.test");
4818
4819 // Remove the uncond branch added to the old block.
4820 Instruction *OldTI = BB->getTerminator();
4821 Builder.SetInsertPoint(OldTI);
4822
4823 // There can be an unintended UB if extra values are Poison. Before the
4824 // transformation, extra values may not be evaluated according to the
4825 // condition, and it will not raise UB. But after transformation, we are
4826 // evaluating extra values before checking the condition, and it will raise
4827 // UB. It can be solved by adding freeze instruction to extra values.
4828 AssumptionCache *AC = Options.AC;
4829
4830 if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr))
4831 ExtraCase = Builder.CreateFreeze(ExtraCase);
4832
4833 if (TrueWhenEqual)
4834 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
4835 else
4836 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
4837
4838 OldTI->eraseFromParent();
4839
4840 if (DTU)
4841 Updates.push_back({DominatorTree::Insert, BB, EdgeBB});
4842
4843 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
4844 // for the edge we just added.
4845 AddPredecessorToBlock(EdgeBB, BB, NewBB);
4846
4847 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
4848 << "\nEXTRABB = " << *BB);
4849 BB = NewBB;
4850 }
4851
4852 Builder.SetInsertPoint(BI);
4853 // Convert pointer to int before we switch.
4854 if (CompVal->getType()->isPointerTy()) {
4855 CompVal = Builder.CreatePtrToInt(
4856 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
4857 }
4858
4859 // Create the new switch instruction now.
4860 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
4861
4862 // Add all of the 'cases' to the switch instruction.
4863 for (unsigned i = 0, e = Values.size(); i != e; ++i)
4864 New->addCase(Values[i], EdgeBB);
4865
4866 // We added edges from PI to the EdgeBB. As such, if there were any
4867 // PHI nodes in EdgeBB, they need entries to be added corresponding to
4868 // the number of edges added.
4869 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
4870 PHINode *PN = cast<PHINode>(BBI);
4871 Value *InVal = PN->getIncomingValueForBlock(BB);
4872 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
4873 PN->addIncoming(InVal, BB);
4874 }
4875
4876 // Erase the old branch instruction.
4878 if (DTU)
4879 DTU->applyUpdates(Updates);
4880
4881 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
4882 return true;
4883}
4884
4885bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
4886 if (isa<PHINode>(RI->getValue()))
4887 return simplifyCommonResume(RI);
4888 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
4889 RI->getValue() == RI->getParent()->getFirstNonPHI())
4890 // The resume must unwind the exception that caused control to branch here.
4891 return simplifySingleResume(RI);
4892
4893 return false;
4894}
4895
4896// Check if cleanup block is empty
4898 for (Instruction &I : R) {
4899 auto *II = dyn_cast<IntrinsicInst>(&I);
4900 if (!II)
4901 return false;
4902
4903 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
4904 switch (IntrinsicID) {
4905 case Intrinsic::dbg_declare:
4906 case Intrinsic::dbg_value:
4907 case Intrinsic::dbg_label:
4908 case Intrinsic::lifetime_end:
4909 break;
4910 default:
4911 return false;
4912 }
4913 }
4914 return true;
4915}
4916
4917// Simplify resume that is shared by several landing pads (phi of landing pad).
4918bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
4919 BasicBlock *BB = RI->getParent();
4920
4921 // Check that there are no other instructions except for debug and lifetime
4922 // intrinsics between the phi's and resume instruction.
4925 return false;
4926
4927 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
4928 auto *PhiLPInst = cast<PHINode>(RI->getValue());
4929
4930 // Check incoming blocks to see if any of them are trivial.
4931 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
4932 Idx++) {
4933 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
4934 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
4935
4936 // If the block has other successors, we can not delete it because
4937 // it has other dependents.
4938 if (IncomingBB->getUniqueSuccessor() != BB)
4939 continue;
4940
4941 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
4942 // Not the landing pad that caused the control to branch here.
4943 if (IncomingValue != LandingPad)
4944 continue;
4945
4947 make_range(LandingPad->getNextNode(), IncomingBB->getTerminator())))
4948 TrivialUnwindBlocks.insert(IncomingBB);
4949 }
4950
4951 // If no trivial unwind blocks, don't do any simplifications.
4952 if (TrivialUnwindBlocks.empty())
4953 return false;
4954
4955 // Turn all invokes that unwind here into calls.
4956 for (auto *TrivialBB : TrivialUnwindBlocks) {
4957 // Blocks that will be simplified should be removed from the phi node.
4958 // Note there could be multiple edges to the resume block, and we need
4959 // to remove them all.
4960 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
4961 BB->removePredecessor(TrivialBB, true);
4962
4963 for (BasicBlock *Pred :
4965 removeUnwindEdge(Pred, DTU);
4966 ++NumInvokes;
4967 }
4968
4969 // In each SimplifyCFG run, only the current processed block can be erased.
4970 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
4971 // of erasing TrivialBB, we only remove the branch to the common resume
4972 // block so that we can later erase the resume block since it has no
4973 // predecessors.
4974 TrivialBB->getTerminator()->eraseFromParent();
4975 new UnreachableInst(RI->getContext(), TrivialBB);
4976 if (DTU)
4977 DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}});
4978 }
4979
4980 // Delete the resume block if all its predecessors have been removed.
4981 if (pred_empty(BB))
4982 DeleteDeadBlock(BB, DTU);
4983
4984 return !TrivialUnwindBlocks.empty();
4985}
4986
4987// Simplify resume that is only used by a single (non-phi) landing pad.
4988bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
4989 BasicBlock *BB = RI->getParent();
4990 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI());
4991 assert(RI->getValue() == LPInst &&
4992 "Resume must unwind the exception that caused control to here");
4993
4994 // Check that there are no other instructions except for debug intrinsics.
4996 make_range<Instruction *>(LPInst->getNextNode(), RI)))
4997 return false;
4998
4999 // Turn all invokes that unwind here into calls and delete the basic block.
5001 removeUnwindEdge(Pred, DTU);
5002 ++NumInvokes;
5003 }
5004
5005 // The landingpad is now unreachable. Zap it.
5006 DeleteDeadBlock(BB, DTU);
5007 return true;
5008}
5009
5011 // If this is a trivial cleanup pad that executes no instructions, it can be
5012 // eliminated. If the cleanup pad continues to the caller, any predecessor
5013 // that is an EH pad will be updated to continue to the caller and any
5014 // predecessor that terminates with an invoke instruction will have its invoke
5015 // instruction converted to a call instruction. If the cleanup pad being
5016 // simplified does not continue to the caller, each predecessor will be
5017 // updated to continue to the unwind destination of the cleanup pad being
5018 // simplified.
5019 BasicBlock *BB = RI->getParent();
5020 CleanupPadInst *CPInst = RI->getCleanupPad();
5021 if (CPInst->getParent() != BB)
5022 // This isn't an empty cleanup.
5023 return false;
5024
5025 // We cannot kill the pad if it has multiple uses. This typically arises
5026 // from unreachable basic blocks.
5027 if (!CPInst->hasOneUse())
5028 return false;
5029
5030 // Check that there are no other instructions except for benign intrinsics.
5032 make_range<Instruction *>(CPInst->getNextNode(), RI)))
5033 return false;
5034
5035 // If the cleanup return we are simplifying unwinds to the caller, this will
5036 // set UnwindDest to nullptr.
5037 BasicBlock *UnwindDest = RI->getUnwindDest();
5038 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
5039
5040 // We're about to remove BB from the control flow. Before we do, sink any
5041 // PHINodes into the unwind destination. Doing this before changing the
5042 // control flow avoids some potentially slow checks, since we can currently
5043 // be certain that UnwindDest and BB have no common predecessors (since they
5044 // are both EH pads).
5045 if (UnwindDest) {
5046 // First, go through the PHI nodes in UnwindDest and update any nodes that
5047 // reference the block we are removing
5048 for (PHINode &DestPN : UnwindDest->phis()) {
5049 int Idx = DestPN.getBasicBlockIndex(BB);
5050 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
5051 assert(Idx != -1);
5052 // This PHI node has an incoming value that corresponds to a control
5053 // path through the cleanup pad we are removing. If the incoming
5054 // value is in the cleanup pad, it must be a PHINode (because we
5055 // verified above that the block is otherwise empty). Otherwise, the
5056 // value is either a constant or a value that dominates the cleanup
5057 // pad being removed.
5058 //
5059 // Because BB and UnwindDest are both EH pads, all of their
5060 // predecessors must unwind to these blocks, and since no instruction
5061 // can have multiple unwind destinations, there will be no overlap in
5062 // incoming blocks between SrcPN and DestPN.
5063 Value *SrcVal = DestPN.getIncomingValue(Idx);
5064 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
5065
5066 bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB;
5067 for (auto *Pred : predecessors(BB)) {
5068 Value *Incoming =
5069 NeedPHITranslation ? SrcPN->getIncomingValueForBlock(Pred) : SrcVal;
5070 DestPN.addIncoming(Incoming, Pred);
5071 }
5072 }
5073
5074 // Sink any remaining PHI nodes directly into UnwindDest.
5075 Instruction *InsertPt = DestEHPad;
5076 for (PHINode &PN : make_early_inc_range(BB->phis())) {
5077 if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB))
5078 // If the PHI node has no uses or all of its uses are in this basic
5079 // block (meaning they are debug or lifetime intrinsics), just leave
5080 // it. It will be erased when we erase BB below.
5081 continue;
5082
5083 // Otherwise, sink this PHI node into UnwindDest.
5084 // Any predecessors to UnwindDest which are not already represented
5085 // must be back edges which inherit the value from the path through
5086 // BB. In this case, the PHI value must reference itself.
5087 for (auto *pred : predecessors(UnwindDest))
5088 if (pred != BB)
5089 PN.addIncoming(&PN, pred);
5090 PN.moveBefore(InsertPt);
5091 // Also, add a dummy incoming value for the original BB itself,
5092 // so that the PHI is well-formed until we drop said predecessor.
5093 PN.addIncoming(PoisonValue::get(PN.getType()), BB);
5094 }
5095 }
5096
5097 std::vector<DominatorTree::UpdateType> Updates;
5098
5099 // We use make_early_inc_range here because we will remove all predecessors.
5101 if (UnwindDest == nullptr) {
5102 if (DTU) {
5103 DTU->applyUpdates(Updates);
5104 Updates.clear();
5105 }
5106 removeUnwindEdge(PredBB, DTU);
5107 ++NumInvokes;
5108 } else {
5109 BB->removePredecessor(PredBB);
5110 Instruction *TI = PredBB->getTerminator();
5111 TI->replaceUsesOfWith(BB, UnwindDest);
5112 if (DTU) {
5113 Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest});
5114 Updates.push_back({DominatorTree::Delete, PredBB, BB});
5115 }
5116 }
5117 }
5118
5119 if (DTU)
5120 DTU->applyUpdates(Updates);
5121
5122 DeleteDeadBlock(BB, DTU);
5123
5124 return true;
5125}
5126
5127// Try to merge two cleanuppads together.
5129 // Skip any cleanuprets which unwind to caller, there is nothing to merge
5130 // with.
5131 BasicBlock *UnwindDest = RI->getUnwindDest();
5132 if (!UnwindDest)
5133 return false;
5134
5135 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
5136 // be safe to merge without code duplication.
5137 if (UnwindDest->getSinglePredecessor() != RI->getParent())
5138 return false;
5139
5140 // Verify that our cleanuppad's unwind destination is another cleanuppad.
5141 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
5142 if (!SuccessorCleanupPad)
5143 return false;
5144
5145 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
5146 // Replace any uses of the successor cleanupad with the predecessor pad
5147 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
5148 // funclet bundle operands.
5149 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
5150 // Remove the old cleanuppad.
5151 SuccessorCleanupPad->eraseFromParent();
5152 // Now, we simply replace the cleanupret with a branch to the unwind
5153 // destination.
5154 BranchInst::Create(UnwindDest, RI->getParent());
5155 RI->eraseFromParent();
5156
5157 return true;
5158}
5159
5160bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
5161 // It is possible to transiantly have an undef cleanuppad operand because we
5162 // have deleted some, but not all, dead blocks.
5163 // Eventually, this block will be deleted.
5164 if (isa<UndefValue>(RI->