LLVM 24.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/Sequence.h"
20#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/StringRef.h"
31#include "llvm/Analysis/Loads.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"
56#include "llvm/IR/Metadata.h"
57#include "llvm/IR/Module.h"
58#include "llvm/IR/NoFolder.h"
59#include "llvm/IR/Operator.h"
62#include "llvm/IR/Type.h"
63#include "llvm/IR/Use.h"
64#include "llvm/IR/User.h"
65#include "llvm/IR/Value.h"
66#include "llvm/IR/ValueHandle.h"
70#include "llvm/Support/Debug.h"
80#include <algorithm>
81#include <cassert>
82#include <climits>
83#include <cstddef>
84#include <cstdint>
85#include <iterator>
86#include <map>
87#include <optional>
88#include <set>
89#include <tuple>
90#include <utility>
91#include <vector>
92
93using namespace llvm;
94using namespace PatternMatch;
95
96#define DEBUG_TYPE "simplifycfg"
97
98namespace llvm {
99
101 "simplifycfg-require-and-preserve-domtree", cl::Hidden,
102
103 cl::desc(
104 "Temporary development switch used to gradually uplift SimplifyCFG "
105 "into preserving DomTree,"));
106
107// Chosen as 2 so as to be cheap, but still to have enough power to fold
108// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
109// To catch this, we need to fold a compare and a select, hence '2' being the
110// minimum reasonable default.
112 "phi-node-folding-threshold", cl::Hidden, cl::init(2),
113 cl::desc(
114 "Control the amount of phi node folding to perform (default = 2)"));
115
117 "two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4),
118 cl::desc("Control the maximal total instruction cost that we are willing "
119 "to speculatively execute to fold a 2-entry PHI node into a "
120 "select (default = 4)"));
121
122static cl::opt<bool>
123 HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true),
124 cl::desc("Hoist common instructions up to the parent block"));
125
127 "simplifycfg-hoist-loads-with-cond-faulting", cl::Hidden, cl::init(true),
128 cl::desc("Hoist loads if the target supports conditional faulting"));
129
131 "simplifycfg-hoist-stores-with-cond-faulting", cl::Hidden, cl::init(true),
132 cl::desc("Hoist stores if the target supports conditional faulting"));
133
135 "hoist-loads-stores-with-cond-faulting-threshold", cl::Hidden, cl::init(6),
136 cl::desc("Control the maximal conditional load/store that we are willing "
137 "to speculatively execute to eliminate conditional branch "
138 "(default = 6)"));
139
141 HoistCommonSkipLimit("simplifycfg-hoist-common-skip-limit", cl::Hidden,
142 cl::init(20),
143 cl::desc("Allow reordering across at most this many "
144 "instructions when hoisting"));
145
146static cl::opt<bool>
147 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
148 cl::desc("Sink common instructions down to the end block"));
149
151 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
152 cl::desc("Hoist conditional stores if an unconditional store precedes"));
153
155 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
156 cl::desc("Hoist conditional stores even if an unconditional store does not "
157 "precede - hoist multiple conditional stores into a single "
158 "predicated store"));
159
161 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
162 cl::desc("When merging conditional stores, do so even if the resultant "
163 "basic blocks are unlikely to be if-converted as a result"));
164
166 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
167 cl::desc("Allow exactly one expensive instruction to be speculatively "
168 "executed"));
169
171 "max-speculation-depth", cl::Hidden, cl::init(10),
172 cl::desc("Limit maximum recursion depth when calculating costs of "
173 "speculatively executed instructions"));
174
175static cl::opt<int>
176 MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden,
177 cl::init(10),
178 cl::desc("Max size of a block which is still considered "
179 "small enough to thread through"));
180
181// Two is chosen to allow one negation and a logical combine.
183 BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden,
184 cl::init(2),
185 cl::desc("Maximum cost of combining conditions when "
186 "folding branches"));
187
189 "simplifycfg-branch-fold-common-dest-vector-multiplier", cl::Hidden,
190 cl::init(2),
191 cl::desc("Multiplier to apply to threshold when determining whether or not "
192 "to fold branch to common destination when vector operations are "
193 "present"));
194
196 "simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(true),
197 cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"));
198
200 "max-switch-cases-per-result", cl::Hidden, cl::init(16),
201 cl::desc("Limit cases to analyze when converting a switch to select"));
202
204 "max-jump-threading-live-blocks", cl::Hidden, cl::init(24),
205 cl::desc("Limit number of blocks a define in a threaded block is allowed "
206 "to be live in"));
207
209
210} // end namespace llvm
211
212STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
213STATISTIC(NumLinearMaps,
214 "Number of switch instructions turned into linear mapping");
215STATISTIC(NumLookupTables,
216 "Number of switch instructions turned into lookup tables");
218 NumLookupTablesHoles,
219 "Number of switch instructions turned into lookup tables (holes checked)");
220STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
221STATISTIC(NumFoldValueComparisonIntoPredecessors,
222 "Number of value comparisons folded into predecessor basic blocks");
223STATISTIC(NumFoldBranchToCommonDest,
224 "Number of branches folded into predecessor basic block");
226 NumHoistCommonCode,
227 "Number of common instruction 'blocks' hoisted up to the begin block");
228STATISTIC(NumHoistCommonInstrs,
229 "Number of common instructions hoisted up to the begin block");
230STATISTIC(NumSinkCommonCode,
231 "Number of common instruction 'blocks' sunk down to the end block");
232STATISTIC(NumSinkCommonInstrs,
233 "Number of common instructions sunk down to the end block");
234STATISTIC(NumSpeculations, "Number of speculative executed instructions");
235STATISTIC(NumInvokes,
236 "Number of invokes with empty resume blocks simplified into calls");
237STATISTIC(NumInvokesMerged, "Number of invokes that were merged together");
238STATISTIC(NumInvokeSetsFormed, "Number of invoke sets that were formed");
239
240namespace {
241
242// The first field contains the value that the switch produces when a certain
243// case group is selected, and the second field is a vector containing the
244// cases composing the case group.
245using SwitchCaseResultVectorTy =
247
248// The first field contains the phi node that generates a result of the switch
249// and the second field contains the value generated for a certain case in the
250// switch for that PHI.
251using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
252
253/// ValueEqualityComparisonCase - Represents a case of a switch.
254struct ValueEqualityComparisonCase {
256 BasicBlock *Dest;
257
258 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
259 : Value(Value), Dest(Dest) {}
260
261 bool operator<(ValueEqualityComparisonCase RHS) const {
262 // Comparing pointers is ok as we only rely on the order for uniquing.
263 return Value < RHS.Value;
264 }
265
266 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
267};
268
269class SimplifyCFGOpt {
270 const TargetTransformInfo &TTI;
271 DomTreeUpdater *DTU;
272 const DataLayout &DL;
273 ArrayRef<WeakVH> LoopHeaders;
274 const SimplifyCFGOptions &Options;
275 bool Resimplify;
276
277 Value *isValueEqualityComparison(Instruction *TI);
278 BasicBlock *getValueEqualityComparisonCases(
279 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
280 bool simplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
281 BasicBlock *Pred,
282 IRBuilder<> &Builder);
283 bool performValueComparisonIntoPredecessorFolding(Instruction *TI, Value *&CV,
284 Instruction *PTI,
285 IRBuilder<> &Builder);
286 bool foldValueComparisonIntoPredecessors(Instruction *TI,
287 IRBuilder<> &Builder);
288
289 bool simplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
290 bool simplifySingleResume(ResumeInst *RI);
291 bool simplifyCommonResume(ResumeInst *RI);
292 bool simplifyCleanupReturn(CleanupReturnInst *RI);
293 bool simplifyUnreachable(UnreachableInst *UI);
294 bool simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
295 bool simplifyDuplicateSwitchArms(SwitchInst *SI, DomTreeUpdater *DTU);
296 bool simplifyIndirectBr(IndirectBrInst *IBI);
297 bool simplifyUncondBranch(UncondBrInst *BI, IRBuilder<> &Builder);
298 bool simplifyCondBranch(CondBrInst *BI, IRBuilder<> &Builder);
299 bool foldCondBranchOnValueKnownInPredecessor(CondBrInst *BI);
300
301 bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
302 IRBuilder<> &Builder);
303 bool tryToSimplifyUncondBranchWithICmpSelectInIt(ICmpInst *ICI,
304 SelectInst *Select,
305 IRBuilder<> &Builder);
306 bool hoistCommonCodeFromSuccessors(Instruction *TI, bool AllInstsEqOnly);
307 bool hoistSuccIdenticalTerminatorToSwitchOrIf(
308 Instruction *TI, Instruction *I1,
309 SmallVectorImpl<Instruction *> &OtherSuccTIs,
310 ArrayRef<BasicBlock *> UniqueSuccessors);
311 bool speculativelyExecuteBB(CondBrInst *BI, BasicBlock *ThenBB);
312 bool simplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
313 BasicBlock *TrueBB, BasicBlock *FalseBB,
314 uint32_t TrueWeight, uint32_t FalseWeight);
315 bool simplifyBranchOnICmpChain(CondBrInst *BI, IRBuilder<> &Builder,
316 const DataLayout &DL);
317 bool simplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select);
318 bool simplifySwitchOnSelectRemap(SwitchInst *SI, SelectInst *Select, Value *X,
319 ConstantInt *C, bool Negate);
320 bool simplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI);
321 bool turnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder);
322 bool simplifyDuplicatePredecessors(BasicBlock *Succ, DomTreeUpdater *DTU);
323
324public:
325 SimplifyCFGOpt(const TargetTransformInfo &TTI, DomTreeUpdater *DTU,
326 const DataLayout &DL, ArrayRef<WeakVH> LoopHeaders,
327 const SimplifyCFGOptions &Opts)
328 : TTI(TTI), DTU(DTU), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {
329 assert((!DTU || !DTU->hasPostDomTree()) &&
330 "SimplifyCFG is not yet capable of maintaining validity of a "
331 "PostDomTree, so don't ask for it.");
332 }
333
334 bool simplifyOnce(BasicBlock *BB);
335 bool run(BasicBlock *BB);
336
337 // Helper to set Resimplify and return change indication.
338 bool requestResimplify() {
339 Resimplify = true;
340 return true;
341 }
342};
343
344// we synthesize a || b as select a, true, b
345// we synthesize a && b as select a, b, false
346// this function determines if SI is playing one of those roles.
347[[maybe_unused]] bool
348isSelectInRoleOfConjunctionOrDisjunction(const SelectInst *SI) {
349 return ((isa<ConstantInt>(SI->getTrueValue()) &&
350 (dyn_cast<ConstantInt>(SI->getTrueValue())->isOne())) ||
351 (isa<ConstantInt>(SI->getFalseValue()) &&
352 (dyn_cast<ConstantInt>(SI->getFalseValue())->isNullValue())));
353}
354
355} // end anonymous namespace
356
357/// Return true if all the PHI nodes in the basic block \p BB
358/// receive compatible (identical) incoming values when coming from
359/// all of the predecessor blocks that are specified in \p IncomingBlocks.
360///
361/// Note that if the values aren't exactly identical, but \p EquivalenceSet
362/// is provided, and *both* of the values are present in the set,
363/// then they are considered equal.
365 BasicBlock *BB, ArrayRef<BasicBlock *> IncomingBlocks,
366 SmallPtrSetImpl<Value *> *EquivalenceSet = nullptr) {
367 assert(IncomingBlocks.size() == 2 &&
368 "Only for a pair of incoming blocks at the time!");
369
370 // FIXME: it is okay if one of the incoming values is an `undef` value,
371 // iff the other incoming value is guaranteed to be a non-poison value.
372 // FIXME: it is okay if one of the incoming values is a `poison` value.
373 return all_of(BB->phis(), [IncomingBlocks, EquivalenceSet](PHINode &PN) {
374 Value *IV0 = PN.getIncomingValueForBlock(IncomingBlocks[0]);
375 Value *IV1 = PN.getIncomingValueForBlock(IncomingBlocks[1]);
376 if (IV0 == IV1)
377 return true;
378 if (EquivalenceSet && EquivalenceSet->contains(IV0) &&
379 EquivalenceSet->contains(IV1))
380 return true;
381 return false;
382 });
383}
384
385/// Return true if it is safe to merge these two
386/// terminator instructions together.
387static bool
389 SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
390 if (SI1 == SI2)
391 return false; // Can't merge with self!
392
393 // It is not safe to merge these two switch instructions if they have a common
394 // successor, and if that successor has a PHI node, and if *that* PHI node has
395 // conflicting incoming values from the two switch blocks.
396 BasicBlock *SI1BB = SI1->getParent();
397 BasicBlock *SI2BB = SI2->getParent();
398
400 bool Fail = false;
401 for (BasicBlock *Succ : successors(SI2BB)) {
402 if (!SI1Succs.count(Succ))
403 continue;
404 if (incomingValuesAreCompatible(Succ, {SI1BB, SI2BB}))
405 continue;
406 Fail = true;
407 if (FailBlocks)
408 FailBlocks->insert(Succ);
409 else
410 break;
411 }
412
413 return !Fail;
414}
415
416/// Update PHI nodes in Succ to indicate that there will now be entries in it
417/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
418/// will be the same as those coming in from ExistPred, an existing predecessor
419/// of Succ.
420static void addPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
421 BasicBlock *ExistPred,
422 MemorySSAUpdater *MSSAU = nullptr) {
423 for (PHINode &PN : Succ->phis())
424 PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
425 if (MSSAU)
426 if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ))
427 MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred);
428}
429
430/// Compute an abstract "cost" of speculating the given instruction,
431/// which is assumed to be safe to speculate. TCC_Free means cheap,
432/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
433/// expensive.
435 const TargetTransformInfo &TTI) {
436 return TTI.getInstructionCost(I, TargetTransformInfo::TCK_SizeAndLatency);
437}
438
439/// If we have a merge point of an "if condition" as accepted above,
440/// return true if the specified value dominates the block. We don't handle
441/// the true generality of domination here, just a special case which works
442/// well enough for us.
443///
444/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
445/// see if V (which must be an instruction) and its recursive operands
446/// that do not dominate BB have a combined cost lower than Budget and
447/// are non-trapping. If both are true, the instruction is inserted into the
448/// set and true is returned.
449///
450/// The cost for most non-trapping instructions is defined as 1 except for
451/// Select whose cost is 2.
452///
453/// After this function returns, Cost is increased by the cost of
454/// V plus its non-dominating operands. If that cost is greater than
455/// Budget, false is returned and Cost is undefined.
457 Value *V, BasicBlock *BB, Instruction *InsertPt,
458 SmallPtrSetImpl<Instruction *> &AggressiveInsts, InstructionCost &Cost,
460 SmallPtrSetImpl<Instruction *> &ZeroCostInstructions, unsigned Depth = 0) {
461 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
462 // so limit the recursion depth.
463 // TODO: While this recursion limit does prevent pathological behavior, it
464 // would be better to track visited instructions to avoid cycles.
466 return false;
467
469 if (!I) {
470 // Non-instructions dominate all instructions and can be executed
471 // unconditionally.
472 return true;
473 }
474 BasicBlock *PBB = I->getParent();
475
476 // We don't want to allow weird loops that might have the "if condition" in
477 // the bottom of this block.
478 if (PBB == BB)
479 return false;
480
481 // If this instruction is defined in a block that contains an unconditional
482 // branch to BB, then it must be in the 'conditional' part of the "if
483 // statement". If not, it definitely dominates the region.
485 if (!BI || BI->getSuccessor() != BB)
486 return true;
487
488 // If we have seen this instruction before, don't count it again.
489 if (AggressiveInsts.count(I))
490 return true;
491
492 // Okay, it looks like the instruction IS in the "condition". Check to
493 // see if it's a cheap instruction to unconditionally compute, and if it
494 // only uses stuff defined outside of the condition. If so, hoist it out.
495 if (!isSafeToSpeculativelyExecute(I, InsertPt, AC))
496 return false;
497
498 // Overflow arithmetic instruction plus extract value are usually generated
499 // when a division is being replaced. But, in this case, the zero check may
500 // still be kept in the code. In that case it would be worth to hoist these
501 // two instruction out of the basic block. Let's treat this pattern as one
502 // single cheap instruction here!
503 WithOverflowInst *OverflowInst;
504 if (match(I, m_ExtractValue<1>(m_OneUse(m_WithOverflowInst(OverflowInst))))) {
505 ZeroCostInstructions.insert(OverflowInst);
506 Cost += 1;
507 } else if (!ZeroCostInstructions.contains(I))
508 Cost += computeSpeculationCost(I, TTI);
509
510 // Allow exactly one instruction to be speculated regardless of its cost
511 // (as long as it is safe to do so).
512 // This is intended to flatten the CFG even if the instruction is a division
513 // or other expensive operation. The speculation of an expensive instruction
514 // is expected to be undone in CodeGenPrepare if the speculation has not
515 // enabled further IR optimizations.
516 if (Cost > Budget &&
517 (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0 ||
518 !Cost.isValid()))
519 return false;
520
521 // Okay, we can only really hoist these out if their operands do
522 // not take us over the cost threshold.
523 for (Use &Op : I->operands())
524 if (!dominatesMergePoint(Op, BB, InsertPt, AggressiveInsts, Cost, Budget,
525 TTI, AC, ZeroCostInstructions, Depth + 1))
526 return false;
527 // Okay, it's safe to do this! Remember this instruction.
528 AggressiveInsts.insert(I);
529 return true;
530}
531
532/// Extract ConstantInt from value, looking through IntToPtr
533/// and PointerNullValue. Return NULL if value is not a constant int.
535 // Normal constant int.
537 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
538 return CI;
539
540 // It is not safe to look through inttoptr or ptrtoint when using unstable
541 // pointer types.
542 if (DL.hasUnstableRepresentation(V->getType()))
543 return nullptr;
544
545 // This is some kind of pointer constant. Turn it into a pointer-sized
546 // ConstantInt if possible.
547 IntegerType *IntPtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
548
549 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
551 return ConstantInt::get(IntPtrTy, 0);
552
553 // IntToPtr const int, we can look through this if the semantics of
554 // inttoptr for this address space are a simple (truncating) bitcast.
556 if (CE->getOpcode() == Instruction::IntToPtr)
557 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
558 // The constant is very likely to have the right type already.
559 if (CI->getType() == IntPtrTy)
560 return CI;
561 else
562 return cast<ConstantInt>(
563 ConstantFoldIntegerCast(CI, IntPtrTy, /*isSigned=*/false, DL));
564 }
565 return nullptr;
566}
567
568namespace {
569
570/// Given a chain of or (||) or and (&&) comparison of a value against a
571/// constant, this will try to recover the information required for a switch
572/// structure.
573/// It will depth-first traverse the chain of comparison, seeking for patterns
574/// like %a == 12 or %a < 4 and combine them to produce a set of integer
575/// representing the different cases for the switch.
576/// Note that if the chain is composed of '||' it will build the set of elements
577/// that matches the comparisons (i.e. any of this value validate the chain)
578/// while for a chain of '&&' it will build the set elements that make the test
579/// fail.
580struct ConstantComparesGatherer {
581 const DataLayout &DL;
582
583 /// Value found for the switch comparison
584 Value *CompValue = nullptr;
585
586 /// Extra clause to be checked before the switch
587 Value *Extra = nullptr;
588
589 /// Set of integers to match in switch
591
592 /// Number of comparisons matched in the and/or chain
593 unsigned UsedICmps = 0;
594
595 /// If the elements in Vals matches the comparisons
596 bool IsEq = false;
597
598 // Used to check if the first matched CompValue shall be the Extra check.
599 bool IgnoreFirstMatch = false;
600 bool MultipleMatches = false;
601
602 /// Construct and compute the result for the comparison instruction Cond
603 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
604 gather(Cond);
605 if (CompValue || !MultipleMatches)
606 return;
607 Extra = nullptr;
608 Vals.clear();
609 UsedICmps = 0;
610 IgnoreFirstMatch = true;
611 gather(Cond);
612 }
613
614 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
615 ConstantComparesGatherer &
616 operator=(const ConstantComparesGatherer &) = delete;
617
618private:
619 /// Try to set the current value used for the comparison, it succeeds only if
620 /// it wasn't set before or if the new value is the same as the old one
621 bool setValueOnce(Value *NewVal) {
622 if (IgnoreFirstMatch) {
623 IgnoreFirstMatch = false;
624 return false;
625 }
626 if (CompValue && CompValue != NewVal) {
627 MultipleMatches = true;
628 return false;
629 }
630 CompValue = NewVal;
631 return true;
632 }
633
634 /// Try to match Instruction "I" as a comparison against a constant and
635 /// populates the array Vals with the set of values that match (or do not
636 /// match depending on isEQ).
637 /// Return false on failure. On success, the Value the comparison matched
638 /// against is placed in CompValue.
639 /// If CompValue is already set, the function is expected to fail if a match
640 /// is found but the value compared to is different.
641 bool matchInstruction(Instruction *I, bool isEQ) {
642 if (match(I, m_Not(m_Instruction(I))))
643 isEQ = !isEQ;
644
645 Value *Val;
646 if (match(I, m_NUWTrunc(m_Value(Val)))) {
647 // If we already have a value for the switch, it has to match!
648 if (!setValueOnce(Val))
649 return false;
650 UsedICmps++;
651 Vals.push_back(ConstantInt::get(cast<IntegerType>(Val->getType()), isEQ));
652 return true;
653 }
654 // If this is an icmp against a constant, handle this as one of the cases.
655 ICmpInst *ICI;
656 ConstantInt *C;
657 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
658 (C = getConstantInt(I->getOperand(1), DL)))) {
659 return false;
660 }
661
662 Value *RHSVal;
663 const APInt *RHSC;
664
665 // Pattern match a special case
666 // (x & ~2^z) == y --> x == y || x == y|2^z
667 // This undoes a transformation done by instcombine to fuse 2 compares.
668 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
669 // It's a little bit hard to see why the following transformations are
670 // correct. Here is a CVC3 program to verify them for 64-bit values:
671
672 /*
673 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
674 x : BITVECTOR(64);
675 y : BITVECTOR(64);
676 z : BITVECTOR(64);
677 mask : BITVECTOR(64) = BVSHL(ONE, z);
678 QUERY( (y & ~mask = y) =>
679 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
680 );
681 QUERY( (y | mask = y) =>
682 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
683 );
684 */
685
686 // Please note that each pattern must be a dual implication (<--> or
687 // iff). One directional implication can create spurious matches. If the
688 // implication is only one-way, an unsatisfiable condition on the left
689 // side can imply a satisfiable condition on the right side. Dual
690 // implication ensures that satisfiable conditions are transformed to
691 // other satisfiable conditions and unsatisfiable conditions are
692 // transformed to other unsatisfiable conditions.
693
694 // Here is a concrete example of a unsatisfiable condition on the left
695 // implying a satisfiable condition on the right:
696 //
697 // mask = (1 << z)
698 // (x & ~mask) == y --> (x == y || x == (y | mask))
699 //
700 // Substituting y = 3, z = 0 yields:
701 // (x & -2) == 3 --> (x == 3 || x == 2)
702
703 // Pattern match a special case:
704 /*
705 QUERY( (y & ~mask = y) =>
706 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
707 );
708 */
709 if (match(ICI->getOperand(0),
710 m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
711 APInt Mask = ~*RHSC;
712 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
713 // If we already have a value for the switch, it has to match!
714 if (!setValueOnce(RHSVal))
715 return false;
716
717 Vals.push_back(C);
718 Vals.push_back(
719 ConstantInt::get(C->getContext(),
720 C->getValue() | Mask));
721 UsedICmps++;
722 return true;
723 }
724 }
725
726 // Pattern match a special case:
727 /*
728 QUERY( (y | mask = y) =>
729 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
730 );
731 */
732 if (match(ICI->getOperand(0),
733 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
734 APInt Mask = *RHSC;
735 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
736 // If we already have a value for the switch, it has to match!
737 if (!setValueOnce(RHSVal))
738 return false;
739
740 Vals.push_back(C);
741 Vals.push_back(ConstantInt::get(C->getContext(),
742 C->getValue() & ~Mask));
743 UsedICmps++;
744 return true;
745 }
746 }
747
748 // If we already have a value for the switch, it has to match!
749 if (!setValueOnce(ICI->getOperand(0)))
750 return false;
751
752 UsedICmps++;
753 Vals.push_back(C);
754 return true;
755 }
756
757 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
758 ConstantRange Span =
760
761 // Shift the range if the compare is fed by an add. This is the range
762 // compare idiom as emitted by instcombine.
763 Value *CandidateVal = I->getOperand(0);
764 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
765 Span = Span.subtract(*RHSC);
766 CandidateVal = RHSVal;
767 }
768
769 // If this is an and/!= check, then we are looking to build the set of
770 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
771 // x != 0 && x != 1.
772 if (!isEQ)
773 Span = Span.inverse();
774
775 // If there are a ton of values, we don't want to make a ginormous switch.
776 if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
777 return false;
778 }
779
780 // If we already have a value for the switch, it has to match!
781 if (!setValueOnce(CandidateVal))
782 return false;
783
784 // Add all values from the range to the set
785 APInt Tmp = Span.getLower();
786 do
787 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
788 while (++Tmp != Span.getUpper());
789
790 UsedICmps++;
791 return true;
792 }
793
794 /// Given a potentially 'or'd or 'and'd together collection of icmp
795 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
796 /// the value being compared, and stick the list constants into the Vals
797 /// vector.
798 /// One "Extra" case is allowed to differ from the other.
799 void gather(Value *V) {
800 Value *Op0, *Op1;
801 if (match(V, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
802 IsEq = true;
803 else if (match(V, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
804 IsEq = false;
805 else
806 return;
807 // Keep a stack (SmallVector for efficiency) for depth-first traversal
808 SmallVector<Value *, 8> DFT{Op0, Op1};
809 SmallPtrSet<Value *, 8> Visited{V, Op0, Op1};
810
811 while (!DFT.empty()) {
812 V = DFT.pop_back_val();
813
814 if (Instruction *I = dyn_cast<Instruction>(V)) {
815 // If it is a || (or && depending on isEQ), process the operands.
816 if (IsEq ? match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1)))
817 : match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
818 if (Visited.insert(Op1).second)
819 DFT.push_back(Op1);
820 if (Visited.insert(Op0).second)
821 DFT.push_back(Op0);
822
823 continue;
824 }
825
826 // Try to match the current instruction
827 if (matchInstruction(I, IsEq))
828 // Match succeed, continue the loop
829 continue;
830 }
831
832 // One element of the sequence of || (or &&) could not be match as a
833 // comparison against the same value as the others.
834 // We allow only one "Extra" case to be checked before the switch
835 if (!Extra) {
836 Extra = V;
837 continue;
838 }
839 // Failed to parse a proper sequence, abort now
840 CompValue = nullptr;
841 break;
842 }
843 }
844};
845
846} // end anonymous namespace
847
849 MemorySSAUpdater *MSSAU = nullptr) {
850 Instruction *Cond = nullptr;
852 Cond = dyn_cast<Instruction>(SI->getCondition());
853 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
854 Cond = dyn_cast<Instruction>(BI->getCondition());
855 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
856 Cond = dyn_cast<Instruction>(IBI->getAddress());
857 }
858
859 TI->eraseFromParent();
860 if (Cond)
862}
863
864/// Return true if the specified terminator checks
865/// to see if a value is equal to constant integer value.
866Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
867 Value *CV = nullptr;
868 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
869 // Do not permit merging of large switch instructions into their
870 // predecessors unless there is only one predecessor.
871 if (!SI->getParent()->hasNPredecessorsOrMore(128 / SI->getNumSuccessors()))
872 CV = SI->getCondition();
873 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(TI))
874 if (BI->getCondition()->hasOneUse()) {
875 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
876 if (ICI->isEquality() && getConstantInt(ICI->getOperand(1), DL))
877 CV = ICI->getOperand(0);
878 } else if (auto *Trunc = dyn_cast<TruncInst>(BI->getCondition())) {
879 if (Trunc->hasNoUnsignedWrap())
880 CV = Trunc->getOperand(0);
881 }
882 }
883
884 // Unwrap any lossless ptrtoint cast (except for unstable pointers).
885 if (CV) {
886 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
887 Value *Ptr = PTII->getPointerOperand();
888 if (DL.hasUnstableRepresentation(Ptr->getType()))
889 return CV;
890 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
891 CV = Ptr;
892 }
893 }
894 return CV;
895}
896
897/// Given a value comparison instruction,
898/// decode all of the 'cases' that it represents and return the 'default' block.
899BasicBlock *SimplifyCFGOpt::getValueEqualityComparisonCases(
900 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
901 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
902 Cases.reserve(SI->getNumCases());
903 for (auto Case : SI->cases())
904 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
905 Case.getCaseSuccessor()));
906 return SI->getDefaultDest();
907 }
908
909 CondBrInst *BI = cast<CondBrInst>(TI);
910 Value *Cond = BI->getCondition();
911 ICmpInst::Predicate Pred;
912 ConstantInt *C;
913 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
914 Pred = ICI->getPredicate();
915 C = getConstantInt(ICI->getOperand(1), DL);
916 } else {
917 Pred = ICmpInst::ICMP_NE;
918 auto *Trunc = cast<TruncInst>(Cond);
919 C = ConstantInt::get(cast<IntegerType>(Trunc->getOperand(0)->getType()), 0);
920 }
921 BasicBlock *Succ = BI->getSuccessor(Pred == ICmpInst::ICMP_NE);
922 Cases.push_back(ValueEqualityComparisonCase(C, Succ));
923 return BI->getSuccessor(Pred == ICmpInst::ICMP_EQ);
924}
925
926/// Given a vector of bb/value pairs, remove any entries
927/// in the list that match the specified block.
928static void
930 std::vector<ValueEqualityComparisonCase> &Cases) {
931 llvm::erase(Cases, BB);
932}
933
934/// Return true if there are any keys in C1 that exist in C2 as well.
935static bool valuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
936 std::vector<ValueEqualityComparisonCase> &C2) {
937 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
938
939 // Make V1 be smaller than V2.
940 if (V1->size() > V2->size())
941 std::swap(V1, V2);
942
943 if (V1->empty())
944 return false;
945 if (V1->size() == 1) {
946 // Just scan V2.
947 ConstantInt *TheVal = (*V1)[0].Value;
948 for (const ValueEqualityComparisonCase &VECC : *V2)
949 if (TheVal == VECC.Value)
950 return true;
951 }
952
953 // Otherwise, just sort both lists and compare element by element.
954 array_pod_sort(V1->begin(), V1->end());
955 array_pod_sort(V2->begin(), V2->end());
956 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
957 while (i1 != e1 && i2 != e2) {
958 if ((*V1)[i1].Value == (*V2)[i2].Value)
959 return true;
960 if ((*V1)[i1].Value < (*V2)[i2].Value)
961 ++i1;
962 else
963 ++i2;
964 }
965 return false;
966}
967
968/// If TI is known to be a terminator instruction and its block is known to
969/// only have a single predecessor block, check to see if that predecessor is
970/// also a value comparison with the same value, and if that comparison
971/// determines the outcome of this comparison. If so, simplify TI. This does a
972/// very limited form of jump threading.
973bool SimplifyCFGOpt::simplifyEqualityComparisonWithOnlyPredecessor(
974 Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
975 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
976 if (!PredVal)
977 return false; // Not a value comparison in predecessor.
978
979 Value *ThisVal = isValueEqualityComparison(TI);
980 assert(ThisVal && "This isn't a value comparison!!");
981 if (ThisVal != PredVal)
982 return false; // Different predicates.
983
984 // TODO: Preserve branch weight metadata, similarly to how
985 // foldValueComparisonIntoPredecessors preserves it.
986
987 // Find out information about when control will move from Pred to TI's block.
988 std::vector<ValueEqualityComparisonCase> PredCases;
989 BasicBlock *PredDef =
990 getValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
991 eliminateBlockCases(PredDef, PredCases); // Remove default from cases.
992
993 // Find information about how control leaves this block.
994 std::vector<ValueEqualityComparisonCase> ThisCases;
995 BasicBlock *ThisDef = getValueEqualityComparisonCases(TI, ThisCases);
996 eliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
997
998 // If TI's block is the default block from Pred's comparison, potentially
999 // simplify TI based on this knowledge.
1000 if (PredDef == TI->getParent()) {
1001 // If we are here, we know that the value is none of those cases listed in
1002 // PredCases. If there are any cases in ThisCases that are in PredCases, we
1003 // can simplify TI.
1004 if (!valuesOverlap(PredCases, ThisCases))
1005 return false;
1006
1007 if (isa<CondBrInst>(TI)) {
1008 // Okay, one of the successors of this condbr is dead. Convert it to a
1009 // uncond br.
1010 assert(ThisCases.size() == 1 && "Branch can only have one case!");
1011 // Insert the new branch.
1012 Instruction *NI = Builder.CreateBr(ThisDef);
1013 (void)NI;
1014
1015 // Remove PHI node entries for the dead edge.
1016 ThisCases[0].Dest->removePredecessor(PredDef);
1017
1018 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1019 << "Through successor TI: " << *TI << "Leaving: " << *NI
1020 << "\n");
1021
1023
1024 if (DTU)
1025 DTU->applyUpdates(
1026 {{DominatorTree::Delete, PredDef, ThisCases[0].Dest}});
1027
1028 return true;
1029 }
1030
1031 SwitchInstProfUpdateWrapper SI = *cast<SwitchInst>(TI);
1032 // Okay, TI has cases that are statically dead, prune them away.
1033 SmallPtrSet<Constant *, 16> DeadCases;
1034 for (const ValueEqualityComparisonCase &Case : PredCases)
1035 DeadCases.insert(Case.Value);
1036
1037 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1038 << "Through successor TI: " << *TI);
1039
1040 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
1041 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
1042 --i;
1043 auto *Successor = i->getCaseSuccessor();
1044 if (DTU)
1045 ++NumPerSuccessorCases[Successor];
1046 if (DeadCases.count(i->getCaseValue())) {
1047 Successor->removePredecessor(PredDef);
1048 SI.removeCase(i);
1049 if (DTU)
1050 --NumPerSuccessorCases[Successor];
1051 }
1052 }
1053
1054 if (DTU) {
1055 std::vector<DominatorTree::UpdateType> Updates;
1056 for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
1057 if (I.second == 0)
1058 Updates.push_back({DominatorTree::Delete, PredDef, I.first});
1059 DTU->applyUpdates(Updates);
1060 }
1061
1062 LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n");
1063 return true;
1064 }
1065
1066 // Otherwise, TI's block must correspond to some matched value. Find out
1067 // which value (or set of values) this is.
1068 ConstantInt *TIV = nullptr;
1069 BasicBlock *TIBB = TI->getParent();
1070 for (const auto &[Value, Dest] : PredCases)
1071 if (Dest == TIBB) {
1072 if (TIV)
1073 return false; // Cannot handle multiple values coming to this block.
1074 TIV = Value;
1075 }
1076 assert(TIV && "No edge from pred to succ?");
1077
1078 // Okay, we found the one constant that our value can be if we get into TI's
1079 // BB. Find out which successor will unconditionally be branched to.
1080 BasicBlock *TheRealDest = nullptr;
1081 for (const auto &[Value, Dest] : ThisCases)
1082 if (Value == TIV) {
1083 TheRealDest = Dest;
1084 break;
1085 }
1086
1087 // If not handled by any explicit cases, it is handled by the default case.
1088 if (!TheRealDest)
1089 TheRealDest = ThisDef;
1090
1091 SmallPtrSet<BasicBlock *, 2> RemovedSuccs;
1092
1093 // Remove PHI node entries for dead edges.
1094 BasicBlock *CheckEdge = TheRealDest;
1095 for (BasicBlock *Succ : successors(TIBB))
1096 if (Succ != CheckEdge) {
1097 if (Succ != TheRealDest)
1098 RemovedSuccs.insert(Succ);
1099 Succ->removePredecessor(TIBB);
1100 } else
1101 CheckEdge = nullptr;
1102
1103 // Insert the new branch.
1104 Instruction *NI = Builder.CreateBr(TheRealDest);
1105 (void)NI;
1106
1107 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1108 << "Through successor TI: " << *TI << "Leaving: " << *NI
1109 << "\n");
1110
1112 if (DTU) {
1113 SmallVector<DominatorTree::UpdateType, 2> Updates;
1114 Updates.reserve(RemovedSuccs.size());
1115 for (auto *RemovedSucc : RemovedSuccs)
1116 Updates.push_back({DominatorTree::Delete, TIBB, RemovedSucc});
1117 DTU->applyUpdates(Updates);
1118 }
1119 return true;
1120}
1121
1122namespace {
1123
1124/// This class implements a stable ordering of constant
1125/// integers that does not depend on their address. This is important for
1126/// applications that sort ConstantInt's to ensure uniqueness.
1127struct ConstantIntOrdering {
1128 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1129 return LHS->getValue().ult(RHS->getValue());
1130 }
1131};
1132
1133} // end anonymous namespace
1134
1136 ConstantInt *const *P2) {
1137 const ConstantInt *LHS = *P1;
1138 const ConstantInt *RHS = *P2;
1139 if (LHS == RHS)
1140 return 0;
1141 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
1142}
1143
1144/// Get Weights of a given terminator, the default weight is at the front
1145/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
1146/// metadata.
1148 SmallVectorImpl<uint64_t> &Weights) {
1149 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
1150 assert(MD && "Invalid branch-weight metadata");
1151 extractFromBranchWeightMD64(MD, Weights);
1152
1153 // If TI is a conditional eq, the default case is the false case,
1154 // and the corresponding branch-weight data is at index 2. We swap the
1155 // default weight to be the first entry.
1156 if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
1157 assert(Weights.size() == 2);
1158 auto *ICI = dyn_cast<ICmpInst>(BI->getCondition());
1159 if (!ICI)
1160 return;
1161
1162 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1163 std::swap(Weights.front(), Weights.back());
1164 }
1165}
1166
1168 BasicBlock *BB, BasicBlock *PredBlock, ValueToValueMapTy &VMap) {
1169 Instruction *PTI = PredBlock->getTerminator();
1170
1171 // If we have bonus instructions, clone them into the predecessor block.
1172 // Note that there may be multiple predecessor blocks, so we cannot move
1173 // bonus instructions to a predecessor block.
1174 for (Instruction &BonusInst : *BB) {
1175 if (BonusInst.isTerminator())
1176 continue;
1177
1178 // Skip cloning pseudo probes into the predecessor, as it would overcount
1179 // otherwise.
1180 if (isa<PseudoProbeInst>(BonusInst))
1181 continue;
1182
1183 Instruction *NewBonusInst = BonusInst.clone();
1184
1185 if (!NewBonusInst->getDebugLoc().isSameSourceLocation(PTI->getDebugLoc())) {
1186 // Unless the instruction has the same !dbg location as the original
1187 // branch, drop it. When we fold the bonus instructions we want to make
1188 // sure we reset their debug locations in order to avoid stepping on
1189 // dead code caused by folding dead branches.
1190 NewBonusInst->setDebugLoc(DebugLoc::getDropped());
1191 } else if (const DebugLoc &DL = NewBonusInst->getDebugLoc()) {
1192 mapAtomInstance(DL, VMap);
1193 }
1194
1195 RemapInstruction(NewBonusInst, VMap,
1197
1198 // If we speculated an instruction, we need to drop any metadata that may
1199 // result in undefined behavior, as the metadata might have been valid
1200 // only given the branch precondition.
1201 // Similarly strip attributes on call parameters that may cause UB in
1202 // location the call is moved to.
1203 NewBonusInst->dropUBImplyingAttrsAndMetadata();
1204
1205 NewBonusInst->insertInto(PredBlock, PTI->getIterator());
1206 auto Range = NewBonusInst->cloneDebugInfoFrom(&BonusInst);
1207 RemapDbgRecordRange(NewBonusInst->getModule(), Range, VMap,
1209
1210 NewBonusInst->takeName(&BonusInst);
1211 BonusInst.setName(NewBonusInst->getName() + ".old");
1212 VMap[&BonusInst] = NewBonusInst;
1213
1214 // Update (liveout) uses of bonus instructions,
1215 // now that the bonus instruction has been cloned into predecessor.
1216 // Note that we expect to be in a block-closed SSA form for this to work!
1217 for (Use &U : make_early_inc_range(BonusInst.uses())) {
1218 auto *UI = cast<Instruction>(U.getUser());
1219 auto *PN = dyn_cast<PHINode>(UI);
1220 if (!PN) {
1221 assert(UI->getParent() == BB && BonusInst.comesBefore(UI) &&
1222 "If the user is not a PHI node, then it should be in the same "
1223 "block as, and come after, the original bonus instruction.");
1224 continue; // Keep using the original bonus instruction.
1225 }
1226 // Is this the block-closed SSA form PHI node?
1227 if (PN->getIncomingBlock(U) == BB)
1228 continue; // Great, keep using the original bonus instruction.
1229 // The only other alternative is an "use" when coming from
1230 // the predecessor block - here we should refer to the cloned bonus instr.
1231 assert(PN->getIncomingBlock(U) == PredBlock &&
1232 "Not in block-closed SSA form?");
1233 U.set(NewBonusInst);
1234 }
1235 }
1236
1237 // Key Instructions: We may have propagated atom info into the pred. If the
1238 // pred's terminator already has atom info do nothing as merging would drop
1239 // one atom group anyway. If it doesn't, propagte the remapped atom group
1240 // from BB's terminator.
1241 if (auto &PredDL = PTI->getDebugLoc()) {
1242 auto &DL = BB->getTerminator()->getDebugLoc();
1243 if (!PredDL->getAtomGroup() && DL && DL->getAtomGroup() &&
1244 PredDL.isSameSourceLocation(DL)) {
1245 PTI->setDebugLoc(DL);
1246 RemapSourceAtom(PTI, VMap);
1247 }
1248 }
1249}
1250
1251bool SimplifyCFGOpt::performValueComparisonIntoPredecessorFolding(
1252 Instruction *TI, Value *&CV, Instruction *PTI, IRBuilder<> &Builder) {
1253 BasicBlock *BB = TI->getParent();
1254 BasicBlock *Pred = PTI->getParent();
1255
1257
1258 // Figure out which 'cases' to copy from SI to PSI.
1259 std::vector<ValueEqualityComparisonCase> BBCases;
1260 BasicBlock *BBDefault = getValueEqualityComparisonCases(TI, BBCases);
1261
1262 std::vector<ValueEqualityComparisonCase> PredCases;
1263 BasicBlock *PredDefault = getValueEqualityComparisonCases(PTI, PredCases);
1264
1265 // Based on whether the default edge from PTI goes to BB or not, fill in
1266 // PredCases and PredDefault with the new switch cases we would like to
1267 // build.
1268 SmallMapVector<BasicBlock *, int, 8> NewSuccessors;
1269
1270 // Update the branch weight metadata along the way
1271 SmallVector<uint64_t, 8> Weights;
1272 bool PredHasWeights = hasBranchWeightMD(*PTI);
1273 bool SuccHasWeights = hasBranchWeightMD(*TI);
1274
1275 if (PredHasWeights) {
1276 getBranchWeights(PTI, Weights);
1277 // branch-weight metadata is inconsistent here.
1278 if (Weights.size() != 1 + PredCases.size())
1279 PredHasWeights = SuccHasWeights = false;
1280 } else if (SuccHasWeights)
1281 // If there are no predecessor weights but there are successor weights,
1282 // populate Weights with 1, which will later be scaled to the sum of
1283 // successor's weights
1284 Weights.assign(1 + PredCases.size(), 1);
1285
1286 SmallVector<uint64_t, 8> SuccWeights;
1287 if (SuccHasWeights) {
1288 getBranchWeights(TI, SuccWeights);
1289 // branch-weight metadata is inconsistent here.
1290 if (SuccWeights.size() != 1 + BBCases.size())
1291 PredHasWeights = SuccHasWeights = false;
1292 } else if (PredHasWeights)
1293 SuccWeights.assign(1 + BBCases.size(), 1);
1294
1295 if (PredDefault == BB) {
1296 // If this is the default destination from PTI, only the edges in TI
1297 // that don't occur in PTI, or that branch to BB will be activated.
1298 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1299 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1300 if (PredCases[i].Dest != BB)
1301 PTIHandled.insert(PredCases[i].Value);
1302 else {
1303 // The default destination is BB, we don't need explicit targets.
1304 std::swap(PredCases[i], PredCases.back());
1305
1306 if (PredHasWeights || SuccHasWeights) {
1307 // Increase weight for the default case.
1308 Weights[0] += Weights[i + 1];
1309 std::swap(Weights[i + 1], Weights.back());
1310 Weights.pop_back();
1311 }
1312
1313 PredCases.pop_back();
1314 --i;
1315 --e;
1316 }
1317
1318 // Reconstruct the new switch statement we will be building.
1319 if (PredDefault != BBDefault) {
1320 PredDefault->removePredecessor(Pred);
1321 if (DTU && PredDefault != BB)
1322 Updates.push_back({DominatorTree::Delete, Pred, PredDefault});
1323 PredDefault = BBDefault;
1324 ++NewSuccessors[BBDefault];
1325 }
1326
1327 unsigned CasesFromPred = Weights.size();
1328 uint64_t ValidTotalSuccWeight = 0;
1329 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1330 if (!PTIHandled.count(BBCases[i].Value) && BBCases[i].Dest != BBDefault) {
1331 PredCases.push_back(BBCases[i]);
1332 ++NewSuccessors[BBCases[i].Dest];
1333 if (SuccHasWeights || PredHasWeights) {
1334 // The default weight is at index 0, so weight for the ith case
1335 // should be at index i+1. Scale the cases from successor by
1336 // PredDefaultWeight (Weights[0]).
1337 Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1338 ValidTotalSuccWeight += SuccWeights[i + 1];
1339 }
1340 }
1341
1342 if (SuccHasWeights || PredHasWeights) {
1343 ValidTotalSuccWeight += SuccWeights[0];
1344 // Scale the cases from predecessor by ValidTotalSuccWeight.
1345 for (unsigned i = 1; i < CasesFromPred; ++i)
1346 Weights[i] *= ValidTotalSuccWeight;
1347 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1348 Weights[0] *= SuccWeights[0];
1349 }
1350 } else {
1351 // If this is not the default destination from PSI, only the edges
1352 // in SI that occur in PSI with a destination of BB will be
1353 // activated.
1354 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1355 std::map<ConstantInt *, uint64_t> WeightsForHandled;
1356 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1357 if (PredCases[i].Dest == BB) {
1358 PTIHandled.insert(PredCases[i].Value);
1359
1360 if (PredHasWeights || SuccHasWeights) {
1361 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1362 std::swap(Weights[i + 1], Weights.back());
1363 Weights.pop_back();
1364 }
1365
1366 std::swap(PredCases[i], PredCases.back());
1367 PredCases.pop_back();
1368 --i;
1369 --e;
1370 }
1371
1372 // Okay, now we know which constants were sent to BB from the
1373 // predecessor. Figure out where they will all go now.
1374 for (const ValueEqualityComparisonCase &Case : BBCases)
1375 if (PTIHandled.count(Case.Value)) {
1376 // If this is one we are capable of getting...
1377 if (PredHasWeights || SuccHasWeights)
1378 Weights.push_back(WeightsForHandled[Case.Value]);
1379 PredCases.push_back(Case);
1380 ++NewSuccessors[Case.Dest];
1381 PTIHandled.erase(Case.Value); // This constant is taken care of
1382 }
1383
1384 // If there are any constants vectored to BB that TI doesn't handle,
1385 // they must go to the default destination of TI.
1386 for (ConstantInt *I : PTIHandled) {
1387 if (PredHasWeights || SuccHasWeights)
1388 Weights.push_back(WeightsForHandled[I]);
1389 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1390 ++NewSuccessors[BBDefault];
1391 }
1392 }
1393
1394 // Okay, at this point, we know which new successor Pred will get. Make
1395 // sure we update the number of entries in the PHI nodes for these
1396 // successors.
1397 SmallPtrSet<BasicBlock *, 2> SuccsOfPred;
1398 if (DTU) {
1399 SuccsOfPred = {llvm::from_range, successors(Pred)};
1400 Updates.reserve(Updates.size() + NewSuccessors.size());
1401 }
1402 for (const std::pair<BasicBlock *, int /*Num*/> &NewSuccessor :
1403 NewSuccessors) {
1404 for (auto I : seq(NewSuccessor.second)) {
1405 (void)I;
1406 addPredecessorToBlock(NewSuccessor.first, Pred, BB);
1407 }
1408 if (DTU && !SuccsOfPred.contains(NewSuccessor.first))
1409 Updates.push_back({DominatorTree::Insert, Pred, NewSuccessor.first});
1410 }
1411
1412 Builder.SetInsertPoint(PTI);
1413 // Convert pointer to int before we switch.
1414 if (CV->getType()->isPointerTy()) {
1415 assert(!DL.hasUnstableRepresentation(CV->getType()) &&
1416 "Should not end up here with unstable pointers");
1417 CV =
1418 Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), "magicptr");
1419 }
1420
1421 // Now that the successors are updated, create the new Switch instruction.
1422 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, PredCases.size());
1423 NewSI->setDebugLoc(PTI->getDebugLoc());
1424 for (ValueEqualityComparisonCase &V : PredCases)
1425 NewSI->addCase(V.Value, V.Dest);
1426
1427 if (PredHasWeights || SuccHasWeights)
1428 setFittedBranchWeights(*NewSI, Weights, /*IsExpected=*/false,
1429 /*ElideAllZero=*/true);
1430
1432
1433 // Okay, last check. If BB is still a successor of PSI, then we must
1434 // have an infinite loop case. If so, add an infinitely looping block
1435 // to handle the case to preserve the behavior of the code.
1436 BasicBlock *InfLoopBlock = nullptr;
1437 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1438 if (NewSI->getSuccessor(i) == BB) {
1439 if (!InfLoopBlock) {
1440 // Insert it at the end of the function, because it's either code,
1441 // or it won't matter if it's hot. :)
1442 InfLoopBlock =
1443 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
1444 UncondBrInst::Create(InfLoopBlock, InfLoopBlock);
1445 if (DTU)
1446 Updates.push_back(
1447 {DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
1448 }
1449 NewSI->setSuccessor(i, InfLoopBlock);
1450 }
1451
1452 if (DTU) {
1453 if (InfLoopBlock)
1454 Updates.push_back({DominatorTree::Insert, Pred, InfLoopBlock});
1455
1456 Updates.push_back({DominatorTree::Delete, Pred, BB});
1457
1458 DTU->applyUpdates(Updates);
1459 }
1460
1461 ++NumFoldValueComparisonIntoPredecessors;
1462 return true;
1463}
1464
1465/// The specified terminator is a value equality comparison instruction
1466/// (either a switch or a branch on "X == c").
1467/// See if any of the predecessors of the terminator block are value comparisons
1468/// on the same value. If so, and if safe to do so, fold them together.
1469bool SimplifyCFGOpt::foldValueComparisonIntoPredecessors(Instruction *TI,
1470 IRBuilder<> &Builder) {
1471 BasicBlock *BB = TI->getParent();
1472 Value *CV = isValueEqualityComparison(TI); // CondVal
1473 assert(CV && "Not a comparison?");
1474
1475 bool Changed = false;
1476
1477 SmallSetVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
1478 while (!Preds.empty()) {
1479 BasicBlock *Pred = Preds.pop_back_val();
1480 Instruction *PTI = Pred->getTerminator();
1481
1482 // Don't try to fold into itself.
1483 if (Pred == BB)
1484 continue;
1485
1486 // See if the predecessor is a comparison with the same value.
1487 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
1488 if (PCV != CV)
1489 continue;
1490
1491 SmallSetVector<BasicBlock *, 4> FailBlocks;
1492 if (!safeToMergeTerminators(TI, PTI, &FailBlocks)) {
1493 for (auto *Succ : FailBlocks) {
1494 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split", DTU))
1495 return false;
1496 }
1497 }
1498
1499 performValueComparisonIntoPredecessorFolding(TI, CV, PTI, Builder);
1500 Changed = true;
1501 }
1502 return Changed;
1503}
1504
1505// If we would need to insert a select that uses the value of this invoke
1506// (comments in hoistSuccIdenticalTerminatorToSwitchOrIf explain why we would
1507// need to do this), we can't hoist the invoke, as there is nowhere to put the
1508// select in this case.
1510 Instruction *I1, Instruction *I2) {
1511 for (BasicBlock *Succ : successors(BB1)) {
1512 for (const PHINode &PN : Succ->phis()) {
1513 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1514 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1515 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1516 return false;
1517 }
1518 }
1519 }
1520 return true;
1521}
1522
1523// Get interesting characteristics of instructions that
1524// `hoistCommonCodeFromSuccessors` didn't hoist. They restrict what kind of
1525// instructions can be reordered across.
1531
1533 // Pseudo probes don't constrain reordering of other instructions.
1535 return 0;
1536 unsigned Flags = 0;
1537 if (I->mayReadFromMemory())
1538 Flags |= SkipReadMem;
1539 // We can't arbitrarily move around allocas, e.g. moving allocas (especially
1540 // inalloca) across stacksave/stackrestore boundaries.
1541 if (I->mayHaveSideEffects() || isa<AllocaInst>(I))
1542 Flags |= SkipSideEffect;
1544 Flags |= SkipImplicitControlFlow;
1545 return Flags;
1546}
1547
1548// Returns true if it is safe to reorder an instruction across preceding
1549// instructions in a basic block.
1550static bool isSafeToHoistInstr(Instruction *I, unsigned Flags) {
1551 // Don't reorder a store over a load.
1552 if ((Flags & SkipReadMem) && I->mayWriteToMemory())
1553 return false;
1554
1555 // If we have seen an instruction with side effects, it's unsafe to reorder an
1556 // instruction which reads memory or itself has side effects.
1557 if ((Flags & SkipSideEffect) &&
1558 (I->mayReadFromMemory() || I->mayHaveSideEffects() || isa<AllocaInst>(I)))
1559 return false;
1560
1561 // Reordering across an instruction which does not necessarily transfer
1562 // control to the next instruction is speculation.
1564 return false;
1565
1566 // Hoisting of llvm.deoptimize is only legal together with the next return
1567 // instruction, which this pass is not always able to do.
1568 if (auto *CB = dyn_cast<CallBase>(I))
1569 if (CB->getIntrinsicID() == Intrinsic::experimental_deoptimize)
1570 return false;
1571
1572 // It's also unsafe/illegal to hoist an instruction above its instruction
1573 // operands
1574 BasicBlock *BB = I->getParent();
1575 for (Value *Op : I->operands()) {
1576 if (auto *J = dyn_cast<Instruction>(Op))
1577 if (J->getParent() == BB)
1578 return false;
1579 }
1580
1581 return true;
1582}
1583
1584static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified = false);
1585
1586/// Helper function for hoistCommonCodeFromSuccessors. Return true if identical
1587/// instructions \p I1 and \p I2 can and should be hoisted.
1589 const TargetTransformInfo &TTI) {
1590 // If we're going to hoist a call, make sure that the two instructions
1591 // we're commoning/hoisting are both marked with musttail, or neither of
1592 // them is marked as such. Otherwise, we might end up in a situation where
1593 // we hoist from a block where the terminator is a `ret` to a block where
1594 // the terminator is a `br`, and `musttail` calls expect to be followed by
1595 // a return.
1596 auto *C1 = dyn_cast<CallInst>(I1);
1597 auto *C2 = dyn_cast<CallInst>(I2);
1598 if (C1 && C2)
1599 if (C1->isMustTailCall() != C2->isMustTailCall())
1600 return false;
1601
1602 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1603 return false;
1604
1605 // If any of the two call sites has nomerge or convergent attribute, stop
1606 // hoisting.
1607 if (const auto *CB1 = dyn_cast<CallBase>(I1))
1608 if (CB1->cannotMerge() || CB1->isConvergent())
1609 return false;
1610 if (const auto *CB2 = dyn_cast<CallBase>(I2))
1611 if (CB2->cannotMerge() || CB2->isConvergent())
1612 return false;
1613
1614 return true;
1615}
1616
1617/// Hoists DbgVariableRecords from \p I1 and \p OtherInstrs that are identical
1618/// in lock-step to \p TI. This matches how dbg.* intrinsics are hoisting in
1619/// hoistCommonCodeFromSuccessors. e.g. The input:
1620/// I1 DVRs: { x, z },
1621/// OtherInsts: { I2 DVRs: { x, y, z } }
1622/// would result in hoisting only DbgVariableRecord x.
1624 Instruction *TI, Instruction *I1,
1625 SmallVectorImpl<Instruction *> &OtherInsts) {
1626 if (!I1->hasDbgRecords())
1627 return;
1628 using CurrentAndEndIt =
1629 std::pair<DbgRecord::self_iterator, DbgRecord::self_iterator>;
1630 // Vector of {Current, End} iterators.
1632 Itrs.reserve(OtherInsts.size() + 1);
1633 // Helper lambdas for lock-step checks:
1634 // Return true if this Current == End.
1635 auto atEnd = [](const CurrentAndEndIt &Pair) {
1636 return Pair.first == Pair.second;
1637 };
1638 // Return true if all Current are identical.
1639 auto allIdentical = [](const SmallVector<CurrentAndEndIt> &Itrs) {
1640 return all_of(make_first_range(ArrayRef(Itrs).drop_front()),
1642 return Itrs[0].first->isIdenticalToWhenDefined(*I);
1643 });
1644 };
1645
1646 // Collect the iterators.
1647 Itrs.push_back(
1648 {I1->getDbgRecordRange().begin(), I1->getDbgRecordRange().end()});
1649 for (Instruction *Other : OtherInsts) {
1650 if (!Other->hasDbgRecords())
1651 return;
1652 Itrs.push_back(
1653 {Other->getDbgRecordRange().begin(), Other->getDbgRecordRange().end()});
1654 }
1655
1656 // Iterate in lock-step until any of the DbgRecord lists are exausted. If
1657 // the lock-step DbgRecord are identical, hoist all of them to TI.
1658 // This replicates the dbg.* intrinsic behaviour in
1659 // hoistCommonCodeFromSuccessors.
1660 while (none_of(Itrs, atEnd)) {
1661 bool HoistDVRs = allIdentical(Itrs);
1662 for (CurrentAndEndIt &Pair : Itrs) {
1663 // Increment Current iterator now as we may be about to move the
1664 // DbgRecord.
1665 DbgRecord &DR = *Pair.first++;
1666 if (HoistDVRs) {
1667 DR.removeFromParent();
1668 TI->getParent()->insertDbgRecordBefore(&DR, TI->getIterator());
1669 }
1670 }
1671 }
1672}
1673
1675 const Instruction *I2) {
1676 if (I1->isIdenticalToWhenDefined(I2, /*IntersectAttrs=*/true))
1677 return true;
1678
1679 if (auto *Cmp1 = dyn_cast<CmpInst>(I1))
1680 if (auto *Cmp2 = dyn_cast<CmpInst>(I2))
1681 return Cmp1->getPredicate() == Cmp2->getSwappedPredicate() &&
1682 Cmp1->getOperand(0) == Cmp2->getOperand(1) &&
1683 Cmp1->getOperand(1) == Cmp2->getOperand(0);
1684
1685 if (I1->isCommutative() && I1->isSameOperationAs(I2)) {
1686 return I1->getOperand(0) == I2->getOperand(1) &&
1687 I1->getOperand(1) == I2->getOperand(0) &&
1688 equal(drop_begin(I1->operands(), 2), drop_begin(I2->operands(), 2));
1689 }
1690
1691 return false;
1692}
1693
1694/// If the target supports conditional faulting,
1695/// we look for the following pattern:
1696/// \code
1697/// BB:
1698/// ...
1699/// %cond = icmp ult %x, %y
1700/// br i1 %cond, label %TrueBB, label %FalseBB
1701/// FalseBB:
1702/// store i32 1, ptr %q, align 4
1703/// ...
1704/// TrueBB:
1705/// %maskedloadstore = load i32, ptr %b, align 4
1706/// store i32 %maskedloadstore, ptr %p, align 4
1707/// ...
1708/// \endcode
1709///
1710/// and transform it into:
1711///
1712/// \code
1713/// BB:
1714/// ...
1715/// %cond = icmp ult %x, %y
1716/// %maskedloadstore = cload i32, ptr %b, %cond
1717/// cstore i32 %maskedloadstore, ptr %p, %cond
1718/// cstore i32 1, ptr %q, ~%cond
1719/// br i1 %cond, label %TrueBB, label %FalseBB
1720/// FalseBB:
1721/// ...
1722/// TrueBB:
1723/// ...
1724/// \endcode
1725///
1726/// where cload/cstore are represented by llvm.masked.load/store intrinsics,
1727/// e.g.
1728///
1729/// \code
1730/// %vcond = bitcast i1 %cond to <1 x i1>
1731/// %v0 = call <1 x i32> @llvm.masked.load.v1i32.p0
1732/// (ptr %b, i32 4, <1 x i1> %vcond, <1 x i32> poison)
1733/// %maskedloadstore = bitcast <1 x i32> %v0 to i32
1734/// call void @llvm.masked.store.v1i32.p0
1735/// (<1 x i32> %v0, ptr %p, i32 4, <1 x i1> %vcond)
1736/// %cond.not = xor i1 %cond, true
1737/// %vcond.not = bitcast i1 %cond.not to <1 x i>
1738/// call void @llvm.masked.store.v1i32.p0
1739/// (<1 x i32> <i32 1>, ptr %q, i32 4, <1x i1> %vcond.not)
1740/// \endcode
1741///
1742/// So we need to turn hoisted load/store into cload/cstore.
1743///
1744/// \param BI The branch instruction.
1745/// \param SpeculatedConditionalLoadsStores The load/store instructions that
1746/// will be speculated.
1747/// \param Invert indicates if speculates FalseBB. Only used in triangle CFG.
1749 CondBrInst *BI,
1750 SmallVectorImpl<Instruction *> &SpeculatedConditionalLoadsStores,
1751 std::optional<bool> Invert, Instruction *Sel) {
1752 auto &Context = BI->getParent()->getContext();
1753 auto *VCondTy = FixedVectorType::get(Type::getInt1Ty(Context), 1);
1754 auto *Cond = BI->getCondition();
1755 // Construct the condition if needed.
1756 BasicBlock *BB = BI->getParent();
1757 Value *Mask = nullptr;
1758 Value *MaskFalse = nullptr;
1759 Value *MaskTrue = nullptr;
1760 if (Invert.has_value()) {
1761 IRBuilder<> Builder(Sel ? Sel : SpeculatedConditionalLoadsStores.back());
1762 Mask = Builder.CreateBitCast(
1763 *Invert ? Builder.CreateXor(Cond, ConstantInt::getTrue(Context)) : Cond,
1764 VCondTy);
1765 } else {
1766 IRBuilder<> Builder(BI);
1767 MaskFalse = Builder.CreateBitCast(
1768 Builder.CreateXor(Cond, ConstantInt::getTrue(Context)), VCondTy);
1769 MaskTrue = Builder.CreateBitCast(Cond, VCondTy);
1770 }
1771 auto PeekThroughBitcasts = [](Value *V) {
1772 while (auto *BitCast = dyn_cast<BitCastInst>(V))
1773 V = BitCast->getOperand(0);
1774 return V;
1775 };
1776 for (auto *I : SpeculatedConditionalLoadsStores) {
1777 IRBuilder<> Builder(Invert.has_value() ? I : BI);
1778 if (!Invert.has_value())
1779 Mask = I->getParent() == BI->getSuccessor(0) ? MaskTrue : MaskFalse;
1780 // We currently assume conditional faulting load/store is supported for
1781 // scalar types only when creating new instructions. This can be easily
1782 // extended for vector types in the future.
1783 assert(!getLoadStoreType(I)->isVectorTy() && "not implemented");
1784 auto *Op0 = I->getOperand(0);
1785 CallInst *MaskedLoadStore = nullptr;
1786 if (auto *LI = dyn_cast<LoadInst>(I)) {
1787 // Handle Load.
1788 auto *Ty = I->getType();
1789 PHINode *PN = nullptr;
1790 Value *PassThru = nullptr;
1791 if (Invert.has_value())
1792 for (User *U : I->users()) {
1793 if ((PN = dyn_cast<PHINode>(U))) {
1794 PassThru = Builder.CreateBitCast(
1795 PeekThroughBitcasts(PN->getIncomingValueForBlock(BB)),
1796 FixedVectorType::get(Ty, 1));
1797 } else if (auto *Ins = cast<Instruction>(U);
1798 Sel && Ins->getParent() == BB) {
1799 // This happens when store or/and a speculative instruction between
1800 // load and store were hoisted to the BB. Make sure the masked load
1801 // inserted before its use.
1802 // We assume there's one of such use.
1803 Builder.SetInsertPoint(Ins);
1804 }
1805 }
1806 MaskedLoadStore = Builder.CreateMaskedLoad(
1807 FixedVectorType::get(Ty, 1), Op0, LI->getAlign(), Mask, PassThru);
1808 Value *NewLoadStore = Builder.CreateBitCast(MaskedLoadStore, Ty);
1809 if (PN)
1810 PN->setIncomingValue(PN->getBasicBlockIndex(BB), NewLoadStore);
1811 I->replaceAllUsesWith(NewLoadStore);
1812 } else {
1813 // Handle Store.
1814 auto *StoredVal = Builder.CreateBitCast(
1815 PeekThroughBitcasts(Op0), FixedVectorType::get(Op0->getType(), 1));
1816 MaskedLoadStore = Builder.CreateMaskedStore(
1817 StoredVal, I->getOperand(1), cast<StoreInst>(I)->getAlign(), Mask);
1818 }
1819 // For non-debug metadata, only !annotation, !range, !nonnull and !align are
1820 // kept when hoisting (see Instruction::dropUBImplyingAttrsAndMetadata).
1821 //
1822 // !nonnull, !align : Not support pointer type, no need to keep.
1823 // !range: Load type is changed from scalar to vector, but the metadata on
1824 // vector specifies a per-element range, so the semantics stay the
1825 // same. Keep it.
1826 // !annotation: Not impact semantics. Keep it.
1827 if (const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range))
1828 MaskedLoadStore->addRangeRetAttr(getConstantRangeFromMetadata(*Ranges));
1829 I->dropUBImplyingAttrsAndUnknownMetadata({LLVMContext::MD_annotation});
1830 // FIXME: DIAssignID is not supported for masked store yet.
1831 // (Verifier::visitDIAssignIDMetadata)
1833 I->eraseMetadataIf([](unsigned MDKind, MDNode *Node) {
1834 return Node->getMetadataID() == Metadata::DIAssignIDKind;
1835 });
1836 MaskedLoadStore->copyMetadata(*I);
1837 I->eraseFromParent();
1838 }
1839}
1840
1842 const TargetTransformInfo &TTI) {
1843 // Not handle volatile or atomic.
1844 bool IsStore = false;
1845 if (auto *L = dyn_cast<LoadInst>(I)) {
1846 if (!L->isSimple() || !HoistLoadsWithCondFaulting)
1847 return false;
1848 } else if (auto *S = dyn_cast<StoreInst>(I)) {
1849 if (!S->isSimple() || !HoistStoresWithCondFaulting)
1850 return false;
1851 IsStore = true;
1852 } else
1853 return false;
1854
1855 // llvm.masked.load/store use i32 for alignment while load/store use i64.
1856 // That's why we have the alignment limitation.
1857 // FIXME: Update the prototype of the intrinsics?
1858 return TTI.hasConditionalLoadStoreForType(getLoadStoreType(I), IsStore) &&
1860}
1861
1862/// Hoist any common code in the successor blocks up into the block. This
1863/// function guarantees that BB dominates all successors. If AllInstsEqOnly is
1864/// given, only perform hoisting in case all successors blocks contain matching
1865/// instructions only. In that case, all instructions can be hoisted and the
1866/// original branch will be replaced and selects for PHIs are added.
1867bool SimplifyCFGOpt::hoistCommonCodeFromSuccessors(Instruction *TI,
1868 bool AllInstsEqOnly) {
1869 // This does very trivial matching, with limited scanning, to find identical
1870 // instructions in the two blocks. In particular, we don't want to get into
1871 // O(N1*N2*...) situations here where Ni are the sizes of these successors. As
1872 // such, we currently just scan for obviously identical instructions in an
1873 // identical order, possibly separated by the same number of non-identical
1874 // instructions.
1875 BasicBlock *BB = TI->getParent();
1876 unsigned int SuccSize = succ_size(BB);
1877 if (SuccSize < 2)
1878 return false;
1879
1880 // If either of the blocks has it's address taken, then we can't do this fold,
1881 // because the code we'd hoist would no longer run when we jump into the block
1882 // by it's address.
1883 SmallSetVector<BasicBlock *, 4> UniqueSuccessors(from_range, successors(BB));
1884 for (auto *Succ : UniqueSuccessors) {
1885 if (Succ->hasAddressTaken())
1886 return false;
1887 // Use getUniquePredecessor instead of getSinglePredecessor to support
1888 // multi-cases successors in switch.
1889 if (Succ->getUniquePredecessor())
1890 continue;
1891 // If Succ has >1 predecessors, continue to check if the Succ contains only
1892 // one `unreachable` inst. Since executing `unreachable` inst is an UB, we
1893 // can relax the condition based on the assumptiom that the program would
1894 // never enter Succ and trigger such an UB.
1895 if (isa<UnreachableInst>(*Succ->begin()))
1896 continue;
1897 return false;
1898 }
1899 // The second of pair is a SkipFlags bitmask.
1900 using SuccIterPair = std::pair<BasicBlock::iterator, unsigned>;
1901 SmallVector<SuccIterPair, 8> SuccIterPairs;
1902 for (auto *Succ : UniqueSuccessors) {
1903 BasicBlock::iterator SuccItr = Succ->begin();
1904 if (isa<PHINode>(*SuccItr))
1905 return false;
1906 SuccIterPairs.push_back(SuccIterPair(SuccItr, 0));
1907 }
1908
1909 if (AllInstsEqOnly) {
1910 // Check if all instructions in the successor blocks match. This allows
1911 // hoisting all instructions and removing the blocks we are hoisting from,
1912 // so does not add any new instructions.
1913
1914 // Check if sizes and terminators of all successors match.
1915 unsigned Size0 = UniqueSuccessors[0]->size();
1916 Instruction *Term0 = UniqueSuccessors[0]->getTerminator();
1917 bool AllSame =
1918 all_of(drop_begin(UniqueSuccessors), [Term0, Size0](BasicBlock *Succ) {
1919 return Succ->getTerminator()->isIdenticalTo(Term0) &&
1920 Succ->size() == Size0;
1921 });
1922 if (!AllSame)
1923 return false;
1924 LockstepReverseIterator<true> LRI(UniqueSuccessors.getArrayRef());
1925 while (LRI.isValid()) {
1926 Instruction *I0 = (*LRI)[0];
1927 if (any_of(*LRI, [I0](Instruction *I) {
1928 return !areIdenticalUpToCommutativity(I0, I);
1929 })) {
1930 return false;
1931 }
1932 --LRI;
1933 }
1934 // Now we know that all instructions in all successors can be hoisted. Let
1935 // the loop below handle the hoisting.
1936 }
1937
1938 // Count how many instructions were not hoisted so far. There's a limit on how
1939 // many instructions we skip, serving as a compilation time control as well as
1940 // preventing excessive increase of life ranges.
1941 unsigned NumSkipped = 0;
1942 // If we find an unreachable instruction at the beginning of a basic block, we
1943 // can still hoist instructions from the rest of the basic blocks.
1944 if (SuccIterPairs.size() > 2) {
1945 erase_if(SuccIterPairs,
1946 [](const auto &Pair) { return isa<UnreachableInst>(Pair.first); });
1947 if (SuccIterPairs.size() < 2)
1948 return false;
1949 }
1950
1951 bool Changed = false;
1952
1953 for (;;) {
1954 auto *SuccIterPairBegin = SuccIterPairs.begin();
1955 auto &BB1ItrPair = *SuccIterPairBegin++;
1956 auto OtherSuccIterPairRange =
1957 iterator_range(SuccIterPairBegin, SuccIterPairs.end());
1958 auto OtherSuccIterRange = make_first_range(OtherSuccIterPairRange);
1959
1960 Instruction *I1 = &*BB1ItrPair.first;
1961
1962 bool AllInstsAreIdentical = true;
1963 bool HasTerminator = I1->isTerminator();
1964 for (auto &SuccIter : OtherSuccIterRange) {
1965 Instruction *I2 = &*SuccIter;
1966 HasTerminator |= I2->isTerminator();
1967 if (AllInstsAreIdentical && (!areIdenticalUpToCommutativity(I1, I2) ||
1968 MMRAMetadata(*I1) != MMRAMetadata(*I2)))
1969 AllInstsAreIdentical = false;
1970 }
1971
1972 SmallVector<Instruction *, 8> OtherInsts;
1973 for (auto &SuccIter : OtherSuccIterRange)
1974 OtherInsts.push_back(&*SuccIter);
1975
1976 // If we are hoisting the terminator instruction, don't move one (making a
1977 // broken BB), instead clone it, and remove BI.
1978 if (HasTerminator) {
1979 // Even if BB, which contains only one unreachable instruction, is ignored
1980 // at the beginning of the loop, we can hoist the terminator instruction.
1981 // If any instructions remain in the block, we cannot hoist terminators.
1982 if (NumSkipped || !AllInstsAreIdentical) {
1983 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
1984 return Changed;
1985 }
1986
1987 return hoistSuccIdenticalTerminatorToSwitchOrIf(
1988 TI, I1, OtherInsts, UniqueSuccessors.getArrayRef()) ||
1989 Changed;
1990 }
1991
1992 if (AllInstsAreIdentical) {
1993 unsigned SkipFlagsBB1 = BB1ItrPair.second;
1994 AllInstsAreIdentical =
1995 isSafeToHoistInstr(I1, SkipFlagsBB1) &&
1996 all_of(OtherSuccIterPairRange, [=](const auto &Pair) {
1997 Instruction *I2 = &*Pair.first;
1998 unsigned SkipFlagsBB2 = Pair.second;
1999 // Even if the instructions are identical, it may not
2000 // be safe to hoist them if we have skipped over
2001 // instructions with side effects or their operands
2002 // weren't hoisted.
2003 return isSafeToHoistInstr(I2, SkipFlagsBB2) &&
2005 });
2006 }
2007
2008 // A musttail call must be immediately followed by a ret, so hoisting is
2009 // only legal if its ret is hoisted with it on the next iteration. That is,
2010 // no instruction has been skipped (the entire successor can be hoisted into
2011 // the predecessor) and the call is directly followed by a ret.
2012 if (auto *CI = dyn_cast<CallInst>(I1);
2013 AllInstsAreIdentical && CI && CI->isMustTailCall()) {
2014 AllInstsAreIdentical =
2015 NumSkipped == 0 && all_of(SuccIterPairs, [](const SuccIterPair &P) {
2016 return isa<ReturnInst>(*std::next(P.first));
2017 });
2018 }
2019
2020 if (AllInstsAreIdentical) {
2021 BB1ItrPair.first++;
2022 // For a normal instruction, we just move one to right before the
2023 // branch, then replace all uses of the other with the first. Finally,
2024 // we remove the now redundant second instruction.
2025 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
2026 // We've just hoisted DbgVariableRecords; move I1 after them (before TI)
2027 // and leave any that were not hoisted behind (by calling moveBefore
2028 // rather than moveBeforePreserving).
2029 I1->moveBefore(TI->getIterator());
2030 for (auto &SuccIter : OtherSuccIterRange) {
2031 Instruction *I2 = &*SuccIter++;
2032 assert(I2 != I1);
2033 if (!I2->use_empty())
2034 I2->replaceAllUsesWith(I1);
2035 I1->andIRFlags(I2);
2036 if (auto *CB = dyn_cast<CallBase>(I1)) {
2037 bool Success = CB->tryIntersectAttributes(cast<CallBase>(I2));
2038 assert(Success && "We should not be trying to hoist callbases "
2039 "with non-intersectable attributes");
2040 // For NDEBUG Compile.
2041 (void)Success;
2042 }
2043
2044 combineMetadataForCSE(I1, I2, true);
2045 // I1 and I2 are being combined into a single instruction. Its debug
2046 // location is the merged locations of the original instructions.
2047 I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
2048 I2->eraseFromParent();
2049 }
2050 if (!Changed)
2051 NumHoistCommonCode += SuccIterPairs.size();
2052 Changed = true;
2053 NumHoistCommonInstrs += SuccIterPairs.size();
2054 } else {
2055 if (NumSkipped >= HoistCommonSkipLimit) {
2056 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
2057 return Changed;
2058 }
2059 // We are about to skip over a pair of non-identical instructions. Record
2060 // if any have characteristics that would prevent reordering instructions
2061 // across them.
2062 for (auto &SuccIterPair : SuccIterPairs) {
2063 Instruction *I = &*SuccIterPair.first++;
2064 SuccIterPair.second |= skippedInstrFlags(I);
2065 }
2066 ++NumSkipped;
2067 }
2068 }
2069}
2070
2071bool SimplifyCFGOpt::hoistSuccIdenticalTerminatorToSwitchOrIf(
2072 Instruction *TI, Instruction *I1,
2073 SmallVectorImpl<Instruction *> &OtherSuccTIs,
2074 ArrayRef<BasicBlock *> UniqueSuccessors) {
2075
2076 auto *BI = dyn_cast<CondBrInst>(TI);
2077
2078 bool Changed = false;
2079 BasicBlock *TIParent = TI->getParent();
2080 BasicBlock *BB1 = I1->getParent();
2081
2082 // Use only for an if statement.
2083 auto *I2 = *OtherSuccTIs.begin();
2084 auto *BB2 = I2->getParent();
2085 if (BI) {
2086 assert(OtherSuccTIs.size() == 1);
2087 assert(BI->getSuccessor(0) == I1->getParent());
2088 assert(BI->getSuccessor(1) == I2->getParent());
2089 }
2090
2091 // In the case of an if statement, we try to hoist an invoke.
2092 // FIXME: Can we define a safety predicate for CallBr?
2093 // FIXME: Test case llvm/test/Transforms/SimplifyCFG/2009-06-15-InvokeCrash.ll
2094 // removed in 4c923b3b3fd0ac1edebf0603265ca3ba51724937 commit?
2095 if (isa<InvokeInst>(I1) && (!BI || !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
2096 return false;
2097
2098 // TODO: callbr hoisting currently disabled pending further study.
2099 if (isa<CallBrInst>(I1))
2100 return false;
2101
2102 for (BasicBlock *Succ : successors(BB1)) {
2103 for (PHINode &PN : Succ->phis()) {
2104 Value *BB1V = PN.getIncomingValueForBlock(BB1);
2105 for (Instruction *OtherSuccTI : OtherSuccTIs) {
2106 Value *BB2V = PN.getIncomingValueForBlock(OtherSuccTI->getParent());
2107 if (BB1V == BB2V)
2108 continue;
2109
2110 // In the case of an if statement, check for
2111 // passingValueIsAlwaysUndefined here because we would rather eliminate
2112 // undefined control flow then converting it to a select.
2113 if (!BI || passingValueIsAlwaysUndefined(BB1V, &PN) ||
2115 return false;
2116 }
2117 }
2118 }
2119
2120 // Hoist DbgVariableRecords attached to the terminator to match dbg.*
2121 // intrinsic hoisting behaviour in hoistCommonCodeFromSuccessors.
2122 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherSuccTIs);
2123 // Clone the terminator and hoist it into the pred, without any debug info.
2124 Instruction *NT = I1->clone();
2125 NT->insertInto(TIParent, TI->getIterator());
2126 if (!NT->getType()->isVoidTy()) {
2127 I1->replaceAllUsesWith(NT);
2128 for (Instruction *OtherSuccTI : OtherSuccTIs)
2129 OtherSuccTI->replaceAllUsesWith(NT);
2130 NT->takeName(I1);
2131 }
2132 Changed = true;
2133 NumHoistCommonInstrs += OtherSuccTIs.size() + 1;
2134
2135 // Ensure terminator gets a debug location, even an unknown one, in case
2136 // it involves inlinable calls.
2138 Locs.push_back(I1->getDebugLoc());
2139 for (auto *OtherSuccTI : OtherSuccTIs)
2140 Locs.push_back(OtherSuccTI->getDebugLoc());
2141 NT->setDebugLoc(DebugLoc::getMergedLocations(Locs));
2142
2143 // PHIs created below will adopt NT's merged DebugLoc.
2144 IRBuilder<NoFolder> Builder(NT);
2145
2146 // In the case of an if statement, hoisting one of the terminators from our
2147 // successor is a great thing. Unfortunately, the successors of the if/else
2148 // blocks may have PHI nodes in them. If they do, all PHI entries for BB1/BB2
2149 // must agree for all PHI nodes, so we insert select instruction to compute
2150 // the final result.
2151 if (BI) {
2152 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
2153 for (BasicBlock *Succ : successors(BB1)) {
2154 for (PHINode &PN : Succ->phis()) {
2155 Value *BB1V = PN.getIncomingValueForBlock(BB1);
2156 Value *BB2V = PN.getIncomingValueForBlock(BB2);
2157 if (BB1V == BB2V)
2158 continue;
2159
2160 // These values do not agree. Insert a select instruction before NT
2161 // that determines the right value.
2162 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
2163 if (!SI) {
2164 // Propagate fast-math-flags from phi node to its replacement select.
2166 BI->getCondition(), BB1V, BB2V,
2167 isa<FPMathOperator>(PN) ? &PN : nullptr,
2168 BB1V->getName() + "." + BB2V->getName(), BI));
2169 }
2170
2171 // Make the PHI node use the select for all incoming values for BB1/BB2
2172 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2173 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
2174 PN.setIncomingValue(i, SI);
2175 }
2176 }
2177 }
2178
2180
2181 // Update any PHI nodes in our new successors.
2182 SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
2183 for (BasicBlock *Succ : successors(BB1)) {
2184 addPredecessorToBlock(Succ, TIParent, BB1);
2185
2186 if (DTU && VisitedSuccs.insert(Succ).second)
2187 Updates.push_back({DominatorTree::Insert, TIParent, Succ});
2188 }
2189
2190 if (DTU) {
2191 // TI might be a switch with multi-cases destination, so we need to care for
2192 // the duplication of successors.
2193 for (BasicBlock *Succ : UniqueSuccessors)
2194 Updates.push_back({DominatorTree::Delete, TIParent, Succ});
2195 }
2196
2198 if (DTU)
2199 DTU->applyUpdates(Updates);
2200 return Changed;
2201}
2202
2203// TODO: Refine this. This should avoid cases like turning constant memcpy sizes
2204// into variables.
2206 int OpIdx) {
2207 // Divide/Remainder by constant is typically much cheaper than by variable.
2208 if (I->isIntDivRem())
2209 return OpIdx != 1;
2210 return !isa<IntrinsicInst>(I);
2211}
2212
2213// All instructions in Insts belong to different blocks that all unconditionally
2214// branch to a common successor. Analyze each instruction and return true if it
2215// would be possible to sink them into their successor, creating one common
2216// instruction instead. For every value that would be required to be provided by
2217// PHI node (because an operand varies in each input block), add to PHIOperands.
2220 DenseMap<const Use *, SmallVector<Value *, 4>> &PHIOperands) {
2221 // Prune out obviously bad instructions to move. Each instruction must have
2222 // the same number of uses, and we check later that the uses are consistent.
2223 std::optional<unsigned> NumUses;
2224 for (auto *I : Insts) {
2225 // These instructions may change or break semantics if moved.
2226 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
2227 I->getType()->isTokenTy())
2228 return false;
2229
2230 // Do not try to sink an instruction in an infinite loop - it can cause
2231 // this algorithm to infinite loop.
2232 if (I->getParent()->getSingleSuccessor() == I->getParent())
2233 return false;
2234
2235 // Conservatively return false if I is an inline-asm instruction. Sinking
2236 // and merging inline-asm instructions can potentially create arguments
2237 // that cannot satisfy the inline-asm constraints.
2238 // If the instruction has nomerge or convergent attribute, return false.
2239 if (const auto *C = dyn_cast<CallBase>(I))
2240 if (C->isInlineAsm() || C->cannotMerge() || C->isConvergent())
2241 return false;
2242
2243 if (!NumUses)
2244 NumUses = I->getNumUses();
2245 else if (NumUses != I->getNumUses())
2246 return false;
2247 }
2248
2249 const Instruction *I0 = Insts.front();
2250 const auto I0MMRA = MMRAMetadata(*I0);
2251 for (auto *I : Insts) {
2252 if (!I->isSameOperationAs(I0, Instruction::CompareUsingIntersectedAttrs))
2253 return false;
2254
2255 // Treat MMRAs conservatively. This pass can be quite aggressive and
2256 // could drop a lot of MMRAs otherwise.
2257 if (MMRAMetadata(*I) != I0MMRA)
2258 return false;
2259 }
2260
2261 // Uses must be consistent: If I0 is used in a phi node in the sink target,
2262 // then the other phi operands must match the instructions from Insts. This
2263 // also has to hold true for any phi nodes that would be created as a result
2264 // of sinking. Both of these cases are represented by PhiOperands.
2265 for (const Use &U : I0->uses()) {
2266 auto It = PHIOperands.find(&U);
2267 if (It == PHIOperands.end())
2268 // There may be uses in other blocks when sinking into a loop header.
2269 return false;
2270 if (!equal(Insts, It->second))
2271 return false;
2272 }
2273
2274 // For calls to be sinkable, they must all be indirect, or have same callee.
2275 // I.e. if we have two direct calls to different callees, we don't want to
2276 // turn that into an indirect call. Likewise, if we have an indirect call,
2277 // and a direct call, we don't actually want to have a single indirect call.
2278 if (isa<CallBase>(I0)) {
2279 auto IsIndirectCall = [](const Instruction *I) {
2280 return cast<CallBase>(I)->isIndirectCall();
2281 };
2282 bool HaveIndirectCalls = any_of(Insts, IsIndirectCall);
2283 bool AllCallsAreIndirect = all_of(Insts, IsIndirectCall);
2284 if (HaveIndirectCalls) {
2285 if (!AllCallsAreIndirect)
2286 return false;
2287 } else {
2288 // All callees must be identical.
2289 Value *Callee = nullptr;
2290 for (const Instruction *I : Insts) {
2291 Value *CurrCallee = cast<CallBase>(I)->getCalledOperand();
2292 if (!Callee)
2293 Callee = CurrCallee;
2294 else if (Callee != CurrCallee)
2295 return false;
2296 }
2297 }
2298 }
2299
2300 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
2301 Value *Op = I0->getOperand(OI);
2302 auto SameAsI0 = [&I0, OI](const Instruction *I) {
2303 assert(I->getNumOperands() == I0->getNumOperands());
2304 return I->getOperand(OI) == I0->getOperand(OI);
2305 };
2306 if (!all_of(Insts, SameAsI0)) {
2307 auto CanReplaceOperand = [OI](const Instruction *I) {
2308 return canReplaceOperandWithVariable(I, OI);
2309 };
2311 !all_of(Insts, CanReplaceOperand))
2312 // We can't create a PHI from this operand.
2313 return false;
2314 auto &Ops = PHIOperands[&I0->getOperandUse(OI)];
2315 for (auto *I : Insts)
2316 Ops.push_back(I->getOperand(OI));
2317 }
2318 }
2319 return true;
2320}
2321
2322// Assuming canSinkInstructions(Blocks) has returned true, sink the last
2323// instruction of every block in Blocks to their common successor, commoning
2324// into one instruction.
2326 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
2327
2328 // canSinkInstructions returning true guarantees that every block has at
2329 // least one non-terminator instruction.
2331 for (auto *BB : Blocks) {
2332 Instruction *I = BB->getTerminator();
2333 I = I->getPrevNode();
2334 Insts.push_back(I);
2335 }
2336
2337 // We don't need to do any more checking here; canSinkInstructions should
2338 // have done it all for us.
2339 SmallVector<Value*, 4> NewOperands;
2340 Instruction *I0 = Insts.front();
2341 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
2342 // This check is different to that in canSinkInstructions. There, we
2343 // cared about the global view once simplifycfg (and instcombine) have
2344 // completed - it takes into account PHIs that become trivially
2345 // simplifiable. However here we need a more local view; if an operand
2346 // differs we create a PHI and rely on instcombine to clean up the very
2347 // small mess we may make.
2348 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
2349 return I->getOperand(O) != I0->getOperand(O);
2350 });
2351 if (!NeedPHI) {
2352 NewOperands.push_back(I0->getOperand(O));
2353 continue;
2354 }
2355
2356 // Create a new PHI in the successor block and populate it.
2357 auto *Op = I0->getOperand(O);
2358 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
2359 auto *PN =
2360 PHINode::Create(Op->getType(), Insts.size(), Op->getName() + ".sink");
2361 PN->insertBefore(BBEnd->begin());
2362 for (auto *I : Insts)
2363 PN->addIncoming(I->getOperand(O), I->getParent());
2364 NewOperands.push_back(PN);
2365 }
2366
2367 // Arbitrarily use I0 as the new "common" instruction; remap its operands
2368 // and move it to the start of the successor block.
2369 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
2370 I0->getOperandUse(O).set(NewOperands[O]);
2371
2372 I0->moveBefore(*BBEnd, BBEnd->getFirstInsertionPt());
2373
2374 // Update metadata and IR flags, and merge debug locations.
2375 for (auto *I : Insts)
2376 if (I != I0) {
2377 // The debug location for the "common" instruction is the merged locations
2378 // of all the commoned instructions. We start with the original location
2379 // of the "common" instruction and iteratively merge each location in the
2380 // loop below.
2381 // This is an N-way merge, which will be inefficient if I0 is a CallInst.
2382 // However, as N-way merge for CallInst is rare, so we use simplified API
2383 // instead of using complex API for N-way merge.
2384 I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
2385 combineMetadataForCSE(I0, I, true);
2386 I0->andIRFlags(I);
2387 if (auto *CB = dyn_cast<CallBase>(I0)) {
2388 bool Success = CB->tryIntersectAttributes(cast<CallBase>(I));
2389 assert(Success && "We should not be trying to sink callbases "
2390 "with non-intersectable attributes");
2391 // For NDEBUG Compile.
2392 (void)Success;
2393 }
2394 }
2395
2396 for (User *U : make_early_inc_range(I0->users())) {
2397 // canSinkLastInstruction checked that all instructions are only used by
2398 // phi nodes in a way that allows replacing the phi node with the common
2399 // instruction.
2400 auto *PN = cast<PHINode>(U);
2401 PN->replaceAllUsesWith(I0);
2402 PN->eraseFromParent();
2403 }
2404
2405 // Finally nuke all instructions apart from the common instruction.
2406 for (auto *I : Insts) {
2407 if (I == I0)
2408 continue;
2409 // The remaining uses are debug users, replace those with the common inst.
2410 // In most (all?) cases this just introduces a use-before-def.
2411 assert(I->user_empty() && "Inst unexpectedly still has non-dbg users");
2412 I->replaceAllUsesWith(I0);
2413 I->eraseFromParent();
2414 }
2415}
2416
2417/// Check whether BB's predecessors end with unconditional branches. If it is
2418/// true, sink any common code from the predecessors to BB.
2420 DomTreeUpdater *DTU) {
2421 // We support two situations:
2422 // (1) all incoming arcs are unconditional
2423 // (2) there are non-unconditional incoming arcs
2424 //
2425 // (2) is very common in switch defaults and
2426 // else-if patterns;
2427 //
2428 // if (a) f(1);
2429 // else if (b) f(2);
2430 //
2431 // produces:
2432 //
2433 // [if]
2434 // / \
2435 // [f(1)] [if]
2436 // | | \
2437 // | | |
2438 // | [f(2)]|
2439 // \ | /
2440 // [ end ]
2441 //
2442 // [end] has two unconditional predecessor arcs and one conditional. The
2443 // conditional refers to the implicit empty 'else' arc. This conditional
2444 // arc can also be caused by an empty default block in a switch.
2445 //
2446 // In this case, we attempt to sink code from all *unconditional* arcs.
2447 // If we can sink instructions from these arcs (determined during the scan
2448 // phase below) we insert a common successor for all unconditional arcs and
2449 // connect that to [end], to enable sinking:
2450 //
2451 // [if]
2452 // / \
2453 // [x(1)] [if]
2454 // | | \
2455 // | | \
2456 // | [x(2)] |
2457 // \ / |
2458 // [sink.split] |
2459 // \ /
2460 // [ end ]
2461 //
2462 SmallVector<BasicBlock*,4> UnconditionalPreds;
2463 bool HaveNonUnconditionalPredecessors = false;
2464 for (auto *PredBB : predecessors(BB)) {
2465 auto *PredBr = dyn_cast<UncondBrInst>(PredBB->getTerminator());
2466 if (PredBr)
2467 UnconditionalPreds.push_back(PredBB);
2468 else
2469 HaveNonUnconditionalPredecessors = true;
2470 }
2471 if (UnconditionalPreds.size() < 2)
2472 return false;
2473
2474 // We take a two-step approach to tail sinking. First we scan from the end of
2475 // each block upwards in lockstep. If the n'th instruction from the end of each
2476 // block can be sunk, those instructions are added to ValuesToSink and we
2477 // carry on. If we can sink an instruction but need to PHI-merge some operands
2478 // (because they're not identical in each instruction) we add these to
2479 // PHIOperands.
2480 // We prepopulate PHIOperands with the phis that already exist in BB.
2482 for (PHINode &PN : BB->phis()) {
2484 for (const Use &U : PN.incoming_values())
2485 IncomingVals.insert({PN.getIncomingBlock(U), &U});
2486 auto &Ops = PHIOperands[IncomingVals[UnconditionalPreds[0]]];
2487 for (BasicBlock *Pred : UnconditionalPreds)
2488 Ops.push_back(*IncomingVals[Pred]);
2489 }
2490
2491 int ScanIdx = 0;
2492 SmallPtrSet<Value*,4> InstructionsToSink;
2493 LockstepReverseIterator<true> LRI(UnconditionalPreds);
2494 while (LRI.isValid() &&
2495 canSinkInstructions(*LRI, PHIOperands)) {
2496 LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
2497 << "\n");
2498 InstructionsToSink.insert_range(*LRI);
2499 ++ScanIdx;
2500 --LRI;
2501 }
2502
2503 // If no instructions can be sunk, early-return.
2504 if (ScanIdx == 0)
2505 return false;
2506
2507 bool followedByDeoptOrUnreachable = IsBlockFollowedByDeoptOrUnreachable(BB);
2508
2509 if (!followedByDeoptOrUnreachable) {
2510 // Check whether this is the pointer operand of a load/store.
2511 auto IsMemOperand = [](Use &U) {
2512 auto *I = cast<Instruction>(U.getUser());
2513 if (isa<LoadInst>(I))
2514 return U.getOperandNo() == LoadInst::getPointerOperandIndex();
2515 if (isa<StoreInst>(I))
2516 return U.getOperandNo() == StoreInst::getPointerOperandIndex();
2517 return false;
2518 };
2519
2520 // Okay, we *could* sink last ScanIdx instructions. But how many can we
2521 // actually sink before encountering instruction that is unprofitable to
2522 // sink?
2523 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator<true> &LRI) {
2524 unsigned NumPHIInsts = 0;
2525 for (Use &U : (*LRI)[0]->operands()) {
2526 auto It = PHIOperands.find(&U);
2527 if (It != PHIOperands.end() && !all_of(It->second, [&](Value *V) {
2528 return InstructionsToSink.contains(V);
2529 })) {
2530 ++NumPHIInsts;
2531 // Do not separate a load/store from the gep producing the address.
2532 // The gep can likely be folded into the load/store as an addressing
2533 // mode. Additionally, a load of a gep is easier to analyze than a
2534 // load of a phi.
2535 if (IsMemOperand(U) &&
2536 any_of(It->second, [](Value *V) { return isa<GEPOperator>(V); }))
2537 return false;
2538 // FIXME: this check is overly optimistic. We may end up not sinking
2539 // said instruction, due to the very same profitability check.
2540 // See @creating_too_many_phis in sink-common-code.ll.
2541 }
2542 }
2543 LLVM_DEBUG(dbgs() << "SINK: #phi insts: " << NumPHIInsts << "\n");
2544 return NumPHIInsts <= 1;
2545 };
2546
2547 // We've determined that we are going to sink last ScanIdx instructions,
2548 // and recorded them in InstructionsToSink. Now, some instructions may be
2549 // unprofitable to sink. But that determination depends on the instructions
2550 // that we are going to sink.
2551
2552 // First, forward scan: find the first instruction unprofitable to sink,
2553 // recording all the ones that are profitable to sink.
2554 // FIXME: would it be better, after we detect that not all are profitable.
2555 // to either record the profitable ones, or erase the unprofitable ones?
2556 // Maybe we need to choose (at runtime) the one that will touch least
2557 // instrs?
2558 LRI.reset();
2559 int Idx = 0;
2560 SmallPtrSet<Value *, 4> InstructionsProfitableToSink;
2561 while (Idx < ScanIdx) {
2562 if (!ProfitableToSinkInstruction(LRI)) {
2563 // Too many PHIs would be created.
2564 LLVM_DEBUG(
2565 dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
2566 break;
2567 }
2568 InstructionsProfitableToSink.insert_range(*LRI);
2569 --LRI;
2570 ++Idx;
2571 }
2572
2573 // If no instructions can be sunk, early-return.
2574 if (Idx == 0)
2575 return false;
2576
2577 // Did we determine that (only) some instructions are unprofitable to sink?
2578 if (Idx < ScanIdx) {
2579 // Okay, some instructions are unprofitable.
2580 ScanIdx = Idx;
2581 InstructionsToSink = InstructionsProfitableToSink;
2582
2583 // But, that may make other instructions unprofitable, too.
2584 // So, do a backward scan, do any earlier instructions become
2585 // unprofitable?
2586 assert(
2587 !ProfitableToSinkInstruction(LRI) &&
2588 "We already know that the last instruction is unprofitable to sink");
2589 ++LRI;
2590 --Idx;
2591 while (Idx >= 0) {
2592 // If we detect that an instruction becomes unprofitable to sink,
2593 // all earlier instructions won't be sunk either,
2594 // so preemptively keep InstructionsProfitableToSink in sync.
2595 // FIXME: is this the most performant approach?
2596 for (auto *I : *LRI)
2597 InstructionsProfitableToSink.erase(I);
2598 if (!ProfitableToSinkInstruction(LRI)) {
2599 // Everything starting with this instruction won't be sunk.
2600 ScanIdx = Idx;
2601 InstructionsToSink = InstructionsProfitableToSink;
2602 }
2603 ++LRI;
2604 --Idx;
2605 }
2606 }
2607
2608 // If no instructions can be sunk, early-return.
2609 if (ScanIdx == 0)
2610 return false;
2611 }
2612
2613 bool Changed = false;
2614
2615 if (HaveNonUnconditionalPredecessors) {
2616 if (!followedByDeoptOrUnreachable) {
2617 // It is always legal to sink common instructions from unconditional
2618 // predecessors. However, if not all predecessors are unconditional,
2619 // this transformation might be pessimizing. So as a rule of thumb,
2620 // don't do it unless we'd sink at least one non-speculatable instruction.
2621 // See https://bugs.llvm.org/show_bug.cgi?id=30244
2622 LRI.reset();
2623 int Idx = 0;
2624 bool Profitable = false;
2625 while (Idx < ScanIdx) {
2626 if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
2627 Profitable = true;
2628 break;
2629 }
2630 --LRI;
2631 ++Idx;
2632 }
2633 if (!Profitable)
2634 return false;
2635 }
2636
2637 LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
2638 // We have a conditional edge and we're going to sink some instructions.
2639 // Insert a new block postdominating all blocks we're going to sink from.
2640 if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split", DTU))
2641 // Edges couldn't be split.
2642 return false;
2643 Changed = true;
2644 }
2645
2646 // Now that we've analyzed all potential sinking candidates, perform the
2647 // actual sink. We iteratively sink the last non-terminator of the source
2648 // blocks into their common successor unless doing so would require too
2649 // many PHI instructions to be generated (currently only one PHI is allowed
2650 // per sunk instruction).
2651 //
2652 // We can use InstructionsToSink to discount values needing PHI-merging that will
2653 // actually be sunk in a later iteration. This allows us to be more
2654 // aggressive in what we sink. This does allow a false positive where we
2655 // sink presuming a later value will also be sunk, but stop half way through
2656 // and never actually sink it which means we produce more PHIs than intended.
2657 // This is unlikely in practice though.
2658 int SinkIdx = 0;
2659 for (; SinkIdx != ScanIdx; ++SinkIdx) {
2660 LLVM_DEBUG(dbgs() << "SINK: Sink: "
2661 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
2662 << "\n");
2663
2664 // Because we've sunk every instruction in turn, the current instruction to
2665 // sink is always at index 0.
2666 LRI.reset();
2667
2668 sinkLastInstruction(UnconditionalPreds);
2669 NumSinkCommonInstrs++;
2670 Changed = true;
2671 }
2672 if (SinkIdx != 0)
2673 ++NumSinkCommonCode;
2674 return Changed;
2675}
2676
2677namespace {
2678
2679struct CompatibleSets {
2680 using SetTy = SmallVector<InvokeInst *, 2>;
2681
2683
2684 static bool shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes);
2685
2686 SetTy &getCompatibleSet(InvokeInst *II);
2687
2688 void insert(InvokeInst *II);
2689};
2690
2691CompatibleSets::SetTy &CompatibleSets::getCompatibleSet(InvokeInst *II) {
2692 // Perform a linear scan over all the existing sets, see if the new `invoke`
2693 // is compatible with any particular set. Since we know that all the `invokes`
2694 // within a set are compatible, only check the first `invoke` in each set.
2695 // WARNING: at worst, this has quadratic complexity.
2696 for (CompatibleSets::SetTy &Set : Sets) {
2697 if (CompatibleSets::shouldBelongToSameSet({Set.front(), II}))
2698 return Set;
2699 }
2700
2701 // Otherwise, we either had no sets yet, or this invoke forms a new set.
2702 return Sets.emplace_back();
2703}
2704
2705void CompatibleSets::insert(InvokeInst *II) {
2706 getCompatibleSet(II).emplace_back(II);
2707}
2708
2709bool CompatibleSets::shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes) {
2710 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2711
2712 // Can we theoretically merge these `invoke`s?
2713 auto IsIllegalToMerge = [](InvokeInst *II) {
2714 return II->cannotMerge() || II->isInlineAsm();
2715 };
2716 if (any_of(Invokes, IsIllegalToMerge))
2717 return false;
2718
2719 // Either both `invoke`s must be direct,
2720 // or both `invoke`s must be indirect.
2721 auto IsIndirectCall = [](InvokeInst *II) { return II->isIndirectCall(); };
2722 bool HaveIndirectCalls = any_of(Invokes, IsIndirectCall);
2723 bool AllCallsAreIndirect = all_of(Invokes, IsIndirectCall);
2724 if (HaveIndirectCalls) {
2725 if (!AllCallsAreIndirect)
2726 return false;
2727 } else {
2728 // All callees must be identical.
2729 Value *Callee = nullptr;
2730 for (InvokeInst *II : Invokes) {
2731 Value *CurrCallee = II->getCalledOperand();
2732 assert(CurrCallee && "There is always a called operand.");
2733 if (!Callee)
2734 Callee = CurrCallee;
2735 else if (Callee != CurrCallee)
2736 return false;
2737 }
2738 }
2739
2740 // Either both `invoke`s must not have a normal destination,
2741 // or both `invoke`s must have a normal destination,
2742 auto HasNormalDest = [](InvokeInst *II) {
2743 return !isa<UnreachableInst>(II->getNormalDest()->getFirstNonPHIOrDbg());
2744 };
2745 if (any_of(Invokes, HasNormalDest)) {
2746 // Do not merge `invoke` that does not have a normal destination with one
2747 // that does have a normal destination, even though doing so would be legal.
2748 if (!all_of(Invokes, HasNormalDest))
2749 return false;
2750
2751 // All normal destinations must be identical.
2752 BasicBlock *NormalBB = nullptr;
2753 for (InvokeInst *II : Invokes) {
2754 BasicBlock *CurrNormalBB = II->getNormalDest();
2755 assert(CurrNormalBB && "There is always a 'continue to' basic block.");
2756 if (!NormalBB)
2757 NormalBB = CurrNormalBB;
2758 else if (NormalBB != CurrNormalBB)
2759 return false;
2760 }
2761
2762 // In the normal destination, the incoming values for these two `invoke`s
2763 // must be compatible.
2764 SmallPtrSet<Value *, 16> EquivalenceSet(llvm::from_range, Invokes);
2766 NormalBB, {Invokes[0]->getParent(), Invokes[1]->getParent()},
2767 &EquivalenceSet))
2768 return false;
2769 }
2770
2771#ifndef NDEBUG
2772 // All unwind destinations must be identical.
2773 // We know that because we have started from said unwind destination.
2774 BasicBlock *UnwindBB = nullptr;
2775 for (InvokeInst *II : Invokes) {
2776 BasicBlock *CurrUnwindBB = II->getUnwindDest();
2777 assert(CurrUnwindBB && "There is always an 'unwind to' basic block.");
2778 if (!UnwindBB)
2779 UnwindBB = CurrUnwindBB;
2780 else
2781 assert(UnwindBB == CurrUnwindBB && "Unexpected unwind destination.");
2782 }
2783#endif
2784
2785 // In the unwind destination, the incoming values for these two `invoke`s
2786 // must be compatible.
2788 Invokes.front()->getUnwindDest(),
2789 {Invokes[0]->getParent(), Invokes[1]->getParent()}))
2790 return false;
2791
2792 // Ignoring arguments, these `invoke`s must be identical,
2793 // including operand bundles.
2794 const InvokeInst *II0 = Invokes.front();
2795 for (auto *II : Invokes.drop_front())
2796 if (!II->isSameOperationAs(II0, Instruction::CompareUsingIntersectedAttrs))
2797 return false;
2798
2799 // Can we theoretically form the data operands for the merged `invoke`?
2800 auto IsIllegalToMergeArguments = [](auto Ops) {
2801 Use &U0 = std::get<0>(Ops);
2802 Use &U1 = std::get<1>(Ops);
2803 if (U0 == U1)
2804 return false;
2806 U0.getOperandNo());
2807 };
2808 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2809 if (any_of(zip(Invokes[0]->data_ops(), Invokes[1]->data_ops()),
2810 IsIllegalToMergeArguments))
2811 return false;
2812
2813 return true;
2814}
2815
2816} // namespace
2817
2818// Merge all invokes in the provided set, all of which are compatible
2819// as per the `CompatibleSets::shouldBelongToSameSet()`.
2821 DomTreeUpdater *DTU) {
2822 assert(Invokes.size() >= 2 && "Must have at least two invokes to merge.");
2823
2825 if (DTU)
2826 Updates.reserve(2 + 3 * Invokes.size());
2827
2828 bool HasNormalDest =
2829 !isa<UnreachableInst>(Invokes[0]->getNormalDest()->getFirstNonPHIOrDbg());
2830
2831 // Clone one of the invokes into a new basic block.
2832 // Since they are all compatible, it doesn't matter which invoke is cloned.
2833 InvokeInst *MergedInvoke = [&Invokes, HasNormalDest]() {
2834 InvokeInst *II0 = Invokes.front();
2835 BasicBlock *II0BB = II0->getParent();
2836 BasicBlock *InsertBeforeBlock =
2837 II0->getParent()->getIterator()->getNextNode();
2838 Function *Func = II0BB->getParent();
2839 LLVMContext &Ctx = II0->getContext();
2840
2841 BasicBlock *MergedInvokeBB = BasicBlock::Create(
2842 Ctx, II0BB->getName() + ".invoke", Func, InsertBeforeBlock);
2843
2844 auto *MergedInvoke = cast<InvokeInst>(II0->clone());
2845 // NOTE: all invokes have the same attributes, so no handling needed.
2846 MergedInvoke->insertInto(MergedInvokeBB, MergedInvokeBB->end());
2847
2848 if (!HasNormalDest) {
2849 // This set does not have a normal destination,
2850 // so just form a new block with unreachable terminator.
2851 BasicBlock *MergedNormalDest = BasicBlock::Create(
2852 Ctx, II0BB->getName() + ".cont", Func, InsertBeforeBlock);
2853 auto *UI = new UnreachableInst(Ctx, MergedNormalDest);
2854 UI->setDebugLoc(DebugLoc::getTemporary());
2855 MergedInvoke->setNormalDest(MergedNormalDest);
2856 }
2857
2858 // The unwind destination, however, remainds identical for all invokes here.
2859
2860 return MergedInvoke;
2861 }();
2862
2863 if (DTU) {
2864 // Predecessor blocks that contained these invokes will now branch to
2865 // the new block that contains the merged invoke, ...
2866 for (InvokeInst *II : Invokes)
2867 Updates.push_back(
2868 {DominatorTree::Insert, II->getParent(), MergedInvoke->getParent()});
2869
2870 // ... which has the new `unreachable` block as normal destination,
2871 // or unwinds to the (same for all `invoke`s in this set) `landingpad`,
2872 for (BasicBlock *SuccBBOfMergedInvoke : successors(MergedInvoke))
2873 Updates.push_back({DominatorTree::Insert, MergedInvoke->getParent(),
2874 SuccBBOfMergedInvoke});
2875
2876 // Since predecessor blocks now unconditionally branch to a new block,
2877 // they no longer branch to their original successors.
2878 for (InvokeInst *II : Invokes)
2879 for (BasicBlock *SuccOfPredBB : successors(II->getParent()))
2880 Updates.push_back(
2881 {DominatorTree::Delete, II->getParent(), SuccOfPredBB});
2882 }
2883
2884 bool IsIndirectCall = Invokes[0]->isIndirectCall();
2885
2886 // Form the merged operands for the merged invoke.
2887 for (Use &U : MergedInvoke->operands()) {
2888 // Only PHI together the indirect callees and data operands.
2889 if (MergedInvoke->isCallee(&U)) {
2890 if (!IsIndirectCall)
2891 continue;
2892 } else if (!MergedInvoke->isDataOperand(&U))
2893 continue;
2894
2895 // Don't create trivial PHI's with all-identical incoming values.
2896 bool NeedPHI = any_of(Invokes, [&U](InvokeInst *II) {
2897 return II->getOperand(U.getOperandNo()) != U.get();
2898 });
2899 if (!NeedPHI)
2900 continue;
2901
2902 // Form a PHI out of all the data ops under this index.
2904 U->getType(), /*NumReservedValues=*/Invokes.size(), "", MergedInvoke->getIterator());
2905 for (InvokeInst *II : Invokes)
2906 PN->addIncoming(II->getOperand(U.getOperandNo()), II->getParent());
2907
2908 U.set(PN);
2909 }
2910
2911 // We've ensured that each PHI node has compatible (identical) incoming values
2912 // when coming from each of the `invoke`s in the current merge set,
2913 // so update the PHI nodes accordingly.
2914 for (BasicBlock *Succ : successors(MergedInvoke))
2915 addPredecessorToBlock(Succ, /*NewPred=*/MergedInvoke->getParent(),
2916 /*ExistPred=*/Invokes.front()->getParent());
2917
2918 // And finally, replace the original `invoke`s with an unconditional branch
2919 // to the block with the merged `invoke`. Also, give that merged `invoke`
2920 // the merged debugloc of all the original `invoke`s.
2921 DILocation *MergedDebugLoc = nullptr;
2922 for (InvokeInst *II : Invokes) {
2923 // Compute the debug location common to all the original `invoke`s.
2924 if (!MergedDebugLoc)
2925 MergedDebugLoc = II->getDebugLoc();
2926 else
2927 MergedDebugLoc =
2928 DebugLoc::getMergedLocation(MergedDebugLoc, II->getDebugLoc());
2929
2930 // And replace the old `invoke` with an unconditionally branch
2931 // to the block with the merged `invoke`.
2932 for (BasicBlock *OrigSuccBB : successors(II->getParent()))
2933 OrigSuccBB->removePredecessor(II->getParent());
2934 auto *BI = UncondBrInst::Create(MergedInvoke->getParent(), II->getParent());
2935 // The unconditional branch is part of the replacement for the original
2936 // invoke, so should use its DebugLoc.
2937 BI->setDebugLoc(II->getDebugLoc());
2938 bool Success = MergedInvoke->tryIntersectAttributes(II);
2939 assert(Success && "Merged invokes with incompatible attributes");
2940 // For NDEBUG Compile
2941 (void)Success;
2942 II->replaceAllUsesWith(MergedInvoke);
2943 II->eraseFromParent();
2944 ++NumInvokesMerged;
2945 }
2946 MergedInvoke->setDebugLoc(MergedDebugLoc);
2947 ++NumInvokeSetsFormed;
2948
2949 if (DTU)
2950 DTU->applyUpdates(Updates);
2951}
2952
2953/// If this block is a `landingpad` exception handling block, categorize all
2954/// the predecessor `invoke`s into sets, with all `invoke`s in each set
2955/// being "mergeable" together, and then merge invokes in each set together.
2956///
2957/// This is a weird mix of hoisting and sinking. Visually, it goes from:
2958/// [...] [...]
2959/// | |
2960/// [invoke0] [invoke1]
2961/// / \ / \
2962/// [cont0] [landingpad] [cont1]
2963/// to:
2964/// [...] [...]
2965/// \ /
2966/// [invoke]
2967/// / \
2968/// [cont] [landingpad]
2969///
2970/// But of course we can only do that if the invokes share the `landingpad`,
2971/// edges invoke0->cont0 and invoke1->cont1 are "compatible",
2972/// and the invoked functions are "compatible".
2975 return false;
2976
2977 bool Changed = false;
2978
2979 // FIXME: generalize to all exception handling blocks?
2980 if (!BB->isLandingPad())
2981 return Changed;
2982
2983 CompatibleSets Grouper;
2984
2985 // Record all the predecessors of this `landingpad`. As per verifier,
2986 // the only allowed predecessor is the unwind edge of an `invoke`.
2987 // We want to group "compatible" `invokes` into the same set to be merged.
2988 for (BasicBlock *PredBB : predecessors(BB))
2989 Grouper.insert(cast<InvokeInst>(PredBB->getTerminator()));
2990
2991 // And now, merge `invoke`s that were grouped togeter.
2992 for (ArrayRef<InvokeInst *> Invokes : Grouper.Sets) {
2993 if (Invokes.size() < 2)
2994 continue;
2995 Changed = true;
2996 mergeCompatibleInvokesImpl(Invokes, DTU);
2997 }
2998
2999 return Changed;
3000}
3001
3002namespace {
3003/// Track ephemeral values, which should be ignored for cost-modelling
3004/// purposes. Requires walking instructions in reverse order.
3005class EphemeralValueTracker {
3006 SmallPtrSet<const Instruction *, 32> EphValues;
3007
3008 bool isEphemeral(const Instruction *I) {
3009 if (isa<AssumeInst>(I))
3010 return true;
3011 return !I->mayHaveSideEffects() && !I->isTerminator() &&
3012 all_of(I->users(), [&](const User *U) {
3013 return EphValues.count(cast<Instruction>(U));
3014 });
3015 }
3016
3017public:
3018 bool track(const Instruction *I) {
3019 if (isEphemeral(I)) {
3020 EphValues.insert(I);
3021 return true;
3022 }
3023 return false;
3024 }
3025
3026 bool contains(const Instruction *I) const { return EphValues.contains(I); }
3027};
3028} // namespace
3029
3030/// Determine if we can hoist sink a sole store instruction out of a
3031/// conditional block.
3032///
3033/// We are looking for code like the following:
3034/// BrBB:
3035/// store i32 %add, i32* %arrayidx2
3036/// ... // No other stores or function calls (we could be calling a memory
3037/// ... // function).
3038/// %cmp = icmp ult %x, %y
3039/// br i1 %cmp, label %EndBB, label %ThenBB
3040/// ThenBB:
3041/// store i32 %add5, i32* %arrayidx2
3042/// br label EndBB
3043/// EndBB:
3044/// ...
3045/// We are going to transform this into:
3046/// BrBB:
3047/// store i32 %add, i32* %arrayidx2
3048/// ... //
3049/// %cmp = icmp ult %x, %y
3050/// %add.add5 = select i1 %cmp, i32 %add, %add5
3051/// store i32 %add.add5, i32* %arrayidx2
3052/// ...
3053///
3054/// \return The pointer to the value of the previous store if the store can be
3055/// hoisted into the predecessor block. 0 otherwise.
3057 BasicBlock *StoreBB, BasicBlock *EndBB) {
3058 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
3059 if (!StoreToHoist)
3060 return nullptr;
3061
3062 // Volatile or atomic.
3063 if (!StoreToHoist->isSimple())
3064 return nullptr;
3065
3066 Value *StorePtr = StoreToHoist->getPointerOperand();
3067 Type *StoreTy = StoreToHoist->getValueOperand()->getType();
3068
3069 // Look for a store to the same pointer in BrBB.
3070 unsigned MaxNumInstToLookAt = 9;
3071 // Skip pseudo probe intrinsic calls which are not really killing any memory
3072 // accesses.
3073 for (Instruction &CurI : reverse(*BrBB)) {
3074 if (!MaxNumInstToLookAt)
3075 break;
3076 --MaxNumInstToLookAt;
3077
3078 if (isa<PseudoProbeInst>(CurI))
3079 continue;
3080
3081 // Could be calling an instruction that affects memory like free().
3082 if (CurI.mayWriteToMemory() && !isa<StoreInst>(CurI))
3083 return nullptr;
3084
3085 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
3086 // Found the previous store to same location and type. Make sure it is
3087 // simple, to avoid introducing a spurious non-atomic write after an
3088 // atomic write.
3089 if (SI->getPointerOperand() == StorePtr &&
3090 SI->getValueOperand()->getType() == StoreTy && SI->isSimple() &&
3091 SI->getAlign() >= StoreToHoist->getAlign())
3092 // Found the previous store, return its value operand.
3093 return SI->getValueOperand();
3094 return nullptr; // Unknown store.
3095 }
3096
3097 if (auto *LI = dyn_cast<LoadInst>(&CurI)) {
3098 if (LI->getPointerOperand() == StorePtr && LI->getType() == StoreTy &&
3099 LI->isSimple() && LI->getAlign() >= StoreToHoist->getAlign()) {
3100 Value *Obj = getUnderlyingObject(StorePtr);
3101 bool ExplicitlyDereferenceableOnly;
3102 // The dereferenceability query here is only required to satisfy the
3103 // writable contract, actual dereferenceability is proven by the
3104 // presence of an access. As such, we can ignore frees.
3105 if (isWritableObject(Obj, ExplicitlyDereferenceableOnly) &&
3108 .WithoutRet) &&
3109 (!ExplicitlyDereferenceableOnly ||
3110 isDereferenceablePointer(StorePtr, StoreTy, LI->getDataLayout(),
3111 /*IgnoreFree=*/true))) {
3112 // Found a previous load, return it.
3113 return LI;
3114 }
3115 }
3116 // The load didn't work out, but we may still find a store.
3117 }
3118 }
3119
3120 return nullptr;
3121}
3122
3123/// Estimate the cost of the insertion(s) and check that the PHI nodes can be
3124/// converted to selects.
3126 BasicBlock *EndBB,
3127 unsigned &SpeculatedInstructions,
3128 InstructionCost &Cost,
3129 const TargetTransformInfo &TTI) {
3131 BB->getParent()->hasMinSize()
3134
3135 bool HaveRewritablePHIs = false;
3136 for (PHINode &PN : EndBB->phis()) {
3137 Value *OrigV = PN.getIncomingValueForBlock(BB);
3138 Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
3139
3140 // FIXME: Try to remove some of the duplication with
3141 // hoistCommonCodeFromSuccessors. Skip PHIs which are trivial.
3142 if (ThenV == OrigV)
3143 continue;
3144
3145 Cost += TTI.getCmpSelInstrCost(Instruction::Select, PN.getType(),
3146 CmpInst::makeCmpResultType(PN.getType()),
3148
3149 // Don't convert to selects if we could remove undefined behavior instead.
3150 if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
3152 return false;
3153
3154 HaveRewritablePHIs = true;
3155 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
3156 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
3157 if (!OrigCE && !ThenCE)
3158 continue; // Known cheap (FIXME: Maybe not true for aggregates).
3159
3160 InstructionCost OrigCost = OrigCE ? computeSpeculationCost(OrigCE, TTI) : 0;
3161 InstructionCost ThenCost = ThenCE ? computeSpeculationCost(ThenCE, TTI) : 0;
3162 InstructionCost MaxCost =
3164 if (OrigCost + ThenCost > MaxCost)
3165 return false;
3166
3167 // Account for the cost of an unfolded ConstantExpr which could end up
3168 // getting expanded into Instructions.
3169 // FIXME: This doesn't account for how many operations are combined in the
3170 // constant expression.
3171 ++SpeculatedInstructions;
3172 if (SpeculatedInstructions > 1)
3173 return false;
3174 }
3175
3176 return HaveRewritablePHIs;
3177}
3178
3180 std::optional<bool> Invert,
3181 const TargetTransformInfo &TTI) {
3182 // If the branch is non-unpredictable, and is predicted to *not* branch to
3183 // the `then` block, then avoid speculating it.
3184 if (BI->getMetadata(LLVMContext::MD_unpredictable))
3185 return true;
3186
3187 uint64_t TWeight, FWeight;
3188 if (!extractBranchWeights(*BI, TWeight, FWeight) || (TWeight + FWeight) == 0)
3189 return true;
3190
3191 if (!Invert.has_value())
3192 return false;
3193
3194 uint64_t EndWeight = *Invert ? TWeight : FWeight;
3195 BranchProbability BIEndProb =
3196 BranchProbability::getBranchProbability(EndWeight, TWeight + FWeight);
3197 BranchProbability Likely = TTI.getPredictableBranchThreshold();
3198 return BIEndProb < Likely;
3199}
3200
3201/// Speculate a conditional basic block flattening the CFG.
3202///
3203/// Note that this is a very risky transform currently. Speculating
3204/// instructions like this is most often not desirable. Instead, there is an MI
3205/// pass which can do it with full awareness of the resource constraints.
3206/// However, some cases are "obvious" and we should do directly. An example of
3207/// this is speculating a single, reasonably cheap instruction.
3208///
3209/// There is only one distinct advantage to flattening the CFG at the IR level:
3210/// it makes very common but simplistic optimizations such as are common in
3211/// instcombine and the DAG combiner more powerful by removing CFG edges and
3212/// modeling their effects with easier to reason about SSA value graphs.
3213///
3214///
3215/// An illustration of this transform is turning this IR:
3216/// \code
3217/// BB:
3218/// %cmp = icmp ult %x, %y
3219/// br i1 %cmp, label %EndBB, label %ThenBB
3220/// ThenBB:
3221/// %sub = sub %x, %y
3222/// br label BB2
3223/// EndBB:
3224/// %phi = phi [ %sub, %ThenBB ], [ 0, %BB ]
3225/// ...
3226/// \endcode
3227///
3228/// Into this IR:
3229/// \code
3230/// BB:
3231/// %cmp = icmp ult %x, %y
3232/// %sub = sub %x, %y
3233/// %cond = select i1 %cmp, 0, %sub
3234/// ...
3235/// \endcode
3236///
3237/// \returns true if the conditional block is removed.
3238bool SimplifyCFGOpt::speculativelyExecuteBB(CondBrInst *BI,
3239 BasicBlock *ThenBB) {
3240 if (!Options.SpeculateBlocks)
3241 return false;
3242
3243 BasicBlock *BB = BI->getParent();
3244 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
3245 InstructionCost Budget =
3247
3248 // If ThenBB is actually on the false edge of the conditional branch, remember
3249 // to swap the select operands later.
3250 bool Invert = false;
3251 if (ThenBB != BI->getSuccessor(0)) {
3252 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
3253 Invert = true;
3254 }
3255 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
3256
3257 if (!isProfitableToSpeculate(BI, Invert, TTI))
3258 return false;
3259
3260 // Keep a count of how many times instructions are used within ThenBB when
3261 // they are candidates for sinking into ThenBB. Specifically:
3262 // - They are defined in BB, and
3263 // - They have no side effects, and
3264 // - All of their uses are in ThenBB.
3265 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
3266
3267 SmallVector<Instruction *, 4> SpeculatedPseudoProbes;
3268
3269 unsigned SpeculatedInstructions = 0;
3270 bool HoistLoadsStores = Options.HoistLoadsStoresWithCondFaulting;
3271 SmallVector<Instruction *, 2> SpeculatedConditionalLoadsStores;
3272 Value *SpeculatedStoreValue = nullptr;
3273 StoreInst *SpeculatedStore = nullptr;
3274 EphemeralValueTracker EphTracker;
3275 for (Instruction &I : reverse(drop_end(*ThenBB))) {
3276 // Skip pseudo probes. The consequence is we lose track of the branch
3277 // probability for ThenBB, which is fine since the optimization here takes
3278 // place regardless of the branch probability.
3279 if (isa<PseudoProbeInst>(I)) {
3280 // The probe should be deleted so that it will not be over-counted when
3281 // the samples collected on the non-conditional path are counted towards
3282 // the conditional path. We leave it for the counts inference algorithm to
3283 // figure out a proper count for an unknown probe.
3284 SpeculatedPseudoProbes.push_back(&I);
3285 continue;
3286 }
3287
3288 // Ignore ephemeral values, they will be dropped by the transform.
3289 if (EphTracker.track(&I))
3290 continue;
3291
3292 // Only speculatively execute a single instruction (not counting the
3293 // terminator) for now.
3294 bool IsSafeCheapLoadStore = HoistLoadsStores &&
3296 SpeculatedConditionalLoadsStores.size() <
3298 // Not count load/store into cost if target supports conditional faulting
3299 // b/c it's cheap to speculate it.
3300 if (IsSafeCheapLoadStore)
3301 SpeculatedConditionalLoadsStores.push_back(&I);
3302 else
3303 ++SpeculatedInstructions;
3304
3305 if (SpeculatedInstructions > 1)
3306 return false;
3307
3308 // Don't hoist the instruction if it's unsafe or expensive.
3309 if (!IsSafeCheapLoadStore &&
3311 !(HoistCondStores && !SpeculatedStoreValue &&
3312 (SpeculatedStoreValue =
3313 isSafeToSpeculateStore(&I, BB, ThenBB, EndBB))))
3314 return false;
3315 if (!IsSafeCheapLoadStore && !SpeculatedStoreValue &&
3318 return false;
3319
3320 // Store the store speculation candidate.
3321 if (!SpeculatedStore && SpeculatedStoreValue)
3322 SpeculatedStore = cast<StoreInst>(&I);
3323
3324 // Do not hoist the instruction if any of its operands are defined but not
3325 // used in BB. The transformation will prevent the operand from
3326 // being sunk into the use block.
3327 for (Use &Op : I.operands()) {
3329 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
3330 continue; // Not a candidate for sinking.
3331
3332 ++SinkCandidateUseCounts[OpI];
3333 }
3334 }
3335
3336 // Consider any sink candidates which are only used in ThenBB as costs for
3337 // speculation. Note, while we iterate over a DenseMap here, we are summing
3338 // and so iteration order isn't significant.
3339 for (const auto &[Inst, Count] : SinkCandidateUseCounts)
3340 if (Inst->hasNUses(Count)) {
3341 ++SpeculatedInstructions;
3342 if (SpeculatedInstructions > 1)
3343 return false;
3344 }
3345
3346 // Check that we can insert the selects and that it's not too expensive to do
3347 // so.
3348 bool Convert =
3349 SpeculatedStore != nullptr || !SpeculatedConditionalLoadsStores.empty();
3351 Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB,
3352 SpeculatedInstructions, Cost, TTI);
3353 if (!Convert || Cost > Budget)
3354 return false;
3355
3356 // If we get here, we can hoist the instruction and if-convert.
3357 LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
3358
3359 Instruction *Sel = nullptr;
3360 Value *BrCond = BI->getCondition();
3361 // Insert a select of the value of the speculated store.
3362 if (SpeculatedStoreValue) {
3363 IRBuilder<NoFolder> Builder(BI);
3364 Value *OrigV = SpeculatedStore->getValueOperand();
3365 Value *TrueV = SpeculatedStore->getValueOperand();
3366 Value *FalseV = SpeculatedStoreValue;
3367 if (Invert)
3368 std::swap(TrueV, FalseV);
3369 Value *S = Builder.CreateSelect(
3370 BrCond, TrueV, FalseV, "spec.store.select", BI);
3371 Sel = cast<Instruction>(S);
3372 SpeculatedStore->setOperand(0, S);
3373 SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
3374 SpeculatedStore->getDebugLoc());
3375 // The value stored is still conditional, but the store itself is now
3376 // unconditionally executed, so we must be sure that any linked dbg.assign
3377 // intrinsics are tracking the new stored value (the result of the
3378 // select). If we don't, and the store were to be removed by another pass
3379 // (e.g. DSE), then we'd eventually end up emitting a location describing
3380 // the conditional value, unconditionally.
3381 //
3382 // === Before this transformation ===
3383 // pred:
3384 // store %one, %x.dest, !DIAssignID !1
3385 // dbg.assign %one, "x", ..., !1, ...
3386 // br %cond if.then
3387 //
3388 // if.then:
3389 // store %two, %x.dest, !DIAssignID !2
3390 // dbg.assign %two, "x", ..., !2, ...
3391 //
3392 // === After this transformation ===
3393 // pred:
3394 // store %one, %x.dest, !DIAssignID !1
3395 // dbg.assign %one, "x", ..., !1
3396 /// ...
3397 // %merge = select %cond, %two, %one
3398 // store %merge, %x.dest, !DIAssignID !2
3399 // dbg.assign %merge, "x", ..., !2
3400 for (DbgVariableRecord *DbgAssign :
3401 at::getDVRAssignmentMarkers(SpeculatedStore))
3402 if (llvm::is_contained(DbgAssign->location_ops(), OrigV))
3403 DbgAssign->replaceVariableLocationOp(OrigV, S);
3404 }
3405
3406 // Metadata can be dependent on the condition we are hoisting above.
3407 // Strip all UB-implying metadata on the instruction. Drop the debug loc
3408 // to avoid making it appear as if the condition is a constant, which would
3409 // be misleading while debugging.
3410 // Similarly strip attributes that maybe dependent on condition we are
3411 // hoisting above.
3412 for (auto &I : make_early_inc_range(*ThenBB)) {
3413 if (!SpeculatedStoreValue || &I != SpeculatedStore) {
3414 I.dropLocation();
3415 }
3416 I.dropUBImplyingAttrsAndMetadata();
3417
3418 // Drop ephemeral values.
3419 if (EphTracker.contains(&I)) {
3420 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
3421 I.eraseFromParent();
3422 }
3423 }
3424
3425 // Hoist the instructions.
3426 // Drop DbgVariableRecords attached to these instructions.
3427 for (auto &It : *ThenBB)
3428 for (DbgRecord &DR : make_early_inc_range(It.getDbgRecordRange()))
3429 // Drop all records except assign-kind DbgVariableRecords (dbg.assign
3430 // equivalent).
3431 if (DbgVariableRecord *DVR = dyn_cast<DbgVariableRecord>(&DR);
3432 !DVR || !DVR->isDbgAssign())
3433 It.dropOneDbgRecord(&DR);
3434 BB->splice(BI->getIterator(), ThenBB, ThenBB->begin(),
3435 std::prev(ThenBB->end()));
3436
3437 if (!SpeculatedConditionalLoadsStores.empty())
3438 hoistConditionalLoadsStores(BI, SpeculatedConditionalLoadsStores, Invert,
3439 Sel);
3440
3441 // Insert selects and rewrite the PHI operands.
3442 IRBuilder<NoFolder> Builder(BI);
3443 for (PHINode &PN : EndBB->phis()) {
3444 unsigned OrigI = PN.getBasicBlockIndex(BB);
3445 unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
3446 Value *OrigV = PN.getIncomingValue(OrigI);
3447 Value *ThenV = PN.getIncomingValue(ThenI);
3448
3449 // Skip PHIs which are trivial.
3450 if (OrigV == ThenV)
3451 continue;
3452
3453 // Create a select whose true value is the speculatively executed value and
3454 // false value is the pre-existing value. Swap them if the branch
3455 // destinations were inverted.
3456 Value *TrueV = ThenV, *FalseV = OrigV;
3457 if (Invert)
3458 std::swap(TrueV, FalseV);
3459 // Propagate fast-math flags from the phi node to the replacement select.
3460 Value *V = Builder.CreateSelectFMF(
3461 BrCond, TrueV, FalseV, PN.getFastMathFlagsOrNone(), "spec.select", BI);
3462 PN.setIncomingValue(OrigI, V);
3463 PN.setIncomingValue(ThenI, V);
3464 }
3465
3466 // Remove speculated pseudo probes.
3467 for (Instruction *I : SpeculatedPseudoProbes)
3468 I->eraseFromParent();
3469
3470 ++NumSpeculations;
3471 return true;
3472}
3473
3475
3476// Return false if number of blocks searched is too much.
3477static bool findReaching(BasicBlock *BB, BasicBlock *DefBB,
3478 BlocksSet &ReachesNonLocalUses) {
3479 if (BB == DefBB)
3480 return true;
3481 if (!ReachesNonLocalUses.insert(BB).second)
3482 return true;
3483
3484 if (ReachesNonLocalUses.size() > MaxJumpThreadingLiveBlocks)
3485 return false;
3486 for (BasicBlock *Pred : predecessors(BB))
3487 if (!findReaching(Pred, DefBB, ReachesNonLocalUses))
3488 return false;
3489 return true;
3490}
3491
3492/// Return true if we can thread a branch across this block.
3494 BlocksSet &NonLocalUseBlocks) {
3495 int Size = 0;
3496 EphemeralValueTracker EphTracker;
3497
3498 // Walk the loop in reverse so that we can identify ephemeral values properly
3499 // (values only feeding assumes).
3500 for (Instruction &I : reverse(*BB)) {
3501 // Can't fold blocks that contain noduplicate or convergent calls.
3502 if (CallInst *CI = dyn_cast<CallInst>(&I))
3503 if (CI->cannotDuplicate() || CI->isConvergent())
3504 return false;
3505
3506 // Ignore ephemeral values which are deleted during codegen.
3507 // We will delete Phis while threading, so Phis should not be accounted in
3508 // block's size.
3509 if (!EphTracker.track(&I) && !isa<PHINode>(I)) {
3510 if (Size++ > MaxSmallBlockSize)
3511 return false; // Don't clone large BB's.
3512 }
3513
3514 // Record blocks with non-local uses of values defined in the current basic
3515 // block.
3516 for (User *U : I.users()) {
3518 BasicBlock *UsedInBB = UI->getParent();
3519 if (UsedInBB == BB) {
3520 if (isa<PHINode>(UI))
3521 return false;
3522 } else
3523 NonLocalUseBlocks.insert(UsedInBB);
3524 }
3525
3526 // Looks ok, continue checking.
3527 }
3528
3529 return true;
3530}
3531
3533 BasicBlock *To) {
3534 // Don't look past the block defining the value, we might get the value from
3535 // a previous loop iteration.
3536 auto *I = dyn_cast<Instruction>(V);
3537 if (I && I->getParent() == To)
3538 return nullptr;
3539
3540 // We know the value if the From block branches on it.
3541 auto *BI = dyn_cast<CondBrInst>(From->getTerminator());
3542 if (BI && BI->getCondition() == V &&
3543 BI->getSuccessor(0) != BI->getSuccessor(1))
3544 return BI->getSuccessor(0) == To ? ConstantInt::getTrue(BI->getContext())
3546
3547 return nullptr;
3548}
3549
3551 return CB->isConvergent() && !isa<ConvergenceControlInst>(CB) &&
3553}
3554
3556 BasicBlock *StopBB) {
3557 static constexpr unsigned MaxInstructionsToScan = 512;
3558
3559 // Walk predecessors of StopBB to find blocks that can reach it. Only
3560 // convergent calls on a cycle with StopBB matter - a convergent call on a
3561 // path to function exit cannot have its dynamic instance changed by
3562 // threading.
3563 SmallPtrSet<BasicBlock *, 8> CanReachStop;
3564 SmallPtrSet<BasicBlock *, 8> BlocksWithUncontrolledConvergentCalls;
3566 for (BasicBlock *Pred : predecessors(StopBB))
3567 Worklist.push_back(Pred);
3568
3569 // Cache blocks with relevant calls while building CanReachStop. This keeps
3570 // the instruction scan bounded without a separate block limit.
3571 unsigned NumScannedInstructions = 0;
3572 while (!Worklist.empty()) {
3573 BasicBlock *BB = Worklist.pop_back_val();
3574 if (BB == StopBB)
3575 continue;
3576 if (!CanReachStop.insert(BB).second)
3577 continue;
3578
3579 for (Instruction &I : *BB) {
3580 if (++NumScannedInstructions > MaxInstructionsToScan)
3581 return true;
3582 auto *CB = dyn_cast<CallBase>(&I);
3583 if (CB && isUncontrolledConvergentCall(CB)) {
3584 BlocksWithUncontrolledConvergentCalls.insert(BB);
3585 break;
3586 }
3587 }
3588
3589 append_range(Worklist, predecessors(BB));
3590 }
3591
3592 if (!CanReachStop.contains(From))
3593 return false;
3594
3596 Worklist.push_back(From);
3597
3598 while (!Worklist.empty()) {
3599 BasicBlock *BB = Worklist.pop_back_val();
3600 if (BB == StopBB || !CanReachStop.contains(BB))
3601 continue;
3602
3603 if (!Visited.insert(BB).second)
3604 continue;
3605
3606 if (BlocksWithUncontrolledConvergentCalls.contains(BB))
3607 return true;
3608
3609 append_range(Worklist, successors(BB));
3610 }
3611
3612 return false;
3613}
3614
3615/// If we have a conditional branch on something for which we know the constant
3616/// value in predecessors (e.g. a phi node in the current block), thread edges
3617/// from the predecessor to their ultimate destination.
3620 AssumptionCache *AC, const DataLayout &DL) {
3622 BasicBlock *BB = BI->getParent();
3623 Value *Cond = BI->getCondition();
3625 if (PN && PN->getParent() == BB) {
3626 // Degenerate case of a single entry PHI.
3627 if (PN->getNumIncomingValues() == 1) {
3629 return true;
3630 }
3631
3632 for (Use &U : PN->incoming_values())
3633 if (auto *CB = dyn_cast<ConstantInt>(U))
3634 KnownValues[CB].insert(PN->getIncomingBlock(U));
3635 } else {
3636 for (BasicBlock *Pred : predecessors(BB)) {
3637 if (ConstantInt *CB = getKnownValueOnEdge(Cond, Pred, BB))
3638 KnownValues[CB].insert(Pred);
3639 }
3640 }
3641
3642 if (KnownValues.empty())
3643 return false;
3644
3645 // Now we know that this block has multiple preds and two succs.
3646 // Check that the block is small enough and record which non-local blocks use
3647 // values defined in the block.
3648
3649 BlocksSet NonLocalUseBlocks;
3650 BlocksSet ReachesNonLocalUseBlocks;
3651 if (!blockIsSimpleEnoughToThreadThrough(BB, NonLocalUseBlocks))
3652 return false;
3653
3654 // Jump-threading can only be done to destinations where no values defined
3655 // in BB are live.
3656
3657 // Quickly check if both destinations have uses. If so, jump-threading cannot
3658 // be done.
3659 if (NonLocalUseBlocks.contains(BI->getSuccessor(0)) &&
3660 NonLocalUseBlocks.contains(BI->getSuccessor(1)))
3661 return false;
3662
3663 // Search backward from NonLocalUseBlocks to find which blocks
3664 // reach non-local uses.
3665 for (BasicBlock *UseBB : NonLocalUseBlocks)
3666 // Give up if too many blocks are searched.
3667 if (!findReaching(UseBB, BB, ReachesNonLocalUseBlocks))
3668 return false;
3669
3670 for (const auto &Pair : KnownValues) {
3671 ConstantInt *CB = Pair.first;
3672 ArrayRef<BasicBlock *> PredBBs = Pair.second.getArrayRef();
3673 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
3674
3675 // Okay, we now know that all edges from PredBB should be revectored to
3676 // branch to RealDest.
3677 if (RealDest == BB)
3678 continue; // Skip self loops.
3679
3680 // Skip if the predecessor's terminator is an indirect branch.
3681 if (any_of(PredBBs, [](BasicBlock *PredBB) {
3682 return isa<IndirectBrInst>(PredBB->getTerminator());
3683 }))
3684 continue;
3685
3686 // Only revector to RealDest if no values defined in BB are live.
3687 if (ReachesNonLocalUseBlocks.contains(RealDest))
3688 continue;
3689
3690 // Threading through a branch can bypass a reconvergence point. If the
3691 // destination can execute an uncontrolled convergent operation before
3692 // returning to this block, this may change the dynamic instance of that
3693 // operation.
3694 if (TTI.hasBranchDivergence(BB->getParent()) &&
3696 continue;
3697
3698 LLVM_DEBUG({
3699 dbgs() << "Condition " << *Cond << " in " << BB->getName()
3700 << " has value " << *Pair.first << " in predecessors:\n";
3701 for (const BasicBlock *PredBB : Pair.second)
3702 dbgs() << " " << PredBB->getName() << "\n";
3703 dbgs() << "Threading to destination " << RealDest->getName() << ".\n";
3704 });
3705
3706 // Split the predecessors we are threading into a new edge block. We'll
3707 // clone the instructions into this block, and then redirect it to RealDest.
3708 BasicBlock *EdgeBB = SplitBlockPredecessors(BB, PredBBs, ".critedge", DTU);
3709 if (!EdgeBB)
3710 continue;
3711
3712 // TODO: These just exist to reduce test diff, we can drop them if we like.
3713 EdgeBB->setName(RealDest->getName() + ".critedge");
3714 EdgeBB->moveBefore(RealDest);
3715
3716 // Update PHI nodes.
3717 addPredecessorToBlock(RealDest, EdgeBB, BB);
3718
3719 // BB may have instructions that are being threaded over. Clone these
3720 // instructions into EdgeBB. We know that there will be no uses of the
3721 // cloned instructions outside of EdgeBB.
3722 BasicBlock::iterator InsertPt = EdgeBB->getFirstInsertionPt();
3723 ValueToValueMapTy TranslateMap; // Track translated values.
3724 TranslateMap[Cond] = CB;
3725
3726 // RemoveDIs: track instructions that we optimise away while folding, so
3727 // that we can copy DbgVariableRecords from them later.
3728 BasicBlock::iterator SrcDbgCursor = BB->begin();
3729 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
3730 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
3731 TranslateMap[PN] = PN->getIncomingValueForBlock(EdgeBB);
3732 continue;
3733 }
3734 // Clone the instruction.
3735 Instruction *N = BBI->clone();
3736 // Insert the new instruction into its new home.
3737 N->insertInto(EdgeBB, InsertPt);
3738
3739 if (BBI->hasName())
3740 N->setName(BBI->getName() + ".c");
3741
3742 // Update operands due to translation.
3743 // Key Instructions: Remap all the atom groups.
3744 if (const DebugLoc &DL = BBI->getDebugLoc())
3745 mapAtomInstance(DL, TranslateMap);
3746 RemapInstruction(N, TranslateMap,
3748
3749 // Check for trivial simplification.
3750 if (Value *V = simplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
3751 if (!BBI->use_empty())
3752 TranslateMap[&*BBI] = V;
3753 if (!N->mayHaveSideEffects()) {
3754 N->eraseFromParent(); // Instruction folded away, don't need actual
3755 // inst
3756 N = nullptr;
3757 }
3758 } else {
3759 if (!BBI->use_empty())
3760 TranslateMap[&*BBI] = N;
3761 }
3762 if (N) {
3763 // Copy all debug-info attached to instructions from the last we
3764 // successfully clone, up to this instruction (they might have been
3765 // folded away).
3766 for (; SrcDbgCursor != BBI; ++SrcDbgCursor)
3767 N->cloneDebugInfoFrom(&*SrcDbgCursor);
3768 SrcDbgCursor = std::next(BBI);
3769 // Clone debug-info on this instruction too.
3770 N->cloneDebugInfoFrom(&*BBI);
3771
3772 // Register the new instruction with the assumption cache if necessary.
3773 if (auto *Assume = dyn_cast<AssumeInst>(N))
3774 if (AC)
3775 AC->registerAssumption(Assume);
3776 }
3777 }
3778
3779 for (; &*SrcDbgCursor != BI; ++SrcDbgCursor)
3780 InsertPt->cloneDebugInfoFrom(&*SrcDbgCursor);
3781 InsertPt->cloneDebugInfoFrom(BI);
3782
3783 BB->removePredecessor(EdgeBB);
3784 UncondBrInst *EdgeBI = cast<UncondBrInst>(EdgeBB->getTerminator());
3785 EdgeBI->setSuccessor(0, RealDest);
3786 EdgeBI->setDebugLoc(BI->getDebugLoc());
3787
3788 if (DTU) {
3790 Updates.push_back({DominatorTree::Delete, EdgeBB, BB});
3791 Updates.push_back({DominatorTree::Insert, EdgeBB, RealDest});
3792 DTU->applyUpdates(Updates);
3793 }
3794
3795 // For simplicity, we created a separate basic block for the edge. Merge
3796 // it back into the predecessor if possible. This not only avoids
3797 // unnecessary SimplifyCFG iterations, but also makes sure that we don't
3798 // bypass the check for trivial cycles above.
3799 MergeBlockIntoPredecessor(EdgeBB, DTU);
3800
3801 // Signal repeat, simplifying any other constants.
3802 return std::nullopt;
3803 }
3804
3805 return false;
3806}
3807
3808bool SimplifyCFGOpt::foldCondBranchOnValueKnownInPredecessor(CondBrInst *BI) {
3809 // Note: If BB is a loop header then there is a risk that threading introduces
3810 // a non-canonical loop by moving a back edge. So we avoid this optimization
3811 // for loop headers if NeedCanonicalLoop is set.
3812 if (Options.NeedCanonicalLoop && is_contained(LoopHeaders, BI->getParent()))
3813 return false;
3814
3815 std::optional<bool> Result;
3816 bool EverChanged = false;
3817 do {
3818 // Note that None means "we changed things, but recurse further."
3820 Options.AC, DL);
3821 EverChanged |= Result == std::nullopt || *Result;
3822 } while (Result == std::nullopt);
3823 return EverChanged;
3824}
3825
3826/// Given a BB that starts with the specified two-entry PHI node,
3827/// see if we can eliminate it.
3830 const DataLayout &DL,
3831 bool SpeculateUnpredictables) {
3832 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
3833 // statement", which has a very simple dominance structure. Basically, we
3834 // are trying to find the condition that is being branched on, which
3835 // subsequently causes this merge to happen. We really want control
3836 // dependence information for this check, but simplifycfg can't keep it up
3837 // to date, and this catches most of the cases we care about anyway.
3838 BasicBlock *BB = PN->getParent();
3839
3840 BasicBlock *IfTrue, *IfFalse;
3841 CondBrInst *DomBI = GetIfCondition(BB, IfTrue, IfFalse);
3842 if (!DomBI)
3843 return false;
3844 Value *IfCond = DomBI->getCondition();
3845 // Don't bother if the branch will be constant folded trivially.
3846 if (isa<ConstantInt>(IfCond))
3847 return false;
3848
3849 BasicBlock *DomBlock = DomBI->getParent();
3851 llvm::copy_if(PN->blocks(), std::back_inserter(IfBlocks),
3852 [](BasicBlock *IfBlock) {
3853 return isa<UncondBrInst>(IfBlock->getTerminator());
3854 });
3855 assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) &&
3856 "Will have either one or two blocks to speculate.");
3857
3858 // If the branch is non-unpredictable, see if we either predictably jump to
3859 // the merge bb (if we have only a single 'then' block), or if we predictably
3860 // jump to one specific 'then' block (if we have two of them).
3861 // It isn't beneficial to speculatively execute the code
3862 // from the block that we know is predictably not entered.
3863 bool IsUnpredictable = DomBI->getMetadata(LLVMContext::MD_unpredictable);
3864 if (!IsUnpredictable) {
3865 uint64_t TWeight, FWeight;
3866 if (extractBranchWeights(*DomBI, TWeight, FWeight) &&
3867 (TWeight + FWeight) != 0) {
3868 BranchProbability BITrueProb =
3869 BranchProbability::getBranchProbability(TWeight, TWeight + FWeight);
3870 BranchProbability Likely = TTI.getPredictableBranchThreshold();
3871 BranchProbability BIFalseProb = BITrueProb.getCompl();
3872 if (IfBlocks.size() == 1) {
3873 BranchProbability BIBBProb =
3874 DomBI->getSuccessor(0) == BB ? BITrueProb : BIFalseProb;
3875 if (BIBBProb >= Likely)
3876 return false;
3877 } else {
3878 if (BITrueProb >= Likely || BIFalseProb >= Likely)
3879 return false;
3880 }
3881 }
3882 }
3883
3884 // Don't try to fold an unreachable block. For example, the phi node itself
3885 // can't be the candidate if-condition for a select that we want to form.
3886 if (auto *IfCondPhiInst = dyn_cast<PHINode>(IfCond))
3887 if (IfCondPhiInst->getParent() == BB)
3888 return false;
3889
3890 // Okay, we found that we can merge this two-entry phi node into a select.
3891 // Doing so would require us to fold *all* two entry phi nodes in this block.
3892 // At some point this becomes non-profitable (particularly if the target
3893 // doesn't support cmov's). Only do this transformation if there are two or
3894 // fewer PHI nodes in this block.
3895 unsigned NumPhis = 0;
3896 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
3897 if (NumPhis > 2)
3898 return false;
3899
3900 // Loop over the PHI's seeing if we can promote them all to select
3901 // instructions. While we are at it, keep track of the instructions
3902 // that need to be moved to the dominating block.
3903 SmallPtrSet<Instruction *, 4> AggressiveInsts;
3904 SmallPtrSet<Instruction *, 2> ZeroCostInstructions;
3905 InstructionCost Cost = 0;
3906 InstructionCost Budget =
3908 if (SpeculateUnpredictables && IsUnpredictable)
3909 Budget += TTI.getBranchMispredictPenalty();
3910
3911 bool Changed = false;
3912 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
3913 PHINode *PN = cast<PHINode>(II++);
3914 if (Value *V = simplifyInstruction(PN, {DL, PN})) {
3915 PN->replaceAllUsesWith(V);
3916 PN->eraseFromParent();
3917 Changed = true;
3918 continue;
3919 }
3920
3921 if (!dominatesMergePoint(PN->getIncomingValue(0), BB, DomBI,
3922 AggressiveInsts, Cost, Budget, TTI, AC,
3923 ZeroCostInstructions) ||
3924 !dominatesMergePoint(PN->getIncomingValue(1), BB, DomBI,
3925 AggressiveInsts, Cost, Budget, TTI, AC,
3926 ZeroCostInstructions))
3927 return Changed;
3928 }
3929
3930 // If we folded the first phi, PN dangles at this point. Refresh it. If
3931 // we ran out of PHIs then we simplified them all.
3932 PN = dyn_cast<PHINode>(BB->begin());
3933 if (!PN)
3934 return true;
3935
3936 // Don't fold i1 branches on PHIs which contain binary operators or
3937 // (possibly inverted) select form of or/ands if their parameters are
3938 // an equality test.
3939 auto IsBinOpOrAndEq = [](Value *V) {
3940 CmpPredicate Pred;
3941 if (match(V, m_CombineOr(
3943 m_BinOp(m_Cmp(Pred, m_Value(), m_Value()), m_Value()),
3944 m_BinOp(m_Value(), m_Cmp(Pred, m_Value(), m_Value()))),
3946 m_Cmp(Pred, m_Value(), m_Value()))))) {
3947 return CmpInst::isEquality(Pred);
3948 }
3949 return false;
3950 };
3951 if (PN->getType()->isIntegerTy(1) &&
3952 (IsBinOpOrAndEq(PN->getIncomingValue(0)) ||
3953 IsBinOpOrAndEq(PN->getIncomingValue(1)) || IsBinOpOrAndEq(IfCond)))
3954 return Changed;
3955
3956 // If all PHI nodes are promotable, check to make sure that all instructions
3957 // in the predecessor blocks can be promoted as well. If not, we won't be able
3958 // to get rid of the control flow, so it's not worth promoting to select
3959 // instructions.
3960 for (BasicBlock *IfBlock : IfBlocks)
3961 for (BasicBlock::iterator I = IfBlock->begin(); !I->isTerminator(); ++I)
3962 if (!AggressiveInsts.count(&*I) && !I->isDebugOrPseudoInst()) {
3963 // This is not an aggressive instruction that we can promote.
3964 // Because of this, we won't be able to get rid of the control flow, so
3965 // the xform is not worth it.
3966 return Changed;
3967 }
3968
3969 // If either of the blocks has it's address taken, we can't do this fold.
3970 if (any_of(IfBlocks,
3971 [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); }))
3972 return Changed;
3973
3974 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond;
3975 if (IsUnpredictable) dbgs() << " (unpredictable)";
3976 dbgs() << " T: " << IfTrue->getName()
3977 << " F: " << IfFalse->getName() << "\n");
3978
3979 // If we can still promote the PHI nodes after this gauntlet of tests,
3980 // do all of the PHI's now.
3981
3982 // Move all 'aggressive' instructions, which are defined in the
3983 // conditional parts of the if's up to the dominating block.
3984 for (BasicBlock *IfBlock : IfBlocks)
3985 hoistAllInstructionsInto(DomBlock, DomBI, IfBlock);
3986
3987 IRBuilder<NoFolder> Builder(DomBI);
3988 // Propagate fast-math-flags from phi nodes to replacement selects.
3989 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
3990 // Change the PHI node into a select instruction.
3991 Value *TrueVal = PN->getIncomingValueForBlock(IfTrue);
3992 Value *FalseVal = PN->getIncomingValueForBlock(IfFalse);
3993
3994 Value *Sel = Builder.CreateSelectFMF(IfCond, TrueVal, FalseVal,
3995 isa<FPMathOperator>(PN) ? PN : nullptr,
3996 "", DomBI);
3997 PN->replaceAllUsesWith(Sel);
3998 Sel->takeName(PN);
3999 PN->eraseFromParent();
4000 }
4001
4002 // At this point, all IfBlocks are empty, so our if statement
4003 // has been flattened. Change DomBlock to jump directly to our new block to
4004 // avoid other simplifycfg's kicking in on the diamond.
4005 Builder.CreateBr(BB);
4006
4008 if (DTU) {
4009 Updates.push_back({DominatorTree::Insert, DomBlock, BB});
4010 for (auto *Successor : successors(DomBlock))
4011 Updates.push_back({DominatorTree::Delete, DomBlock, Successor});
4012 }
4013
4014 DomBI->eraseFromParent();
4015 if (DTU)
4016 DTU->applyUpdates(Updates);
4017
4018 return true;
4019}
4020
4023 Value *RHS, const Twine &Name = "") {
4024 // Try to relax logical op to binary op.
4025 if (impliesPoison(RHS, LHS))
4026 return Builder.CreateBinOp(Opc, LHS, RHS, Name);
4027 if (Opc == Instruction::And)
4028 return Builder.CreateLogicalAnd(LHS, RHS, Name);
4029 if (Opc == Instruction::Or)
4030 return Builder.CreateLogicalOr(LHS, RHS, Name);
4031 llvm_unreachable("Invalid logical opcode");
4032}
4033
4034/// Return true if either PBI or BI has branch weight available, and store
4035/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
4036/// not have branch weight, use 1:1 as its weight.
4038 uint64_t &PredTrueWeight,
4039 uint64_t &PredFalseWeight,
4040 uint64_t &SuccTrueWeight,
4041 uint64_t &SuccFalseWeight) {
4042 bool PredHasWeights =
4043 extractBranchWeights(*PBI, PredTrueWeight, PredFalseWeight);
4044 bool SuccHasWeights =
4045 extractBranchWeights(*BI, SuccTrueWeight, SuccFalseWeight);
4046 if (PredHasWeights || SuccHasWeights) {
4047 if (!PredHasWeights)
4048 PredTrueWeight = PredFalseWeight = 1;
4049 if (!SuccHasWeights)
4050 SuccTrueWeight = SuccFalseWeight = 1;
4051 return true;
4052 } else {
4053 return false;
4054 }
4055}
4056
4057/// Determine if the two branches share a common destination and deduce a glue
4058/// that joins the branches' conditions to arrive at the common destination if
4059/// that would be profitable.
4060static std::optional<std::tuple<BasicBlock *, Instruction::BinaryOps, bool>>
4062 const TargetTransformInfo *TTI) {
4063 assert(BI && PBI && "Both blocks must end with a conditional branches.");
4065 "PredBB must be a predecessor of BB.");
4066
4067 // We have the potential to fold the conditions together, but if the
4068 // predecessor branch is predictable, we may not want to merge them.
4069 uint64_t PTWeight, PFWeight;
4070 BranchProbability PBITrueProb, Likely;
4071 if (TTI && !PBI->getMetadata(LLVMContext::MD_unpredictable) &&
4072 extractBranchWeights(*PBI, PTWeight, PFWeight) &&
4073 (PTWeight + PFWeight) != 0) {
4074 PBITrueProb =
4075 BranchProbability::getBranchProbability(PTWeight, PTWeight + PFWeight);
4076 Likely = TTI->getPredictableBranchThreshold();
4077 }
4078
4079 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4080 // Speculate the 2nd condition unless the 1st is probably true.
4081 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
4082 return {{BI->getSuccessor(0), Instruction::Or, false}};
4083 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4084 // Speculate the 2nd condition unless the 1st is probably false.
4085 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
4086 return {{BI->getSuccessor(1), Instruction::And, false}};
4087 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4088 // Speculate the 2nd condition unless the 1st is probably true.
4089 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
4090 return {{BI->getSuccessor(1), Instruction::And, true}};
4091 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4092 // Speculate the 2nd condition unless the 1st is probably false.
4093 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
4094 return {{BI->getSuccessor(0), Instruction::Or, true}};
4095 }
4096 return std::nullopt;
4097}
4098
4100 DomTreeUpdater *DTU,
4101 MemorySSAUpdater *MSSAU,
4102 const TargetTransformInfo *TTI) {
4103 BasicBlock *BB = BI->getParent();
4104 BasicBlock *PredBlock = PBI->getParent();
4105
4106 // Determine if the two branches share a common destination.
4107 BasicBlock *CommonSucc;
4109 bool InvertPredCond;
4110 std::tie(CommonSucc, Opc, InvertPredCond) =
4112
4113 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
4114
4116 BB->getContext(), ConstantFolder{},
4118 // The builder is used to create instructions to eliminate the branch in
4119 // BB. If BB's terminator has !annotation metadata, add it to the new
4120 // instructions.
4121 I->copyMetadata(*BB->getTerminator(), LLVMContext::MD_annotation);
4122 }));
4123 Builder.SetInsertPoint(PBI);
4124
4125 // If we need to invert the condition in the pred block to match, do so now.
4126 if (InvertPredCond) {
4127 InvertBranch(PBI, Builder);
4128 }
4129
4130 BasicBlock *UniqueSucc =
4131 PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1);
4132
4133 // Before cloning instructions, notify the successor basic block that it
4134 // is about to have a new predecessor. This will update PHI nodes,
4135 // which will allow us to update live-out uses of bonus instructions.
4136 addPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU);
4137
4138 // Try to update branch weights.
4139 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4140 SmallVector<uint64_t, 2> MDWeights;
4141 if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4142 SuccTrueWeight, SuccFalseWeight)) {
4143
4144 if (PBI->getSuccessor(0) == BB) {
4145 // PBI: br i1 %x, BB, FalseDest
4146 // BI: br i1 %y, UniqueSucc, FalseDest
4147 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
4148 MDWeights.push_back(PredTrueWeight * SuccTrueWeight);
4149 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
4150 // TrueWeight for PBI * FalseWeight for BI.
4151 // We assume that total weights of a CondBrInst can fit into 32 bits.
4152 // Therefore, we will not have overflow using 64-bit arithmetic.
4153 MDWeights.push_back(PredFalseWeight * (SuccFalseWeight + SuccTrueWeight) +
4154 PredTrueWeight * SuccFalseWeight);
4155 } else {
4156 // PBI: br i1 %x, TrueDest, BB
4157 // BI: br i1 %y, TrueDest, UniqueSucc
4158 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
4159 // FalseWeight for PBI * TrueWeight for BI.
4160 MDWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) +
4161 PredFalseWeight * SuccTrueWeight);
4162 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
4163 MDWeights.push_back(PredFalseWeight * SuccFalseWeight);
4164 }
4165
4166 setFittedBranchWeights(*PBI, MDWeights, /*IsExpected=*/false,
4167 /*ElideAllZero=*/true);
4168
4169 // TODO: If BB is reachable from all paths through PredBlock, then we
4170 // could replace PBI's branch probabilities with BI's.
4171 } else
4172 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
4173
4174 // Now, update the CFG.
4175 PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc);
4176
4177 if (DTU)
4178 DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc},
4179 {DominatorTree::Delete, PredBlock, BB}});
4180
4181 // If BI was a loop latch, it may have had associated loop metadata.
4182 // We need to copy it to the new latch, that is, PBI.
4183 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
4184 PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
4185
4186 ValueToValueMapTy VMap; // maps original values to cloned values
4188
4189 Module *M = BB->getModule();
4190
4191 PredBlock->getTerminator()->cloneDebugInfoFrom(BB->getTerminator());
4192 for (DbgVariableRecord &DVR :
4194 RemapDbgRecord(M, &DVR, VMap,
4196 }
4197
4198 // Now that the Cond was cloned into the predecessor basic block,
4199 // or/and the two conditions together.
4200 Value *BICond = VMap[BI->getCondition()];
4201 PBI->setCondition(
4202 createLogicalOp(Builder, Opc, PBI->getCondition(), BICond, "or.cond"));
4204 if (auto *SI = dyn_cast<SelectInst>(PBI->getCondition()))
4205 if (!MDWeights.empty()) {
4206 assert(isSelectInRoleOfConjunctionOrDisjunction(SI));
4207 setFittedBranchWeights(*SI, {MDWeights[0], MDWeights[1]},
4208 /*IsExpected=*/false, /*ElideAllZero=*/true);
4209 }
4210
4211 ++NumFoldBranchToCommonDest;
4212 return true;
4213}
4214
4215/// Return if an instruction's type or any of its operands' types are a vector
4216/// type.
4217static bool isVectorOp(Instruction &I) {
4218 return I.getType()->isVectorTy() || any_of(I.operands(), [](Use &U) {
4219 return U->getType()->isVectorTy();
4220 });
4221}
4222
4223/// If this basic block is simple enough, and if a predecessor branches to us
4224/// and one of our successors, fold the block into the predecessor and use
4225/// logical operations to pick the right destination.
4227 MemorySSAUpdater *MSSAU,
4228 const TargetTransformInfo *TTI,
4229 AssumptionCache *AC,
4230 unsigned BonusInstThreshold) {
4231 BasicBlock *BB = BI->getParent();
4235
4237
4239 Cond->getParent() != BB || !Cond->hasOneUse())
4240 return false;
4241
4242 // Finally, don't infinitely unroll conditional loops.
4243 if (is_contained(successors(BB), BB))
4244 return false;
4245
4246 // With which predecessors will we want to deal with?
4248 for (BasicBlock *PredBlock : predecessors(BB)) {
4249 CondBrInst *PBI = dyn_cast<CondBrInst>(PredBlock->getTerminator());
4250
4251 // Check that we have two conditional branches. If there is a PHI node in
4252 // the common successor, verify that the same value flows in from both
4253 // blocks.
4254 if (!PBI || !safeToMergeTerminators(BI, PBI))
4255 continue;
4256
4257 // Determine if the two branches share a common destination.
4258 BasicBlock *CommonSucc;
4260 bool InvertPredCond;
4261 if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI))
4262 std::tie(CommonSucc, Opc, InvertPredCond) = *Recipe;
4263 else
4264 continue;
4265
4266 // Check the cost of inserting the necessary logic before performing the
4267 // transformation.
4268 if (TTI) {
4269 Type *Ty = BI->getCondition()->getType();
4270 InstructionCost Cost = TTI->getArithmeticInstrCost(Opc, Ty, CostKind);
4271 if (InvertPredCond && (!PBI->getCondition()->hasOneUse() ||
4272 !isa<CmpInst>(PBI->getCondition())))
4273 Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind);
4274
4276 continue;
4277 }
4278
4279 // Ok, we do want to deal with this predecessor. Record it.
4280 Preds.emplace_back(PredBlock);
4281 }
4282
4283 // If there aren't any predecessors into which we can fold,
4284 // don't bother checking the cost.
4285 if (Preds.empty())
4286 return false;
4287
4288 // Only allow this transformation if computing the condition doesn't involve
4289 // too many instructions and these involved instructions can be executed
4290 // unconditionally. We denote all involved instructions except the condition
4291 // as "bonus instructions", and only allow this transformation when the
4292 // number of the bonus instructions we'll need to create when cloning into
4293 // each predecessor does not exceed a certain threshold.
4294 unsigned NumBonusInsts = 0;
4295 bool SawVectorOp = false;
4296 const unsigned PredCount = Preds.size();
4297 // Speculated instructions will be inserted before the terminator of the
4298 // predecessor. Only handle the simple case of one predecessor.
4299 const Instruction *CxtI =
4300 PredCount == 1 ? Preds[0]->getTerminator() : nullptr;
4301 for (Instruction &I : *BB) {
4302 // Don't check the branch condition comparison itself.
4303 if (&I == Cond)
4304 continue;
4305 // Ignore the terminator.
4307 continue;
4308 // Pseudo probes aren't speculatable but can be dropped on fold.
4310 continue;
4311 // I must be safe to execute unconditionally.
4312 if (!isSafeToSpeculativelyExecute(&I, CxtI, AC))
4313 return false;
4314 SawVectorOp |= isVectorOp(I);
4315
4316 // Account for the cost of duplicating this instruction into each
4317 // predecessor. Ignore free instructions.
4318 if (!TTI || TTI->getInstructionCost(&I, CostKind) !=
4320 NumBonusInsts += PredCount;
4321
4322 // Early exits once we reach the limit.
4323 if (NumBonusInsts >
4324 BonusInstThreshold * BranchFoldToCommonDestVectorMultiplier)
4325 return false;
4326 }
4327
4328 auto IsBCSSAUse = [BB, &I](Use &U) {
4329 auto *UI = cast<Instruction>(U.getUser());
4330 if (auto *PN = dyn_cast<PHINode>(UI))
4331 return PN->getIncomingBlock(U) == BB;
4332 return UI->getParent() == BB && I.comesBefore(UI);
4333 };
4334
4335 // Does this instruction require rewriting of uses?
4336 if (!all_of(I.uses(), IsBCSSAUse))
4337 return false;
4338 }
4339 if (NumBonusInsts >
4340 BonusInstThreshold *
4341 (SawVectorOp ? BranchFoldToCommonDestVectorMultiplier : 1))
4342 return false;
4343
4344 // Ok, we have the budget. Perform the transformation.
4345 for (BasicBlock *PredBlock : Preds) {
4346 auto *PBI = cast<CondBrInst>(PredBlock->getTerminator());
4347 return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI);
4348 }
4349 return false;
4350}
4351
4352// If there is only one store in BB1 and BB2, return it, otherwise return
4353// nullptr.
4355 StoreInst *S = nullptr;
4356 for (auto *BB : {BB1, BB2}) {
4357 if (!BB)
4358 continue;
4359 for (auto &I : *BB)
4360 if (auto *SI = dyn_cast<StoreInst>(&I)) {
4361 if (S)
4362 // Multiple stores seen.
4363 return nullptr;
4364 else
4365 S = SI;
4366 }
4367 }
4368 return S;
4369}
4370
4372 Value *AlternativeV = nullptr) {
4373 // PHI is going to be a PHI node that allows the value V that is defined in
4374 // BB to be referenced in BB's only successor.
4375 //
4376 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
4377 // doesn't matter to us what the other operand is (it'll never get used). We
4378 // could just create a new PHI with an undef incoming value, but that could
4379 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
4380 // other PHI. So here we directly look for some PHI in BB's successor with V
4381 // as an incoming operand. If we find one, we use it, else we create a new
4382 // one.
4383 //
4384 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
4385 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
4386 // where OtherBB is the single other predecessor of BB's only successor.
4387 PHINode *PHI = nullptr;
4388 BasicBlock *Succ = BB->getSingleSuccessor();
4389
4390 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
4391 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
4392 PHI = cast<PHINode>(I);
4393 if (!AlternativeV)
4394 break;
4395
4396 assert(Succ->hasNPredecessors(2));
4397 auto PredI = pred_begin(Succ);
4398 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
4399 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
4400 break;
4401 PHI = nullptr;
4402 }
4403 if (PHI)
4404 return PHI;
4405
4406 // If V is not an instruction defined in BB, just return it.
4407 if (!AlternativeV &&
4408 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
4409 return V;
4410
4411 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge");
4412 PHI->insertBefore(Succ->begin());
4413 PHI->addIncoming(V, BB);
4414 for (BasicBlock *PredBB : predecessors(Succ))
4415 if (PredBB != BB)
4416 PHI->addIncoming(
4417 AlternativeV ? AlternativeV : PoisonValue::get(V->getType()), PredBB);
4418 return PHI;
4419}
4420
4422 BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB,
4423 BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond,
4424 DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) {
4425 // For every pointer, there must be exactly two stores, one coming from
4426 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
4427 // store (to any address) in PTB,PFB or QTB,QFB.
4428 // FIXME: We could relax this restriction with a bit more work and performance
4429 // testing.
4430 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
4431 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
4432 if (!PStore || !QStore)
4433 return false;
4434
4435 // Now check the stores are compatible.
4436 if (!QStore->isUnordered() || !PStore->isUnordered() ||
4437 PStore->getOrdering() != QStore->getOrdering() ||
4438 PStore->getSyncScopeID() != QStore->getSyncScopeID() ||
4439 PStore->getValueOperand()->getType() !=
4440 QStore->getValueOperand()->getType())
4441 return false;
4442
4443 // Check that sinking the store won't cause program behavior changes. Sinking
4444 // the store out of the Q blocks won't change any behavior as we're sinking
4445 // from a block to its unconditional successor. But we're moving a store from
4446 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
4447 // So we need to check that there are no aliasing loads or stores in
4448 // QBI, QTB and QFB. We also need to check there are no conflicting memory
4449 // operations between PStore and the end of its parent block.
4450 //
4451 // The ideal way to do this is to query AliasAnalysis, but we don't
4452 // preserve AA currently so that is dangerous. Be super safe and just
4453 // check there are no other memory operations at all.
4454 for (auto &I : *QFB->getSinglePredecessor())
4455 if (I.mayReadOrWriteMemory())
4456 return false;
4457 for (auto &I : *QFB)
4458 if (&I != QStore && I.mayReadOrWriteMemory())
4459 return false;
4460 if (QTB)
4461 for (auto &I : *QTB)
4462 if (&I != QStore && I.mayReadOrWriteMemory())
4463 return false;
4464 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
4465 I != E; ++I)
4466 if (&*I != PStore && I->mayReadOrWriteMemory())
4467 return false;
4468
4469 // If we're not in aggressive mode, we only optimize if we have some
4470 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
4471 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
4472 if (!BB)
4473 return true;
4474 // Heuristic: if the block can be if-converted/phi-folded and the
4475 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
4476 // thread this store.
4477 InstructionCost Cost = 0;
4478 InstructionCost Budget =
4480 for (auto &I : *BB) {
4481 // Consider terminator instruction to be free.
4482 if (I.isTerminator())
4483 continue;
4484 // If this is one the stores that we want to speculate out of this BB,
4485 // then don't count it's cost, consider it to be free.
4486 if (auto *S = dyn_cast<StoreInst>(&I))
4487 if (llvm::find(FreeStores, S))
4488 continue;
4489 // Else, we have a white-list of instructions that we are ak speculating.
4491 return false; // Not in white-list - not worthwhile folding.
4492 // And finally, if this is a non-free instruction that we are okay
4493 // speculating, ensure that we consider the speculation budget.
4494 Cost +=
4495 TTI.getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
4496 if (Cost > Budget)
4497 return false; // Eagerly refuse to fold as soon as we're out of budget.
4498 }
4499 assert(Cost <= Budget &&
4500 "When we run out of budget we will eagerly return from within the "
4501 "per-instruction loop.");
4502 return true;
4503 };
4504
4505 const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
4507 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
4508 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
4509 return false;
4510
4511 // If PostBB has more than two predecessors, we need to split it so we can
4512 // sink the store.
4513 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
4514 // We know that QFB's only successor is PostBB. And QFB has a single
4515 // predecessor. If QTB exists, then its only successor is also PostBB.
4516 // If QTB does not exist, then QFB's only predecessor has a conditional
4517 // branch to QFB and PostBB.
4518 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
4519 BasicBlock *NewBB =
4520 SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU);
4521 if (!NewBB)
4522 return false;
4523 PostBB = NewBB;
4524 }
4525
4526 // OK, we're going to sink the stores to PostBB. The store has to be
4527 // conditional though, so first create the predicate.
4528 CondBrInst *PBranch =
4530 CondBrInst *QBranch =
4532 Value *PCond = PBranch->getCondition();
4533 Value *QCond = QBranch->getCondition();
4534
4536 PStore->getParent());
4538 QStore->getParent(), PPHI);
4539
4540 BasicBlock::iterator PostBBFirst = PostBB->getFirstInsertionPt();
4541 IRBuilder<> QB(PostBB, PostBBFirst);
4542 QB.SetCurrentDebugLocation(PostBBFirst->getStableDebugLoc());
4543
4544 InvertPCond ^= (PStore->getParent() != PTB);
4545 InvertQCond ^= (QStore->getParent() != QTB);
4546 Value *PPred = InvertPCond ? QB.CreateNot(PCond) : PCond;
4547 Value *QPred = InvertQCond ? QB.CreateNot(QCond) : QCond;
4548
4549 Value *CombinedPred = QB.CreateOr(PPred, QPred);
4550
4551 BasicBlock::iterator InsertPt = QB.GetInsertPoint();
4552 auto *T = SplitBlockAndInsertIfThen(CombinedPred, InsertPt,
4553 /*Unreachable=*/false,
4554 /*BranchWeights=*/nullptr, DTU);
4555 if (hasBranchWeightMD(*PBranch) && hasBranchWeightMD(*QBranch) &&
4557 SmallVector<uint32_t, 2> PWeights, QWeights;
4558 extractBranchWeights(*PBranch, PWeights);
4559 extractBranchWeights(*QBranch, QWeights);
4560 if (InvertPCond)
4561 std::swap(PWeights[0], PWeights[1]);
4562 if (InvertQCond)
4563 std::swap(QWeights[0], QWeights[1]);
4564 auto CombinedWeights = getDisjunctionWeights(PWeights, QWeights);
4566 {CombinedWeights[0], CombinedWeights[1]},
4567 /*IsExpected=*/false, /*ElideAllZero=*/true);
4568 }
4569
4570 QB.SetInsertPoint(T);
4571 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
4572 combineMetadataForCSE(QStore, PStore, true);
4573 SI->copyMetadata(*QStore);
4574 // Update any dbg.assign intrinsics to track the merged value (QPHI) instead
4575 // of the original constant values, likely making these identical.
4576 for (auto *DbgAssign : at::getDVRAssignmentMarkers(SI)) {
4577 if (llvm::is_contained(DbgAssign->location_ops(),
4578 PStore->getValueOperand()))
4579 DbgAssign->replaceVariableLocationOp(PStore->getValueOperand(), QPHI);
4580 if (llvm::is_contained(DbgAssign->location_ops(),
4581 QStore->getValueOperand()))
4582 DbgAssign->replaceVariableLocationOp(QStore->getValueOperand(), QPHI);
4583 }
4584
4585 // Choose the minimum alignment. If we could prove both stores execute, we
4586 // could use biggest one. In this case, though, we only know that one of the
4587 // stores executes. And we don't know it's safe to take the alignment from a
4588 // store that doesn't execute.
4589 SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign()));
4590
4591 if (QStore->isAtomic())
4592 SI->setAtomic(QStore->getOrdering(), QStore->getSyncScopeID());
4593
4594 QStore->eraseFromParent();
4595 PStore->eraseFromParent();
4596
4597 return true;
4598}
4599
4601 DomTreeUpdater *DTU, const DataLayout &DL,
4602 const TargetTransformInfo &TTI) {
4603 // The intention here is to find diamonds or triangles (see below) where each
4604 // conditional block contains a store to the same address. Both of these
4605 // stores are conditional, so they can't be unconditionally sunk. But it may
4606 // be profitable to speculatively sink the stores into one merged store at the
4607 // end, and predicate the merged store on the union of the two conditions of
4608 // PBI and QBI.
4609 //
4610 // This can reduce the number of stores executed if both of the conditions are
4611 // true, and can allow the blocks to become small enough to be if-converted.
4612 // This optimization will also chain, so that ladders of test-and-set
4613 // sequences can be if-converted away.
4614 //
4615 // We only deal with simple diamonds or triangles:
4616 //
4617 // PBI or PBI or a combination of the two
4618 // / \ | \
4619 // PTB PFB | PFB
4620 // \ / | /
4621 // QBI QBI
4622 // / \ | \
4623 // QTB QFB | QFB
4624 // \ / | /
4625 // PostBB PostBB
4626 //
4627 // We model triangles as a type of diamond with a nullptr "true" block.
4628 // Triangles are canonicalized so that the fallthrough edge is represented by
4629 // a true condition, as in the diagram above.
4630 BasicBlock *PTB = PBI->getSuccessor(0);
4631 BasicBlock *PFB = PBI->getSuccessor(1);
4632 BasicBlock *QTB = QBI->getSuccessor(0);
4633 BasicBlock *QFB = QBI->getSuccessor(1);
4634 BasicBlock *PostBB = QFB->getSingleSuccessor();
4635
4636 // Make sure we have a good guess for PostBB. If QTB's only successor is
4637 // QFB, then QFB is a better PostBB.
4638 if (QTB->getSingleSuccessor() == QFB)
4639 PostBB = QFB;
4640
4641 // If we couldn't find a good PostBB, stop.
4642 if (!PostBB)
4643 return false;
4644
4645 bool InvertPCond = false, InvertQCond = false;
4646 // Canonicalize fallthroughs to the true branches.
4647 if (PFB == QBI->getParent()) {
4648 std::swap(PFB, PTB);
4649 InvertPCond = true;
4650 }
4651 if (QFB == PostBB) {
4652 std::swap(QFB, QTB);
4653 InvertQCond = true;
4654 }
4655
4656 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
4657 // and QFB may not. Model fallthroughs as a nullptr block.
4658 if (PTB == QBI->getParent())
4659 PTB = nullptr;
4660 if (QTB == PostBB)
4661 QTB = nullptr;
4662
4663 // Legality bailouts. We must have at least the non-fallthrough blocks and
4664 // the post-dominating block, and the non-fallthroughs must only have one
4665 // predecessor.
4666 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
4667 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
4668 };
4669 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
4670 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
4671 return false;
4672 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
4673 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
4674 return false;
4675 if (!QBI->getParent()->hasNUses(2))
4676 return false;
4677
4678 // OK, this is a sequence of two diamonds or triangles.
4679 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
4680 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
4681 for (auto *BB : {PTB, PFB}) {
4682 if (!BB)
4683 continue;
4684 for (auto &I : *BB)
4686 PStoreAddresses.insert(SI->getPointerOperand());
4687 }
4688 for (auto *BB : {QTB, QFB}) {
4689 if (!BB)
4690 continue;
4691 for (auto &I : *BB)
4693 QStoreAddresses.insert(SI->getPointerOperand());
4694 }
4695
4696 set_intersect(PStoreAddresses, QStoreAddresses);
4697 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
4698 // clear what it contains.
4699 auto &CommonAddresses = PStoreAddresses;
4700
4701 bool Changed = false;
4702 for (auto *Address : CommonAddresses)
4703 Changed |=
4704 mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address,
4705 InvertPCond, InvertQCond, DTU, DL, TTI);
4706 return Changed;
4707}
4708
4709/// If the previous block ended with a widenable branch, determine if reusing
4710/// the target block is profitable and legal. This will have the effect of
4711/// "widening" PBI, but doesn't require us to reason about hosting safety.
4713 DomTreeUpdater *DTU) {
4714 // TODO: This can be generalized in two important ways:
4715 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
4716 // values from the PBI edge.
4717 // 2) We can sink side effecting instructions into BI's fallthrough
4718 // successor provided they doesn't contribute to computation of
4719 // BI's condition.
4720 BasicBlock *IfTrueBB = PBI->getSuccessor(0);
4721 BasicBlock *IfFalseBB = PBI->getSuccessor(1);
4722 if (!isWidenableBranch(PBI) || IfTrueBB != BI->getParent() ||
4723 !BI->getParent()->getSinglePredecessor())
4724 return false;
4725 if (!IfFalseBB->phis().empty())
4726 return false; // TODO
4727 // This helps avoid infinite loop with SimplifyCondBranchToCondBranch which
4728 // may undo the transform done here.
4729 // TODO: There might be a more fine-grained solution to this.
4730 if (!llvm::succ_empty(IfFalseBB))
4731 return false;
4732 // Use lambda to lazily compute expensive condition after cheap ones.
4733 auto NoSideEffects = [](BasicBlock &BB) {
4734 return llvm::none_of(BB, [](const Instruction &I) {
4735 return I.mayWriteToMemory() || I.mayHaveSideEffects();
4736 });
4737 };
4738 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
4739 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
4740 NoSideEffects(*BI->getParent())) {
4741 auto *OldSuccessor = BI->getSuccessor(1);
4742 OldSuccessor->removePredecessor(BI->getParent());
4743 BI->setSuccessor(1, IfFalseBB);
4744 if (DTU)
4745 DTU->applyUpdates(
4746 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4747 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4748 return true;
4749 }
4750 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
4751 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
4752 NoSideEffects(*BI->getParent())) {
4753 auto *OldSuccessor = BI->getSuccessor(0);
4754 OldSuccessor->removePredecessor(BI->getParent());
4755 BI->setSuccessor(0, IfFalseBB);
4756 if (DTU)
4757 DTU->applyUpdates(
4758 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4759 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4760 return true;
4761 }
4762 return false;
4763}
4764
4765/// If we have a conditional branch as a predecessor of another block,
4766/// this function tries to simplify it. We know
4767/// that PBI and BI are both conditional branches, and BI is in one of the
4768/// successor blocks of PBI - PBI branches to BI.
4770 DomTreeUpdater *DTU,
4771 const DataLayout &DL,
4772 const TargetTransformInfo &TTI) {
4773 BasicBlock *BB = BI->getParent();
4774
4775 // If this block ends with a branch instruction, and if there is a
4776 // predecessor that ends on a branch of the same condition, make
4777 // this conditional branch redundant.
4778 if (PBI->getCondition() == BI->getCondition() &&
4779 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
4780 // Okay, the outcome of this conditional branch is statically
4781 // knowable. If this block had a single pred, handle specially, otherwise
4782 // foldCondBranchOnValueKnownInPredecessor() will handle it.
4783 if (BB->getSinglePredecessor()) {
4784 // Turn this into a branch on constant.
4785 bool CondIsTrue = PBI->getSuccessor(0) == BB;
4786 BI->setCondition(
4787 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
4788 return true; // Nuke the branch on constant.
4789 }
4790 }
4791
4792 // If the previous block ended with a widenable branch, determine if reusing
4793 // the target block is profitable and legal. This will have the effect of
4794 // "widening" PBI, but doesn't require us to reason about hosting safety.
4795 if (tryWidenCondBranchToCondBranch(PBI, BI, DTU))
4796 return true;
4797
4798 // If both branches are conditional and both contain stores to the same
4799 // address, remove the stores from the conditionals and create a conditional
4800 // merged store at the end.
4801 if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI))
4802 return true;
4803
4804 // If this is a conditional branch in an empty block, and if any
4805 // predecessors are a conditional branch to one of our destinations,
4806 // fold the conditions into logical ops and one cond br.
4807
4808 // Ignore dbg intrinsics.
4809 if (&*BB->begin() != BI)
4810 return false;
4811
4812 int PBIOp, BIOp;
4813 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4814 PBIOp = 0;
4815 BIOp = 0;
4816 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4817 PBIOp = 0;
4818 BIOp = 1;
4819 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4820 PBIOp = 1;
4821 BIOp = 0;
4822 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4823 PBIOp = 1;
4824 BIOp = 1;
4825 } else {
4826 return false;
4827 }
4828
4829 // Check to make sure that the other destination of this branch
4830 // isn't BB itself. If so, this is an infinite loop that will
4831 // keep getting unwound.
4832 if (PBI->getSuccessor(PBIOp) == BB)
4833 return false;
4834
4835 // If predecessor's branch probability to BB is too low don't merge branches.
4836 SmallVector<uint32_t, 2> PredWeights;
4837 if (!PBI->getMetadata(LLVMContext::MD_unpredictable) &&
4838 extractBranchWeights(*PBI, PredWeights) &&
4839 (static_cast<uint64_t>(PredWeights[0]) + PredWeights[1]) != 0) {
4840
4842 PredWeights[PBIOp],
4843 static_cast<uint64_t>(PredWeights[0]) + PredWeights[1]);
4844
4845 BranchProbability Likely = TTI.getPredictableBranchThreshold();
4846 if (CommonDestProb >= Likely)
4847 return false;
4848 }
4849
4850 // Do not perform this transformation if it would require
4851 // insertion of a large number of select instructions. For targets
4852 // without predication/cmovs, this is a big pessimization.
4853
4854 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
4855 BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1);
4856 unsigned NumPhis = 0;
4857 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
4858 ++II, ++NumPhis) {
4859 if (NumPhis > 2) // Disable this xform.
4860 return false;
4861 }
4862
4863 // Finally, if everything is ok, fold the branches to logical ops.
4864 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
4865
4866 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
4867 << "AND: " << *BI->getParent());
4868
4870
4871 // If OtherDest *is* BB, then BB is a basic block with a single conditional
4872 // branch in it, where one edge (OtherDest) goes back to itself but the other
4873 // exits. We don't *know* that the program avoids the infinite loop
4874 // (even though that seems likely). If we do this xform naively, we'll end up
4875 // recursively unpeeling the loop. Since we know that (after the xform is
4876 // done) that the block *is* infinite if reached, we just make it an obviously
4877 // infinite loop with no cond branch.
4878 if (OtherDest == BB) {
4879 // Insert it at the end of the function, because it's either code,
4880 // or it won't matter if it's hot. :)
4881 BasicBlock *InfLoopBlock =
4882 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
4883 UncondBrInst::Create(InfLoopBlock, InfLoopBlock);
4884 if (DTU)
4885 Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
4886 OtherDest = InfLoopBlock;
4887 }
4888
4889 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4890
4891 // BI may have other predecessors. Because of this, we leave
4892 // it alone, but modify PBI.
4893
4894 // Make sure we get to CommonDest on True&True directions.
4895 Value *PBICond = PBI->getCondition();
4896 IRBuilder<NoFolder> Builder(PBI);
4897 if (PBIOp)
4898 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
4899
4900 Value *BICond = BI->getCondition();
4901 if (BIOp)
4902 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
4903
4904 // Merge the conditions.
4905 Value *Cond =
4906 createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge");
4907
4908 // Modify PBI to branch on the new condition to the new dests.
4909 PBI->setCondition(Cond);
4910 PBI->setSuccessor(0, CommonDest);
4911 PBI->setSuccessor(1, OtherDest);
4912
4913 if (DTU) {
4914 Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest});
4915 Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest});
4916
4917 DTU->applyUpdates(Updates);
4918 }
4919
4920 // Update branch weight for PBI.
4921 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4922 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
4923 bool HasWeights =
4924 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4925 SuccTrueWeight, SuccFalseWeight);
4926 if (HasWeights) {
4927 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4928 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4929 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4930 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4931 // The weight to CommonDest should be PredCommon * SuccTotal +
4932 // PredOther * SuccCommon.
4933 // The weight to OtherDest should be PredOther * SuccOther.
4934 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
4935 PredOther * SuccCommon,
4936 PredOther * SuccOther};
4937
4938 setFittedBranchWeights(*PBI, NewWeights, /*IsExpected=*/false,
4939 /*ElideAllZero=*/true);
4940 // Cond may be a select instruction with the first operand set to "true", or
4941 // the second to "false" (see how createLogicalOp works for `and` and `or`)
4943 if (auto *SI = dyn_cast<SelectInst>(Cond)) {
4944 assert(isSelectInRoleOfConjunctionOrDisjunction(SI));
4945 // The select is predicated on PBICond
4946 assert(SI->getCondition() == PBICond);
4947 // The corresponding probabilities are what was referred to above as
4948 // PredCommon and PredOther.
4949 setFittedBranchWeights(*SI, {PredCommon, PredOther},
4950 /*IsExpected=*/false, /*ElideAllZero=*/true);
4951 }
4952 }
4953
4954 // OtherDest may have phi nodes. If so, add an entry from PBI's
4955 // block that are identical to the entries for BI's block.
4956 addPredecessorToBlock(OtherDest, PBI->getParent(), BB);
4957
4958 // We know that the CommonDest already had an edge from PBI to
4959 // it. If it has PHIs though, the PHIs may have different
4960 // entries for BB and PBI's BB. If so, insert a select to make
4961 // them agree.
4962 for (PHINode &PN : CommonDest->phis()) {
4963 Value *BIV = PN.getIncomingValueForBlock(BB);
4964 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
4965 Value *PBIV = PN.getIncomingValue(PBBIdx);
4966 if (BIV != PBIV) {
4967 // Insert a select in PBI to pick the right value.
4969 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
4970 PN.setIncomingValue(PBBIdx, NV);
4971 // The select has the same condition as PBI, in the same BB. The
4972 // probabilities don't change.
4973 if (HasWeights) {
4974 uint64_t TrueWeight = PBIOp ? PredFalseWeight : PredTrueWeight;
4975 uint64_t FalseWeight = PBIOp ? PredTrueWeight : PredFalseWeight;
4976 setFittedBranchWeights(*NV, {TrueWeight, FalseWeight},
4977 /*IsExpected=*/false, /*ElideAllZero=*/true);
4978 }
4979 }
4980 }
4981
4982 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
4983 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4984
4985 // This basic block is probably dead. We know it has at least
4986 // one fewer predecessor.
4987 return true;
4988}
4989
4990// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
4991// true or to FalseBB if Cond is false.
4992// Takes care of updating the successors and removing the old terminator.
4993// Also makes sure not to introduce new successors by assuming that edges to
4994// non-successor TrueBBs and FalseBBs aren't reachable.
4995bool SimplifyCFGOpt::simplifyTerminatorOnSelect(Instruction *OldTerm,
4996 Value *Cond, BasicBlock *TrueBB,
4997 BasicBlock *FalseBB,
4998 uint32_t TrueWeight,
4999 uint32_t FalseWeight) {
5000 auto *BB = OldTerm->getParent();
5001 // Remove any superfluous successor edges from the CFG.
5002 // First, figure out which successors to preserve.
5003 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
5004 // successor.
5005 BasicBlock *KeepEdge1 = TrueBB;
5006 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
5007
5008 SmallSetVector<BasicBlock *, 2> RemovedSuccessors;
5009
5010 // Then remove the rest.
5011 for (BasicBlock *Succ : successors(OldTerm)) {
5012 // Make sure only to keep exactly one copy of each edge.
5013 if (Succ == KeepEdge1)
5014 KeepEdge1 = nullptr;
5015 else if (Succ == KeepEdge2)
5016 KeepEdge2 = nullptr;
5017 else {
5018 Succ->removePredecessor(BB,
5019 /*KeepOneInputPHIs=*/true);
5020
5021 if (Succ != TrueBB && Succ != FalseBB)
5022 RemovedSuccessors.insert(Succ);
5023 }
5024 }
5025
5026 IRBuilder<> Builder(OldTerm);
5027 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
5028
5029 // Insert an appropriate new terminator.
5030 if (!KeepEdge1 && !KeepEdge2) {
5031 if (TrueBB == FalseBB) {
5032 // We were only looking for one successor, and it was present.
5033 // Create an unconditional branch to it.
5034 Builder.CreateBr(TrueBB);
5035 } else {
5036 // We found both of the successors we were looking for.
5037 // Create a conditional branch sharing the condition of the select.
5038 CondBrInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
5039 setBranchWeights(*NewBI, {TrueWeight, FalseWeight},
5040 /*IsExpected=*/false, /*ElideAllZero=*/true);
5041 }
5042 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
5043 // Neither of the selected blocks were successors, so this
5044 // terminator must be unreachable.
5045 new UnreachableInst(OldTerm->getContext(), OldTerm->getIterator());
5046 } else {
5047 // One of the selected values was a successor, but the other wasn't.
5048 // Insert an unconditional branch to the one that was found;
5049 // the edge to the one that wasn't must be unreachable.
5050 if (!KeepEdge1) {
5051 // Only TrueBB was found.
5052 Builder.CreateBr(TrueBB);
5053 } else {
5054 // Only FalseBB was found.
5055 Builder.CreateBr(FalseBB);
5056 }
5057 }
5058
5060
5061 if (DTU) {
5062 SmallVector<DominatorTree::UpdateType, 2> Updates;
5063 Updates.reserve(RemovedSuccessors.size());
5064 for (auto *RemovedSuccessor : RemovedSuccessors)
5065 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
5066 DTU->applyUpdates(Updates);
5067 }
5068
5069 return true;
5070}
5071
5072// Folds switch(select(icmp eq X, C, K, X)) into switch(X), retargeting
5073// (or adding) the case for C to wherever K currently dispatches to:
5074// %cmp = icmp eq T %x, C
5075// %key = select i1 %cmp, T K, T %x
5076// switch T %key, label %default [ T K, label %case_k ... ]
5077// becomes
5078// switch T %x, label %default [ T C, label %case_k
5079// T K, label %case_k ... ]
5080bool SimplifyCFGOpt::simplifySwitchOnSelectRemap(SwitchInst *SI,
5081 SelectInst *Select, Value *X,
5082 ConstantInt *C, bool Negate) {
5083 Value *TrueVal = Select->getTrueValue();
5084 Value *FalseVal = Select->getFalseValue();
5085 if (Negate)
5086 std::swap(TrueVal, FalseVal);
5087 if (FalseVal != X)
5088 return false;
5089 auto *K = dyn_cast<ConstantInt>(TrueVal);
5090 if (!K)
5091 return false;
5092
5093 BasicBlock *DestFork = SI->findCaseValue(K)->getCaseSuccessor();
5094 auto CaseC = SI->findCaseValue(C);
5095 bool IsDefault = CaseC == SI->case_default();
5096 // Save before setSuccessor()/addCase() change it.
5097 BasicBlock *OldDest = CaseC->getCaseSuccessor();
5098 BasicBlock *BB = SI->getParent();
5099
5100 if (OldDest != DestFork) {
5101 // Case list is changing so we should drop stale profile weights.
5102 SI->setMetadata(LLVMContext::MD_prof, nullptr);
5103 if (!IsDefault)
5104 OldDest->removePredecessor(BB);
5105 if (IsDefault)
5106 SI->addCase(C, DestFork);
5107 else
5108 CaseC->setSuccessor(DestFork);
5109 // Not a new edge (BB->DestFork exists via K), just adding the PHI
5110 // entry.
5111 addPredecessorToBlock(DestFork, BB, BB);
5112
5113 if (!IsDefault) {
5114 // Edge to OldDest is gone only if nothing else still uses it.
5115 bool OldDestStillTargeted = any_of(
5116 successors(SI), [&](BasicBlock *Succ) { return Succ == OldDest; });
5117 if (DTU && !OldDestStillTargeted)
5118 DTU->applyUpdates({{DominatorTree::Delete, BB, OldDest}});
5119 }
5120 }
5121
5122 // X replaces the condition so compare/select are now dead.
5123 SI->setCondition(X);
5125 return true;
5126}
5127
5128// Replaces
5129// (switch (select cond, X, Y)) on constant X, Y
5130// with a branch - conditional if X and Y lead to distinct BBs,
5131// unconditional otherwise.
5132bool SimplifyCFGOpt::simplifySwitchOnSelect(SwitchInst *SI,
5133 SelectInst *Select) {
5134 CmpPredicate Pred;
5135 Value *X;
5136 ConstantInt *C;
5137 if (Select->hasOneUse() &&
5138 match(Select->getCondition(),
5139 m_ICmp(Pred, m_Value(X), m_ConstantInt(C))) &&
5140 ICmpInst::isEquality(Pred) &&
5141 simplifySwitchOnSelectRemap(SI, Select, X, C, Pred == ICmpInst::ICMP_NE))
5142 return true;
5143
5144 // Check for constant integer values in the select.
5145 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
5146 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
5147 if (!TrueVal || !FalseVal)
5148 return false;
5149
5150 // Find the relevant condition and destinations.
5151 Value *Condition = Select->getCondition();
5152 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
5153 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
5154
5155 // Get weight for TrueBB and FalseBB.
5156 uint32_t TrueWeight = 0, FalseWeight = 0;
5157 SmallVector<uint64_t, 8> Weights;
5158 bool HasWeights = hasBranchWeightMD(*SI);
5159 if (HasWeights) {
5160 getBranchWeights(SI, Weights);
5161 if (Weights.size() == 1 + SI->getNumCases()) {
5162 TrueWeight =
5163 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
5164 FalseWeight =
5165 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
5166 }
5167 }
5168
5169 // Perform the actual simplification.
5170 return simplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
5171 FalseWeight);
5172}
5173
5174// Replaces
5175// (indirectbr (select cond, blockaddress(@fn, BlockA),
5176// blockaddress(@fn, BlockB)))
5177// with
5178// (br cond, BlockA, BlockB).
5179bool SimplifyCFGOpt::simplifyIndirectBrOnSelect(IndirectBrInst *IBI,
5180 SelectInst *SI) {
5181 // Check that both operands of the select are block addresses.
5182 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
5183 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
5184 if (!TBA || !FBA)
5185 return false;
5186
5187 // Extract the actual blocks.
5188 BasicBlock *TrueBB = TBA->getBasicBlock();
5189 BasicBlock *FalseBB = FBA->getBasicBlock();
5190
5191 // The select's profile becomes the profile of the conditional branch that
5192 // replaces the indirect branch.
5193 SmallVector<uint32_t> SelectBranchWeights(2);
5195 extractBranchWeights(*SI, SelectBranchWeights);
5196 // Perform the actual simplification.
5197 return simplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
5198 SelectBranchWeights[0],
5199 SelectBranchWeights[1]);
5200}
5201
5202/// This is called when we find an icmp instruction
5203/// (a seteq/setne with a constant) as the only instruction in a
5204/// block that ends with an uncond branch. We are looking for a very specific
5205/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
5206/// this case, we merge the first two "or's of icmp" into a switch, but then the
5207/// default value goes to an uncond block with a seteq in it, we get something
5208/// like:
5209///
5210/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
5211/// DEFAULT:
5212/// %tmp = icmp eq i8 %A, 92
5213/// br label %end
5214/// end:
5215/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
5216///
5217/// We prefer to split the edge to 'end' so that there is a true/false entry to
5218/// the PHI, merging the third icmp into the switch.
5219bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
5220 ICmpInst *ICI, IRBuilder<> &Builder) {
5221 // Select == nullptr means we assume that there is a hidden no-op select
5222 // instruction of `_ = select %icmp, true, false` after `%icmp = icmp ...`
5223 return tryToSimplifyUncondBranchWithICmpSelectInIt(ICI, nullptr, Builder);
5224}
5225
5226/// Similar to tryToSimplifyUncondBranchWithICmpInIt, but handle a more generic
5227/// case. This is called when we find an icmp instruction (a seteq/setne with a
5228/// constant) and its following select instruction as the only TWO instructions
5229/// in a block that ends with an uncond branch. We are looking for a very
5230/// specific pattern that occurs when "
5231/// if (A == 1) return C1;
5232/// if (A == 2) return C2;
5233/// if (A < 3) return C3;
5234/// return C4;
5235/// " gets simplified. In this case, we merge the first two "branches of icmp"
5236/// into a switch, but then the default value goes to an uncond block with a lt
5237/// icmp and select in it, as InstCombine can not simplify "A < 3" as "A == 2".
5238/// After SimplifyCFG and other subsequent optimizations (e.g., SCCP), we might
5239/// get something like:
5240///
5241/// case1:
5242/// switch i8 %A, label %DEFAULT [ i8 0, label %end i8 1, label %case2 ]
5243/// case2:
5244/// br label %end
5245/// DEFAULT:
5246/// %tmp = icmp eq i8 %A, 2
5247/// %val = select i1 %tmp, i8 C3, i8 C4
5248/// br label %end
5249/// end:
5250/// _ = phi i8 [ C1, %case1 ], [ C2, %case2 ], [ %val, %DEFAULT ]
5251///
5252/// We prefer to split the edge to 'end' so that there are TWO entries of V3/V4
5253/// to the PHI, merging the icmp & select into the switch, as follows:
5254///
5255/// case1:
5256/// switch i8 %A, label %DEFAULT [
5257/// i8 0, label %end
5258/// i8 1, label %case2
5259/// i8 2, label %case3
5260/// ]
5261/// case2:
5262/// br label %end
5263/// case3:
5264/// br label %end
5265/// DEFAULT:
5266/// br label %end
5267/// end:
5268/// _ = phi i8 [ C1, %case1 ], [ C2, %case2 ], [ C3, %case2 ], [ C4, %DEFAULT]
5269bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpSelectInIt(
5270 ICmpInst *ICI, SelectInst *Select, IRBuilder<> &Builder) {
5271 BasicBlock *BB = ICI->getParent();
5272
5273 // If the block has any PHIs in it or the icmp/select has multiple uses, it is
5274 // too complex.
5275 /// TODO: support multi-phis in succ BB of select's BB.
5276 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse() ||
5277 (Select && !Select->hasOneUse()))
5278 return false;
5279
5280 // The pattern we're looking for is where our only predecessor is a switch on
5281 // 'V' and this block is the default case for the switch. In this case we can
5282 // fold the compared value into the switch to simplify things.
5283 BasicBlock *Pred = BB->getSinglePredecessor();
5284 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
5285 return false;
5286
5287 Value *IcmpCond;
5288 ConstantInt *NewCaseVal;
5289 CmpPredicate Predicate;
5290
5291 // Match icmp X, C
5292 if (!match(ICI,
5293 m_ICmp(Predicate, m_Value(IcmpCond), m_ConstantInt(NewCaseVal))))
5294 return false;
5295
5296 Value *SelectCond, *SelectTrueVal, *SelectFalseVal;
5298 if (!Select) {
5299 // If Select == nullptr, we can assume that there is a hidden no-op select
5300 // just after icmp
5301 SelectCond = ICI;
5302 SelectTrueVal = Builder.getTrue();
5303 SelectFalseVal = Builder.getFalse();
5304 User = ICI->user_back();
5305 } else {
5306 SelectCond = Select->getCondition();
5307 // Check if the select condition is the same as the icmp condition.
5308 if (SelectCond != ICI)
5309 return false;
5310 SelectTrueVal = Select->getTrueValue();
5311 SelectFalseVal = Select->getFalseValue();
5312 User = Select->user_back();
5313 }
5314
5315 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
5316 if (SI->getCondition() != IcmpCond)
5317 return false;
5318
5319 // If BB is reachable on a non-default case, then we simply know the value of
5320 // V in this block. Substitute it and constant fold the icmp instruction
5321 // away.
5322 if (SI->getDefaultDest() != BB) {
5323 ConstantInt *VVal = SI->findCaseDest(BB);
5324 assert(VVal && "Should have a unique destination value");
5325 ICI->setOperand(0, VVal);
5326
5327 if (Value *V = simplifyInstruction(ICI, {DL, ICI})) {
5328 ICI->replaceAllUsesWith(V);
5329 ICI->eraseFromParent();
5330 }
5331 // BB is now empty, so it is likely to simplify away.
5332 return requestResimplify();
5333 }
5334
5335 // Ok, the block is reachable from the default dest. If the constant we're
5336 // comparing exists in one of the other edges, then we can constant fold ICI
5337 // and zap it.
5338 if (SI->findCaseValue(NewCaseVal) != SI->case_default()) {
5339 Value *V;
5340 if (Predicate == ICmpInst::ICMP_EQ)
5342 else
5344
5345 ICI->replaceAllUsesWith(V);
5346 ICI->eraseFromParent();
5347 // BB is now empty, so it is likely to simplify away.
5348 return requestResimplify();
5349 }
5350
5351 // The use of the select has to be in the 'end' block, by the only PHI node in
5352 // the block.
5353 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
5354 PHINode *PHIUse = dyn_cast<PHINode>(User);
5355 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
5357 return false;
5358
5359 // If the icmp is a SETEQ, then the default dest gets SelectFalseVal, the new
5360 // edge gets SelectTrueVal in the PHI.
5361 Value *DefaultCst = SelectFalseVal;
5362 Value *NewCst = SelectTrueVal;
5363
5364 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
5365 std::swap(DefaultCst, NewCst);
5366
5367 // Replace Select (which is used by the PHI for the default value) with
5368 // SelectFalseVal or SelectTrueVal depending on if ICI is EQ or NE.
5369 if (Select) {
5370 Select->replaceAllUsesWith(DefaultCst);
5371 Select->eraseFromParent();
5372 } else {
5373 ICI->replaceAllUsesWith(DefaultCst);
5374 }
5375 ICI->eraseFromParent();
5376
5377 SmallVector<DominatorTree::UpdateType, 2> Updates;
5378
5379 // Okay, the switch goes to this block on a default value. Add an edge from
5380 // the switch to the merge point on the compared value.
5381 BasicBlock *NewBB =
5382 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
5383 {
5384 SwitchInstProfUpdateWrapper SIW(*SI);
5385 auto W0 = SIW.getSuccessorWeight(0);
5387 if (W0) {
5388 NewW = ((uint64_t(*W0) + 1) >> 1);
5389 SIW.setSuccessorWeight(0, *NewW);
5390 }
5391 SIW.addCase(NewCaseVal, NewBB, NewW);
5392 if (DTU)
5393 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
5394 }
5395
5396 // NewBB branches to the phi block, add the uncond branch and the phi entry.
5397 Builder.SetInsertPoint(NewBB);
5398 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
5399 Builder.CreateBr(SuccBlock);
5400 PHIUse->addIncoming(NewCst, NewBB);
5401 if (DTU) {
5402 Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock});
5403 DTU->applyUpdates(Updates);
5404 }
5405 return true;
5406}
5407
5408/// Check to see if it is branching on an or/and chain of icmp instructions, and
5409/// fold it into a switch instruction if so.
5410bool SimplifyCFGOpt::simplifyBranchOnICmpChain(CondBrInst *BI,
5411 IRBuilder<> &Builder,
5412 const DataLayout &DL) {
5414 if (!Cond)
5415 return false;
5416
5417 // Change br (X == 0 | X == 1), T, F into a switch instruction.
5418 // If this is a bunch of seteq's or'd together, or if it's a bunch of
5419 // 'setne's and'ed together, collect them.
5420
5421 // Try to gather values from a chain of and/or to be turned into a switch
5422 ConstantComparesGatherer ConstantCompare(Cond, DL);
5423 // Unpack the result
5424 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
5425 Value *CompVal = ConstantCompare.CompValue;
5426 unsigned UsedICmps = ConstantCompare.UsedICmps;
5427 Value *ExtraCase = ConstantCompare.Extra;
5428 bool TrueWhenEqual = ConstantCompare.IsEq;
5429
5430 // If we didn't have a multiply compared value, fail.
5431 if (!CompVal)
5432 return false;
5433
5434 // Avoid turning single icmps into a switch.
5435 if (UsedICmps <= 1)
5436 return false;
5437
5438 // There might be duplicate constants in the list, which the switch
5439 // instruction can't handle, remove them now.
5441 Values.erase(llvm::unique(Values), Values.end());
5442
5443 // If Extra was used, we require at least two switch values to do the
5444 // transformation. A switch with one value is just a conditional branch.
5445 if (ExtraCase && Values.size() < 2)
5446 return false;
5447
5448 SmallVector<uint32_t> BranchWeights;
5449 const bool HasProfile = !ProfcheckDisableMetadataFixes &&
5450 extractBranchWeights(*BI, BranchWeights);
5451
5452 // Figure out which block is which destination.
5453 BasicBlock *DefaultBB = BI->getSuccessor(1);
5454 BasicBlock *EdgeBB = BI->getSuccessor(0);
5455 if (!TrueWhenEqual) {
5456 std::swap(DefaultBB, EdgeBB);
5457 if (HasProfile)
5458 std::swap(BranchWeights[0], BranchWeights[1]);
5459 }
5460
5461 BasicBlock *BB = BI->getParent();
5462
5463 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
5464 << " cases into SWITCH. BB is:\n"
5465 << *BB);
5466
5467 SmallVector<DominatorTree::UpdateType, 2> Updates;
5468
5469 // If there are any extra values that couldn't be folded into the switch
5470 // then we evaluate them with an explicit branch first. Split the block
5471 // right before the condbr to handle it.
5472 if (ExtraCase) {
5473 BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr,
5474 /*MSSAU=*/nullptr, "switch.early.test");
5475
5476 // Remove the uncond branch added to the old block.
5477 Instruction *OldTI = BB->getTerminator();
5478 Builder.SetInsertPoint(OldTI);
5479
5480 // There can be an unintended UB if extra values are Poison. Before the
5481 // transformation, extra values may not be evaluated according to the
5482 // condition, and it will not raise UB. But after transformation, we are
5483 // evaluating extra values before checking the condition, and it will raise
5484 // UB. It can be solved by adding freeze instruction to extra values.
5485 AssumptionCache *AC = Options.AC;
5486
5487 if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr))
5488 ExtraCase = Builder.CreateFreeze(ExtraCase);
5489
5490 // We don't have any info about this condition.
5491 auto *Br = TrueWhenEqual ? Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB)
5492 : Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
5494
5495 OldTI->eraseFromParent();
5496
5497 if (DTU)
5498 Updates.push_back({DominatorTree::Insert, BB, EdgeBB});
5499
5500 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
5501 // for the edge we just added.
5502 addPredecessorToBlock(EdgeBB, BB, NewBB);
5503
5504 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
5505 << "\nEXTRABB = " << *BB);
5506 BB = NewBB;
5507 }
5508
5509 Builder.SetInsertPoint(BI);
5510 // Convert pointer to int before we switch.
5511 if (CompVal->getType()->isPointerTy()) {
5512 assert(!DL.hasUnstableRepresentation(CompVal->getType()) &&
5513 "Should not end up here with unstable pointers");
5514 CompVal = Builder.CreatePtrToInt(
5515 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
5516 }
5517
5518 // Check if we can represent the values as a contiguous range. If so, we use a
5519 // range check + conditional branch instead of a switch.
5520 if (Values.front()->getValue() - Values.back()->getValue() ==
5521 Values.size() - 1) {
5522 ConstantRange RangeToCheck = ConstantRange::getNonEmpty(
5523 Values.back()->getValue(), Values.front()->getValue() + 1);
5524 APInt Offset, RHS;
5525 ICmpInst::Predicate Pred;
5526 RangeToCheck.getEquivalentICmp(Pred, RHS, Offset);
5527 Value *X = CompVal;
5528 if (!Offset.isZero())
5529 X = Builder.CreateAdd(X, ConstantInt::get(CompVal->getType(), Offset));
5530 Value *Cond =
5531 Builder.CreateICmp(Pred, X, ConstantInt::get(CompVal->getType(), RHS));
5532 CondBrInst *NewBI = Builder.CreateCondBr(Cond, EdgeBB, DefaultBB);
5533 if (HasProfile)
5534 setBranchWeights(*NewBI, BranchWeights, /*IsExpected=*/false);
5535 // We don't need to update PHI nodes since we don't add any new edges.
5536 } else {
5537 // Create the new switch instruction now.
5538 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
5539 if (HasProfile) {
5540 // We know the weight of the default case. We don't know the weight of the
5541 // other cases, but rather than completely lose profiling info, we split
5542 // the remaining probability equally over them.
5543 SmallVector<uint32_t> NewWeights(Values.size() + 1);
5544 NewWeights[0] = BranchWeights[1]; // this is the default, and we swapped
5545 // if TrueWhenEqual.
5546 for (auto &V : drop_begin(NewWeights))
5547 V = BranchWeights[0] / Values.size();
5548 setBranchWeights(*New, NewWeights, /*IsExpected=*/false);
5549 }
5550
5551 // Add all of the 'cases' to the switch instruction.
5552 for (ConstantInt *Val : Values)
5553 New->addCase(Val, EdgeBB);
5554
5555 // We added edges from PI to the EdgeBB. As such, if there were any
5556 // PHI nodes in EdgeBB, they need entries to be added corresponding to
5557 // the number of edges added.
5558 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
5559 PHINode *PN = cast<PHINode>(BBI);
5560 Value *InVal = PN->getIncomingValueForBlock(BB);
5561 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
5562 PN->addIncoming(InVal, BB);
5563 }
5564 }
5565
5566 // Erase the old branch instruction.
5568 if (DTU)
5569 DTU->applyUpdates(Updates);
5570
5571 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
5572 return true;
5573}
5574
5575bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
5576 if (isa<PHINode>(RI->getValue()))
5577 return simplifyCommonResume(RI);
5578 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHIIt()) &&
5579 RI->getValue() == &*RI->getParent()->getFirstNonPHIIt())
5580 // The resume must unwind the exception that caused control to branch here.
5581 return simplifySingleResume(RI);
5582
5583 return false;
5584}
5585
5586// Check if cleanup block is empty
5588 for (Instruction &I : R) {
5589 auto *II = dyn_cast<IntrinsicInst>(&I);
5590 if (!II)
5591 return false;
5592
5593 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
5594 switch (IntrinsicID) {
5595 case Intrinsic::dbg_declare:
5596 case Intrinsic::dbg_value:
5597 case Intrinsic::dbg_label:
5598 case Intrinsic::lifetime_end:
5599 break;
5600 default:
5601 return false;
5602 }
5603 }
5604 return true;
5605}
5606
5607// Simplify resume that is shared by several landing pads (phi of landing pad).
5608bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
5609 BasicBlock *BB = RI->getParent();
5610
5611 // Check that there are no other instructions except for debug and lifetime
5612 // intrinsics between the phi's and resume instruction.
5613 if (!isCleanupBlockEmpty(make_range(RI->getParent()->getFirstNonPHIIt(),
5614 BB->getTerminator()->getIterator())))
5615 return false;
5616
5617 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
5618 auto *PhiLPInst = cast<PHINode>(RI->getValue());
5619
5620 // Check incoming blocks to see if any of them are trivial.
5621 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
5622 Idx++) {
5623 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
5624 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
5625
5626 // If the block has other successors, we can not delete it because
5627 // it has other dependents.
5628 if (IncomingBB->getUniqueSuccessor() != BB)
5629 continue;
5630
5631 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHIIt());
5632 // Not the landing pad that caused the control to branch here.
5633 if (IncomingValue != LandingPad)
5634 continue;
5635
5637 make_range(LandingPad->getNextNode(), IncomingBB->getTerminator())))
5638 TrivialUnwindBlocks.insert(IncomingBB);
5639 }
5640
5641 // If no trivial unwind blocks, don't do any simplifications.
5642 if (TrivialUnwindBlocks.empty())
5643 return false;
5644
5645 // Turn all invokes that unwind here into calls.
5646 for (auto *TrivialBB : TrivialUnwindBlocks) {
5647 // Blocks that will be simplified should be removed from the phi node.
5648 // Note there could be multiple edges to the resume block, and we need
5649 // to remove them all.
5650 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
5651 BB->removePredecessor(TrivialBB, true);
5652
5653 for (BasicBlock *Pred :
5655 removeUnwindEdge(Pred, DTU);
5656 ++NumInvokes;
5657 }
5658
5659 // In each SimplifyCFG run, only the current processed block can be erased.
5660 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
5661 // of erasing TrivialBB, we only remove the branch to the common resume
5662 // block so that we can later erase the resume block since it has no
5663 // predecessors.
5664 TrivialBB->getTerminator()->eraseFromParent();
5665 new UnreachableInst(RI->getContext(), TrivialBB);
5666 if (DTU)
5667 DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}});
5668 }
5669
5670 // Delete the resume block if all its predecessors have been removed.
5671 if (pred_empty(BB))
5672 DeleteDeadBlock(BB, DTU);
5673
5674 return !TrivialUnwindBlocks.empty();
5675}
5676
5677// Simplify resume that is only used by a single (non-phi) landing pad.
5678bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
5679 BasicBlock *BB = RI->getParent();
5680 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHIIt());
5681 assert(RI->getValue() == LPInst &&
5682 "Resume must unwind the exception that caused control to here");
5683
5684 // Check that there are no other instructions except for debug intrinsics.
5686 make_range<Instruction *>(LPInst->getNextNode(), RI)))
5687 return false;
5688
5689 // Turn all invokes that unwind here into calls and delete the basic block.
5690 for (BasicBlock *Pred : llvm::make_early_inc_range(predecessors(BB))) {
5691 removeUnwindEdge(Pred, DTU);
5692 ++NumInvokes;
5693 }
5694
5695 // The landingpad is now unreachable. Zap it.
5696 DeleteDeadBlock(BB, DTU);
5697 return true;
5698}
5699
5701 // If this is a trivial cleanup pad that executes no instructions, it can be
5702 // eliminated. If the cleanup pad continues to the caller, any predecessor
5703 // that is an EH pad will be updated to continue to the caller and any
5704 // predecessor that terminates with an invoke instruction will have its invoke
5705 // instruction converted to a call instruction. If the cleanup pad being
5706 // simplified does not continue to the caller, each predecessor will be
5707 // updated to continue to the unwind destination of the cleanup pad being
5708 // simplified.
5709 BasicBlock *BB = RI->getParent();
5710 CleanupPadInst *CPInst = RI->getCleanupPad();
5711 if (CPInst->getParent() != BB)
5712 // This isn't an empty cleanup.
5713 return false;
5714
5715 // We cannot kill the pad if it has multiple uses. This typically arises
5716 // from unreachable basic blocks.
5717 if (!CPInst->hasOneUse())
5718 return false;
5719
5720 // Check that there are no other instructions except for benign intrinsics.
5722 make_range<Instruction *>(CPInst->getNextNode(), RI)))
5723 return false;
5724
5725 // If the cleanup return we are simplifying unwinds to the caller, this will
5726 // set UnwindDest to nullptr.
5727 BasicBlock *UnwindDest = RI->getUnwindDest();
5728
5729 // We're about to remove BB from the control flow. Before we do, sink any
5730 // PHINodes into the unwind destination. Doing this before changing the
5731 // control flow avoids some potentially slow checks, since we can currently
5732 // be certain that UnwindDest and BB have no common predecessors (since they
5733 // are both EH pads).
5734 if (UnwindDest) {
5735 // First, go through the PHI nodes in UnwindDest and update any nodes that
5736 // reference the block we are removing
5737 for (PHINode &DestPN : UnwindDest->phis()) {
5738 int Idx = DestPN.getBasicBlockIndex(BB);
5739 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
5740 assert(Idx != -1);
5741 // This PHI node has an incoming value that corresponds to a control
5742 // path through the cleanup pad we are removing. If the incoming
5743 // value is in the cleanup pad, it must be a PHINode (because we
5744 // verified above that the block is otherwise empty). Otherwise, the
5745 // value is either a constant or a value that dominates the cleanup
5746 // pad being removed.
5747 //
5748 // Because BB and UnwindDest are both EH pads, all of their
5749 // predecessors must unwind to these blocks, and since no instruction
5750 // can have multiple unwind destinations, there will be no overlap in
5751 // incoming blocks between SrcPN and DestPN.
5752 Value *SrcVal = DestPN.getIncomingValue(Idx);
5753 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
5754
5755 bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB;
5756 for (auto *Pred : predecessors(BB)) {
5757 Value *Incoming =
5758 NeedPHITranslation ? SrcPN->getIncomingValueForBlock(Pred) : SrcVal;
5759 DestPN.addIncoming(Incoming, Pred);
5760 }
5761 }
5762
5763 // Sink any remaining PHI nodes directly into UnwindDest.
5764 BasicBlock::iterator InsertPt = UnwindDest->getFirstNonPHIIt();
5765 for (PHINode &PN : make_early_inc_range(BB->phis())) {
5766 if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB))
5767 // If the PHI node has no uses or all of its uses are in this basic
5768 // block (meaning they are debug or lifetime intrinsics), just leave
5769 // it. It will be erased when we erase BB below.
5770 continue;
5771
5772 // Otherwise, sink this PHI node into UnwindDest.
5773 // Any predecessors to UnwindDest which are not already represented
5774 // must be back edges which inherit the value from the path through
5775 // BB. In this case, the PHI value must reference itself.
5776 for (auto *pred : predecessors(UnwindDest))
5777 if (pred != BB)
5778 PN.addIncoming(&PN, pred);
5779 PN.moveBefore(InsertPt);
5780 // Also, add a dummy incoming value for the original BB itself,
5781 // so that the PHI is well-formed until we drop said predecessor.
5782 PN.addIncoming(PoisonValue::get(PN.getType()), BB);
5783 }
5784 }
5785
5786 std::vector<DominatorTree::UpdateType> Updates;
5787
5788 // We use make_early_inc_range here because we will remove all predecessors.
5790 if (UnwindDest == nullptr) {
5791 if (DTU) {
5792 DTU->applyUpdates(Updates);
5793 Updates.clear();
5794 }
5795 removeUnwindEdge(PredBB, DTU);
5796 ++NumInvokes;
5797 } else {
5798 BB->removePredecessor(PredBB);
5799 Instruction *TI = PredBB->getTerminator();
5800 TI->replaceUsesOfWith(BB, UnwindDest);
5801 if (DTU) {
5802 Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest});
5803 Updates.push_back({DominatorTree::Delete, PredBB, BB});
5804 }
5805 }
5806 }
5807
5808 if (DTU)
5809 DTU->applyUpdates(Updates);
5810
5811 DeleteDeadBlock(BB, DTU);
5812
5813 return true;
5814}
5815
5816// Try to merge two cleanuppads together.
5818 // Skip any cleanuprets which unwind to caller, there is nothing to merge
5819 // with.
5820 BasicBlock *UnwindDest = RI->getUnwindDest();
5821 if (!UnwindDest)
5822 return false;
5823
5824 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
5825 // be safe to merge without code duplication.
5826 if (UnwindDest->getSinglePredecessor() != RI->getParent())
5827 return false;
5828
5829 // Verify that our cleanuppad's unwind destination is another cleanuppad.
5830 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
5831 if (!SuccessorCleanupPad)
5832 return false;
5833
5834 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
5835 // Replace any uses of the successor cleanupad with the predecessor pad
5836 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
5837 // funclet bundle operands.
5838 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
5839 // Remove the old cleanuppad.
5840 SuccessorCleanupPad->eraseFromParent();
5841 // Now, we simply replace the cleanupret with a branch to the unwind
5842 // destination.
5843 UncondBrInst::Create(UnwindDest, RI->getParent());
5844 RI->eraseFromParent();
5845
5846 return true;
5847}
5848
5849bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
5850 // It is possible to transiantly have an undef cleanuppad operand because we
5851 // have deleted some, but not all, dead blocks.
5852 // Eventually, this block will be deleted.
5853 if (isa<UndefValue>(RI->getOperand(0)))
5854 return false;
5855
5856 if (mergeCleanupPad(RI))
5857 return true;
5858
5859 if (removeEmptyCleanup(RI, DTU))
5860 return true;
5861
5862 return false;
5863}
5864
5865// WARNING: keep in sync with InstCombinerImpl::visitUnreachableInst()!
5866bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
5867 BasicBlock *BB = UI->getParent();
5868
5869 bool Changed = false;
5870
5871 // Ensure that any debug-info records that used to occur after the Unreachable
5872 // are moved to in front of it -- otherwise they'll "dangle" at the end of
5873 // the block.
5875
5876 // Debug-info records on the unreachable inst itself should be deleted, as
5877 // below we delete everything past the final executable instruction.
5878 UI->dropDbgRecords();
5879
5880 // If there are any instructions immediately before the unreachable that can
5881 // be removed, do so.
5882 while (UI->getIterator() != BB->begin()) {
5884 --BBI;
5885
5887 break; // Can not drop any more instructions. We're done here.
5888 // Otherwise, this instruction can be freely erased,
5889 // even if it is not side-effect free.
5890
5891 // Note that deleting EH's here is in fact okay, although it involves a bit
5892 // of subtle reasoning. If this inst is an EH, all the predecessors of this
5893 // block will be the unwind edges of Invoke/CatchSwitch/CleanupReturn,
5894 // and we can therefore guarantee this block will be erased.
5895
5896 // If we're deleting this, we're deleting any subsequent debug info, so
5897 // delete DbgRecords.
5898 BBI->dropDbgRecords();
5899
5900 // Delete this instruction (any uses are guaranteed to be dead)
5901 BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
5902 BBI->eraseFromParent();
5903 Changed = true;
5904 }
5905
5906 // If the unreachable instruction is the first in the block, take a gander
5907 // at all of the predecessors of this instruction, and simplify them.
5908 if (&BB->front() != UI)
5909 return Changed;
5910
5911 std::vector<DominatorTree::UpdateType> Updates;
5912
5913 SmallSetVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
5914 for (BasicBlock *Predecessor : Preds) {
5915 Instruction *TI = Predecessor->getTerminator();
5916 IRBuilder<> Builder(TI);
5917 if (isa<UncondBrInst>(TI)) {
5918 new UnreachableInst(TI->getContext(), TI->getIterator());
5919 TI->eraseFromParent();
5920 Changed = true;
5921 if (DTU)
5922 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5923 } else if (auto *BI = dyn_cast<CondBrInst>(TI)) {
5924 // We could either have a proper unconditional branch,
5925 // or a degenerate conditional branch with matching destinations.
5926 if (BI->getSuccessor(0) == BI->getSuccessor(1)) {
5927 new UnreachableInst(TI->getContext(), TI->getIterator());
5928 TI->eraseFromParent();
5929 Changed = true;
5930 } else {
5931 Value* Cond = BI->getCondition();
5932 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
5933 "The destinations are guaranteed to be different here.");
5934 CallInst *Assumption;
5935 if (BI->getSuccessor(0) == BB) {
5936 Assumption = Builder.CreateAssumption(Builder.CreateNot(Cond));
5937 Builder.CreateBr(BI->getSuccessor(1));
5938 } else {
5939 assert(BI->getSuccessor(1) == BB && "Incorrect CFG");
5940 Assumption = Builder.CreateAssumption(Cond);
5941 Builder.CreateBr(BI->getSuccessor(0));
5942 }
5943 if (Options.AC)
5944 Options.AC->registerAssumption(cast<AssumeInst>(Assumption));
5945
5947 Changed = true;
5948 }
5949 if (DTU)
5950 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5951 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
5952 SwitchInstProfUpdateWrapper SU(*SI);
5953 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
5954 if (i->getCaseSuccessor() != BB) {
5955 ++i;
5956 continue;
5957 }
5958 BB->removePredecessor(SU->getParent());
5959 i = SU.removeCase(i);
5960 e = SU->case_end();
5961 Changed = true;
5962 }
5963 // Note that the default destination can't be removed!
5964 if (DTU && SI->getDefaultDest() != BB)
5965 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5966 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
5967 if (II->getUnwindDest() == BB) {
5968 if (DTU) {
5969 DTU->applyUpdates(Updates);
5970 Updates.clear();
5971 }
5972 auto *CI = cast<CallInst>(removeUnwindEdge(TI->getParent(), DTU));
5973 if (!CI->doesNotThrow())
5974 CI->setDoesNotThrow();
5975 Changed = true;
5976 }
5977 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
5978 if (CSI->getUnwindDest() == BB) {
5979 if (DTU) {
5980 DTU->applyUpdates(Updates);
5981 Updates.clear();
5982 }
5983 removeUnwindEdge(TI->getParent(), DTU);
5984 Changed = true;
5985 continue;
5986 }
5987
5988 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
5989 E = CSI->handler_end();
5990 I != E; ++I) {
5991 if (*I == BB) {
5992 CSI->removeHandler(I);
5993 --I;
5994 --E;
5995 Changed = true;
5996 }
5997 }
5998 if (DTU)
5999 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6000 if (CSI->getNumHandlers() == 0) {
6001 if (CSI->hasUnwindDest()) {
6002 // Redirect all predecessors of the block containing CatchSwitchInst
6003 // to instead branch to the CatchSwitchInst's unwind destination.
6004 if (DTU) {
6005 for (auto *PredecessorOfPredecessor : predecessors(Predecessor)) {
6006 Updates.push_back({DominatorTree::Insert,
6007 PredecessorOfPredecessor,
6008 CSI->getUnwindDest()});
6009 Updates.push_back({DominatorTree::Delete,
6010 PredecessorOfPredecessor, Predecessor});
6011 }
6012 }
6013 Predecessor->replaceAllUsesWith(CSI->getUnwindDest());
6014 } else {
6015 // Rewrite all preds to unwind to caller (or from invoke to call).
6016 if (DTU) {
6017 DTU->applyUpdates(Updates);
6018 Updates.clear();
6019 }
6020 SmallVector<BasicBlock *, 8> EHPreds(predecessors(Predecessor));
6021 for (BasicBlock *EHPred : EHPreds)
6022 removeUnwindEdge(EHPred, DTU);
6023 }
6024 // The catchswitch is no longer reachable.
6025 new UnreachableInst(CSI->getContext(), CSI->getIterator());
6026 CSI->eraseFromParent();
6027 Changed = true;
6028 }
6029 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
6030 (void)CRI;
6031 assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB &&
6032 "Expected to always have an unwind to BB.");
6033 if (DTU)
6034 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6035 new UnreachableInst(TI->getContext(), TI->getIterator());
6036 TI->eraseFromParent();
6037 Changed = true;
6038 }
6039 }
6040
6041 if (DTU)
6042 DTU->applyUpdates(Updates);
6043
6044 // If this block is now dead, remove it.
6045 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
6046 DeleteDeadBlock(BB, DTU);
6047 return true;
6048 }
6049
6050 return Changed;
6051}
6052
6061
6062static std::optional<ContiguousCasesResult>
6065 BasicBlock *Dest, BasicBlock *OtherDest) {
6066 assert(Cases.size() >= 1);
6067
6069 const APInt &Min = Cases.back()->getValue();
6070 const APInt &Max = Cases.front()->getValue();
6071 APInt Offset = Max - Min;
6072 size_t ContiguousOffset = Cases.size() - 1;
6073 if (Offset == ContiguousOffset) {
6074 return ContiguousCasesResult{
6075 /*Min=*/Cases.back(),
6076 /*Max=*/Cases.front(),
6077 /*Dest=*/Dest,
6078 /*OtherDest=*/OtherDest,
6079 /*Cases=*/&Cases,
6080 /*OtherCases=*/&OtherCases,
6081 };
6082 }
6083 ConstantRange CR = computeConstantRange(Condition, /*ForSigned=*/false,
6084 SimplifyQuery(Dest->getDataLayout()));
6085 // If this is a wrapping contiguous range, that is, [Min, OtherMin] +
6086 // [OtherMax, Max] (also [OtherMax, OtherMin]), [OtherMin+1, OtherMax-1] is a
6087 // contiguous range for the other destination. N.B. If CR is not a full range,
6088 // Max+1 is not equal to Min. It's not continuous in arithmetic.
6089 if (Max == CR.getUnsignedMax() && Min == CR.getUnsignedMin()) {
6090 assert(Cases.size() >= 2);
6091 auto *It =
6092 std::adjacent_find(Cases.begin(), Cases.end(), [](auto L, auto R) {
6093 return L->getValue() != R->getValue() + 1;
6094 });
6095 if (It == Cases.end())
6096 return std::nullopt;
6097 auto [OtherMax, OtherMin] = std::make_pair(*It, *std::next(It));
6098 if ((Max - OtherMax->getValue()) + (OtherMin->getValue() - Min) ==
6099 Cases.size() - 2) {
6100 return ContiguousCasesResult{
6101 /*Min=*/cast<ConstantInt>(
6102 ConstantInt::get(OtherMin->getType(), OtherMin->getValue() + 1)),
6103 /*Max=*/
6105 ConstantInt::get(OtherMax->getType(), OtherMax->getValue() - 1)),
6106 /*Dest=*/OtherDest,
6107 /*OtherDest=*/Dest,
6108 /*Cases=*/&OtherCases,
6109 /*OtherCases=*/&Cases,
6110 };
6111 }
6112 }
6113 return std::nullopt;
6114}
6115
6117 DomTreeUpdater *DTU,
6118 bool RemoveOrigDefaultBlock = true) {
6119 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
6120 auto *BB = Switch->getParent();
6121 auto *OrigDefaultBlock = Switch->getDefaultDest();
6122 if (RemoveOrigDefaultBlock)
6123 OrigDefaultBlock->removePredecessor(BB);
6124 BasicBlock *NewDefaultBlock = BasicBlock::Create(
6125 BB->getContext(), BB->getName() + ".unreachabledefault", BB->getParent(),
6126 OrigDefaultBlock);
6127 auto *UI = new UnreachableInst(Switch->getContext(), NewDefaultBlock);
6129 Switch->setDefaultDest(&*NewDefaultBlock);
6130 if (DTU) {
6132 Updates.push_back({DominatorTree::Insert, BB, &*NewDefaultBlock});
6133 if (RemoveOrigDefaultBlock &&
6134 !is_contained(successors(BB), OrigDefaultBlock))
6135 Updates.push_back({DominatorTree::Delete, BB, &*OrigDefaultBlock});
6136 DTU->applyUpdates(Updates);
6137 }
6138}
6139
6140/// Turn a switch into an integer range comparison and branch.
6141/// Switches with more than 2 destinations are ignored.
6142/// Switches with 1 destination are also ignored.
6143bool SimplifyCFGOpt::turnSwitchRangeIntoICmp(SwitchInst *SI,
6144 IRBuilder<> &Builder) {
6145 assert(SI->getNumCases() > 1 && "Degenerate switch?");
6146
6147 bool HasDefault = !SI->defaultDestUnreachable();
6148
6149 auto *BB = SI->getParent();
6150 // Partition the cases into two sets with different destinations.
6151 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
6152 BasicBlock *DestB = nullptr;
6155
6156 for (auto Case : SI->cases()) {
6157 BasicBlock *Dest = Case.getCaseSuccessor();
6158 if (!DestA)
6159 DestA = Dest;
6160 if (Dest == DestA) {
6161 CasesA.push_back(Case.getCaseValue());
6162 continue;
6163 }
6164 if (!DestB)
6165 DestB = Dest;
6166 if (Dest == DestB) {
6167 CasesB.push_back(Case.getCaseValue());
6168 continue;
6169 }
6170 return false; // More than two destinations.
6171 }
6172 if (!DestB)
6173 return false; // All destinations are the same and the default is unreachable
6174
6175 assert(DestA && DestB &&
6176 "Single-destination switch should have been folded.");
6177 assert(DestA != DestB);
6178 assert(DestB != SI->getDefaultDest());
6179 assert(!CasesB.empty() && "There must be non-default cases.");
6180 assert(!CasesA.empty() || HasDefault);
6181
6182 // Figure out if one of the sets of cases form a contiguous range.
6183 std::optional<ContiguousCasesResult> ContiguousCases;
6184
6185 // Only one icmp is needed when there is only one case.
6186 if (!HasDefault && CasesA.size() == 1)
6187 ContiguousCases = ContiguousCasesResult{
6188 /*Min=*/CasesA[0],
6189 /*Max=*/CasesA[0],
6190 /*Dest=*/DestA,
6191 /*OtherDest=*/DestB,
6192 /*Cases=*/&CasesA,
6193 /*OtherCases=*/&CasesB,
6194 };
6195 else if (CasesB.size() == 1)
6196 ContiguousCases = ContiguousCasesResult{
6197 /*Min=*/CasesB[0],
6198 /*Max=*/CasesB[0],
6199 /*Dest=*/DestB,
6200 /*OtherDest=*/DestA,
6201 /*Cases=*/&CasesB,
6202 /*OtherCases=*/&CasesA,
6203 };
6204 // Correctness: Cases to the default destination cannot be contiguous cases.
6205 else if (!HasDefault)
6206 ContiguousCases =
6207 findContiguousCases(SI->getCondition(), CasesA, CasesB, DestA, DestB);
6208
6209 if (!ContiguousCases)
6210 ContiguousCases =
6211 findContiguousCases(SI->getCondition(), CasesB, CasesA, DestB, DestA);
6212
6213 if (!ContiguousCases)
6214 return false;
6215
6216 auto [Min, Max, Dest, OtherDest, Cases, OtherCases] = *ContiguousCases;
6217
6218 // Start building the compare and branch.
6219
6221 Constant *NumCases = ConstantInt::get(Offset->getType(),
6222 Max->getValue() - Min->getValue() + 1);
6223 Instruction *NewBI;
6224 if (NumCases->isOneValue()) {
6225 assert(Max->getValue() == Min->getValue());
6226 Value *Cmp = Builder.CreateICmpEQ(SI->getCondition(), Min);
6227 NewBI = Builder.CreateCondBr(Cmp, Dest, OtherDest);
6228 }
6229 // If NumCases overflowed, then all possible values jump to the successor.
6230 else if (NumCases->isNullValue() && !Cases->empty()) {
6231 NewBI = Builder.CreateBr(Dest);
6232 } else {
6233 Value *Sub = SI->getCondition();
6234 if (!Offset->isNullValue())
6235 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
6236 Value *Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
6237 NewBI = Builder.CreateCondBr(Cmp, Dest, OtherDest);
6238 }
6239
6240 // Update weight for the newly-created conditional branch.
6241 if (hasBranchWeightMD(*SI) && isa<CondBrInst>(NewBI)) {
6242 SmallVector<uint64_t, 8> Weights;
6243 getBranchWeights(SI, Weights);
6244 if (Weights.size() == 1 + SI->getNumCases()) {
6245 uint64_t TrueWeight = 0;
6246 uint64_t FalseWeight = 0;
6247 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
6248 if (SI->getSuccessor(I) == Dest)
6249 TrueWeight += Weights[I];
6250 else
6251 FalseWeight += Weights[I];
6252 }
6253 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
6254 TrueWeight /= 2;
6255 FalseWeight /= 2;
6256 }
6257 setFittedBranchWeights(*NewBI, {TrueWeight, FalseWeight},
6258 /*IsExpected=*/false, /*ElideAllZero=*/true);
6259 }
6260 }
6261
6262 // Prune obsolete incoming values off the successors' PHI nodes.
6263 for (auto &PHI : make_early_inc_range(Dest->phis())) {
6264 unsigned PreviousEdges = Cases->size();
6265 if (Dest == SI->getDefaultDest())
6266 ++PreviousEdges;
6267 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
6268 PHI.removeIncomingValue(SI->getParent());
6269 }
6270 for (auto &PHI : make_early_inc_range(OtherDest->phis())) {
6271 unsigned PreviousEdges = OtherCases->size();
6272 if (OtherDest == SI->getDefaultDest())
6273 ++PreviousEdges;
6274 unsigned E = PreviousEdges - 1;
6275 // Remove all incoming values from OtherDest if OtherDest is unreachable.
6276 if (isa<UncondBrInst>(NewBI))
6277 ++E;
6278 for (unsigned I = 0; I != E; ++I)
6279 PHI.removeIncomingValue(SI->getParent());
6280 }
6281
6282 // Clean up the default block.
6283 SmallVector<DominatorTree::UpdateType, 2> Updates;
6284 if (!HasDefault) {
6285 BasicBlock *OrigDefaultBlock = SI->getDefaultDest();
6286 OrigDefaultBlock->removePredecessor(BB);
6287 Updates.push_back({DominatorTree::Delete, BB, OrigDefaultBlock});
6288 }
6289
6290 // Drop the switch.
6291 SI->eraseFromParent();
6292
6293 if (isa<UncondBrInst>(NewBI))
6294 Updates.push_back({DominatorTree::Delete, BB, OtherDest});
6295
6296 if (DTU)
6297 DTU->applyUpdates(Updates);
6298 return true;
6299}
6300
6301/// Compute masked bits for the condition of a switch
6302/// and use it to remove dead cases.
6304 AssumptionCache *AC,
6305 const DataLayout &DL) {
6306 Value *Cond = SI->getCondition();
6309 bool IsKnownValuesValid = collectPossibleValues(Cond, KnownValues, 4);
6310
6311 // We can also eliminate cases by determining that their values are outside of
6312 // the limited range of the condition based on how many significant (non-sign)
6313 // bits are in the condition value.
6314 unsigned MaxSignificantBitsInCond =
6316
6317 // Gather dead cases.
6319 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
6320 SmallVector<BasicBlock *, 8> UniqueSuccessors;
6321 for (const auto &Case : SI->cases()) {
6322 auto *Successor = Case.getCaseSuccessor();
6323 if (DTU) {
6324 auto [It, Inserted] = NumPerSuccessorCases.try_emplace(Successor);
6325 if (Inserted)
6326 UniqueSuccessors.push_back(Successor);
6327 ++It->second;
6328 }
6329 ConstantInt *CaseC = Case.getCaseValue();
6330 const APInt &CaseVal = CaseC->getValue();
6331 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
6332 (CaseVal.getSignificantBits() > MaxSignificantBitsInCond) ||
6333 (IsKnownValuesValid && !KnownValues.contains(CaseC))) {
6334 DeadCases.push_back(CaseC);
6335 if (DTU)
6336 --NumPerSuccessorCases[Successor];
6337 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
6338 << " is dead.\n");
6339 } else if (IsKnownValuesValid)
6340 KnownValues.erase(CaseC);
6341 }
6342
6343 // If we can prove that the cases must cover all possible values, the
6344 // default destination becomes dead and we can remove it. If we know some
6345 // of the bits in the value, we can use that to more precisely compute the
6346 // number of possible unique case values.
6347 bool HasDefault = !SI->defaultDestUnreachable();
6348 const unsigned NumUnknownBits =
6349 Known.getBitWidth() - (Known.Zero | Known.One).popcount();
6350 assert(NumUnknownBits <= Known.getBitWidth());
6351 if (HasDefault && DeadCases.empty()) {
6352 if (IsKnownValuesValid && all_of(KnownValues, IsaPred<UndefValue>)) {
6354 return true;
6355 }
6356
6357 if (NumUnknownBits < 64 /* avoid overflow */) {
6358 uint64_t AllNumCases = 1ULL << NumUnknownBits;
6359 if (SI->getNumCases() == AllNumCases) {
6361 return true;
6362 }
6363 // When only one case value is missing, replace default with that case.
6364 // Eliminating the default branch will provide more opportunities for
6365 // optimization, such as lookup tables.
6366 if (SI->getNumCases() == AllNumCases - 1) {
6367 assert(NumUnknownBits > 1 && "Should be canonicalized to a branch");
6368 IntegerType *CondTy = cast<IntegerType>(Cond->getType());
6369 if (CondTy->getIntegerBitWidth() > 64 ||
6370 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
6371 return false;
6372
6373 uint64_t MissingCaseVal = 0;
6374 for (const auto &Case : SI->cases())
6375 MissingCaseVal ^= Case.getCaseValue()->getValue().getLimitedValue();
6376 auto *MissingCase = cast<ConstantInt>(
6377 ConstantInt::get(Cond->getType(), MissingCaseVal));
6379 SIW.addCase(MissingCase, SI->getDefaultDest(),
6380 SIW.getSuccessorWeight(0));
6382 /*RemoveOrigDefaultBlock*/ false);
6383 SIW.setSuccessorWeight(0, 0);
6384 return true;
6385 }
6386 }
6387 }
6388
6389 if (DeadCases.empty())
6390 return false;
6391
6393 for (ConstantInt *DeadCase : DeadCases) {
6394 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
6395 assert(CaseI != SI->case_default() &&
6396 "Case was not found. Probably mistake in DeadCases forming.");
6397 // Prune unused values from PHI nodes.
6398 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
6399 SIW.removeCase(CaseI);
6400 }
6401
6402 if (DTU) {
6403 std::vector<DominatorTree::UpdateType> Updates;
6404 for (auto *Successor : UniqueSuccessors)
6405 if (NumPerSuccessorCases[Successor] == 0)
6406 Updates.push_back({DominatorTree::Delete, SI->getParent(), Successor});
6407 DTU->applyUpdates(Updates);
6408 }
6409
6410 return true;
6411}
6412
6413/// If BB would be eligible for simplification by
6414/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
6415/// by an unconditional branch), look at the phi node for BB in the successor
6416/// block and see if the incoming value is equal to CaseValue. If so, return
6417/// the phi node, and set PhiIndex to BB's index in the phi node.
6419 BasicBlock *BB, int *PhiIndex) {
6420 if (&*BB->getFirstNonPHIIt() != BB->getTerminator())
6421 return nullptr; // BB must be empty to be a candidate for simplification.
6422 if (!BB->getSinglePredecessor())
6423 return nullptr; // BB must be dominated by the switch.
6424
6426 if (!Branch)
6427 return nullptr; // Terminator must be unconditional branch.
6428
6429 BasicBlock *Succ = Branch->getSuccessor();
6430
6431 for (PHINode &PHI : Succ->phis()) {
6432 int Idx = PHI.getBasicBlockIndex(BB);
6433 assert(Idx >= 0 && "PHI has no entry for predecessor?");
6434
6435 Value *InValue = PHI.getIncomingValue(Idx);
6436 if (InValue != CaseValue)
6437 continue;
6438
6439 *PhiIndex = Idx;
6440 return &PHI;
6441 }
6442
6443 return nullptr;
6444}
6445
6446/// Try to forward the condition of a switch instruction to a phi node
6447/// dominated by the switch, if that would mean that some of the destination
6448/// blocks of the switch can be folded away. Return true if a change is made.
6450 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
6451
6452 ForwardingNodesMap ForwardingNodes;
6453 BasicBlock *SwitchBlock = SI->getParent();
6454 bool Changed = false;
6455 for (const auto &Case : SI->cases()) {
6456 ConstantInt *CaseValue = Case.getCaseValue();
6457 BasicBlock *CaseDest = Case.getCaseSuccessor();
6458
6459 // Replace phi operands in successor blocks that are using the constant case
6460 // value rather than the switch condition variable:
6461 // switchbb:
6462 // switch i32 %x, label %default [
6463 // i32 17, label %succ
6464 // ...
6465 // succ:
6466 // %r = phi i32 ... [ 17, %switchbb ] ...
6467 // -->
6468 // %r = phi i32 ... [ %x, %switchbb ] ...
6469
6470 for (PHINode &Phi : CaseDest->phis()) {
6471 // This only works if there is exactly 1 incoming edge from the switch to
6472 // a phi. If there is >1, that means multiple cases of the switch map to 1
6473 // value in the phi, and that phi value is not the switch condition. Thus,
6474 // this transform would not make sense (the phi would be invalid because
6475 // a phi can't have different incoming values from the same block).
6476 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
6477 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
6478 count(Phi.blocks(), SwitchBlock) == 1) {
6479 Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
6480 Changed = true;
6481 }
6482 }
6483
6484 // Collect phi nodes that are indirectly using this switch's case constants.
6485 int PhiIdx;
6486 if (auto *Phi = findPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
6487 ForwardingNodes[Phi].push_back(PhiIdx);
6488 }
6489
6490 for (auto &ForwardingNode : ForwardingNodes) {
6491 PHINode *Phi = ForwardingNode.first;
6492 SmallVectorImpl<int> &Indexes = ForwardingNode.second;
6493 // Check if it helps to fold PHI.
6494 if (Indexes.size() < 2 && !llvm::is_contained(Phi->incoming_values(), SI->getCondition()))
6495 continue;
6496
6497 for (int Index : Indexes)
6498 Phi->setIncomingValue(Index, SI->getCondition());
6499 Changed = true;
6500 }
6501
6502 return Changed;
6503}
6504
6505/// Return true if the backend will be able to handle
6506/// initializing an array of constants like C.
6508 if (C->isThreadDependent())
6509 return false;
6510 if (C->isDLLImportDependent())
6511 return false;
6512
6515 return false;
6516
6517 // Globals cannot contain scalable types.
6518 if (C->getType()->isScalableTy())
6519 return false;
6520
6522 // Pointer casts and in-bounds GEPs will not prohibit the backend from
6523 // materializing the array of constants.
6524 Constant *StrippedC = cast<Constant>(CE->stripInBoundsConstantOffsets());
6525 if (StrippedC == C || !validLookupTableConstant(StrippedC, TTI))
6526 return false;
6527 }
6528
6529 if (!TTI.shouldBuildLookupTablesForConstant(C))
6530 return false;
6531
6532 return true;
6533}
6534
6535/// If V is a Constant, return it. Otherwise, try to look up
6536/// its constant value in ConstantPool, returning 0 if it's not there.
6537static Constant *
6540 if (Constant *C = dyn_cast<Constant>(V))
6541 return C;
6542 return ConstantPool.lookup(V);
6543}
6544
6545/// Try to fold instruction I into a constant. This works for
6546/// simple instructions such as binary operations where both operands are
6547/// constant or can be replaced by constants from the ConstantPool. Returns the
6548/// resulting constant on success, 0 otherwise.
6549static Constant *
6553 Constant *A = lookupConstant(Select->getCondition(), ConstantPool);
6554 if (!A)
6555 return nullptr;
6556 if (A->isAllOnesValue())
6557 return lookupConstant(Select->getTrueValue(), ConstantPool);
6558 if (A->isNullValue())
6559 return lookupConstant(Select->getFalseValue(), ConstantPool);
6560 return nullptr;
6561 }
6562
6564 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
6565 if (Constant *A = lookupConstant(I->getOperand(N), ConstantPool))
6566 COps.push_back(A);
6567 else
6568 return nullptr;
6569 }
6570
6571 return ConstantFoldInstOperands(I, COps, DL);
6572}
6573
6574/// Try to determine the resulting constant values in phi nodes
6575/// at the common destination basic block, *CommonDest, for one of the case
6576/// destinations CaseDest corresponding to value CaseVal (nullptr for the
6577/// default case), of a switch instruction SI.
6578static bool
6580 BasicBlock **CommonDest,
6581 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
6582 const DataLayout &DL, const TargetTransformInfo &TTI) {
6583 // The block from which we enter the common destination.
6584 BasicBlock *Pred = SI->getParent();
6585
6586 // If CaseDest is empty except for some side-effect free instructions through
6587 // which we can constant-propagate the CaseVal, continue to its successor.
6589 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
6590 for (Instruction &I : *CaseDest) {
6591 if (I.isTerminator()) {
6592 // If the terminator is a simple branch, continue to the next block.
6593 if (I.getNumSuccessors() != 1 || I.isSpecialTerminator())
6594 return false;
6595 Pred = CaseDest;
6596 CaseDest = I.getSuccessor(0);
6597 } else if (Constant *C = constantFold(&I, DL, ConstantPool)) {
6598 // Instruction is side-effect free and constant.
6599
6600 // If the instruction has uses outside this block or a phi node slot for
6601 // the block, it is not safe to bypass the instruction since it would then
6602 // no longer dominate all its uses.
6603 for (auto &Use : I.uses()) {
6604 User *User = Use.getUser();
6606 if (I->getParent() == CaseDest)
6607 continue;
6608 if (PHINode *Phi = dyn_cast<PHINode>(User))
6609 if (Phi->getIncomingBlock(Use) == CaseDest)
6610 continue;
6611 return false;
6612 }
6613
6614 ConstantPool.insert(std::make_pair(&I, C));
6615 } else {
6616 break;
6617 }
6618 }
6619
6620 // If we did not have a CommonDest before, use the current one.
6621 if (!*CommonDest)
6622 *CommonDest = CaseDest;
6623 // If the destination isn't the common one, abort.
6624 if (CaseDest != *CommonDest)
6625 return false;
6626
6627 // Get the values for this case from phi nodes in the destination block.
6628 for (PHINode &PHI : (*CommonDest)->phis()) {
6629 int Idx = PHI.getBasicBlockIndex(Pred);
6630 if (Idx == -1)
6631 continue;
6632
6633 Constant *ConstVal =
6634 lookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
6635 if (!ConstVal)
6636 return false;
6637
6638 // Be conservative about which kinds of constants we support.
6639 if (!validLookupTableConstant(ConstVal, TTI))
6640 return false;
6641
6642 Res.push_back(std::make_pair(&PHI, ConstVal));
6643 }
6644
6645 return Res.size() > 0;
6646}
6647
6648// Helper function used to add CaseVal to the list of cases that generate
6649// Result. Returns the updated number of cases that generate this result.
6650static size_t mapCaseToResult(ConstantInt *CaseVal,
6651 SwitchCaseResultVectorTy &UniqueResults,
6652 Constant *Result) {
6653 for (auto &I : UniqueResults) {
6654 if (I.first == Result) {
6655 I.second.push_back(CaseVal);
6656 return I.second.size();
6657 }
6658 }
6659 UniqueResults.push_back(
6660 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
6661 return 1;
6662}
6663
6664// Helper function that initializes a map containing
6665// results for the PHI node of the common destination block for a switch
6666// instruction. Returns false if multiple PHI nodes have been found or if
6667// there is not a common destination block for the switch.
6669 BasicBlock *&CommonDest,
6670 SwitchCaseResultVectorTy &UniqueResults,
6671 Constant *&DefaultResult,
6672 const DataLayout &DL,
6673 const TargetTransformInfo &TTI,
6674 uintptr_t MaxUniqueResults) {
6675 for (const auto &I : SI->cases()) {
6676 ConstantInt *CaseVal = I.getCaseValue();
6677
6678 // Resulting value at phi nodes for this case value.
6679 SwitchCaseResultsTy Results;
6680 if (!getCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
6681 DL, TTI))
6682 return false;
6683
6684 // Only one value per case is permitted.
6685 if (Results.size() > 1)
6686 return false;
6687
6688 // Add the case->result mapping to UniqueResults.
6689 const size_t NumCasesForResult =
6690 mapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
6691
6692 // Early out if there are too many cases for this result.
6693 if (NumCasesForResult > MaxSwitchCasesPerResult)
6694 return false;
6695
6696 // Early out if there are too many unique results.
6697 if (UniqueResults.size() > MaxUniqueResults)
6698 return false;
6699
6700 // Check the PHI consistency.
6701 if (!PHI)
6702 PHI = Results[0].first;
6703 else if (PHI != Results[0].first)
6704 return false;
6705 }
6706 // Find the default result value.
6708 getCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
6709 DL, TTI);
6710 // If the default value is not found abort unless the default destination
6711 // is unreachable.
6712 DefaultResult =
6713 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
6714
6715 return DefaultResult || SI->defaultDestUnreachable();
6716}
6717
6718// Helper function that checks if it is possible to transform a switch with only
6719// two cases (or two cases + default) that produces a result into a select.
6720// TODO: Handle switches with more than 2 cases that map to the same result.
6721// The branch weights correspond to the provided Condition (i.e. if Condition is
6722// modified from the original SwitchInst, the caller must adjust the weights)
6723static Value *foldSwitchToSelect(const SwitchCaseResultVectorTy &ResultVector,
6724 Constant *DefaultResult, Value *Condition,
6725 IRBuilder<> &Builder, const DataLayout &DL,
6726 ArrayRef<uint32_t> BranchWeights) {
6727 // If we are selecting between only two cases transform into a simple
6728 // select or a two-way select if default is possible.
6729 // Example:
6730 // switch (a) { %0 = icmp eq i32 %a, 10
6731 // case 10: return 42; %1 = select i1 %0, i32 42, i32 4
6732 // case 20: return 2; ----> %2 = icmp eq i32 %a, 20
6733 // default: return 4; %3 = select i1 %2, i32 2, i32 %1
6734 // }
6735
6736 const bool HasBranchWeights =
6737 !BranchWeights.empty() && !ProfcheckDisableMetadataFixes;
6738
6739 if (ResultVector.size() == 2 && ResultVector[0].second.size() == 1 &&
6740 ResultVector[1].second.size() == 1) {
6741 ConstantInt *FirstCase = ResultVector[0].second[0];
6742 ConstantInt *SecondCase = ResultVector[1].second[0];
6743 Value *SelectValue = ResultVector[1].first;
6744 if (DefaultResult) {
6745 Value *ValueCompare =
6746 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
6747 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
6748 DefaultResult, "switch.select");
6749 if (auto *SI = dyn_cast<SelectInst>(SelectValue);
6750 SI && HasBranchWeights) {
6751 // We start with 3 probabilities, where the numerator is the
6752 // corresponding BranchWeights[i], and the denominator is the sum over
6753 // BranchWeights. We want the probability and negative probability of
6754 // Condition == SecondCase.
6755 assert(BranchWeights.size() == 3);
6757 *SI, {BranchWeights[2], BranchWeights[0] + BranchWeights[1]},
6758 /*IsExpected=*/false, /*ElideAllZero=*/true);
6759 }
6760 }
6761 Value *ValueCompare =
6762 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
6763 Value *Ret = Builder.CreateSelect(ValueCompare, ResultVector[0].first,
6764 SelectValue, "switch.select");
6765 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6766 // We may have had a DefaultResult. Base the position of the first and
6767 // second's branch weights accordingly. Also the proability that Condition
6768 // != FirstCase needs to take that into account.
6769 assert(BranchWeights.size() >= 2);
6770 size_t FirstCasePos = (Condition != nullptr);
6771 size_t SecondCasePos = FirstCasePos + 1;
6772 uint32_t DefaultCase = (Condition != nullptr) ? BranchWeights[0] : 0;
6774 {BranchWeights[FirstCasePos],
6775 DefaultCase + BranchWeights[SecondCasePos]},
6776 /*IsExpected=*/false, /*ElideAllZero=*/true);
6777 }
6778 return Ret;
6779 }
6780
6781 // Handle the degenerate case where two cases have the same result value.
6782 if (ResultVector.size() == 1 && DefaultResult) {
6783 ArrayRef<ConstantInt *> CaseValues = ResultVector[0].second;
6784 unsigned CaseCount = CaseValues.size();
6785 // n bits group cases map to the same result:
6786 // case 0,4 -> Cond & 0b1..1011 == 0 ? result : default
6787 // case 0,2,4,6 -> Cond & 0b1..1001 == 0 ? result : default
6788 // case 0,2,8,10 -> Cond & 0b1..0101 == 0 ? result : default
6789 if (isPowerOf2_32(CaseCount)) {
6790 ConstantInt *MinCaseVal = CaseValues[0];
6791 // If there are bits that are set exclusively by CaseValues, we
6792 // can transform the switch into a select if the conjunction of
6793 // all the values uniquely identify CaseValues.
6794 APInt AndMask = APInt::getAllOnes(MinCaseVal->getBitWidth());
6795
6796 // Find the minimum value and compute the and of all the case values.
6797 for (auto *Case : CaseValues) {
6798 if (Case->getValue().slt(MinCaseVal->getValue()))
6799 MinCaseVal = Case;
6800 AndMask &= Case->getValue();
6801 }
6802 KnownBits Known = computeKnownBits(Condition, DL);
6803
6804 if (!AndMask.isZero() && Known.getMaxValue().uge(AndMask)) {
6805 // Compute the number of bits that are free to vary.
6806 unsigned FreeBits = Known.countMaxActiveBits() - AndMask.popcount();
6807
6808 // Check if the number of values covered by the mask is equal
6809 // to the number of cases.
6810 if (FreeBits == Log2_32(CaseCount)) {
6811 Value *And = Builder.CreateAnd(Condition, AndMask);
6812 Value *Cmp = Builder.CreateICmpEQ(
6813 And, Constant::getIntegerValue(And->getType(), AndMask));
6814 Value *Ret =
6815 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6816 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6817 // We know there's a Default case. We base the resulting branch
6818 // weights off its probability.
6819 assert(BranchWeights.size() >= 2);
6821 *SI,
6822 {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6823 /*IsExpected=*/false, /*ElideAllZero=*/true);
6824 }
6825 return Ret;
6826 }
6827 }
6828
6829 // Mark the bits case number touched.
6830 APInt BitMask = APInt::getZero(MinCaseVal->getBitWidth());
6831 for (auto *Case : CaseValues)
6832 BitMask |= (Case->getValue() - MinCaseVal->getValue());
6833
6834 // Check if cases with the same result can cover all number
6835 // in touched bits.
6836 if (BitMask.popcount() == Log2_32(CaseCount)) {
6837 if (!MinCaseVal->isNullValue())
6838 Condition = Builder.CreateSub(Condition, MinCaseVal);
6839 Value *And = Builder.CreateAnd(Condition, ~BitMask, "switch.and");
6840 Value *Cmp = Builder.CreateICmpEQ(
6841 And, Constant::getNullValue(And->getType()), "switch.selectcmp");
6842 Value *Ret =
6843 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6844 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6845 assert(BranchWeights.size() >= 2);
6847 *SI,
6848 {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6849 /*IsExpected=*/false, /*ElideAllZero=*/true);
6850 }
6851 return Ret;
6852 }
6853 }
6854
6855 // Handle the degenerate case where two cases have the same value.
6856 if (CaseValues.size() == 2) {
6857 Value *Cmp1 = Builder.CreateICmpEQ(Condition, CaseValues[0],
6858 "switch.selectcmp.case1");
6859 Value *Cmp2 = Builder.CreateICmpEQ(Condition, CaseValues[1],
6860 "switch.selectcmp.case2");
6861 Value *Cmp = Builder.CreateOr(Cmp1, Cmp2, "switch.selectcmp");
6862 Value *Ret =
6863 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6864 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6865 assert(BranchWeights.size() >= 2);
6867 *SI, {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6868 /*IsExpected=*/false, /*ElideAllZero=*/true);
6869 }
6870 return Ret;
6871 }
6872 }
6873
6874 return nullptr;
6875}
6876
6877// Helper function to cleanup a switch instruction that has been converted into
6878// a select, fixing up PHI nodes and basic blocks.
6880 Value *SelectValue,
6881 IRBuilder<> &Builder,
6882 DomTreeUpdater *DTU) {
6883 std::vector<DominatorTree::UpdateType> Updates;
6884
6885 BasicBlock *SelectBB = SI->getParent();
6886 BasicBlock *DestBB = PHI->getParent();
6887
6888 if (DTU && !is_contained(predecessors(DestBB), SelectBB))
6889 Updates.push_back({DominatorTree::Insert, SelectBB, DestBB});
6890 Builder.CreateBr(DestBB);
6891
6892 // Remove the switch.
6893
6894 PHI->removeIncomingValueIf(
6895 [&](unsigned Idx) { return PHI->getIncomingBlock(Idx) == SelectBB; });
6896 PHI->addIncoming(SelectValue, SelectBB);
6897
6898 SmallPtrSet<BasicBlock *, 4> RemovedSuccessors;
6899 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
6900 BasicBlock *Succ = SI->getSuccessor(i);
6901
6902 if (Succ == DestBB)
6903 continue;
6904 Succ->removePredecessor(SelectBB);
6905 if (DTU && RemovedSuccessors.insert(Succ).second)
6906 Updates.push_back({DominatorTree::Delete, SelectBB, Succ});
6907 }
6908 SI->eraseFromParent();
6909 if (DTU)
6910 DTU->applyUpdates(Updates);
6911}
6912
6913/// If a switch is only used to initialize one or more phi nodes in a common
6914/// successor block with only two different constant values, try to replace the
6915/// switch with a select. Returns true if the fold was made.
6917 DomTreeUpdater *DTU, const DataLayout &DL,
6918 const TargetTransformInfo &TTI) {
6919 Value *const Cond = SI->getCondition();
6920 PHINode *PHI = nullptr;
6921 BasicBlock *CommonDest = nullptr;
6922 Constant *DefaultResult;
6923 SwitchCaseResultVectorTy UniqueResults;
6924 // Collect all the cases that will deliver the same value from the switch.
6925 if (!initializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
6926 DL, TTI, /*MaxUniqueResults*/ 2))
6927 return false;
6928
6929 assert(PHI != nullptr && "PHI for value select not found");
6930 Builder.SetInsertPoint(SI);
6931 SmallVector<uint32_t, 4> BranchWeights;
6933 [[maybe_unused]] auto HasWeights =
6935 assert(!HasWeights == (BranchWeights.empty()));
6936 }
6937 assert(BranchWeights.empty() ||
6938 (BranchWeights.size() >=
6939 UniqueResults.size() + (DefaultResult != nullptr)));
6940
6941 Value *SelectValue = foldSwitchToSelect(UniqueResults, DefaultResult, Cond,
6942 Builder, DL, BranchWeights);
6943 if (!SelectValue)
6944 return false;
6945
6946 removeSwitchAfterSelectFold(SI, PHI, SelectValue, Builder, DTU);
6947 return true;
6948}
6949
6950namespace {
6951
6952/// This class finds alternatives for switches to ultimately
6953/// replace the switch.
6954class SwitchReplacement {
6955public:
6956 /// Create a helper for optimizations to use as a switch replacement.
6957 /// Find a better representation for the content of Values,
6958 /// using DefaultValue to fill any holes in the table.
6959 SwitchReplacement(
6960 Module &M, uint64_t TableSize, ConstantInt *Offset,
6961 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
6962 Constant *DefaultValue, const DataLayout &DL,
6963 const TargetTransformInfo &TTI, const StringRef &FuncName);
6964
6965 /// Build instructions with Builder to retrieve values using Index
6966 /// and replace the switch.
6967 Value *replaceSwitch(Value *Index, IRBuilder<> &Builder, const DataLayout &DL,
6968 Function *Func);
6969
6970 /// Return true if a table with TableSize elements of
6971 /// type ElementType would fit in a target-legal register.
6972 static bool wouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
6973 Type *ElementType);
6974
6975 /// Return the default value of the switch.
6976 Constant *getDefaultValue();
6977
6978 /// Return true if the replacement is a lookup table.
6979 bool isLookupTable();
6980
6981 /// Return true if the replacement is a bit map.
6982 bool isBitMap();
6983
6984private:
6985 // Depending on the switch, there are different alternatives.
6986 enum {
6987 // For switches where each case contains the same value, we just have to
6988 // store that single value and return it for each lookup.
6989 SingleValueKind,
6990
6991 // For switches where there is a linear relationship between table index
6992 // and values. We calculate the result with a simple multiplication
6993 // and addition instead of a table lookup.
6994 LinearMapKind,
6995
6996 // For small tables with integer elements, we can pack them into a bitmap
6997 // that fits into a target-legal register. Values are retrieved by
6998 // shift and mask operations.
6999 BitMapKind,
7000
7001 // The table is stored as an array of values. Values are retrieved by load
7002 // instructions from the table.
7003 LookupTableKind
7004 } Kind;
7005
7006 // The default value of the switch.
7007 Constant *DefaultValue;
7008
7009 // The type of the output values.
7010 Type *ValueType;
7011
7012 // For SingleValueKind, this is the single value.
7013 Constant *SingleValue = nullptr;
7014
7015 // For BitMapKind, this is the bitmap.
7016 ConstantInt *BitMap = nullptr;
7017 IntegerType *BitMapElementTy = nullptr;
7018
7019 // For LinearMapKind, these are the constants used to derive the value.
7020 ConstantInt *LinearOffset = nullptr;
7021 ConstantInt *LinearMultiplier = nullptr;
7022 bool LinearMapValWrapped = false;
7023
7024 // For LookupTableKind, this is the table.
7025 Constant *Initializer = nullptr;
7026};
7027
7028} // end anonymous namespace
7029
7030SwitchReplacement::SwitchReplacement(
7031 Module &M, uint64_t TableSize, ConstantInt *Offset,
7032 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
7033 Constant *DefaultValue, const DataLayout &DL,
7034 const TargetTransformInfo &TTI, const StringRef &FuncName)
7035 : DefaultValue(DefaultValue) {
7036 assert(Values.size() && "Can't build lookup table without values!");
7037 assert(TableSize >= Values.size() && "Can't fit values in table!");
7038
7039 // If all values in the table are equal, this is that value.
7040 SingleValue = Values.begin()->second;
7041
7042 ValueType = Values.begin()->second->getType();
7043
7044 // Build up the table contents.
7045 SmallVector<Constant *, 64> TableContents(TableSize);
7046 for (const auto &[CaseVal, CaseRes] : Values) {
7047 assert(CaseRes->getType() == ValueType);
7048
7049 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
7050 TableContents[Idx] = CaseRes;
7051
7052 if (SingleValue && !isa<PoisonValue>(CaseRes) && CaseRes != SingleValue)
7053 SingleValue = isa<PoisonValue>(SingleValue) ? CaseRes : nullptr;
7054 }
7055
7056 // Fill in any holes in the table with the default result.
7057 if (Values.size() < TableSize) {
7058 assert(DefaultValue &&
7059 "Need a default value to fill the lookup table holes.");
7060 assert(DefaultValue->getType() == ValueType);
7061 for (uint64_t I = 0; I < TableSize; ++I) {
7062 if (!TableContents[I])
7063 TableContents[I] = DefaultValue;
7064 }
7065
7066 // If the default value is poison, all the holes are poison.
7067 bool DefaultValueIsPoison = isa<PoisonValue>(DefaultValue);
7068
7069 if (DefaultValue != SingleValue && !DefaultValueIsPoison)
7070 SingleValue = nullptr;
7071 }
7072
7073 // If each element in the table contains the same value, we only need to store
7074 // that single value.
7075 if (SingleValue) {
7076 Kind = SingleValueKind;
7077 return;
7078 }
7079
7080 // Check if we can derive the value with a linear transformation from the
7081 // table index.
7083 bool LinearMappingPossible = true;
7084 APInt PrevVal;
7085 APInt DistToPrev;
7086 // When linear map is monotonic and signed overflow doesn't happen on
7087 // maximum index, we can attach nsw on Add and Mul.
7088 bool NonMonotonic = false;
7089 assert(TableSize >= 2 && "Should be a SingleValue table.");
7090 // Check if there is the same distance between two consecutive values.
7091 for (uint64_t I = 0; I < TableSize; ++I) {
7092 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
7093
7094 if (!ConstVal && isa<PoisonValue>(TableContents[I])) {
7095 // This is an poison, so it's (probably) a lookup table hole.
7096 // To prevent any regressions from before we switched to using poison as
7097 // the default value, holes will fall back to using the first value.
7098 // This can be removed once we add proper handling for poisons in lookup
7099 // tables.
7100 ConstVal = dyn_cast<ConstantInt>(Values[0].second);
7101 }
7102
7103 if (!ConstVal) {
7104 // This is an undef. We could deal with it, but undefs in lookup tables
7105 // are very seldom. It's probably not worth the additional complexity.
7106 LinearMappingPossible = false;
7107 break;
7108 }
7109 const APInt &Val = ConstVal->getValue();
7110 if (I != 0) {
7111 APInt Dist = Val - PrevVal;
7112 if (I == 1) {
7113 DistToPrev = Dist;
7114 } else if (Dist != DistToPrev) {
7115 LinearMappingPossible = false;
7116 break;
7117 }
7118 NonMonotonic |=
7119 Dist.isStrictlyPositive() ? Val.sle(PrevVal) : Val.sgt(PrevVal);
7120 }
7121 PrevVal = Val;
7122 }
7123 if (LinearMappingPossible) {
7124 LinearOffset = cast<ConstantInt>(TableContents[0]);
7125 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
7126 APInt M = LinearMultiplier->getValue();
7127 bool MayWrap = true;
7128 if (isIntN(M.getBitWidth(), TableSize - 1))
7129 (void)M.smul_ov(APInt(M.getBitWidth(), TableSize - 1), MayWrap);
7130 LinearMapValWrapped = NonMonotonic || MayWrap;
7131 Kind = LinearMapKind;
7132 return;
7133 }
7134 }
7135
7136 // If the type is integer and the table fits in a register, build a bitmap.
7137 if (wouldFitInRegister(DL, TableSize, ValueType)) {
7139 APInt TableInt(TableSize * IT->getBitWidth(), 0);
7140 for (uint64_t I = TableSize; I > 0; --I) {
7141 TableInt <<= IT->getBitWidth();
7142 // Insert values into the bitmap. Undef values are set to zero.
7143 if (!isa<UndefValue>(TableContents[I - 1])) {
7144 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
7145 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
7146 }
7147 }
7148 BitMap = ConstantInt::get(M.getContext(), TableInt);
7149 BitMapElementTy = IT;
7150 Kind = BitMapKind;
7151 return;
7152 }
7153
7154 if (auto *IT = dyn_cast<IntegerType>(ValueType)) {
7155 ConstantRange Range(IT->getBitWidth(), false);
7156 for (Constant *Value : TableContents)
7157 if (!isa<UndefValue>(Value))
7158 Range = Range.unionWith(cast<ConstantInt>(Value)->getValue());
7159 // TODO: handle sign extension as well?
7160 unsigned NeededBitWidth =
7161 std::max(TTI.getMinimumLookupTableEntryBitWidth(),
7162 unsigned(PowerOf2Ceil(Range.getActiveBits())));
7163 if (NeededBitWidth < IT->getBitWidth()) {
7164 IntegerType *DstTy = IntegerType::get(IT->getContext(), NeededBitWidth);
7165 for (Constant *&Value : TableContents)
7166 Value = ConstantFoldCastInstruction(Instruction::Trunc, Value, DstTy);
7167 }
7168 }
7169
7170 // Store the table in an array.
7171 auto *TableTy = ArrayType::get(TableContents[0]->getType(), TableSize);
7172 Initializer = ConstantArray::get(TableTy, TableContents);
7173
7174 Kind = LookupTableKind;
7175}
7176
7177Value *SwitchReplacement::replaceSwitch(Value *Index, IRBuilder<> &Builder,
7178 const DataLayout &DL, Function *Func) {
7179 switch (Kind) {
7180 case SingleValueKind:
7181 return SingleValue;
7182 case LinearMapKind: {
7183 ++NumLinearMaps;
7184 // Derive the result value from the input value.
7185 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
7186 false, "switch.idx.cast");
7187 if (!LinearMultiplier->isOne())
7188 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult",
7189 /*HasNUW = */ false,
7190 /*HasNSW = */ !LinearMapValWrapped);
7191
7192 if (!LinearOffset->isZero())
7193 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset",
7194 /*HasNUW = */ false,
7195 /*HasNSW = */ !LinearMapValWrapped);
7196 return Result;
7197 }
7198 case BitMapKind: {
7199 ++NumBitMaps;
7200 // Type of the bitmap (e.g. i59).
7201 IntegerType *MapTy = BitMap->getIntegerType();
7202
7203 // Cast Index to the same type as the bitmap.
7204 // Note: The Index is <= the number of elements in the table, so
7205 // truncating it to the width of the bitmask is safe.
7206 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
7207
7208 // Multiply the shift amount by the element width. NUW/NSW can always be
7209 // set, because wouldFitInRegister guarantees Index * ShiftAmt is in
7210 // BitMap's bit width.
7211 ShiftAmt = Builder.CreateMul(
7212 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
7213 "switch.shiftamt",/*HasNUW =*/true,/*HasNSW =*/true);
7214
7215 // Shift down.
7216 Value *DownShifted =
7217 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
7218 // Mask off.
7219 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
7220 }
7221 case LookupTableKind: {
7222 ++NumLookupTables;
7223 auto *Table =
7224 new GlobalVariable(*Func->getParent(), Initializer->getType(),
7225 /*isConstant=*/true, GlobalVariable::PrivateLinkage,
7226 Initializer, "switch.table." + Func->getName());
7227 Table->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
7228 // Set the alignment to that of an array items. We will be only loading one
7229 // value out of it.
7230 Table->setAlignment(DL.getPrefTypeAlign(ValueType));
7231 Type *IndexTy = DL.getIndexType(Table->getType());
7232 auto *ArrayTy = cast<ArrayType>(Table->getValueType());
7233
7234 if (Index->getType() != IndexTy) {
7235 unsigned OldBitWidth = Index->getType()->getIntegerBitWidth();
7236 Index = Builder.CreateZExtOrTrunc(Index, IndexTy);
7237 if (auto *Zext = dyn_cast<ZExtInst>(Index))
7238 Zext->setNonNeg(
7239 isUIntN(OldBitWidth - 1, ArrayTy->getNumElements() - 1));
7240 }
7241
7242 Value *GEPIndices[] = {ConstantInt::get(IndexTy, 0), Index};
7243 Value *GEP =
7244 Builder.CreateInBoundsGEP(ArrayTy, Table, GEPIndices, "switch.gep");
7245 Value *Load =
7246 Builder.CreateLoad(ArrayTy->getElementType(), GEP, "switch.load");
7247 if (Load->getType() == ValueType)
7248 return Load;
7249 return Builder.CreateZExt(Load, ValueType, "switch.ext");
7250 }
7251 }
7252 llvm_unreachable("Unknown helper kind!");
7253}
7254
7255bool SwitchReplacement::wouldFitInRegister(const DataLayout &DL,
7256 uint64_t TableSize,
7257 Type *ElementType) {
7258 auto *IT = dyn_cast<IntegerType>(ElementType);
7259 if (!IT)
7260 return false;
7261 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
7262 // are <= 15, we could try to narrow the type.
7263
7264 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
7265 if (TableSize >= UINT_MAX / IT->getBitWidth())
7266 return false;
7267 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
7268}
7269
7271 const DataLayout &DL) {
7272 // Allow any legal type.
7273 if (TTI.isTypeLegal(Ty))
7274 return true;
7275
7276 auto *IT = dyn_cast<IntegerType>(Ty);
7277 if (!IT)
7278 return false;
7279
7280 // Also allow power of 2 integer types that have at least 8 bits and fit in
7281 // a register. These types are common in frontend languages and targets
7282 // usually support loads of these types.
7283 // TODO: We could relax this to any integer that fits in a register and rely
7284 // on ABI alignment and padding in the table to allow the load to be widened.
7285 // Or we could widen the constants and truncate the load.
7286 unsigned BitWidth = IT->getBitWidth();
7287 return BitWidth >= 8 && isPowerOf2_32(BitWidth) &&
7288 DL.fitsInLegalInteger(IT->getBitWidth());
7289}
7290
7291Constant *SwitchReplacement::getDefaultValue() { return DefaultValue; }
7292
7293bool SwitchReplacement::isLookupTable() { return Kind == LookupTableKind; }
7294
7295bool SwitchReplacement::isBitMap() { return Kind == BitMapKind; }
7296
7297static bool isSwitchDense(uint64_t NumCases, uint64_t CaseRange, bool OptSize) {
7298 // 40% is the default density for building a jump table in optsize/minsize
7299 // mode, 10% is the default density for jump tables. See also
7300 // TargetLoweringBase::isSuitableForJumpTable(), which this function was based
7301 // on.
7302 const uint64_t MinDensity = OptSize ? 40 : 10;
7303
7304 if (CaseRange >= UINT64_MAX / 100)
7305 return false; // Avoid multiplication overflows below.
7306
7307 return NumCases * 100 >= CaseRange * MinDensity;
7308}
7309
7310static bool isSwitchDense(ArrayRef<int64_t> Values, bool OptSize) {
7311 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
7312 uint64_t Range = Diff + 1;
7313 if (Range < Diff)
7314 return false; // Overflow.
7315
7316 return isSwitchDense(Values.size(), Range, OptSize);
7317}
7318
7319static std::optional<unsigned>
7321 bool OptSize) {
7322 assert(Values.size() > 1 && "expected multiple switch cases");
7323 if (!llvm::all_of(Values, [Base](int64_t V) { return V >= Base; }))
7324 return std::nullopt;
7325
7326 // First, transform the values by subtracting Base.
7327 SmallVector<int64_t, 4> ReducedValues(Values);
7328 uint64_t ReducedValuesOr = 0;
7329 for (auto &V : ReducedValues) {
7330 uint64_t Reduced = (uint64_t)V - (uint64_t)Base;
7331 ReducedValuesOr |= Reduced;
7332 V = (int64_t)Reduced;
7333 }
7334
7335 // Conceptually, the reduced values are non-negative distances from Base.
7336 // Since the rest of the transform is bitwise only, treat them as unsigned
7337 // bit patterns from here.
7338
7339 // countr_zero(0) returns 64. As Values is guaranteed to have more than
7340 // one element and LLVM disallows duplicate cases, ReducedValuesOr will
7341 // have at least one bit set, so Shift will be less than 64.
7342 unsigned Shift = llvm::countr_zero(ReducedValuesOr);
7343 assert(Shift < 64);
7344 if (Shift > 0)
7345 for (auto &V : ReducedValues)
7346 V = (int64_t)((uint64_t)V >> Shift);
7347
7348 if (!isSwitchDense(ReducedValues, OptSize))
7349 return std::nullopt;
7350
7351 return Shift;
7352}
7353
7354/// Determine whether a lookup table should be built for this switch, based on
7355/// the number of cases, size of the table, and the types of the results.
7356// TODO: We could support larger than legal types by limiting based on the
7357// number of loads required and/or table size. If the constants are small we
7358// could use smaller table entries and extend after the load.
7360 const TargetTransformInfo &TTI,
7361 const DataLayout &DL,
7362 const SmallVector<Type *> &ResultTypes) {
7363 if (SI->getNumCases() > TableSize)
7364 return false; // TableSize overflowed.
7365
7366 bool AllTablesFitInRegister = true;
7367 bool HasIllegalType = false;
7368 for (const auto &Ty : ResultTypes) {
7369 // Saturate this flag to true.
7370 HasIllegalType = HasIllegalType || !isTypeLegalForLookupTable(Ty, TTI, DL);
7371
7372 // Saturate this flag to false.
7373 AllTablesFitInRegister =
7374 AllTablesFitInRegister &&
7375 SwitchReplacement::wouldFitInRegister(DL, TableSize, Ty);
7376
7377 // If both flags saturate, we're done. NOTE: This *only* works with
7378 // saturating flags, and all flags have to saturate first due to the
7379 // non-deterministic behavior of iterating over a dense map.
7380 if (HasIllegalType && !AllTablesFitInRegister)
7381 break;
7382 }
7383
7384 // If each table would fit in a register, we should build it anyway.
7385 if (AllTablesFitInRegister)
7386 return true;
7387
7388 // Don't build a table that doesn't fit in-register if it has illegal types.
7389 if (HasIllegalType)
7390 return false;
7391
7392 return isSwitchDense(SI->getNumCases(), TableSize,
7393 SI->getFunction()->hasOptSize());
7394}
7395
7397 ConstantInt &MinCaseVal, const ConstantInt &MaxCaseVal,
7398 bool HasDefaultResults, const SmallVector<Type *> &ResultTypes,
7399 const DataLayout &DL, const TargetTransformInfo &TTI) {
7400 if (MinCaseVal.isNullValue())
7401 return true;
7402 if (MinCaseVal.isNegative() ||
7403 MaxCaseVal.getLimitedValue() == std::numeric_limits<uint64_t>::max() ||
7404 !HasDefaultResults)
7405 return false;
7406 return all_of(ResultTypes, [&](const auto &ResultType) {
7407 return SwitchReplacement::wouldFitInRegister(
7408 DL, MaxCaseVal.getLimitedValue() + 1 /* TableSize */, ResultType);
7409 });
7410}
7411
7412/// Try to reuse the switch table index compare. Following pattern:
7413/// \code
7414/// if (idx < tablesize)
7415/// r = table[idx]; // table does not contain default_value
7416/// else
7417/// r = default_value;
7418/// if (r != default_value)
7419/// ...
7420/// \endcode
7421/// Is optimized to:
7422/// \code
7423/// cond = idx < tablesize;
7424/// if (cond)
7425/// r = table[idx];
7426/// else
7427/// r = default_value;
7428/// if (cond)
7429/// ...
7430/// \endcode
7431/// Jump threading will then eliminate the second if(cond).
7433 User *PhiUser, BasicBlock *PhiBlock, CondBrInst *RangeCheckBranch,
7434 Constant *DefaultValue,
7435 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
7437 if (!CmpInst)
7438 return;
7439
7440 // We require that the compare is in the same block as the phi so that jump
7441 // threading can do its work afterwards.
7442 if (CmpInst->getParent() != PhiBlock)
7443 return;
7444
7446 if (!CmpOp1)
7447 return;
7448
7449 Value *RangeCmp = RangeCheckBranch->getCondition();
7450 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
7451 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
7452
7453 // Check if the compare with the default value is constant true or false.
7454 const DataLayout &DL = PhiBlock->getDataLayout();
7456 CmpInst->getPredicate(), DefaultValue, CmpOp1, DL);
7457 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
7458 return;
7459
7460 // Check if the compare with the case values is distinct from the default
7461 // compare result.
7462 for (auto ValuePair : Values) {
7464 CmpInst->getPredicate(), ValuePair.second, CmpOp1, DL);
7465 if (!CaseConst || CaseConst == DefaultConst ||
7466 (CaseConst != TrueConst && CaseConst != FalseConst))
7467 return;
7468 }
7469
7470 // Check if the branch instruction dominates the phi node. It's a simple
7471 // dominance check, but sufficient for our needs.
7472 // Although this check is invariant in the calling loops, it's better to do it
7473 // at this late stage. Practically we do it at most once for a switch.
7474 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
7475 for (BasicBlock *Pred : predecessors(PhiBlock)) {
7476 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
7477 return;
7478 }
7479
7480 if (DefaultConst == FalseConst) {
7481 // The compare yields the same result. We can replace it.
7482 CmpInst->replaceAllUsesWith(RangeCmp);
7483 ++NumTableCmpReuses;
7484 } else {
7485 // The compare yields the same result, just inverted. We can replace it.
7486 Value *InvertedTableCmp = BinaryOperator::CreateXor(
7487 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
7488 RangeCheckBranch->getIterator());
7489 CmpInst->replaceAllUsesWith(InvertedTableCmp);
7490 ++NumTableCmpReuses;
7491 }
7492}
7493
7494/// If the switch is only used to initialize one or more phi nodes in a common
7495/// successor block with different constant values, replace the switch with
7496/// lookup tables.
7498 DomTreeUpdater *DTU, const DataLayout &DL,
7499 const TargetTransformInfo &TTI,
7500 bool ConvertSwitchToLookupTable) {
7501 assert(SI->getNumCases() > 1 && "Degenerate switch?");
7502
7503 BasicBlock *BB = SI->getParent();
7504 Function *Fn = BB->getParent();
7505
7506 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
7507 // split off a dense part and build a lookup table for that.
7508
7509 // FIXME: This creates arrays of GEPs to constant strings, which means each
7510 // GEP needs a runtime relocation in PIC code. We should just build one big
7511 // string and lookup indices into that.
7512
7513 // Ignore switches with less than three cases. Lookup tables will not make
7514 // them faster, so we don't analyze them.
7515 if (SI->getNumCases() < 3)
7516 return false;
7517
7518 // Figure out the corresponding result for each case value and phi node in the
7519 // common destination, as well as the min and max case values.
7520 assert(!SI->cases().empty());
7521 SwitchInst::CaseIt CI = SI->case_begin();
7522 ConstantInt *MinCaseVal = CI->getCaseValue();
7523 ConstantInt *MaxCaseVal = CI->getCaseValue();
7524
7525 BasicBlock *CommonDest = nullptr;
7526
7527 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
7529
7531 SmallVector<Type *> ResultTypes;
7533
7534 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
7535 ConstantInt *CaseVal = CI->getCaseValue();
7536 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
7537 MinCaseVal = CaseVal;
7538 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
7539 MaxCaseVal = CaseVal;
7540
7541 // Resulting value at phi nodes for this case value.
7543 ResultsTy Results;
7544 if (!getCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
7545 Results, DL, TTI))
7546 return false;
7547
7548 // Append the result and result types from this case to the list for each
7549 // phi.
7550 for (const auto &I : Results) {
7551 PHINode *PHI = I.first;
7552 Constant *Value = I.second;
7553 auto [It, Inserted] = ResultLists.try_emplace(PHI);
7554 if (Inserted)
7555 PHIs.push_back(PHI);
7556 It->second.push_back(std::make_pair(CaseVal, Value));
7557 ResultTypes.push_back(PHI->getType());
7558 }
7559 }
7560
7561 // If the table has holes, we need a constant result for the default case
7562 // or a bitmask that fits in a register.
7563 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
7564 bool HasDefaultResults =
7565 getCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
7566 DefaultResultsList, DL, TTI);
7567 for (const auto &I : DefaultResultsList) {
7568 PHINode *PHI = I.first;
7569 Constant *Result = I.second;
7570 DefaultResults[PHI] = Result;
7571 }
7572
7573 bool UseSwitchConditionAsTableIndex = shouldUseSwitchConditionAsTableIndex(
7574 *MinCaseVal, *MaxCaseVal, HasDefaultResults, ResultTypes, DL, TTI);
7575 uint64_t TableSize;
7576 ConstantInt *TableIndexOffset;
7577 if (UseSwitchConditionAsTableIndex) {
7578 TableSize = MaxCaseVal->getLimitedValue() + 1;
7579 TableIndexOffset = ConstantInt::get(MaxCaseVal->getIntegerType(), 0);
7580 } else {
7581 TableSize =
7582 (MaxCaseVal->getValue() - MinCaseVal->getValue()).getLimitedValue() + 1;
7583
7584 TableIndexOffset = MinCaseVal;
7585 }
7586
7587 // If the default destination is unreachable, or if the lookup table covers
7588 // all values of the conditional variable, branch directly to the lookup table
7589 // BB. Otherwise, check that the condition is within the case range.
7590 uint64_t NumResults = ResultLists[PHIs[0]].size();
7591 bool DefaultIsReachable = !SI->defaultDestUnreachable();
7592
7593 bool TableHasHoles = (NumResults < TableSize);
7594
7595 // If the table has holes but the default destination doesn't produce any
7596 // constant results, the lookup table entries corresponding to the holes will
7597 // contain poison.
7598 bool AllHolesArePoison = TableHasHoles && !HasDefaultResults;
7599
7600 // If the default destination doesn't produce a constant result but is still
7601 // reachable, and the lookup table has holes, we need to use a mask to
7602 // determine if the current index should load from the lookup table or jump
7603 // to the default case.
7604 // The mask is unnecessary if the table has holes but the default destination
7605 // is unreachable, as in that case the holes must also be unreachable.
7606 bool NeedMask = AllHolesArePoison && DefaultIsReachable;
7607 if (NeedMask) {
7608 // As an extra penalty for the validity test we require more cases.
7609 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
7610 return false;
7611 if (!DL.fitsInLegalInteger(TableSize))
7612 return false;
7613 }
7614
7615 if (!shouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
7616 return false;
7617
7618 // Compute the table index value.
7619 Value *TableIndex;
7620 if (UseSwitchConditionAsTableIndex) {
7621 TableIndex = SI->getCondition();
7622 if (HasDefaultResults) {
7623 // Grow the table to cover all possible index values to avoid the range
7624 // check. It will use the default result to fill in the table hole later,
7625 // so make sure it exist.
7626 ConstantRange CR = computeConstantRange(TableIndex, /*ForSigned=*/false,
7627 SimplifyQuery(DL));
7628 // Grow the table shouldn't have any size impact by checking
7629 // wouldFitInRegister.
7630 // TODO: Consider growing the table also when it doesn't fit in a register
7631 // if no optsize is specified.
7632 const uint64_t UpperBound = CR.getUpper().getLimitedValue();
7633 if (!CR.isUpperWrapped() &&
7634 all_of(ResultTypes, [&](const auto &ResultType) {
7635 return SwitchReplacement::wouldFitInRegister(DL, UpperBound,
7636 ResultType);
7637 })) {
7638 // There may be some case index larger than the UpperBound (unreachable
7639 // case), so make sure the table size does not get smaller.
7640 TableSize = std::max(UpperBound, TableSize);
7641 // The default branch is unreachable after we enlarge the lookup table.
7642 // Adjust DefaultIsReachable to reuse code path.
7643 DefaultIsReachable = false;
7644 }
7645 }
7646 }
7647
7648 // Keep track of the switch replacement for each phi
7650 for (PHINode *PHI : PHIs) {
7651 const auto &ResultList = ResultLists[PHI];
7652
7653 Type *ResultType = ResultList.begin()->second->getType();
7654 // Use any value to fill the lookup table holes.
7655 Constant *DefaultVal =
7656 AllHolesArePoison ? PoisonValue::get(ResultType) : DefaultResults[PHI];
7657 StringRef FuncName = Fn->getName();
7658 SwitchReplacement Replacement(*Fn->getParent(), TableSize, TableIndexOffset,
7659 ResultList, DefaultVal, DL, TTI, FuncName);
7660 PhiToReplacementMap.insert({PHI, Replacement});
7661 }
7662
7663 bool AnyLookupTables = any_of(
7664 PhiToReplacementMap, [](auto &KV) { return KV.second.isLookupTable(); });
7665 bool AnyBitMaps = any_of(PhiToReplacementMap,
7666 [](auto &KV) { return KV.second.isBitMap(); });
7667
7668 // A few conditions prevent the generation of lookup tables:
7669 // 1. The target does not support lookup tables.
7670 // 2. The "no-jump-tables" function attribute is set.
7671 // However, these objections do not apply to other switch replacements, like
7672 // the bitmap, so we only stop here if any of these conditions are met and we
7673 // want to create a LUT. Otherwise, continue with the switch replacement.
7674 if (AnyLookupTables &&
7675 (!TTI.shouldBuildLookupTables() ||
7676 Fn->getFnAttribute("no-jump-tables").getValueAsBool()))
7677 return false;
7678
7679 // In the early optimization pipeline, disable formation of lookup tables,
7680 // bit maps and mask checks, as they may inhibit further optimization.
7681 if (!ConvertSwitchToLookupTable &&
7682 (AnyLookupTables || AnyBitMaps || NeedMask))
7683 return false;
7684
7685 Builder.SetInsertPoint(SI);
7686 // TableIndex is the switch condition - TableIndexOffset if we don't
7687 // use the condition directly
7688 if (!UseSwitchConditionAsTableIndex) {
7689 // If the default is unreachable, all case values are s>= MinCaseVal. Then
7690 // we can try to attach nsw.
7691 bool MayWrap = true;
7692 if (!DefaultIsReachable) {
7693 APInt Res =
7694 MaxCaseVal->getValue().ssub_ov(MinCaseVal->getValue(), MayWrap);
7695 (void)Res;
7696 }
7697 TableIndex = Builder.CreateSub(SI->getCondition(), TableIndexOffset,
7698 "switch.tableidx", /*HasNUW =*/false,
7699 /*HasNSW =*/!MayWrap);
7700 }
7701
7702 std::vector<DominatorTree::UpdateType> Updates;
7703
7704 // Compute the maximum table size representable by the integer type we are
7705 // switching upon.
7706 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
7707 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
7708 assert(MaxTableSize >= TableSize &&
7709 "It is impossible for a switch to have more entries than the max "
7710 "representable value of its input integer type's size.");
7711
7712 // Create the BB that does the lookups.
7713 Module &Mod = *CommonDest->getParent()->getParent();
7714 BasicBlock *LookupBB = BasicBlock::Create(
7715 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
7716
7717 CondBrInst *RangeCheckBranch = nullptr;
7718 CondBrInst *CondBranch = nullptr;
7719
7720 Builder.SetInsertPoint(SI);
7721 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
7722 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
7723 Builder.CreateBr(LookupBB);
7724 if (DTU)
7725 Updates.push_back({DominatorTree::Insert, BB, LookupBB});
7726 // Note: We call removeProdecessor later since we need to be able to get the
7727 // PHI value for the default case in case we're using a bit mask.
7728 } else {
7729 Value *Cmp = Builder.CreateICmpULT(
7730 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
7731 RangeCheckBranch =
7732 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
7733 CondBranch = RangeCheckBranch;
7734 if (DTU)
7735 Updates.push_back({DominatorTree::Insert, BB, LookupBB});
7736 }
7737
7738 // Populate the BB that does the lookups.
7739 Builder.SetInsertPoint(LookupBB);
7740
7741 if (NeedMask) {
7742 // Before doing the lookup, we do the hole check. The LookupBB is therefore
7743 // re-purposed to do the hole check, and we create a new LookupBB.
7744 BasicBlock *MaskBB = LookupBB;
7745 MaskBB->setName("switch.hole_check");
7746 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
7747 CommonDest->getParent(), CommonDest);
7748
7749 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
7750 // unnecessary illegal types.
7751 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
7752 APInt MaskInt(TableSizePowOf2, 0);
7753 APInt One(TableSizePowOf2, 1);
7754 // Build bitmask; fill in a 1 bit for every case.
7755 const ResultListTy &ResultList = ResultLists[PHIs[0]];
7756 for (const auto &Result : ResultList) {
7757 uint64_t Idx = (Result.first->getValue() - TableIndexOffset->getValue())
7758 .getLimitedValue();
7759 MaskInt |= One << Idx;
7760 }
7761 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
7762
7763 // Get the TableIndex'th bit of the bitmask.
7764 // If this bit is 0 (meaning hole) jump to the default destination,
7765 // else continue with table lookup.
7766 IntegerType *MapTy = TableMask->getIntegerType();
7767 Value *MaskIndex =
7768 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
7769 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
7770 Value *LoBit = Builder.CreateTrunc(
7771 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
7772 CondBranch = Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
7773 if (DTU) {
7774 Updates.push_back({DominatorTree::Insert, MaskBB, LookupBB});
7775 Updates.push_back({DominatorTree::Insert, MaskBB, SI->getDefaultDest()});
7776 }
7777 Builder.SetInsertPoint(LookupBB);
7778 addPredecessorToBlock(SI->getDefaultDest(), MaskBB, BB);
7779 }
7780
7781 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
7782 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
7783 // do not delete PHINodes here.
7784 SI->getDefaultDest()->removePredecessor(BB,
7785 /*KeepOneInputPHIs=*/true);
7786 if (DTU)
7787 Updates.push_back({DominatorTree::Delete, BB, SI->getDefaultDest()});
7788 }
7789
7790 for (PHINode *PHI : PHIs) {
7791 const ResultListTy &ResultList = ResultLists[PHI];
7792 auto Replacement = PhiToReplacementMap.at(PHI);
7793 auto *Result = Replacement.replaceSwitch(TableIndex, Builder, DL, Fn);
7794 // Do a small peephole optimization: re-use the switch table compare if
7795 // possible.
7796 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
7797 BasicBlock *PhiBlock = PHI->getParent();
7798 // Search for compare instructions which use the phi.
7799 for (auto *User : PHI->users()) {
7800 reuseTableCompare(User, PhiBlock, RangeCheckBranch,
7801 Replacement.getDefaultValue(), ResultList);
7802 }
7803 }
7804
7805 PHI->addIncoming(Result, LookupBB);
7806 }
7807
7808 Builder.CreateBr(CommonDest);
7809 if (DTU)
7810 Updates.push_back({DominatorTree::Insert, LookupBB, CommonDest});
7811
7812 SmallVector<uint32_t> BranchWeights;
7813 const bool HasBranchWeights = CondBranch && !ProfcheckDisableMetadataFixes &&
7814 extractBranchWeights(*SI, BranchWeights);
7815 uint64_t ToLookupWeight = 0;
7816 uint64_t ToDefaultWeight = 0;
7817
7818 // Remove the switch.
7819 SmallPtrSet<BasicBlock *, 8> RemovedSuccessors;
7820 for (unsigned I = 0, E = SI->getNumSuccessors(); I < E; ++I) {
7821 BasicBlock *Succ = SI->getSuccessor(I);
7822
7823 if (Succ == SI->getDefaultDest()) {
7824 if (HasBranchWeights)
7825 ToDefaultWeight += BranchWeights[I];
7826 continue;
7827 }
7828 Succ->removePredecessor(BB);
7829 if (DTU && RemovedSuccessors.insert(Succ).second)
7830 Updates.push_back({DominatorTree::Delete, BB, Succ});
7831 if (HasBranchWeights)
7832 ToLookupWeight += BranchWeights[I];
7833 }
7834 SI->eraseFromParent();
7835 if (HasBranchWeights)
7836 setFittedBranchWeights(*CondBranch, {ToLookupWeight, ToDefaultWeight},
7837 /*IsExpected=*/false);
7838 if (DTU)
7839 DTU->applyUpdates(Updates);
7840
7841 if (NeedMask)
7842 ++NumLookupTablesHoles;
7843 return true;
7844}
7845
7846/// Try to transform a switch that has "holes" in it to a contiguous sequence
7847/// of cases.
7848///
7849/// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
7850/// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
7851///
7852/// This converts a sparse switch into a dense switch which allows better
7853/// lowering and could also allow transforming into a lookup table.
7855 const DataLayout &DL,
7856 const TargetTransformInfo &TTI) {
7857 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
7858 if (CondTy->getIntegerBitWidth() > 64 ||
7859 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
7860 return false;
7861 // Only bother with this optimization if there are more than 3 switch cases;
7862 // SDAG will only bother creating jump tables for 4 or more cases.
7863 if (SI->getNumCases() < 4)
7864 return false;
7865
7866 // This transform is agnostic to the signedness of the input or case values. We
7867 // can treat the case values as signed or unsigned. We can optimize more common
7868 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
7869 // as signed.
7871 for (const auto &C : SI->cases())
7872 Values.push_back(C.getCaseValue()->getValue().getSExtValue());
7874
7875 // If the switch is already dense, there's nothing useful to do here.
7876 bool OptSize = SI->getFunction()->hasOptSize();
7877 if (isSwitchDense(Values, OptSize))
7878 return false;
7879
7880 // Find a Base and corresponding Shift that results in a dense switch range.
7881 // Values[0] is the local minimum.
7882 int64_t Base = Values[0];
7883 std::optional<unsigned> Shift;
7884 // Prefer Base=0 when shifting out common low zero bits still produces a dense
7885 // range, as this avoids an unnecessary `(condition - local_min)` expression.
7886 // However, avoiding the subtract can leave a wider reduced range than using
7887 // the local minimum, so require Base=0 to satisfy the stricter optsize
7888 // density threshold before falling back to the normal density policy for
7889 // local-min.
7890 if ((Shift = getDenseSwitchRangeReductionShift(Values, /*Base=*/0,
7891 /*OptSize=*/true)))
7892 Base = 0;
7893 else if (Base != 0)
7895
7896 if (!Shift)
7897 return false;
7898
7899 // The obvious transform is to shift the switch condition right and emit a
7900 // check that the condition actually cleanly divided by GCD, i.e.
7901 // C & (1 << Shift - 1) == 0
7902 // inserting a new CFG edge to handle the case where it didn't divide cleanly.
7903 //
7904 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
7905 // shift and puts the shifted-off bits in the uppermost bits. If any of these
7906 // are nonzero then the switch condition will be very large and will hit the
7907 // default case.
7908 //
7909 // This transform can be done speculatively because it is so cheap - it
7910 // results in a single rotate operation being inserted.
7911
7912 auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
7913 Builder.SetInsertPoint(SI);
7914 Value *Sub = SI->getCondition();
7915 if (Base != 0)
7916 Sub = Builder.CreateSub(Sub, ConstantInt::getSigned(Ty, Base));
7917 Value *Rot = Builder.CreateIntrinsic(
7918 Ty, Intrinsic::fshl,
7919 {Sub, Sub, ConstantInt::get(Ty, Ty->getBitWidth() - *Shift)});
7920 SI->replaceUsesOfWith(SI->getCondition(), Rot);
7921
7922 for (auto Case : SI->cases()) {
7923 auto *Orig = Case.getCaseValue();
7924 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base, true);
7925 Case.setValue(cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(*Shift))));
7926 }
7927 return true;
7928}
7929
7930/// Tries to transform the switch when the condition is umin with a constant.
7931/// In that case, the default branch can be replaced by the constant's branch.
7932/// This method also removes dead cases when the simplification cannot replace
7933/// the default branch.
7934///
7935/// For example:
7936/// switch(umin(a, 3)) {
7937/// case 0:
7938/// case 1:
7939/// case 2:
7940/// case 3:
7941/// case 4:
7942/// // ...
7943/// default:
7944/// unreachable
7945/// }
7946///
7947/// Transforms into:
7948///
7949/// switch(a) {
7950/// case 0:
7951/// case 1:
7952/// case 2:
7953/// default:
7954/// // This is case 3
7955/// }
7957 Value *A;
7959
7960 if (!match(SI->getCondition(), m_UMin(m_Value(A), m_ConstantInt(Constant))))
7961 return false;
7962
7965 BasicBlock *BB = SIW->getParent();
7966
7967 // Dead cases are removed even when the simplification fails.
7968 // A case is dead when its value is higher than the Constant.
7969 for (auto I = SI->case_begin(), E = SI->case_end(); I != E;) {
7970 if (!I->getCaseValue()->getValue().ugt(Constant->getValue())) {
7971 ++I;
7972 continue;
7973 }
7974 BasicBlock *DeadCaseBB = I->getCaseSuccessor();
7975 DeadCaseBB->removePredecessor(BB);
7976 I = SIW.removeCase(I);
7977 E = SIW->case_end();
7978 if (!is_contained(successors(BB), DeadCaseBB))
7979 Updates.push_back({DominatorTree::Delete, BB, DeadCaseBB});
7980 }
7981
7982 auto Case = SI->findCaseValue(Constant);
7983 // If the case value is not found, `findCaseValue` returns the default case.
7984 // In this scenario, since there is no explicit `case 3:`, the simplification
7985 // fails. The simplification also fails when the switch’s default destination
7986 // is reachable.
7987 if (!SI->defaultDestUnreachable() || Case == SI->case_default()) {
7988 if (DTU)
7989 DTU->applyUpdates(Updates);
7990 return !Updates.empty();
7991 }
7992
7993 BasicBlock *Unreachable = SI->getDefaultDest();
7994 SIW.replaceDefaultDest(Case);
7995 SIW.removeCase(Case);
7996 SIW->setCondition(A);
7997
7998 Updates.push_back({DominatorTree::Delete, BB, Unreachable});
7999
8000 if (DTU)
8001 DTU->applyUpdates(Updates);
8002
8003 return true;
8004}
8005
8007 const DataLayout &DL,
8008 AssumptionCache *AC) {
8009 assert(SI);
8010 if (SI->defaultDestUnreachable())
8011 return false;
8012
8013 // If it can be proved that the switch condition takes some concrete value
8014 // in the default block, we can make some nice simplifications to the
8015 // switch.
8016 BasicBlock *Default = SI->getDefaultDest();
8017 const Instruction *CxtI = &*Default->getFirstNonPHIIt();
8019 SI->getCondition(),
8020 SimplifyQuery(DL, /*DT=*/nullptr, AC, CxtI).allowEphemerals(true));
8021 if (!Known.isConstant())
8022 return false;
8023
8024 // At this point, we know that only one value can be mapped to the
8025 // default block. So, if a case doesn't exist for it already, we
8026 // can create one pointing to the default block.
8027 ConstantInt *CaseVal =
8028 ConstantInt::get(SI->getContext(), Known.getConstant());
8029 const llvm::SwitchInst::CaseIt CaseIt = SI->findCaseValue(CaseVal);
8030 if (CaseIt == SI->case_default()) {
8032 SIW.addCase(CaseVal, Default, SIW.getSuccessorWeight(0));
8033 SIW.setSuccessorWeight(0, 0);
8034 }
8035 // If there is a pre-existing case for the constant, the default branch
8036 // will be removed rather than being moved. Thus, we are removing an edge
8037 // in the CFG, and need to update any PHIs in the default block.
8038 createUnreachableSwitchDefault(SI, DTU, /*RemoveOrigDefaultBlock=*/CaseIt !=
8039 SI->case_default());
8040
8041 assert(SI->getNumCases() > 0 && "Switch should have at least one case");
8042 assert(SI->findCaseValue(CaseVal) != SI->case_default() &&
8043 "Proven value should have a dedicated case");
8044 assert(SI->defaultDestUnreachable());
8045 return true;
8046}
8047
8048/// Tries to transform switch of powers of two to reduce switch range.
8049/// For example, switch like:
8050/// switch (C) { case 1: case 2: case 64: case 128: }
8051/// will be transformed to:
8052/// switch (count_trailing_zeros(C)) { case 0: case 1: case 6: case 7: }
8053///
8054/// This transformation allows better lowering and may transform the switch
8055/// instruction into a sequence of bit manipulation and a smaller
8056/// log2(C)-indexed value table (instead of traditionally emitting a load of the
8057/// address of the jump target, and indirectly jump to it).
8059 DomTreeUpdater *DTU,
8060 const DataLayout &DL,
8061 const TargetTransformInfo &TTI) {
8062 Value *Condition = SI->getCondition();
8063 LLVMContext &Context = SI->getContext();
8064 auto *CondTy = cast<IntegerType>(Condition->getType());
8065
8066 if (CondTy->getIntegerBitWidth() > 64 ||
8067 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
8068 return false;
8069
8070 // Ensure trailing zeroes count intrinsic emission is not too expensive.
8071 IntrinsicCostAttributes Attrs(Intrinsic::cttz, CondTy,
8072 {Condition, ConstantInt::getTrue(Context)});
8073 if (TTI.getIntrinsicInstrCost(Attrs, TTI::TCK_SizeAndLatency) >
8074 TTI::TCC_Basic * 2)
8075 return false;
8076
8077 // Only bother with this optimization if there are more than 3 switch cases.
8078 // SDAG will start emitting jump tables for 4 or more cases.
8079 if (SI->getNumCases() < 4)
8080 return false;
8081
8082 // Check that switch cases are powers of two.
8084 for (const auto &Case : SI->cases()) {
8085 uint64_t CaseValue = Case.getCaseValue()->getValue().getZExtValue();
8086 if (llvm::has_single_bit(CaseValue))
8087 Values.push_back(CaseValue);
8088 else
8089 return false;
8090 }
8091
8092 // isSwichDense requires case values to be sorted.
8094 if (!isSwitchDense(Values.size(),
8095 llvm::countr_zero(Values.back()) -
8096 llvm::countr_zero(Values.front()) + 1,
8097 SI->getFunction()->hasOptSize()))
8098 // Transform is unable to generate dense switch.
8099 return false;
8100
8101 Builder.SetInsertPoint(SI);
8102
8103 if (!SI->defaultDestUnreachable()) {
8104 // Let non-power-of-two inputs jump to the default case, when the latter is
8105 // reachable.
8106 auto *PopC = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Condition);
8107 auto *IsPow2 = Builder.CreateICmpEQ(PopC, ConstantInt::get(CondTy, 1));
8108
8109 auto *OrigBB = SI->getParent();
8110 auto *DefaultCaseBB = SI->getDefaultDest();
8111 BasicBlock *SplitBB = SplitBlock(OrigBB, SI, DTU);
8112 auto It = OrigBB->getTerminator()->getIterator();
8113 SmallVector<uint32_t> Weights;
8114 auto HasWeights =
8116 auto *BI = CondBrInst::Create(IsPow2, SplitBB, DefaultCaseBB, It);
8117 if (HasWeights && any_of(Weights, not_equal_to(0))) {
8118 // IsPow2 covers a subset of the cases in which we'd go to the default
8119 // label. The other is those powers of 2 that don't appear in the case
8120 // statement. We don't know the distribution of the values coming in, so
8121 // the safest is to split 50-50 the original probability to `default`.
8122 uint64_t OrigDenominator =
8124 SmallVector<uint64_t> NewWeights(2);
8125 NewWeights[1] = Weights[0] / 2;
8126 NewWeights[0] = OrigDenominator - NewWeights[1];
8127 setFittedBranchWeights(*BI, NewWeights, /*IsExpected=*/false);
8128 // The probability of executing the default block stays constant. It was
8129 // p_d = Weights[0] / OrigDenominator
8130 // we rewrite as W/D
8131 // We want to find the probability of the default branch of the switch
8132 // statement. Let's call it X. We have W/D = W/2D + X * (1-W/2D)
8133 // i.e. the original probability is the probability we go to the default
8134 // branch from the BI branch, or we take the default branch on the SI.
8135 // Meaning X = W / (2D - W), or (W/2) / (D - W/2)
8136 // This matches using W/2 for the default branch probability numerator and
8137 // D-W/2 as the denominator.
8138 Weights[0] = NewWeights[1];
8139 uint64_t CasesDenominator = OrigDenominator - Weights[0];
8140 for (auto &W : drop_begin(Weights))
8141 W = NewWeights[0] * static_cast<double>(W) / CasesDenominator;
8142
8143 setBranchWeights(*SI, Weights, /*IsExpected=*/false);
8144 }
8145 // BI is handling the default case for SI, and so should share its DebugLoc.
8146 BI->setDebugLoc(SI->getDebugLoc());
8147 It->eraseFromParent();
8148
8149 addPredecessorToBlock(DefaultCaseBB, OrigBB, SplitBB);
8150 if (DTU)
8151 DTU->applyUpdates({{DominatorTree::Insert, OrigBB, DefaultCaseBB}});
8152 }
8153
8154 // Replace each case with its trailing zeros number.
8155 for (auto &Case : SI->cases()) {
8156 auto *OrigValue = Case.getCaseValue();
8157 Case.setValue(ConstantInt::get(OrigValue->getIntegerType(),
8158 OrigValue->getValue().countr_zero()));
8159 }
8160
8161 // Replace condition with its trailing zeros number.
8162 auto *ConditionTrailingZeros = Builder.CreateIntrinsic(
8163 Intrinsic::cttz, {CondTy}, {Condition, ConstantInt::getTrue(Context)});
8164
8165 SI->setCondition(ConditionTrailingZeros);
8166
8167 return true;
8168}
8169
8170/// Fold switch over ucmp/scmp intrinsic to br if two of the switch arms have
8171/// the same destination.
8173 DomTreeUpdater *DTU) {
8174 auto *Cmp = dyn_cast<CmpIntrinsic>(SI->getCondition());
8175 if (!Cmp || !Cmp->hasOneUse())
8176 return false;
8177
8179 bool HasWeights = extractBranchWeights(getBranchWeightMDNode(*SI), Weights);
8180 if (!HasWeights)
8181 Weights.resize(4); // Avoid checking HasWeights everywhere.
8182
8183 // Normalize to [us]cmp == Res ? Succ : OtherSucc.
8184 int64_t Res;
8185 BasicBlock *Succ, *OtherSucc;
8186 uint32_t SuccWeight = 0, OtherSuccWeight = 0;
8187 BasicBlock *Unreachable = nullptr;
8188
8189 if (SI->getNumCases() == 2) {
8190 // Find which of 1, 0 or -1 is missing (handled by default dest).
8191 SmallSet<int64_t, 3> Missing;
8192 Missing.insert(1);
8193 Missing.insert(0);
8194 Missing.insert(-1);
8195
8196 Succ = SI->getDefaultDest();
8197 SuccWeight = Weights[0];
8198 OtherSucc = nullptr;
8199 for (auto &Case : SI->cases()) {
8200 std::optional<int64_t> Val =
8201 Case.getCaseValue()->getValue().trySExtValue();
8202 if (!Val)
8203 return false;
8204 if (!Missing.erase(*Val))
8205 return false;
8206 if (OtherSucc && OtherSucc != Case.getCaseSuccessor())
8207 return false;
8208 OtherSucc = Case.getCaseSuccessor();
8209 OtherSuccWeight += Weights[Case.getSuccessorIndex()];
8210 }
8211
8212 assert(Missing.size() == 1 && "Should have one case left");
8213 Res = *Missing.begin();
8214 } else if (SI->getNumCases() == 3 && SI->defaultDestUnreachable()) {
8215 // Normalize so that Succ is taken once and OtherSucc twice.
8216 Unreachable = SI->getDefaultDest();
8217 Succ = OtherSucc = nullptr;
8218 for (auto &Case : SI->cases()) {
8219 BasicBlock *NewSucc = Case.getCaseSuccessor();
8220 uint32_t Weight = Weights[Case.getSuccessorIndex()];
8221 if (!OtherSucc || OtherSucc == NewSucc) {
8222 OtherSucc = NewSucc;
8223 OtherSuccWeight += Weight;
8224 } else if (!Succ) {
8225 Succ = NewSucc;
8226 SuccWeight = Weight;
8227 } else if (Succ == NewSucc) {
8228 std::swap(Succ, OtherSucc);
8229 std::swap(SuccWeight, OtherSuccWeight);
8230 } else
8231 return false;
8232 }
8233 for (auto &Case : SI->cases()) {
8234 std::optional<int64_t> Val =
8235 Case.getCaseValue()->getValue().trySExtValue();
8236 if (!Val || (Val != 1 && Val != 0 && Val != -1))
8237 return false;
8238 if (Case.getCaseSuccessor() == Succ) {
8239 Res = *Val;
8240 break;
8241 }
8242 }
8243 } else {
8244 return false;
8245 }
8246
8247 // Determine predicate for the missing case.
8249 switch (Res) {
8250 case 1:
8251 Pred = ICmpInst::ICMP_UGT;
8252 break;
8253 case 0:
8254 Pred = ICmpInst::ICMP_EQ;
8255 break;
8256 case -1:
8257 Pred = ICmpInst::ICMP_ULT;
8258 break;
8259 }
8260 if (Cmp->isSigned())
8261 Pred = ICmpInst::getSignedPredicate(Pred);
8262
8263 MDNode *NewWeights = nullptr;
8264 if (HasWeights)
8265 NewWeights = MDBuilder(SI->getContext())
8266 .createBranchWeights(SuccWeight, OtherSuccWeight);
8267
8268 BasicBlock *BB = SI->getParent();
8269 Builder.SetInsertPoint(SI->getIterator());
8270 Value *ICmp = Builder.CreateICmp(Pred, Cmp->getLHS(), Cmp->getRHS());
8271 Builder.CreateCondBr(ICmp, Succ, OtherSucc, NewWeights,
8272 SI->getMetadata(LLVMContext::MD_unpredictable));
8273 OtherSucc->removePredecessor(BB);
8274 if (Unreachable)
8275 Unreachable->removePredecessor(BB);
8276 SI->eraseFromParent();
8277 Cmp->eraseFromParent();
8278 if (DTU && Unreachable)
8279 DTU->applyUpdates({{DominatorTree::Delete, BB, Unreachable}});
8280 return true;
8281}
8282
8283/// Checking whether two BBs are equal depends on the contents of the
8284/// BasicBlock and the incoming values of their successor PHINodes.
8285/// PHINode::getIncomingValueForBlock is O(|Preds|), so we'd like to avoid
8286/// calling this function on each BasicBlock every time isEqual is called,
8287/// especially since the same BasicBlock may be passed as an argument multiple
8288/// times. To do this, we can precompute a map of PHINode -> Pred BasicBlock ->
8289/// IncomingValue and add it in the Wrapper so isEqual can do O(1) checking
8290/// of the incoming values.
8293
8294 // One Phi usually has < 8 incoming values.
8298
8299 // We only merge the identical non-entry BBs with
8300 // - terminator unconditional br to Succ (pending relaxation),
8301 // - does not have address taken / weird control.
8302 static bool canBeMerged(const BasicBlock *BB) {
8303 assert(BB && "Expected non-null BB");
8304 // Entry block cannot be eliminated or have predecessors.
8305 if (BB->isEntryBlock())
8306 return false;
8307
8308 // Single successor and must be Succ.
8309 // FIXME: Relax that the terminator is a BranchInst by checking for equality
8310 // on other kinds of terminators. We decide to only support unconditional
8311 // branches for now for compile time reasons.
8312 auto *BI = dyn_cast<UncondBrInst>(BB->getTerminator());
8313 if (!BI)
8314 return false;
8315
8316 // Avoid blocks that are "address-taken" (blockaddress) or have unusual
8317 // uses.
8318 if (BB->hasAddressTaken() || BB->isEHPad())
8319 return false;
8320
8321 // TODO: relax this condition to merge equal blocks with >1 instructions?
8322 // Here, we use a O(1) form of the O(n) comparison of `size() != 1`.
8323 if (&BB->front() != &BB->back())
8324 return false;
8325
8326 // The BB must have at least one predecessor.
8327 if (pred_empty(BB))
8328 return false;
8329
8330 return true;
8331 }
8332};
8333
8335 static unsigned getHashValue(const EqualBBWrapper *EBW) {
8336 BasicBlock *BB = EBW->BB;
8338 assert(BB->size() == 1 && "Expected just a single branch in the BB");
8339
8340 // Since we assume the BB is just a single UncondBrInst with a single
8341 // successor, we hash as the BB and the incoming Values of its successor
8342 // PHIs. Initially, we tried to just use the successor BB as the hash, but
8343 // including the incoming PHI values leads to better performance.
8344 // We also tried to build a map from BB -> Succs.IncomingValues ahead of
8345 // time and passing it in EqualBBWrapper, but this slowed down the average
8346 // compile time without having any impact on the worst case compile time.
8347 BasicBlock *Succ = BI->getSuccessor();
8348 auto PhiValsForBB = map_range(Succ->phis(), [&](PHINode &Phi) {
8349 return (*EBW->PhiPredIVs)[&Phi][BB];
8350 });
8351 return hash_combine(Succ, hash_combine_range(PhiValsForBB));
8352 }
8353 static bool isEqual(const EqualBBWrapper *LHS, const EqualBBWrapper *RHS) {
8354 BasicBlock *A = LHS->BB;
8355 BasicBlock *B = RHS->BB;
8356
8357 // FIXME: we checked that the size of A and B are both 1 in
8358 // mergeIdenticalUncondBBs to make the Case list smaller to
8359 // improve performance. If we decide to support BasicBlocks with more
8360 // than just a single instruction, we need to check that A.size() ==
8361 // B.size() here, and we need to check more than just the BranchInsts
8362 // for equality.
8363
8364 UncondBrInst *ABI = cast<UncondBrInst>(A->getTerminator());
8365 UncondBrInst *BBI = cast<UncondBrInst>(B->getTerminator());
8366 if (ABI->getSuccessor() != BBI->getSuccessor())
8367 return false;
8368
8369 // Need to check that PHIs in successor have matching values.
8370 BasicBlock *Succ = ABI->getSuccessor();
8371 auto IfPhiIVMatch = [&](PHINode &Phi) {
8372 // Replace O(|Pred|) Phi.getIncomingValueForBlock with this O(1) hashmap
8373 // query.
8374 auto &PredIVs = (*LHS->PhiPredIVs)[&Phi];
8375 return PredIVs[A] == PredIVs[B];
8376 };
8377 return all_of(Succ->phis(), IfPhiIVMatch);
8378 }
8379};
8380
8381// Merge identical BBs into one of them.
8383 DomTreeUpdater *DTU) {
8384 if (Candidates.size() < 2)
8385 return false;
8386
8387 // Build Cases. Skip BBs that are not candidates for simplification. Mark
8388 // PHINodes which need to be processed into PhiPredIVs. We decide to process
8389 // an entire PHI at once after the loop, opposed to calling
8390 // getIncomingValueForBlock inside this loop, since each call to
8391 // getIncomingValueForBlock is O(|Preds|).
8392 EqualBBWrapper::Phi2IVsMap PhiPredIVs;
8394 BBs2Merge.reserve(Candidates.size());
8396
8397 for (BasicBlock *BB : Candidates) {
8398 BasicBlock *Succ = BB->getSingleSuccessor();
8399 assert(Succ && "Expected unconditional BB");
8400 BBs2Merge.emplace_back(EqualBBWrapper{BB, &PhiPredIVs});
8401 Phis.insert_range(make_pointer_range(Succ->phis()));
8402 }
8403
8404 // Precompute a data structure to improve performance of isEqual for
8405 // EqualBBWrapper.
8406 PhiPredIVs.reserve(Phis.size());
8407 for (PHINode *Phi : Phis) {
8408 auto &IVs =
8409 PhiPredIVs.try_emplace(Phi, Phi->getNumIncomingValues()).first->second;
8410 // Pre-fill all incoming for O(1) lookup as Phi.getIncomingValueForBlock is
8411 // O(|Pred|).
8412 for (auto &IV : Phi->incoming_values())
8413 IVs.insert({Phi->getIncomingBlock(IV), IV.get()});
8414 }
8415
8416 // Group duplicates using DenseSet with custom equality/hashing.
8417 // Build a set such that if the EqualBBWrapper exists in the set and another
8418 // EqualBBWrapper isEqual, then the equivalent EqualBBWrapper which is not in
8419 // the set should be replaced with the one in the set. If the EqualBBWrapper
8420 // is not in the set, then it should be added to the set so other
8421 // EqualBBWrapper can check against it in the same manner. We use
8422 // EqualBBWrapper instead of just BasicBlock because we'd like to pass around
8423 // information to isEquality, getHashValue, and when doing the replacement
8424 // with better performance.
8426 Keep.reserve(BBs2Merge.size());
8427
8429 Updates.reserve(BBs2Merge.size() * 2);
8430
8431 bool MadeChange = false;
8432
8433 // Helper: redirect all edges X -> DeadPred to X -> LivePred.
8434 auto RedirectIncomingEdges = [&](BasicBlock *Dead, BasicBlock *Live) {
8437 if (DTU) {
8438 // All predecessors of DeadPred (except the common predecessor) will be
8439 // moved to LivePred.
8440 Updates.reserve(Updates.size() + DeadPreds.size() * 2);
8442 predecessors(Live));
8443 for (BasicBlock *PredOfDead : DeadPreds) {
8444 // Do not modify those common predecessors of DeadPred and LivePred.
8445 if (!LivePreds.contains(PredOfDead))
8446 Updates.push_back({DominatorTree::Insert, PredOfDead, Live});
8447 Updates.push_back({DominatorTree::Delete, PredOfDead, Dead});
8448 }
8449 }
8450 LLVM_DEBUG(dbgs() << "Replacing duplicate pred BB ";
8451 Dead->printAsOperand(dbgs()); dbgs() << " with pred ";
8452 Live->printAsOperand(dbgs()); dbgs() << " for ";
8453 Live->getSingleSuccessor()->printAsOperand(dbgs());
8454 dbgs() << "\n");
8455 // Replace successors in all predecessors of DeadPred.
8456 for (BasicBlock *PredOfDead : DeadPreds) {
8457 Instruction *T = PredOfDead->getTerminator();
8458 T->replaceSuccessorWith(Dead, Live);
8459 }
8460 };
8461
8462 // Try to eliminate duplicate predecessors.
8463 for (const auto &EBW : BBs2Merge) {
8464 // EBW is a candidate for simplification. If we find a duplicate BB,
8465 // replace it.
8466 const auto &[It, Inserted] = Keep.insert(&EBW);
8467 if (Inserted)
8468 continue;
8469
8470 // Found duplicate: merge P into canonical predecessor It->Pred.
8471 BasicBlock *KeepBB = (*It)->BB;
8472 BasicBlock *DeadBB = EBW.BB;
8473
8474 // Avoid merging a BB with itself.
8475 if (KeepBB == DeadBB)
8476 continue;
8477
8478 // Redirect all edges into DeadPred to KeepPred.
8479 RedirectIncomingEdges(DeadBB, KeepBB);
8480
8481 // Now DeadBB should become unreachable; leave DCE to later,
8482 // but we can try to simplify it if it only branches to Succ.
8483 // (We won't erase here to keep the routine simple and DT-safe.)
8484 assert(pred_empty(DeadBB) && "DeadBB should be unreachable.");
8485 MadeChange = true;
8486 }
8487
8488 if (DTU && !Updates.empty())
8489 DTU->applyUpdates(Updates);
8490
8491 return MadeChange;
8492}
8493
8494bool SimplifyCFGOpt::simplifyDuplicateSwitchArms(SwitchInst *SI,
8495 DomTreeUpdater *DTU) {
8496 // Collect candidate switch-arms top-down.
8497 SmallSetVector<BasicBlock *, 16> FilteredArms(
8500 return mergeIdenticalBBs(FilteredArms.getArrayRef(), DTU);
8501}
8502
8503bool SimplifyCFGOpt::simplifyDuplicatePredecessors(BasicBlock *BB,
8504 DomTreeUpdater *DTU) {
8505 // Need at least 2 predecessors to do anything.
8506 if (!BB || !BB->hasNPredecessorsOrMore(2))
8507 return false;
8508
8509 // Compilation time consideration: retain the canonical loop, otherwise, we
8510 // require more time in the later loop canonicalization.
8511 if (Options.NeedCanonicalLoop && is_contained(LoopHeaders, BB))
8512 return false;
8513
8514 // Collect candidate predecessors bottom-up.
8515 SmallSetVector<BasicBlock *, 8> FilteredPreds(
8518 return mergeIdenticalBBs(FilteredPreds.getArrayRef(), DTU);
8519}
8520
8521bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
8522 BasicBlock *BB = SI->getParent();
8523
8524 if (isValueEqualityComparison(SI)) {
8525 // If we only have one predecessor, and if it is a branch on this value,
8526 // see if that predecessor totally determines the outcome of this switch.
8527 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
8528 if (simplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
8529 return requestResimplify();
8530
8531 Value *Cond = SI->getCondition();
8532 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
8533 if (simplifySwitchOnSelect(SI, Select))
8534 return requestResimplify();
8535
8536 // If the block only contains the switch, see if we can fold the block
8537 // away into any preds.
8538 if (SI == &*BB->begin())
8539 if (foldValueComparisonIntoPredecessors(SI, Builder))
8540 return requestResimplify();
8541 }
8542
8543 // Try to transform the switch into an icmp and a branch.
8544 // The conversion from switch to comparison may lose information on
8545 // impossible switch values, so disable it early in the pipeline.
8546 if (Options.ConvertSwitchRangeToICmp && turnSwitchRangeIntoICmp(SI, Builder))
8547 return requestResimplify();
8548
8549 // Remove unreachable cases.
8550 if (eliminateDeadSwitchCases(SI, DTU, Options.AC, DL))
8551 return requestResimplify();
8552
8553 if (simplifySwitchOfCmpIntrinsic(SI, Builder, DTU))
8554 return requestResimplify();
8555
8556 if (trySwitchToSelect(SI, Builder, DTU, DL, TTI))
8557 return requestResimplify();
8558
8559 if (Options.ForwardSwitchCondToPhi && forwardSwitchConditionToPHI(SI))
8560 return requestResimplify();
8561
8562 // The conversion of switches to arithmetic or lookup table is disabled in
8563 // the early optimization pipeline, as it may lose information or make the
8564 // resulting code harder to analyze.
8565 if (Options.ConvertSwitchToArithmetic || Options.ConvertSwitchToLookupTable)
8566 if (simplifySwitchLookup(SI, Builder, DTU, DL, TTI,
8567 Options.ConvertSwitchToLookupTable))
8568 return requestResimplify();
8569
8570 if (simplifySwitchOfPowersOfTwo(SI, Builder, DTU, DL, TTI))
8571 return requestResimplify();
8572
8573 if (reduceSwitchRange(SI, Builder, DL, TTI))
8574 return requestResimplify();
8575
8576 if (HoistCommon &&
8577 hoistCommonCodeFromSuccessors(SI, !Options.HoistCommonInsts))
8578 return requestResimplify();
8579
8580 // We can merge identical switch arms early to enhance more aggressive
8581 // optimization on switch.
8582 if (simplifyDuplicateSwitchArms(SI, DTU))
8583 return requestResimplify();
8584
8585 if (simplifySwitchWhenUMin(SI, DTU))
8586 return requestResimplify();
8587
8588 if (simplifySwitchDefaultBranch(SI, DTU, DL, Options.AC))
8589 return requestResimplify();
8590
8591 return false;
8592}
8593
8594bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) {
8595 BasicBlock *BB = IBI->getParent();
8596 bool Changed = false;
8597 SmallVector<uint32_t> BranchWeights;
8598 const bool HasBranchWeights = !ProfcheckDisableMetadataFixes &&
8599 extractBranchWeights(*IBI, BranchWeights);
8600
8601 DenseMap<const BasicBlock *, uint64_t> TargetWeight;
8602 if (HasBranchWeights)
8603 for (size_t I = 0, E = IBI->getNumDestinations(); I < E; ++I)
8604 TargetWeight[IBI->getDestination(I)] += BranchWeights[I];
8605
8606 // Eliminate redundant destinations.
8607 SmallPtrSet<Value *, 8> Succs;
8608 SmallSetVector<BasicBlock *, 8> RemovedSuccs;
8609 for (unsigned I = 0, E = IBI->getNumDestinations(); I != E; ++I) {
8610 BasicBlock *Dest = IBI->getDestination(I);
8611 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
8612 if (!Dest->hasAddressTaken())
8613 RemovedSuccs.insert(Dest);
8614 Dest->removePredecessor(BB);
8615 IBI->removeDestination(I);
8616 --I;
8617 --E;
8618 Changed = true;
8619 }
8620 }
8621
8622 if (DTU) {
8623 std::vector<DominatorTree::UpdateType> Updates;
8624 Updates.reserve(RemovedSuccs.size());
8625 for (auto *RemovedSucc : RemovedSuccs)
8626 Updates.push_back({DominatorTree::Delete, BB, RemovedSucc});
8627 DTU->applyUpdates(Updates);
8628 }
8629
8630 if (IBI->getNumDestinations() == 0) {
8631 // If the indirectbr has no successors, change it to unreachable.
8632 new UnreachableInst(IBI->getContext(), IBI->getIterator());
8634 return true;
8635 }
8636
8637 if (IBI->getNumDestinations() == 1) {
8638 // If the indirectbr has one successor, change it to a direct branch.
8641 return true;
8642 }
8643 if (HasBranchWeights) {
8644 SmallVector<uint64_t> NewBranchWeights(IBI->getNumDestinations());
8645 for (size_t I = 0, E = IBI->getNumDestinations(); I < E; ++I)
8646 NewBranchWeights[I] += TargetWeight.find(IBI->getDestination(I))->second;
8647 setFittedBranchWeights(*IBI, NewBranchWeights, /*IsExpected=*/false);
8648 }
8649 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
8650 if (simplifyIndirectBrOnSelect(IBI, SI))
8651 return requestResimplify();
8652 }
8653 return Changed;
8654}
8655
8656/// Given an block with only a single landing pad and a unconditional branch
8657/// try to find another basic block which this one can be merged with. This
8658/// handles cases where we have multiple invokes with unique landing pads, but
8659/// a shared handler.
8660///
8661/// We specifically choose to not worry about merging non-empty blocks
8662/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
8663/// practice, the optimizer produces empty landing pad blocks quite frequently
8664/// when dealing with exception dense code. (see: instcombine, gvn, if-else
8665/// sinking in this file)
8666///
8667/// This is primarily a code size optimization. We need to avoid performing
8668/// any transform which might inhibit optimization (such as our ability to
8669/// specialize a particular handler via tail commoning). We do this by not
8670/// merging any blocks which require us to introduce a phi. Since the same
8671/// values are flowing through both blocks, we don't lose any ability to
8672/// specialize. If anything, we make such specialization more likely.
8673///
8674/// TODO - This transformation could remove entries from a phi in the target
8675/// block when the inputs in the phi are the same for the two blocks being
8676/// merged. In some cases, this could result in removal of the PHI entirely.
8678 BasicBlock *BB, DomTreeUpdater *DTU) {
8679 auto Succ = BB->getUniqueSuccessor();
8680 assert(Succ);
8681 // If there's a phi in the successor block, we'd likely have to introduce
8682 // a phi into the merged landing pad block.
8683 if (isa<PHINode>(*Succ->begin()))
8684 return false;
8685
8686 for (BasicBlock *OtherPred : predecessors(Succ)) {
8687 if (BB == OtherPred)
8688 continue;
8689 BasicBlock::iterator I = OtherPred->begin();
8691 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
8692 continue;
8693 ++I;
8695 if (!BI2 || !BI2->isIdenticalTo(BI))
8696 continue;
8697
8698 std::vector<DominatorTree::UpdateType> Updates;
8699
8700 // We've found an identical block. Update our predecessors to take that
8701 // path instead and make ourselves dead.
8703 for (BasicBlock *Pred : UniquePreds) {
8704 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
8705 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
8706 "unexpected successor");
8707 II->setUnwindDest(OtherPred);
8708 if (DTU) {
8709 Updates.push_back({DominatorTree::Insert, Pred, OtherPred});
8710 Updates.push_back({DominatorTree::Delete, Pred, BB});
8711 }
8712 }
8713
8715 for (BasicBlock *Succ : UniqueSuccs) {
8716 Succ->removePredecessor(BB);
8717 if (DTU)
8718 Updates.push_back({DominatorTree::Delete, BB, Succ});
8719 }
8720
8721 IRBuilder<> Builder(BI);
8722 Builder.CreateUnreachable();
8723 BI->eraseFromParent();
8724 if (DTU)
8725 DTU->applyUpdates(Updates);
8726 return true;
8727 }
8728 return false;
8729}
8730
8731bool SimplifyCFGOpt::simplifyUncondBranch(UncondBrInst *BI,
8732 IRBuilder<> &Builder) {
8733 BasicBlock *BB = BI->getParent();
8734 BasicBlock *Succ = BI->getSuccessor(0);
8735
8736 // If the Terminator is the only non-phi instruction, simplify the block.
8737 // If LoopHeader is provided, check if the block or its successor is a loop
8738 // header. (This is for early invocations before loop simplify and
8739 // vectorization to keep canonical loop forms for nested loops. These blocks
8740 // can be eliminated when the pass is invoked later in the back-end.)
8741 // Note that if BB has only one predecessor then we do not introduce new
8742 // backedge, so we can eliminate BB.
8743 bool NeedCanonicalLoop =
8744 Options.NeedCanonicalLoop &&
8745 (!LoopHeaders.empty() && BB->hasNPredecessorsOrMore(2) &&
8746 (is_contained(LoopHeaders, BB) || is_contained(LoopHeaders, Succ)));
8748 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
8749 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB, DTU))
8750 return true;
8751
8752 // If the only instruction in the block is a seteq/setne comparison against a
8753 // constant, try to simplify the block.
8754 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
8755 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
8756 ++I;
8757 if (I->isTerminator() &&
8758 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
8759 return true;
8760 if (isa<SelectInst>(I) && I->getNextNode()->isTerminator() &&
8761 tryToSimplifyUncondBranchWithICmpSelectInIt(ICI, cast<SelectInst>(I),
8762 Builder))
8763 return true;
8764 }
8765 }
8766
8767 // See if we can merge an empty landing pad block with another which is
8768 // equivalent.
8769 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
8770 ++I;
8771 if (I->isTerminator() && tryToMergeLandingPad(LPad, BI, BB, DTU))
8772 return true;
8773 }
8774
8775 return false;
8776}
8777
8779 BasicBlock *PredPred = nullptr;
8780 for (auto *P : predecessors(BB)) {
8781 BasicBlock *PPred = P->getSinglePredecessor();
8782 if (!PPred || (PredPred && PredPred != PPred))
8783 return nullptr;
8784 PredPred = PPred;
8785 }
8786 return PredPred;
8787}
8788
8789/// Fold the following pattern:
8790/// bb0:
8791/// br i1 %cond1, label %bb1, label %bb2
8792/// bb1:
8793/// br i1 %cond2, label %bb3, label %bb4
8794/// bb2:
8795/// br i1 %cond2, label %bb4, label %bb3
8796/// bb3:
8797/// ...
8798/// bb4:
8799/// ...
8800/// into
8801/// bb0:
8802/// %cond = xor i1 %cond1, %cond2
8803/// br i1 %cond, label %bb4, label %bb3
8804/// bb3:
8805/// ...
8806/// bb4:
8807/// ...
8808/// NOTE: %cond2 always dominates the terminator of bb0.
8810 BasicBlock *BB = BI->getParent();
8811 BasicBlock *BB1 = BI->getSuccessor(0);
8812 BasicBlock *BB2 = BI->getSuccessor(1);
8813 auto IsSimpleSuccessor = [BB](BasicBlock *Succ, CondBrInst *&SuccBI) {
8814 if (Succ == BB)
8815 return false;
8816 if (&Succ->front() != Succ->getTerminator())
8817 return false;
8818 SuccBI = dyn_cast<CondBrInst>(Succ->getTerminator());
8819 if (!SuccBI)
8820 return false;
8821 BasicBlock *Succ1 = SuccBI->getSuccessor(0);
8822 BasicBlock *Succ2 = SuccBI->getSuccessor(1);
8823 return Succ1 != Succ && Succ2 != Succ && Succ1 != BB && Succ2 != BB &&
8824 !isa<PHINode>(Succ1->front()) && !isa<PHINode>(Succ2->front());
8825 };
8826 CondBrInst *BB1BI, *BB2BI;
8827 if (!IsSimpleSuccessor(BB1, BB1BI) || !IsSimpleSuccessor(BB2, BB2BI))
8828 return false;
8829
8830 if (BB1BI->getCondition() != BB2BI->getCondition() ||
8831 BB1BI->getSuccessor(0) != BB2BI->getSuccessor(1) ||
8832 BB1BI->getSuccessor(1) != BB2BI->getSuccessor(0))
8833 return false;
8834
8835 BasicBlock *BB3 = BB1BI->getSuccessor(0);
8836 BasicBlock *BB4 = BB1BI->getSuccessor(1);
8837 // Bail out on trivial cases to avoid bothering to handle the special case in
8838 // the code below.
8839 if (BB3 == BB4)
8840 return false;
8841 IRBuilder<> Builder(BI);
8842 BI->setCondition(
8843 Builder.CreateXor(BI->getCondition(), BB1BI->getCondition()));
8844 BB1->removePredecessor(BB);
8845 BI->setSuccessor(0, BB4);
8846 BB2->removePredecessor(BB);
8847 BI->setSuccessor(1, BB3);
8848 if (DTU) {
8850 Updates.push_back({DominatorTree::Delete, BB, BB1});
8851 Updates.push_back({DominatorTree::Insert, BB, BB4});
8852 Updates.push_back({DominatorTree::Delete, BB, BB2});
8853 Updates.push_back({DominatorTree::Insert, BB, BB3});
8854
8855 DTU->applyUpdates(Updates);
8856 }
8857 bool HasWeight = false;
8858 uint64_t BBTWeight, BBFWeight;
8859 if (extractBranchWeights(*BI, BBTWeight, BBFWeight))
8860 HasWeight = true;
8861 else
8862 BBTWeight = BBFWeight = 1;
8863 uint64_t BB1TWeight, BB1FWeight;
8864 if (extractBranchWeights(*BB1BI, BB1TWeight, BB1FWeight))
8865 HasWeight = true;
8866 else
8867 BB1TWeight = BB1FWeight = 1;
8868 uint64_t BB2TWeight, BB2FWeight;
8869 if (extractBranchWeights(*BB2BI, BB2TWeight, BB2FWeight))
8870 HasWeight = true;
8871 else
8872 BB2TWeight = BB2FWeight = 1;
8873 if (HasWeight) {
8874 uint64_t Weights[2] = {BBTWeight * BB1FWeight + BBFWeight * BB2TWeight,
8875 BBTWeight * BB1TWeight + BBFWeight * BB2FWeight};
8876 setFittedBranchWeights(*BI, Weights, /*IsExpected=*/false,
8877 /*ElideAllZero=*/true);
8878 }
8879 return true;
8880}
8881
8882bool SimplifyCFGOpt::simplifyCondBranch(CondBrInst *BI, IRBuilder<> &Builder) {
8883 assert(
8885 BI->getSuccessor(0) != BI->getSuccessor(1) &&
8886 "Tautological conditional branch should have been eliminated already.");
8887
8888 BasicBlock *BB = BI->getParent();
8889 if (!Options.SimplifyCondBranch ||
8890 BI->getFunction()->hasFnAttribute(Attribute::OptForFuzzing))
8891 return false;
8892
8893 // Conditional branch
8894 if (isValueEqualityComparison(BI)) {
8895 // If we only have one predecessor, and if it is a branch on this value,
8896 // see if that predecessor totally determines the outcome of this
8897 // switch.
8898 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
8899 if (simplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
8900 return requestResimplify();
8901
8902 // This block must be empty, except for the setcond inst, if it exists.
8903 // Ignore pseudo intrinsics.
8904 for (auto &I : *BB) {
8905 if (isa<PseudoProbeInst>(I) ||
8906 &I == cast<Instruction>(BI->getCondition()))
8907 continue;
8908 if (&I == BI)
8909 if (foldValueComparisonIntoPredecessors(BI, Builder))
8910 return requestResimplify();
8911 break;
8912 }
8913 }
8914
8915 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
8916 if (simplifyBranchOnICmpChain(BI, Builder, DL))
8917 return true;
8918
8919 // If this basic block has dominating predecessor blocks and the dominating
8920 // blocks' conditions imply BI's condition, we know the direction of BI.
8921 std::optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
8922 if (Imp) {
8923 // Turn this into a branch on constant.
8924 auto *OldCond = BI->getCondition();
8925 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
8926 : ConstantInt::getFalse(BB->getContext());
8927 BI->setCondition(TorF);
8929 return requestResimplify();
8930 }
8931
8932 // If this basic block is ONLY a compare and a branch, and if a predecessor
8933 // branches to us and one of our successors, fold the comparison into the
8934 // predecessor and use logical operations to pick the right destination.
8935 if (Options.SpeculateBlocks &&
8936 foldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI, Options.AC,
8937 Options.BonusInstThreshold))
8938 return requestResimplify();
8939
8940 // We have a conditional branch to two blocks that are only reachable
8941 // from BI. We know that the condbr dominates the two blocks, so see if
8942 // there is any identical code in the "then" and "else" blocks. If so, we
8943 // can hoist it up to the branching block.
8944 if (BI->getSuccessor(0)->getSinglePredecessor()) {
8945 if (BI->getSuccessor(1)->getSinglePredecessor()) {
8946 if (HoistCommon &&
8947 hoistCommonCodeFromSuccessors(BI, !Options.HoistCommonInsts))
8948 return requestResimplify();
8949
8950 if (BI && Options.HoistLoadsStoresWithCondFaulting &&
8951 isProfitableToSpeculate(BI, std::nullopt, TTI)) {
8952 SmallVector<Instruction *, 2> SpeculatedConditionalLoadsStores;
8953 auto CanSpeculateConditionalLoadsStores = [&]() {
8954 for (auto *Succ : successors(BB)) {
8955 for (Instruction &I : *Succ) {
8956 if (I.isTerminator()) {
8957 if (I.getNumSuccessors() > 1)
8958 return false;
8959 continue;
8960 } else if (!isSafeCheapLoadStore(&I, TTI) ||
8961 SpeculatedConditionalLoadsStores.size() ==
8963 return false;
8964 }
8965 SpeculatedConditionalLoadsStores.push_back(&I);
8966 }
8967 }
8968 return !SpeculatedConditionalLoadsStores.empty();
8969 };
8970
8971 if (CanSpeculateConditionalLoadsStores()) {
8972 hoistConditionalLoadsStores(BI, SpeculatedConditionalLoadsStores,
8973 std::nullopt, nullptr);
8974 return requestResimplify();
8975 }
8976 }
8977 } else {
8978 // If Successor #1 has multiple preds, we may be able to conditionally
8979 // execute Successor #0 if it branches to Successor #1.
8980 Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
8981 if (Succ0TI->getNumSuccessors() == 1 &&
8982 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
8983 if (speculativelyExecuteBB(BI, BI->getSuccessor(0)))
8984 return requestResimplify();
8985 }
8986 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
8987 // If Successor #0 has multiple preds, we may be able to conditionally
8988 // execute Successor #1 if it branches to Successor #0.
8989 Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
8990 if (Succ1TI->getNumSuccessors() == 1 &&
8991 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
8992 if (speculativelyExecuteBB(BI, BI->getSuccessor(1)))
8993 return requestResimplify();
8994 }
8995
8996 // If this is a branch on something for which we know the constant value in
8997 // predecessors (e.g. a phi node in the current block), thread control
8998 // through this block.
8999 if (foldCondBranchOnValueKnownInPredecessor(BI))
9000 return requestResimplify();
9001
9002 // Scan predecessor blocks for conditional branches.
9003 for (BasicBlock *Pred : predecessors(BB))
9004 if (CondBrInst *PBI = dyn_cast<CondBrInst>(Pred->getTerminator()))
9005 if (PBI != BI)
9006 if (SimplifyCondBranchToCondBranch(PBI, BI, DTU, DL, TTI))
9007 return requestResimplify();
9008
9009 // Look for diamond patterns.
9010 if (MergeCondStores)
9011 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
9012 if (CondBrInst *PBI = dyn_cast<CondBrInst>(PrevBB->getTerminator()))
9013 if (PBI != BI)
9014 if (mergeConditionalStores(PBI, BI, DTU, DL, TTI))
9015 return requestResimplify();
9016
9017 // Look for nested conditional branches.
9018 if (mergeNestedCondBranch(BI, DTU))
9019 return requestResimplify();
9020
9021 return false;
9022}
9023
9024/// Check if passing a value to an instruction will cause undefined behavior.
9025static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified) {
9026 assert(V->getType() == I->getType() && "Mismatched types");
9028 if (!C)
9029 return false;
9030
9031 if (I->use_empty())
9032 return false;
9033
9034 if (C->isNullValue() || isa<UndefValue>(C)) {
9035 // Find the first same-block use with a UB-triggering opcode, skipping
9036 // cross-block or before-I uses.
9037 auto FindUse = llvm::find_if(I->uses(), [I](auto &U) {
9038 auto *Use = cast<Instruction>(U.getUser());
9039 // Only same-block uses after I can witness UB at I's program point.
9040 // Self-uses and before-I uses can occur when I is a PHI node.
9041 if (Use->getParent() != I->getParent() || Use == I || Use->comesBefore(I))
9042 return false;
9043 // Change this list when we want to add new instructions.
9044 switch (Use->getOpcode()) {
9045 default:
9046 return false;
9047 case Instruction::GetElementPtr:
9048 case Instruction::Ret:
9049 case Instruction::BitCast:
9050 case Instruction::Load:
9051 case Instruction::Store:
9052 case Instruction::Call:
9053 case Instruction::CallBr:
9054 case Instruction::Invoke:
9055 case Instruction::UDiv:
9056 case Instruction::URem:
9057 // Note: signed div/rem of INT_MIN / -1 is also immediate UB, not
9058 // implemented to avoid code complexity as it is unclear how useful such
9059 // logic is.
9060 case Instruction::SDiv:
9061 case Instruction::SRem:
9062 return true;
9063 }
9064 });
9065 if (FindUse == I->use_end())
9066 return false;
9067 auto &Use = *FindUse;
9068 auto *User = cast<Instruction>(Use.getUser());
9069
9070 // Now make sure that there are no instructions in between that can alter
9071 // control flow (eg. calls)
9072 auto InstrRange =
9073 make_range(std::next(I->getIterator()), User->getIterator());
9074 if (any_of(InstrRange, [](Instruction &I) {
9076 }))
9077 return false;
9078
9079 // Look through GEPs. A load from a GEP derived from NULL is still undefined
9081 if (GEP->getPointerOperand() == I) {
9082 // The type of GEP may differ from the type of base pointer.
9083 // Bail out on vector GEPs, as they are not handled by other checks.
9084 if (GEP->getType()->isVectorTy())
9085 return false;
9086 // The current base address is null, there are four cases to consider:
9087 // getelementptr (TY, null, 0) -> null
9088 // getelementptr (TY, null, not zero) -> may be modified
9089 // getelementptr inbounds (TY, null, 0) -> null
9090 // getelementptr inbounds (TY, null, not zero) -> poison iff null is
9091 // undefined?
9092 if (!GEP->hasAllZeroIndices() &&
9093 (!GEP->isInBounds() ||
9094 NullPointerIsDefined(GEP->getFunction(),
9095 GEP->getPointerAddressSpace())))
9096 PtrValueMayBeModified = true;
9097 return passingValueIsAlwaysUndefined(V, GEP, PtrValueMayBeModified);
9098 }
9099
9100 // Look through return.
9101 if (ReturnInst *Ret = dyn_cast<ReturnInst>(User)) {
9102 bool HasNoUndefAttr =
9103 Ret->getFunction()->hasRetAttribute(Attribute::NoUndef);
9104 // Return undefined to a noundef return value is undefined.
9105 if (isa<UndefValue>(C) && HasNoUndefAttr)
9106 return true;
9107 // Return null to a nonnull+noundef return value is undefined.
9108 if (C->isNullValue() && HasNoUndefAttr &&
9109 Ret->getFunction()->hasRetAttribute(Attribute::NonNull)) {
9110 return !PtrValueMayBeModified;
9111 }
9112 }
9113
9114 // Load from null is undefined.
9115 if (LoadInst *LI = dyn_cast<LoadInst>(User))
9116 if (!LI->isVolatile())
9117 return !NullPointerIsDefined(LI->getFunction(),
9118 LI->getPointerAddressSpace());
9119
9120 // Store to null is undefined.
9122 if (!SI->isVolatile())
9123 return (!NullPointerIsDefined(SI->getFunction(),
9124 SI->getPointerAddressSpace())) &&
9125 SI->getPointerOperand() == I;
9126
9127 // llvm.assume(false/undef) always triggers immediate UB.
9128 if (auto *Assume = dyn_cast<AssumeInst>(User)) {
9129 // Ignore assume operand bundles.
9130 if (I == Assume->getArgOperand(0))
9131 return true;
9132 }
9133
9134 if (auto *CB = dyn_cast<CallBase>(User)) {
9135 if (C->isNullValue() && NullPointerIsDefined(CB->getFunction()))
9136 return false;
9137 // A call to null is undefined.
9138 if (CB->getCalledOperand() == I)
9139 return true;
9140
9141 if (CB->isArgOperand(&Use)) {
9142 unsigned ArgIdx = CB->getArgOperandNo(&Use);
9143 // Passing null to a nonnnull+noundef argument is undefined.
9144 if (isa<ConstantPointerNull>(C) && C->getType()->isPointerTy() &&
9145 CB->paramHasNonNullAttr(ArgIdx, /*AllowUndefOrPoison=*/false))
9146 return !PtrValueMayBeModified;
9147 // Passing undef to a noundef argument is undefined.
9148 if (isa<UndefValue>(C) && CB->isPassingUndefUB(ArgIdx))
9149 return true;
9150 }
9151 }
9152 // Div/Rem by zero is immediate UB
9153 if (match(User, m_BinOp(m_Value(), m_Specific(I))) && User->isIntDivRem())
9154 return true;
9155 }
9156 return false;
9157}
9158
9159/// If BB has an incoming value that will always trigger undefined behavior
9160/// (eg. null pointer dereference), remove the branch leading here.
9162 DomTreeUpdater *DTU,
9163 AssumptionCache *AC) {
9164 for (PHINode &PHI : BB->phis())
9165 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
9166 if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
9167 BasicBlock *Predecessor = PHI.getIncomingBlock(i);
9168 Instruction *T = Predecessor->getTerminator();
9169 IRBuilder<> Builder(T);
9170 if (isa<UncondBrInst>(T)) {
9171 BB->removePredecessor(Predecessor);
9172 // Turn unconditional branches into unreachables.
9173 Builder.CreateUnreachable();
9174 T->eraseFromParent();
9175 if (DTU)
9176 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
9177 return true;
9178 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(T)) {
9179 BB->removePredecessor(Predecessor);
9180 // Handle degenerate conditional branches.
9181 if (BI->getSuccessor(0) == BI->getSuccessor(1)) {
9182 // The only difference from the UncondBrInst path above is that it
9183 // has two edges in CFG.
9184 BB->removePredecessor(Predecessor);
9185 // Turn unconditional branches into unreachables.
9186 Builder.CreateUnreachable();
9187 } else {
9188 // Preserve guarding condition in assume, because it might not be
9189 // inferrable from any dominating condition.
9190 Value *Cond = BI->getCondition();
9191 CallInst *Assumption;
9192 if (BI->getSuccessor(0) == BB)
9193 Assumption = Builder.CreateAssumption(Builder.CreateNot(Cond));
9194 else
9195 Assumption = Builder.CreateAssumption(Cond);
9196 if (AC)
9197 AC->registerAssumption(cast<AssumeInst>(Assumption));
9198 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
9199 : BI->getSuccessor(0));
9200 }
9201 BI->eraseFromParent();
9202 if (DTU)
9203 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
9204 return true;
9205 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
9206 // Redirect all branches leading to UB into
9207 // a newly created unreachable block.
9208 BasicBlock *Unreachable = BasicBlock::Create(
9209 Predecessor->getContext(), "unreachable", BB->getParent(), BB);
9210 Builder.SetInsertPoint(Unreachable);
9211 // The new block contains only one instruction: Unreachable
9212 Builder.CreateUnreachable();
9213 for (const auto &Case : SI->cases())
9214 if (Case.getCaseSuccessor() == BB) {
9215 BB->removePredecessor(Predecessor);
9216 Case.setSuccessor(Unreachable);
9217 }
9218 if (SI->getDefaultDest() == BB) {
9219 BB->removePredecessor(Predecessor);
9220 SI->setDefaultDest(Unreachable);
9221 }
9222
9223 if (DTU)
9224 DTU->applyUpdates(
9225 { { DominatorTree::Insert, Predecessor, Unreachable },
9226 { DominatorTree::Delete, Predecessor, BB } });
9227 return true;
9228 }
9229 }
9230
9231 return false;
9232}
9233
9234bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
9235 bool Changed = false;
9236
9237 assert(BB && BB->getParent() && "Block not embedded in function!");
9238 assert(BB->getTerminator() && "Degenerate basic block encountered!");
9239
9240 // Remove basic blocks that have no predecessors (except the entry block)...
9241 // or that just have themself as a predecessor. These are unreachable.
9242 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
9243 BB->getSinglePredecessor() == BB) {
9244 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
9245 DeleteDeadBlock(BB, DTU);
9246 return true;
9247 }
9248
9249 // Check to see if we can constant propagate this terminator instruction
9250 // away...
9251 Changed |= ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true,
9252 /*TLI=*/nullptr, DTU);
9253
9254 // Check for and eliminate duplicate PHI nodes in this block.
9256
9257 // Check for and remove branches that will always cause undefined behavior.
9259 return requestResimplify();
9260
9261 // Merge basic blocks into their predecessor if there is only one distinct
9262 // pred, and if there is only one distinct successor of the predecessor, and
9263 // if there are no PHI nodes.
9264 if (MergeBlockIntoPredecessor(BB, DTU))
9265 return true;
9266
9267 if (SinkCommon && Options.SinkCommonInsts) {
9268 if (sinkCommonCodeFromPredecessors(BB, DTU) ||
9269 mergeCompatibleInvokes(BB, DTU)) {
9270 // sinkCommonCodeFromPredecessors() does not automatically CSE PHI's,
9271 // so we may now how duplicate PHI's.
9272 // Let's rerun EliminateDuplicatePHINodes() first,
9273 // before foldTwoEntryPHINode() potentially converts them into select's,
9274 // after which we'd need a whole EarlyCSE pass run to cleanup them.
9275 return true;
9276 }
9277 // Merge identical predecessors of this block.
9278 if (simplifyDuplicatePredecessors(BB, DTU))
9279 return true;
9280 }
9281
9282 if (Options.SpeculateBlocks &&
9283 !BB->getParent()->hasFnAttribute(Attribute::OptForFuzzing)) {
9284 // If there is a trivial two-entry PHI node in this basic block, and we can
9285 // eliminate it, do so now.
9286 if (auto *PN = dyn_cast<PHINode>(BB->begin()))
9287 if (PN->getNumIncomingValues() == 2)
9288 if (foldTwoEntryPHINode(PN, TTI, DTU, Options.AC, DL,
9289 Options.SpeculateUnpredictables))
9290 return true;
9291 }
9292
9293 IRBuilder<> Builder(BB);
9295 Builder.SetInsertPoint(Terminator);
9296 switch (Terminator->getOpcode()) {
9297 case Instruction::UncondBr:
9298 Changed |= simplifyUncondBranch(cast<UncondBrInst>(Terminator), Builder);
9299 break;
9300 case Instruction::CondBr:
9301 Changed |= simplifyCondBranch(cast<CondBrInst>(Terminator), Builder);
9302 break;
9303 case Instruction::Resume:
9304 Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder);
9305 break;
9306 case Instruction::CleanupRet:
9307 Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator));
9308 break;
9309 case Instruction::Switch:
9310 Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder);
9311 break;
9312 case Instruction::Unreachable:
9313 Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator));
9314 break;
9315 case Instruction::IndirectBr:
9316 Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator));
9317 break;
9318 }
9319
9320 return Changed;
9321}
9322
9323bool SimplifyCFGOpt::run(BasicBlock *BB) {
9324 bool Changed = false;
9325
9326 // Repeated simplify BB as long as resimplification is requested.
9327 do {
9328 Resimplify = false;
9329
9330 // Perform one round of simplifcation. Resimplify flag will be set if
9331 // another iteration is requested.
9332 Changed |= simplifyOnce(BB);
9333 } while (Resimplify);
9334
9335 return Changed;
9336}
9337
9340 ArrayRef<WeakVH> LoopHeaders) {
9341 return SimplifyCFGOpt(TTI, DTU, BB->getDataLayout(), LoopHeaders,
9342 Options)
9343 .run(BB);
9344}
#define Fail
#define Success
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
unsigned uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
static MachineBasicBlock * OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
Function Alias Analysis Results
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
This file defines the DenseMap class.
@ Default
#define DEBUG_TYPE
Hexagon Common GEP
static bool IsIndirectCall(const MachineInstr *MI)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
static Constant * getFalse(Type *Ty)
For a boolean type or a vector of boolean type, return false or a vector with every element false.
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
This file contains the declarations for metadata subclasses.
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:484
Provides some synthesis utilities to produce sequences of values.
This file defines generic set operations that may be used on set's of different types,...
This file implements a set that has insertion order iteration characteristics.
static std::optional< ContiguousCasesResult > findContiguousCases(Value *Condition, SmallVectorImpl< ConstantInt * > &Cases, SmallVectorImpl< ConstantInt * > &OtherCases, BasicBlock *Dest, BasicBlock *OtherDest)
static void addPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, BasicBlock *ExistPred, MemorySSAUpdater *MSSAU=nullptr)
Update PHI nodes in Succ to indicate that there will now be entries in it from the 'NewPred' block.
static bool validLookupTableConstant(Constant *C, const TargetTransformInfo &TTI)
Return true if the backend will be able to handle initializing an array of constants like C.
static StoreInst * findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2)
static bool isSwitchDense(uint64_t NumCases, uint64_t CaseRange, bool OptSize)
static bool validateAndCostRequiredSelects(BasicBlock *BB, BasicBlock *ThenBB, BasicBlock *EndBB, unsigned &SpeculatedInstructions, InstructionCost &Cost, const TargetTransformInfo &TTI)
Estimate the cost of the insertion(s) and check that the PHI nodes can be converted to selects.
static bool simplifySwitchLookup(SwitchInst *SI, IRBuilder<> &Builder, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI, bool ConvertSwitchToLookupTable)
If the switch is only used to initialize one or more phi nodes in a common successor block with diffe...
static void removeSwitchAfterSelectFold(SwitchInst *SI, PHINode *PHI, Value *SelectValue, IRBuilder<> &Builder, DomTreeUpdater *DTU)
static bool valuesOverlap(std::vector< ValueEqualityComparisonCase > &C1, std::vector< ValueEqualityComparisonCase > &C2)
Return true if there are any keys in C1 that exist in C2 as well.
static bool isProfitableToSpeculate(const CondBrInst *BI, std::optional< bool > Invert, const TargetTransformInfo &TTI)
static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB, BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
static bool mergeCleanupPad(CleanupReturnInst *RI)
static bool isVectorOp(Instruction &I)
Return if an instruction's type or any of its operands' types are a vector type.
static BasicBlock * allPredecessorsComeFromSameSource(BasicBlock *BB)
static void cloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(BasicBlock *BB, BasicBlock *PredBlock, ValueToValueMapTy &VMap)
static int constantIntSortPredicate(ConstantInt *const *P1, ConstantInt *const *P2)
static bool getCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, BasicBlock **CommonDest, SmallVectorImpl< std::pair< PHINode *, Constant * > > &Res, const DataLayout &DL, const TargetTransformInfo &TTI)
Try to determine the resulting constant values in phi nodes at the common destination basic block,...
static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified=false)
Check if passing a value to an instruction will cause undefined behavior.
static std::optional< std::tuple< BasicBlock *, Instruction::BinaryOps, bool > > shouldFoldCondBranchesToCommonDestination(CondBrInst *BI, CondBrInst *PBI, const TargetTransformInfo *TTI)
Determine if the two branches share a common destination and deduce a glue that joins the branches' c...
static bool isSafeToHoistInstr(Instruction *I, unsigned Flags)
static std::optional< bool > foldCondBranchOnValueKnownInPredecessorImpl(CondBrInst *BI, const TargetTransformInfo &TTI, DomTreeUpdater *DTU, AssumptionCache *AC, const DataLayout &DL)
If we have a conditional branch on something for which we know the constant value in predecessors (e....
static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, Instruction *I1, Instruction *I2)
static ConstantInt * getConstantInt(Value *V, const DataLayout &DL)
Extract ConstantInt from value, looking through IntToPtr and PointerNullValue.
static bool simplifySwitchOfCmpIntrinsic(SwitchInst *SI, IRBuilderBase &Builder, DomTreeUpdater *DTU)
Fold switch over ucmp/scmp intrinsic to br if two of the switch arms have the same destination.
static bool shouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, const TargetTransformInfo &TTI, const DataLayout &DL, const SmallVector< Type * > &ResultTypes)
Determine whether a lookup table should be built for this switch, based on the number of cases,...
static Constant * constantFold(Instruction *I, const DataLayout &DL, const SmallDenseMap< Value *, Constant * > &ConstantPool)
Try to fold instruction I into a constant.
static bool areIdenticalUpToCommutativity(const Instruction *I1, const Instruction *I2)
static bool forwardSwitchConditionToPHI(SwitchInst *SI)
Try to forward the condition of a switch instruction to a phi node dominated by the switch,...
static PHINode * findPHIForConditionForwarding(ConstantInt *CaseValue, BasicBlock *BB, int *PhiIndex)
If BB would be eligible for simplification by TryToSimplifyUncondBranchFromEmptyBlock (i....
static bool reachesUncontrolledConvergentCallBeforeBlock(BasicBlock *From, BasicBlock *StopBB)
static bool simplifySwitchOfPowersOfTwo(SwitchInst *SI, IRBuilder<> &Builder, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
Tries to transform switch of powers of two to reduce switch range.
static bool isCleanupBlockEmpty(iterator_range< BasicBlock::iterator > R)
static Value * ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB, Value *AlternativeV=nullptr)
static Value * createLogicalOp(IRBuilderBase &Builder, Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="")
static void hoistConditionalLoadsStores(CondBrInst *BI, SmallVectorImpl< Instruction * > &SpeculatedConditionalLoadsStores, std::optional< bool > Invert, Instruction *Sel)
If the target supports conditional faulting, we look for the following pattern:
static bool shouldHoistCommonInstructions(Instruction *I1, Instruction *I2, const TargetTransformInfo &TTI)
Helper function for hoistCommonCodeFromSuccessors.
static bool reduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder, const DataLayout &DL, const TargetTransformInfo &TTI)
Try to transform a switch that has "holes" in it to a contiguous sequence of cases.
static bool safeToMergeTerminators(Instruction *SI1, Instruction *SI2, SmallSetVector< BasicBlock *, 4 > *FailBlocks=nullptr)
Return true if it is safe to merge these two terminator instructions together.
SkipFlags
@ SkipReadMem
@ SkipSideEffect
@ SkipImplicitControlFlow
static bool simplifySwitchDefaultBranch(SwitchInst *SI, DomTreeUpdater *DTU, const DataLayout &DL, AssumptionCache *AC)
static bool incomingValuesAreCompatible(BasicBlock *BB, ArrayRef< BasicBlock * > IncomingBlocks, SmallPtrSetImpl< Value * > *EquivalenceSet=nullptr)
Return true if all the PHI nodes in the basic block BB receive compatible (identical) incoming values...
static bool trySwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
If a switch is only used to initialize one or more phi nodes in a common successor block with only tw...
static void createUnreachableSwitchDefault(SwitchInst *Switch, DomTreeUpdater *DTU, bool RemoveOrigDefaultBlock=true)
static Value * foldSwitchToSelect(const SwitchCaseResultVectorTy &ResultVector, Constant *DefaultResult, Value *Condition, IRBuilder<> &Builder, const DataLayout &DL, ArrayRef< uint32_t > BranchWeights)
static bool sinkCommonCodeFromPredecessors(BasicBlock *BB, DomTreeUpdater *DTU)
Check whether BB's predecessors end with unconditional branches.
static bool isTypeLegalForLookupTable(Type *Ty, const TargetTransformInfo &TTI, const DataLayout &DL)
static bool eliminateDeadSwitchCases(SwitchInst *SI, DomTreeUpdater *DTU, AssumptionCache *AC, const DataLayout &DL)
Compute masked bits for the condition of a switch and use it to remove dead cases.
static bool blockIsSimpleEnoughToThreadThrough(BasicBlock *BB, BlocksSet &NonLocalUseBlocks)
Return true if we can thread a branch across this block.
static Value * isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, BasicBlock *StoreBB, BasicBlock *EndBB)
Determine if we can hoist sink a sole store instruction out of a conditional block.
static bool foldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI, DomTreeUpdater *DTU, AssumptionCache *AC, const DataLayout &DL, bool SpeculateUnpredictables)
Given a BB that starts with the specified two-entry PHI node, see if we can eliminate it.
static bool findReaching(BasicBlock *BB, BasicBlock *DefBB, BlocksSet &ReachesNonLocalUses)
static bool extractPredSuccWeights(CondBrInst *PBI, CondBrInst *BI, uint64_t &PredTrueWeight, uint64_t &PredFalseWeight, uint64_t &SuccTrueWeight, uint64_t &SuccFalseWeight)
Return true if either PBI or BI has branch weight available, and store the weights in {Pred|Succ}...
static bool initializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest, SwitchCaseResultVectorTy &UniqueResults, Constant *&DefaultResult, const DataLayout &DL, const TargetTransformInfo &TTI, uintptr_t MaxUniqueResults)
static bool shouldUseSwitchConditionAsTableIndex(ConstantInt &MinCaseVal, const ConstantInt &MaxCaseVal, bool HasDefaultResults, const SmallVector< Type * > &ResultTypes, const DataLayout &DL, const TargetTransformInfo &TTI)
static InstructionCost computeSpeculationCost(const User *I, const TargetTransformInfo &TTI)
Compute an abstract "cost" of speculating the given instruction, which is assumed to be safe to specu...
static bool performBranchToCommonDestFolding(CondBrInst *BI, CondBrInst *PBI, DomTreeUpdater *DTU, MemorySSAUpdater *MSSAU, const TargetTransformInfo *TTI)
static std::optional< unsigned > getDenseSwitchRangeReductionShift(ArrayRef< int64_t > Values, int64_t Base, bool OptSize)
SmallPtrSet< BasicBlock *, 8 > BlocksSet
static unsigned skippedInstrFlags(Instruction *I)
static bool mergeCompatibleInvokes(BasicBlock *BB, DomTreeUpdater *DTU)
If this block is a landingpad exception handling block, categorize all the predecessor invokes into s...
static bool replacingOperandWithVariableIsCheap(const Instruction *I, int OpIdx)
static void eraseTerminatorAndDCECond(Instruction *TI, MemorySSAUpdater *MSSAU=nullptr)
static void eliminateBlockCases(BasicBlock *BB, std::vector< ValueEqualityComparisonCase > &Cases)
Given a vector of bb/value pairs, remove any entries in the list that match the specified block.
static bool mergeConditionalStores(CondBrInst *PBI, CondBrInst *QBI, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
static bool mergeNestedCondBranch(CondBrInst *BI, DomTreeUpdater *DTU)
Fold the following pattern: bb0: br i1 cond1, label bb1, label bb2 bb1: br i1 cond2,...
static void sinkLastInstruction(ArrayRef< BasicBlock * > Blocks)
static size_t mapCaseToResult(ConstantInt *CaseVal, SwitchCaseResultVectorTy &UniqueResults, Constant *Result)
static bool tryWidenCondBranchToCondBranch(CondBrInst *PBI, CondBrInst *BI, DomTreeUpdater *DTU)
If the previous block ended with a widenable branch, determine if reusing the target block is profita...
static void mergeCompatibleInvokesImpl(ArrayRef< InvokeInst * > Invokes, DomTreeUpdater *DTU)
static bool mergeIdenticalBBs(ArrayRef< BasicBlock * > Candidates, DomTreeUpdater *DTU)
static void getBranchWeights(Instruction *TI, SmallVectorImpl< uint64_t > &Weights)
Get Weights of a given terminator, the default weight is at the front of the vector.
static bool tryToMergeLandingPad(LandingPadInst *LPad, UncondBrInst *BI, BasicBlock *BB, DomTreeUpdater *DTU)
Given an block with only a single landing pad and a unconditional branch try to find another basic bl...
static Constant * lookupConstant(Value *V, const SmallDenseMap< Value *, Constant * > &ConstantPool)
If V is a Constant, return it.
static bool SimplifyCondBranchToCondBranch(CondBrInst *PBI, CondBrInst *BI, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
If we have a conditional branch as a predecessor of another block, this function tries to simplify it...
static bool canSinkInstructions(ArrayRef< Instruction * > Insts, DenseMap< const Use *, SmallVector< Value *, 4 > > &PHIOperands)
static void hoistLockstepIdenticalDbgVariableRecords(Instruction *TI, Instruction *I1, SmallVectorImpl< Instruction * > &OtherInsts)
Hoists DbgVariableRecords from I1 and OtherInstrs that are identical in lock-step to TI.
static bool removeEmptyCleanup(CleanupReturnInst *RI, DomTreeUpdater *DTU)
static bool removeUndefIntroducingPredecessor(BasicBlock *BB, DomTreeUpdater *DTU, AssumptionCache *AC)
If BB has an incoming value that will always trigger undefined behavior (eg.
static bool isUncontrolledConvergentCall(CallBase *CB)
static bool simplifySwitchWhenUMin(SwitchInst *SI, DomTreeUpdater *DTU)
Tries to transform the switch when the condition is umin with a constant.
static bool isSafeCheapLoadStore(const Instruction *I, const TargetTransformInfo &TTI)
static ConstantInt * getKnownValueOnEdge(Value *V, BasicBlock *From, BasicBlock *To)
static bool dominatesMergePoint(Value *V, BasicBlock *BB, Instruction *InsertPt, SmallPtrSetImpl< Instruction * > &AggressiveInsts, InstructionCost &Cost, InstructionCost Budget, const TargetTransformInfo &TTI, AssumptionCache *AC, SmallPtrSetImpl< Instruction * > &ZeroCostInstructions, unsigned Depth=0)
If we have a merge point of an "if condition" as accepted above, return true if the specified value d...
static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock, CondBrInst *RangeCheckBranch, Constant *DefaultValue, const SmallVectorImpl< std::pair< ConstantInt *, Constant * > > &Values)
Try to reuse the switch table index compare.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:231
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1056
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1691
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1206
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1171
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1552
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:353
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:472
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1996
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1135
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
Definition APInt.h:1595
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1977
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM_ABI bool getValueAsBool() const
Return the attribute's value as a boolean.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:672
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
LLVM_ABI bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:469
LLVM_ABI const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI void flushTerminatorDbgRecords()
Eject any debug-info trailing at the end of a block.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
size_t size() const
Definition BasicBlock.h:467
LLVM_ABI bool isLandingPad() const
Return true if this basic block is a landing pad.
LLVM_ABI bool hasNPredecessorsOrMore(unsigned N) const
Return true if this block has N predecessors or more.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition BasicBlock.h:644
LLVM_ABI const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
BasicBlock * getBasicBlock() const
Definition Constants.h:1125
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
BranchProbability getCompl() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void addRangeRetAttr(const ConstantRange &CR)
adds the range attribute to the list of attributes.
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
bool isConvergent() const
Determine if the invoke is convergent.
Value * getConvergenceControlToken() const
Return the convergence control token for this call, if it exists.
bool isDataOperand(const Use *U) const
bool tryIntersectAttributes(const CallBase *Other)
Try to intersect the attributes from 'this' CallBase and the 'Other' CallBase.
This class represents a function call, abstracting a target machine's calling convention.
mapped_iterator< op_iterator, DerefFnTy > handler_iterator
CleanupPadInst * getCleanupPad() const
Convenience accessor.
BasicBlock * getUnwindDest() const
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
bool isEquality() const
Determine if this is an equals/not equals predicate.
Definition InstrTypes.h:978
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Conditional Branch instruction.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void setCondition(Value *V)
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1316
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
ConstantFolder - Create constants with minimum, target independent, folding.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
bool isNegative() const
Definition Constants.h:214
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
IntegerType * getIntegerType() const
Variant of the getType() method to always return an IntegerType, which reduces the amount of casting ...
Definition Constants.h:198
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A constant pointer value that points to null.
Definition Constants.h:716
This class represents a range of values.
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
LLVM_ABI ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
const APInt & getLower() const
Return the lower value for this range.
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI bool isSizeLargerThan(uint64_t MaxSize) const
Compare set size of this range with Value.
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI bool isUpperWrapped() const
Return true if the exclusive upper bound wraps around the unsigned domain.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange inverse() const
Return a new range that is the logical not of the current set.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
LLVM_ABI bool isOneValue() const
Returns true if the value is one.
Definition Constants.cpp:89
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Base class for non-instruction debug metadata records that have positions within IR.
LLVM_ABI void removeFromParent()
simple_ilist< DbgRecord >::iterator self_iterator
Record of a variable value-assignment, aka a non instruction representation of the dbg....
A debug info location.
Definition DebugLoc.h:126
bool isSameSourceLocation(const DebugLoc &Other) const
Return true if the source locations match, ignoring isImplicitCode and source atom info.
Definition DebugLoc.h:244
static DebugLoc getTemporary()
Definition DebugLoc.h:152
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
Definition DebugLoc.cpp:172
static LLVM_ABI DebugLoc getMergedLocations(ArrayRef< DebugLoc > Locs)
Try to combine the vector of locations passed as input in a single one.
Definition DebugLoc.cpp:159
static DebugLoc getDropped()
Definition DebugLoc.h:155
ValueT & at(const_arg_type_t< KeyT > Val)
Return the entry for the specified key, or abort if no such entry exists.
Definition DenseMap.h:268
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
unsigned size() const
Definition DenseMap.h:172
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:176
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:867