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 auto &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 NewBonusInst->insertInto(PredBlock, PTI->getIterator());
1185
1186 if (!NewBonusInst->getDebugLoc().isSameSourceLocation(PTI->getDebugLoc())) {
1187 // Unless the instruction has the same !dbg location as the original
1188 // branch, drop it. When we fold the bonus instructions we want to make
1189 // sure we reset their debug locations in order to avoid stepping on
1190 // dead code caused by folding dead branches.
1191 NewBonusInst->dropLocation();
1192 } else if (const DebugLoc &DL = NewBonusInst->getDebugLoc()) {
1193 mapAtomInstance(DL, VMap);
1194 }
1195
1196 RemapInstruction(NewBonusInst, VMap,
1198
1199 // If we speculated an instruction, we need to drop any metadata that may
1200 // result in undefined behavior, as the metadata might have been valid
1201 // only given the branch precondition.
1202 // Similarly strip attributes on call parameters that may cause UB in
1203 // location the call is moved to.
1204 NewBonusInst->dropUBImplyingAttrsAndMetadata();
1205
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 else
1432
1433 // The new switch is only known to be unpredictable if both of the comparisons
1434 // it was built from were unpredictable.
1435 if (MDNode *Unpredictable = PTI->getMetadata(LLVMContext::MD_unpredictable))
1436 if (TI->hasMetadata(LLVMContext::MD_unpredictable))
1437 NewSI->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
1438
1440
1441 // Okay, last check. If BB is still a successor of PSI, then we must
1442 // have an infinite loop case. If so, add an infinitely looping block
1443 // to handle the case to preserve the behavior of the code.
1444 BasicBlock *InfLoopBlock = nullptr;
1445 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1446 if (NewSI->getSuccessor(i) == BB) {
1447 if (!InfLoopBlock) {
1448 // Insert it at the end of the function, because it's either code,
1449 // or it won't matter if it's hot. :)
1450 InfLoopBlock =
1451 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
1452 UncondBrInst::Create(InfLoopBlock, InfLoopBlock);
1453 if (DTU)
1454 Updates.push_back(
1455 {DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
1456 }
1457 NewSI->setSuccessor(i, InfLoopBlock);
1458 }
1459
1460 if (DTU) {
1461 if (InfLoopBlock)
1462 Updates.push_back({DominatorTree::Insert, Pred, InfLoopBlock});
1463
1464 Updates.push_back({DominatorTree::Delete, Pred, BB});
1465
1466 DTU->applyUpdates(Updates);
1467 }
1468
1469 ++NumFoldValueComparisonIntoPredecessors;
1470 return true;
1471}
1472
1473/// The specified terminator is a value equality comparison instruction
1474/// (either a switch or a branch on "X == c").
1475/// See if any of the predecessors of the terminator block are value comparisons
1476/// on the same value. If so, and if safe to do so, fold them together.
1477bool SimplifyCFGOpt::foldValueComparisonIntoPredecessors(Instruction *TI,
1478 IRBuilder<> &Builder) {
1479 BasicBlock *BB = TI->getParent();
1480 Value *CV = isValueEqualityComparison(TI); // CondVal
1481 assert(CV && "Not a comparison?");
1482
1483 bool Changed = false;
1484
1485 SmallSetVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
1486 while (!Preds.empty()) {
1487 BasicBlock *Pred = Preds.pop_back_val();
1488 Instruction *PTI = Pred->getTerminator();
1489
1490 // Don't try to fold into itself.
1491 if (Pred == BB)
1492 continue;
1493
1494 // See if the predecessor is a comparison with the same value.
1495 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
1496 if (PCV != CV)
1497 continue;
1498
1499 SmallSetVector<BasicBlock *, 4> FailBlocks;
1500 if (!safeToMergeTerminators(TI, PTI, &FailBlocks)) {
1501 for (auto *Succ : FailBlocks) {
1502 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split", DTU))
1503 return false;
1504 }
1505 }
1506
1507 performValueComparisonIntoPredecessorFolding(TI, CV, PTI, Builder);
1508 Changed = true;
1509 }
1510 return Changed;
1511}
1512
1513// If we would need to insert a select that uses the value of this invoke
1514// (comments in hoistSuccIdenticalTerminatorToSwitchOrIf explain why we would
1515// need to do this), we can't hoist the invoke, as there is nowhere to put the
1516// select in this case.
1518 Instruction *I1, Instruction *I2) {
1519 for (BasicBlock *Succ : successors(BB1)) {
1520 for (const PHINode &PN : Succ->phis()) {
1521 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1522 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1523 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1524 return false;
1525 }
1526 }
1527 }
1528 return true;
1529}
1530
1531// Get interesting characteristics of instructions that
1532// `hoistCommonCodeFromSuccessors` didn't hoist. They restrict what kind of
1533// instructions can be reordered across.
1539
1541 // Pseudo probes don't constrain reordering of other instructions.
1543 return 0;
1544 unsigned Flags = 0;
1545 if (I->mayReadFromMemory())
1546 Flags |= SkipReadMem;
1547 // We can't arbitrarily move around allocas, e.g. moving allocas (especially
1548 // inalloca) across stacksave/stackrestore boundaries.
1549 if (I->mayHaveSideEffects() || isa<AllocaInst>(I))
1550 Flags |= SkipSideEffect;
1552 Flags |= SkipImplicitControlFlow;
1553 return Flags;
1554}
1555
1556// Returns true if it is safe to reorder an instruction across preceding
1557// instructions in a basic block.
1558static bool isSafeToHoistInstr(Instruction *I, unsigned Flags) {
1559 // Don't reorder a store over a load.
1560 if ((Flags & SkipReadMem) && I->mayWriteToMemory())
1561 return false;
1562
1563 // If we have seen an instruction with side effects, it's unsafe to reorder an
1564 // instruction which reads memory or itself has side effects.
1565 if ((Flags & SkipSideEffect) &&
1566 (I->mayReadFromMemory() || I->mayHaveSideEffects() || isa<AllocaInst>(I)))
1567 return false;
1568
1569 // Reordering across an instruction which does not necessarily transfer
1570 // control to the next instruction is speculation.
1572 return false;
1573
1574 // Hoisting of llvm.deoptimize is only legal together with the next return
1575 // instruction, which this pass is not always able to do.
1576 if (auto *CB = dyn_cast<CallBase>(I))
1577 if (CB->getIntrinsicID() == Intrinsic::experimental_deoptimize)
1578 return false;
1579
1580 // It's also unsafe/illegal to hoist an instruction above its instruction
1581 // operands
1582 BasicBlock *BB = I->getParent();
1583 for (Value *Op : I->operands()) {
1584 if (auto *J = dyn_cast<Instruction>(Op))
1585 if (J->getParent() == BB)
1586 return false;
1587 }
1588
1589 return true;
1590}
1591
1592static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified = false);
1593
1594/// Helper function for hoistCommonCodeFromSuccessors. Return true if identical
1595/// instructions \p I1 and \p I2 can and should be hoisted.
1597 const TargetTransformInfo &TTI) {
1598 // If we're going to hoist a call, make sure that the two instructions
1599 // we're commoning/hoisting are both marked with musttail, or neither of
1600 // them is marked as such. Otherwise, we might end up in a situation where
1601 // we hoist from a block where the terminator is a `ret` to a block where
1602 // the terminator is a `br`, and `musttail` calls expect to be followed by
1603 // a return.
1604 auto *C1 = dyn_cast<CallInst>(I1);
1605 auto *C2 = dyn_cast<CallInst>(I2);
1606 if (C1 && C2)
1607 if (C1->isMustTailCall() != C2->isMustTailCall())
1608 return false;
1609
1610 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1611 return false;
1612
1613 // If any of the two call sites has nomerge or convergent attribute, stop
1614 // hoisting.
1615 if (const auto *CB1 = dyn_cast<CallBase>(I1))
1616 if (CB1->cannotMerge() || CB1->isConvergent())
1617 return false;
1618 if (const auto *CB2 = dyn_cast<CallBase>(I2))
1619 if (CB2->cannotMerge() || CB2->isConvergent())
1620 return false;
1621
1622 return true;
1623}
1624
1625/// Hoists DbgVariableRecords from \p I1 and \p OtherInstrs that are identical
1626/// in lock-step to \p TI. This matches how dbg.* intrinsics are hoisting in
1627/// hoistCommonCodeFromSuccessors. e.g. The input:
1628/// I1 DVRs: { x, z },
1629/// OtherInsts: { I2 DVRs: { x, y, z } }
1630/// would result in hoisting only DbgVariableRecord x.
1632 Instruction *TI, Instruction *I1,
1633 SmallVectorImpl<Instruction *> &OtherInsts) {
1634 if (!I1->hasDbgRecords())
1635 return;
1636 using CurrentAndEndIt =
1637 std::pair<DbgRecord::self_iterator, DbgRecord::self_iterator>;
1638 // Vector of {Current, End} iterators.
1640 Itrs.reserve(OtherInsts.size() + 1);
1641 // Helper lambdas for lock-step checks:
1642 // Return true if this Current == End.
1643 auto atEnd = [](const CurrentAndEndIt &Pair) {
1644 return Pair.first == Pair.second;
1645 };
1646 // Return true if all Current are identical.
1647 auto allIdentical = [](const SmallVector<CurrentAndEndIt> &Itrs) {
1648 return all_of(make_first_range(ArrayRef(Itrs).drop_front()),
1650 return Itrs[0].first->isIdenticalToWhenDefined(*I);
1651 });
1652 };
1653
1654 // Collect the iterators.
1655 Itrs.push_back(
1656 {I1->getDbgRecordRange().begin(), I1->getDbgRecordRange().end()});
1657 for (Instruction *Other : OtherInsts) {
1658 if (!Other->hasDbgRecords())
1659 return;
1660 Itrs.push_back(
1661 {Other->getDbgRecordRange().begin(), Other->getDbgRecordRange().end()});
1662 }
1663
1664 // Iterate in lock-step until any of the DbgRecord lists are exausted. If
1665 // the lock-step DbgRecord are identical, hoist all of them to TI.
1666 // This replicates the dbg.* intrinsic behaviour in
1667 // hoistCommonCodeFromSuccessors.
1668 while (none_of(Itrs, atEnd)) {
1669 bool HoistDVRs = allIdentical(Itrs);
1670 for (CurrentAndEndIt &Pair : Itrs) {
1671 // Increment Current iterator now as we may be about to move the
1672 // DbgRecord.
1673 DbgRecord &DR = *Pair.first++;
1674 if (HoistDVRs) {
1675 DR.removeFromParent();
1676 TI->getParent()->insertDbgRecordBefore(&DR, TI->getIterator());
1677 }
1678 }
1679 }
1680}
1681
1683 const Instruction *I2) {
1684 if (I1->isIdenticalToWhenDefined(I2, /*IntersectAttrs=*/true))
1685 return true;
1686
1687 if (auto *Cmp1 = dyn_cast<CmpInst>(I1))
1688 if (auto *Cmp2 = dyn_cast<CmpInst>(I2))
1689 return Cmp1->getPredicate() == Cmp2->getSwappedPredicate() &&
1690 Cmp1->getOperand(0) == Cmp2->getOperand(1) &&
1691 Cmp1->getOperand(1) == Cmp2->getOperand(0);
1692
1693 if (I1->isCommutative() && I1->isSameOperationAs(I2)) {
1694 return I1->getOperand(0) == I2->getOperand(1) &&
1695 I1->getOperand(1) == I2->getOperand(0) &&
1696 equal(drop_begin(I1->operands(), 2), drop_begin(I2->operands(), 2));
1697 }
1698
1699 return false;
1700}
1701
1702/// If the target supports conditional faulting,
1703/// we look for the following pattern:
1704/// \code
1705/// BB:
1706/// ...
1707/// %cond = icmp ult %x, %y
1708/// br i1 %cond, label %TrueBB, label %FalseBB
1709/// FalseBB:
1710/// store i32 1, ptr %q, align 4
1711/// ...
1712/// TrueBB:
1713/// %maskedloadstore = load i32, ptr %b, align 4
1714/// store i32 %maskedloadstore, ptr %p, align 4
1715/// ...
1716/// \endcode
1717///
1718/// and transform it into:
1719///
1720/// \code
1721/// BB:
1722/// ...
1723/// %cond = icmp ult %x, %y
1724/// %maskedloadstore = cload i32, ptr %b, %cond
1725/// cstore i32 %maskedloadstore, ptr %p, %cond
1726/// cstore i32 1, ptr %q, ~%cond
1727/// br i1 %cond, label %TrueBB, label %FalseBB
1728/// FalseBB:
1729/// ...
1730/// TrueBB:
1731/// ...
1732/// \endcode
1733///
1734/// where cload/cstore are represented by llvm.masked.load/store intrinsics,
1735/// e.g.
1736///
1737/// \code
1738/// %vcond = bitcast i1 %cond to <1 x i1>
1739/// %v0 = call <1 x i32> @llvm.masked.load.v1i32.p0
1740/// (ptr %b, i32 4, <1 x i1> %vcond, <1 x i32> poison)
1741/// %maskedloadstore = bitcast <1 x i32> %v0 to i32
1742/// call void @llvm.masked.store.v1i32.p0
1743/// (<1 x i32> %v0, ptr %p, i32 4, <1 x i1> %vcond)
1744/// %cond.not = xor i1 %cond, true
1745/// %vcond.not = bitcast i1 %cond.not to <1 x i>
1746/// call void @llvm.masked.store.v1i32.p0
1747/// (<1 x i32> <i32 1>, ptr %q, i32 4, <1x i1> %vcond.not)
1748/// \endcode
1749///
1750/// So we need to turn hoisted load/store into cload/cstore.
1751///
1752/// \param BI The branch instruction.
1753/// \param SpeculatedConditionalLoadsStores The load/store instructions that
1754/// will be speculated.
1755/// \param Invert indicates if speculates FalseBB. Only used in triangle CFG.
1757 CondBrInst *BI,
1758 SmallVectorImpl<Instruction *> &SpeculatedConditionalLoadsStores,
1759 std::optional<bool> Invert, Instruction *Sel) {
1760 auto &Context = BI->getParent()->getContext();
1761 auto *VCondTy = FixedVectorType::get(Type::getInt1Ty(Context), 1);
1762 auto *Cond = BI->getCondition();
1763 // Construct the condition if needed.
1764 BasicBlock *BB = BI->getParent();
1765 Value *Mask = nullptr;
1766 Value *MaskFalse = nullptr;
1767 Value *MaskTrue = nullptr;
1768 if (Invert.has_value()) {
1769 IRBuilder<> Builder(Sel ? Sel : SpeculatedConditionalLoadsStores.back());
1770 Mask = Builder.CreateBitCast(
1771 *Invert ? Builder.CreateXor(Cond, ConstantInt::getTrue(Context)) : Cond,
1772 VCondTy);
1773 } else {
1774 IRBuilder<> Builder(BI);
1775 MaskFalse = Builder.CreateBitCast(
1776 Builder.CreateXor(Cond, ConstantInt::getTrue(Context)), VCondTy);
1777 MaskTrue = Builder.CreateBitCast(Cond, VCondTy);
1778 }
1779 auto PeekThroughBitcasts = [](Value *V) {
1780 while (auto *BitCast = dyn_cast<BitCastInst>(V))
1781 V = BitCast->getOperand(0);
1782 return V;
1783 };
1784 for (auto *I : SpeculatedConditionalLoadsStores) {
1785 IRBuilder<> Builder(Invert.has_value() ? I : BI);
1786 if (!Invert.has_value())
1787 Mask = I->getParent() == BI->getSuccessor(0) ? MaskTrue : MaskFalse;
1788 // We currently assume conditional faulting load/store is supported for
1789 // scalar types only when creating new instructions. This can be easily
1790 // extended for vector types in the future.
1791 assert(!getLoadStoreType(I)->isVectorTy() && "not implemented");
1792 auto *Op0 = I->getOperand(0);
1793 CallInst *MaskedLoadStore = nullptr;
1794 if (auto *LI = dyn_cast<LoadInst>(I)) {
1795 // Handle Load.
1796 auto *Ty = I->getType();
1797 PHINode *PN = nullptr;
1798 Value *PassThru = nullptr;
1799 if (Invert.has_value())
1800 for (User *U : I->users()) {
1801 if ((PN = dyn_cast<PHINode>(U))) {
1802 PassThru = Builder.CreateBitCast(
1803 PeekThroughBitcasts(PN->getIncomingValueForBlock(BB)),
1804 FixedVectorType::get(Ty, 1));
1805 } else if (auto *Ins = cast<Instruction>(U);
1806 Sel && Ins->getParent() == BB) {
1807 // This happens when store or/and a speculative instruction between
1808 // load and store were hoisted to the BB. Make sure the masked load
1809 // inserted before its use.
1810 // We assume there's one of such use.
1811 Builder.SetInsertPoint(Ins);
1812 }
1813 }
1814 MaskedLoadStore = Builder.CreateMaskedLoad(
1815 FixedVectorType::get(Ty, 1), Op0, LI->getAlign(), Mask, PassThru);
1816 if (const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
1818 if (PassThru && !isa<PoisonValue>(PassThru)) {
1819 auto *C = dyn_cast<Constant>(PassThru);
1820 CR = C ? CR.unionWith(C->toConstantRange())
1821 : ConstantRange::getFull(CR.getBitWidth());
1822 }
1823 MaskedLoadStore->addRangeRetAttr(CR);
1824 }
1825 Value *NewLoadStore = Builder.CreateBitCast(MaskedLoadStore, Ty);
1826 if (PN)
1827 PN->setIncomingValue(PN->getBasicBlockIndex(BB), NewLoadStore);
1828 I->replaceAllUsesWith(NewLoadStore);
1829 } else {
1830 // Handle Store.
1831 auto *StoredVal = Builder.CreateBitCast(
1832 PeekThroughBitcasts(Op0), FixedVectorType::get(Op0->getType(), 1));
1833 MaskedLoadStore = Builder.CreateMaskedStore(
1834 StoredVal, I->getOperand(1), cast<StoreInst>(I)->getAlign(), Mask);
1835 }
1836 // For non-debug metadata, only !annotation, !range, !nonnull and !align are
1837 // kept when hoisting (see Instruction::dropUBImplyingAttrsAndMetadata).
1838 //
1839 // !nonnull, !align : Not support pointer type, no need to keep.
1840 // !range: Kept as a return attribute, widened over PassThru (see above).
1841 // !annotation: Not impact semantics. Keep it.
1842 I->dropUBImplyingAttrsAndUnknownMetadata({LLVMContext::MD_annotation});
1843 // FIXME: DIAssignID is not supported for masked store yet.
1844 // (Verifier::visitDIAssignIDMetadata)
1846 I->eraseMetadataIf([](unsigned MDKind, MDNode *Node) {
1847 return Node->getMetadataID() == Metadata::DIAssignIDKind;
1848 });
1849 MaskedLoadStore->copyMetadata(*I);
1850 I->eraseFromParent();
1851 }
1852}
1853
1855 const TargetTransformInfo &TTI) {
1856 // Not handle volatile or atomic.
1857 bool IsStore = false;
1858 if (auto *L = dyn_cast<LoadInst>(I)) {
1859 if (!L->isSimple() || !HoistLoadsWithCondFaulting)
1860 return false;
1861 } else if (auto *S = dyn_cast<StoreInst>(I)) {
1862 if (!S->isSimple() || !HoistStoresWithCondFaulting)
1863 return false;
1864 IsStore = true;
1865 } else
1866 return false;
1867
1868 // llvm.masked.load/store use i32 for alignment while load/store use i64.
1869 // That's why we have the alignment limitation.
1870 // FIXME: Update the prototype of the intrinsics?
1871 return TTI.hasConditionalLoadStoreForType(getLoadStoreType(I), IsStore) &&
1873}
1874
1875/// Hoist any common code in the successor blocks up into the block. This
1876/// function guarantees that BB dominates all successors. If AllInstsEqOnly is
1877/// given, only perform hoisting in case all successors blocks contain matching
1878/// instructions only. In that case, all instructions can be hoisted and the
1879/// original branch will be replaced and selects for PHIs are added.
1880bool SimplifyCFGOpt::hoistCommonCodeFromSuccessors(Instruction *TI,
1881 bool AllInstsEqOnly) {
1882 // This does very trivial matching, with limited scanning, to find identical
1883 // instructions in the two blocks. In particular, we don't want to get into
1884 // O(N1*N2*...) situations here where Ni are the sizes of these successors. As
1885 // such, we currently just scan for obviously identical instructions in an
1886 // identical order, possibly separated by the same number of non-identical
1887 // instructions.
1888 BasicBlock *BB = TI->getParent();
1889 unsigned int SuccSize = succ_size(BB);
1890 if (SuccSize < 2)
1891 return false;
1892
1893 // If either of the blocks has it's address taken, then we can't do this fold,
1894 // because the code we'd hoist would no longer run when we jump into the block
1895 // by it's address.
1896 SmallSetVector<BasicBlock *, 4> UniqueSuccessors(from_range, successors(BB));
1897 for (auto *Succ : UniqueSuccessors) {
1898 if (Succ->hasAddressTaken())
1899 return false;
1900 // Use getUniquePredecessor instead of getSinglePredecessor to support
1901 // multi-cases successors in switch.
1902 if (Succ->getUniquePredecessor())
1903 continue;
1904 // If Succ has >1 predecessors, continue to check if the Succ contains only
1905 // one `unreachable` inst. Since executing `unreachable` inst is an UB, we
1906 // can relax the condition based on the assumptiom that the program would
1907 // never enter Succ and trigger such an UB.
1908 if (isa<UnreachableInst>(*Succ->begin()))
1909 continue;
1910 return false;
1911 }
1912 // The second of pair is a SkipFlags bitmask.
1913 using SuccIterPair = std::pair<BasicBlock::iterator, unsigned>;
1914 SmallVector<SuccIterPair, 8> SuccIterPairs;
1915 for (auto *Succ : UniqueSuccessors) {
1916 BasicBlock::iterator SuccItr = Succ->begin();
1917 if (isa<PHINode>(*SuccItr))
1918 return false;
1919 SuccIterPairs.push_back(SuccIterPair(SuccItr, 0));
1920 }
1921
1922 if (AllInstsEqOnly) {
1923 // Check if all instructions in the successor blocks match. This allows
1924 // hoisting all instructions and removing the blocks we are hoisting from,
1925 // so does not add any new instructions.
1926
1927 // Check if sizes and terminators of all successors match.
1928 unsigned Size0 = UniqueSuccessors[0]->size();
1929 Instruction *Term0 = UniqueSuccessors[0]->getTerminator();
1930 bool AllSame =
1931 all_of(drop_begin(UniqueSuccessors), [Term0, Size0](BasicBlock *Succ) {
1932 return Succ->getTerminator()->isIdenticalTo(Term0) &&
1933 Succ->size() == Size0;
1934 });
1935 if (!AllSame)
1936 return false;
1937 LockstepReverseIterator<true> LRI(UniqueSuccessors.getArrayRef());
1938 while (LRI.isValid()) {
1939 Instruction *I0 = (*LRI)[0];
1940 if (any_of(*LRI, [I0](Instruction *I) {
1941 return !areIdenticalUpToCommutativity(I0, I);
1942 })) {
1943 return false;
1944 }
1945 --LRI;
1946 }
1947 // Now we know that all instructions in all successors can be hoisted. Let
1948 // the loop below handle the hoisting.
1949 }
1950
1951 // Count how many instructions were not hoisted so far. There's a limit on how
1952 // many instructions we skip, serving as a compilation time control as well as
1953 // preventing excessive increase of life ranges.
1954 unsigned NumSkipped = 0;
1955 // If we find an unreachable instruction at the beginning of a basic block, we
1956 // can still hoist instructions from the rest of the basic blocks.
1957 if (SuccIterPairs.size() > 2) {
1958 erase_if(SuccIterPairs,
1959 [](const auto &Pair) { return isa<UnreachableInst>(Pair.first); });
1960 if (SuccIterPairs.size() < 2)
1961 return false;
1962 }
1963
1964 bool Changed = false;
1965
1966 for (;;) {
1967 auto *SuccIterPairBegin = SuccIterPairs.begin();
1968 auto &BB1ItrPair = *SuccIterPairBegin++;
1969 auto OtherSuccIterPairRange =
1970 iterator_range(SuccIterPairBegin, SuccIterPairs.end());
1971 auto OtherSuccIterRange = make_first_range(OtherSuccIterPairRange);
1972
1973 Instruction *I1 = &*BB1ItrPair.first;
1974
1975 bool AllInstsAreIdentical = true;
1976 bool HasTerminator = I1->isTerminator();
1977 for (auto &SuccIter : OtherSuccIterRange) {
1978 Instruction *I2 = &*SuccIter;
1979 HasTerminator |= I2->isTerminator();
1980 if (AllInstsAreIdentical && (!areIdenticalUpToCommutativity(I1, I2) ||
1981 MMRAMetadata(*I1) != MMRAMetadata(*I2)))
1982 AllInstsAreIdentical = false;
1983 }
1984
1985 SmallVector<Instruction *, 8> OtherInsts;
1986 for (auto &SuccIter : OtherSuccIterRange)
1987 OtherInsts.push_back(&*SuccIter);
1988
1989 // If we are hoisting the terminator instruction, don't move one (making a
1990 // broken BB), instead clone it, and remove BI.
1991 if (HasTerminator) {
1992 // Even if BB, which contains only one unreachable instruction, is ignored
1993 // at the beginning of the loop, we can hoist the terminator instruction.
1994 // If any instructions remain in the block, we cannot hoist terminators.
1995 if (NumSkipped || !AllInstsAreIdentical) {
1996 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
1997 return Changed;
1998 }
1999
2000 return hoistSuccIdenticalTerminatorToSwitchOrIf(
2001 TI, I1, OtherInsts, UniqueSuccessors.getArrayRef()) ||
2002 Changed;
2003 }
2004
2005 if (AllInstsAreIdentical) {
2006 unsigned SkipFlagsBB1 = BB1ItrPair.second;
2007 AllInstsAreIdentical =
2008 isSafeToHoistInstr(I1, SkipFlagsBB1) &&
2009 all_of(OtherSuccIterPairRange, [=](const auto &Pair) {
2010 Instruction *I2 = &*Pair.first;
2011 unsigned SkipFlagsBB2 = Pair.second;
2012 // Even if the instructions are identical, it may not
2013 // be safe to hoist them if we have skipped over
2014 // instructions with side effects or their operands
2015 // weren't hoisted.
2016 return isSafeToHoistInstr(I2, SkipFlagsBB2) &&
2018 });
2019 }
2020
2021 // A musttail call must be immediately followed by a ret, so hoisting is
2022 // only legal if its ret is hoisted with it on the next iteration. That is,
2023 // no instruction has been skipped (the entire successor can be hoisted into
2024 // the predecessor) and the call is directly followed by a ret.
2025 if (auto *CI = dyn_cast<CallInst>(I1);
2026 AllInstsAreIdentical && CI && CI->isMustTailCall()) {
2027 AllInstsAreIdentical =
2028 NumSkipped == 0 && all_of(SuccIterPairs, [](const SuccIterPair &P) {
2029 return isa<ReturnInst>(*std::next(P.first));
2030 });
2031 }
2032
2033 if (AllInstsAreIdentical) {
2034 BB1ItrPair.first++;
2035 // For a normal instruction, we just move one to right before the
2036 // branch, then replace all uses of the other with the first. Finally,
2037 // we remove the now redundant second instruction.
2038 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
2039 // We've just hoisted DbgVariableRecords; move I1 after them (before TI)
2040 // and leave any that were not hoisted behind (by calling moveBefore
2041 // rather than moveBeforePreserving).
2042 I1->moveBefore(TI->getIterator());
2043 for (auto &SuccIter : OtherSuccIterRange) {
2044 Instruction *I2 = &*SuccIter++;
2045 assert(I2 != I1);
2046 if (!I2->use_empty())
2047 I2->replaceAllUsesWith(I1);
2048 I1->andIRFlags(I2);
2049 if (auto *CB = dyn_cast<CallBase>(I1)) {
2050 bool Success = CB->tryIntersectAttributes(cast<CallBase>(I2));
2051 assert(Success && "We should not be trying to hoist callbases "
2052 "with non-intersectable attributes");
2053 // For NDEBUG Compile.
2054 (void)Success;
2055 }
2056
2057 combineMetadataForCSE(I1, I2, true);
2058 // If we are combining select instructions, we mark the profile
2059 // explicitly unknown given we are hoisting the instruction across
2060 // control flow and we have no guarantee that the control flow condition
2061 // we are hoisting across is independent of the select condition.
2062 if (auto *SI = dyn_cast<SelectInst>(I1))
2064 // I1 and I2 are being combined into a single instruction. Its debug
2065 // location is the merged locations of the original instructions.
2066 I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
2067 I2->eraseFromParent();
2068 }
2069 // I1 now executes before the instructions we skipped.
2070 unsigned SkippedFlags = 0;
2071 for (const SuccIterPair &P : SuccIterPairs)
2072 SkippedFlags |= P.second;
2073 if (SkippedFlags & SkipImplicitControlFlow) {
2074 // One of them may throw or not return, so I1 is speculated.
2075 I1->dropUBImplyingAttrsAndMetadata();
2076 }
2077 if (!Changed)
2078 NumHoistCommonCode += SuccIterPairs.size();
2079 Changed = true;
2080 NumHoistCommonInstrs += SuccIterPairs.size();
2081 } else {
2082 if (NumSkipped >= HoistCommonSkipLimit) {
2083 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
2084 return Changed;
2085 }
2086 // We are about to skip over a pair of non-identical instructions. Record
2087 // if any have characteristics that would prevent reordering instructions
2088 // across them.
2089 for (auto &SuccIterPair : SuccIterPairs) {
2090 Instruction *I = &*SuccIterPair.first++;
2091 SuccIterPair.second |= skippedInstrFlags(I);
2092 }
2093 ++NumSkipped;
2094 }
2095 }
2096}
2097
2098bool SimplifyCFGOpt::hoistSuccIdenticalTerminatorToSwitchOrIf(
2099 Instruction *TI, Instruction *I1,
2100 SmallVectorImpl<Instruction *> &OtherSuccTIs,
2101 ArrayRef<BasicBlock *> UniqueSuccessors) {
2102
2103 auto *BI = dyn_cast<CondBrInst>(TI);
2104
2105 bool Changed = false;
2106 BasicBlock *TIParent = TI->getParent();
2107 BasicBlock *BB1 = I1->getParent();
2108
2109 // Use only for an if statement.
2110 auto *I2 = *OtherSuccTIs.begin();
2111 auto *BB2 = I2->getParent();
2112 if (BI) {
2113 assert(OtherSuccTIs.size() == 1);
2114 assert(BI->getSuccessor(0) == I1->getParent());
2115 assert(BI->getSuccessor(1) == I2->getParent());
2116 }
2117
2118 // In the case of an if statement, we try to hoist an invoke.
2119 // FIXME: Can we define a safety predicate for CallBr?
2120 // FIXME: Test case llvm/test/Transforms/SimplifyCFG/2009-06-15-InvokeCrash.ll
2121 // removed in 4c923b3b3fd0ac1edebf0603265ca3ba51724937 commit?
2122 if (isa<InvokeInst>(I1) && (!BI || !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
2123 return false;
2124
2125 // TODO: callbr hoisting currently disabled pending further study.
2126 if (isa<CallBrInst>(I1))
2127 return false;
2128
2129 for (BasicBlock *Succ : successors(BB1)) {
2130 for (PHINode &PN : Succ->phis()) {
2131 Value *BB1V = PN.getIncomingValueForBlock(BB1);
2132 for (Instruction *OtherSuccTI : OtherSuccTIs) {
2133 Value *BB2V = PN.getIncomingValueForBlock(OtherSuccTI->getParent());
2134 if (BB1V == BB2V)
2135 continue;
2136
2137 // In the case of an if statement, check for
2138 // passingValueIsAlwaysUndefined here because we would rather eliminate
2139 // undefined control flow then converting it to a select.
2140 if (!BI || passingValueIsAlwaysUndefined(BB1V, &PN) ||
2142 return false;
2143 }
2144 }
2145 }
2146
2147 // Hoist DbgVariableRecords attached to the terminator to match dbg.*
2148 // intrinsic hoisting behaviour in hoistCommonCodeFromSuccessors.
2149 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherSuccTIs);
2150 // Clone the terminator and hoist it into the pred, without any debug info.
2151 Instruction *NT = I1->clone();
2152 NT->insertInto(TIParent, TI->getIterator());
2153 if (!NT->getType()->isVoidTy()) {
2154 I1->replaceAllUsesWith(NT);
2155 for (Instruction *OtherSuccTI : OtherSuccTIs)
2156 OtherSuccTI->replaceAllUsesWith(NT);
2157 NT->takeName(I1);
2158 }
2159 Changed = true;
2160 NumHoistCommonInstrs += OtherSuccTIs.size() + 1;
2161
2162 // Ensure terminator gets a debug location, even an unknown one, in case
2163 // it involves inlinable calls.
2165 Locs.push_back(I1->getDebugLoc());
2166 for (auto *OtherSuccTI : OtherSuccTIs)
2167 Locs.push_back(OtherSuccTI->getDebugLoc());
2168 NT->setDebugLoc(DebugLoc::getMergedLocations(Locs));
2169
2170 // PHIs created below will adopt NT's merged DebugLoc.
2171 IRBuilder<NoFolder> Builder(NT);
2172
2173 // In the case of an if statement, hoisting one of the terminators from our
2174 // successor is a great thing. Unfortunately, the successors of the if/else
2175 // blocks may have PHI nodes in them. If they do, all PHI entries for BB1/BB2
2176 // must agree for all PHI nodes, so we insert select instruction to compute
2177 // the final result.
2178 if (BI) {
2179 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
2180 for (BasicBlock *Succ : successors(BB1)) {
2181 for (PHINode &PN : Succ->phis()) {
2182 Value *BB1V = PN.getIncomingValueForBlock(BB1);
2183 Value *BB2V = PN.getIncomingValueForBlock(BB2);
2184 if (BB1V == BB2V)
2185 continue;
2186
2187 // These values do not agree. Insert a select instruction before NT
2188 // that determines the right value.
2189 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
2190 if (!SI) {
2191 // Propagate fast-math-flags from phi node to its replacement select.
2193 BI->getCondition(), BB1V, BB2V,
2194 isa<FPMathOperator>(PN) ? &PN : nullptr,
2195 BB1V->getName() + "." + BB2V->getName(), BI));
2196 }
2197
2198 // Make the PHI node use the select for all incoming values for BB1/BB2
2199 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2200 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
2201 PN.setIncomingValue(i, SI);
2202 }
2203 }
2204 }
2205
2207
2208 // Update any PHI nodes in our new successors.
2209 SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
2210 for (BasicBlock *Succ : successors(BB1)) {
2211 addPredecessorToBlock(Succ, TIParent, BB1);
2212
2213 if (DTU && VisitedSuccs.insert(Succ).second)
2214 Updates.push_back({DominatorTree::Insert, TIParent, Succ});
2215 }
2216
2217 if (DTU) {
2218 // TI might be a switch with multi-cases destination, so we need to care for
2219 // the duplication of successors.
2220 for (BasicBlock *Succ : UniqueSuccessors)
2221 Updates.push_back({DominatorTree::Delete, TIParent, Succ});
2222 }
2223
2225 if (DTU)
2226 DTU->applyUpdates(Updates);
2227 return Changed;
2228}
2229
2230// TODO: Refine this. This should avoid cases like turning constant memcpy sizes
2231// into variables.
2233 int OpIdx) {
2234 // Divide/Remainder by constant is typically much cheaper than by variable.
2235 if (I->isIntDivRem())
2236 return OpIdx != 1;
2237 return !isa<IntrinsicInst>(I);
2238}
2239
2240// All instructions in Insts belong to different blocks that all unconditionally
2241// branch to a common successor. Analyze each instruction and return true if it
2242// would be possible to sink them into their successor, creating one common
2243// instruction instead. For every value that would be required to be provided by
2244// PHI node (because an operand varies in each input block), add to PHIOperands.
2247 DenseMap<const Use *, SmallVector<Value *, 4>> &PHIOperands) {
2248 // Prune out obviously bad instructions to move. Each instruction must have
2249 // the same number of uses, and we check later that the uses are consistent.
2250 std::optional<unsigned> NumUses;
2251 for (auto *I : Insts) {
2252 // These instructions may change or break semantics if moved.
2253 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
2254 I->getType()->isTokenTy())
2255 return false;
2256
2257 // Do not try to sink an instruction in an infinite loop - it can cause
2258 // this algorithm to infinite loop.
2259 if (I->getParent()->getSingleSuccessor() == I->getParent())
2260 return false;
2261
2262 // Conservatively return false if I is an inline-asm instruction. Sinking
2263 // and merging inline-asm instructions can potentially create arguments
2264 // that cannot satisfy the inline-asm constraints.
2265 // If the instruction has nomerge or convergent attribute, return false.
2266 if (const auto *C = dyn_cast<CallBase>(I))
2267 if (C->isInlineAsm() || C->cannotMerge() || C->isConvergent())
2268 return false;
2269
2270 if (!NumUses)
2271 NumUses = I->getNumUses();
2272 else if (NumUses != I->getNumUses())
2273 return false;
2274 }
2275
2276 const Instruction *I0 = Insts.front();
2277 const auto I0MMRA = MMRAMetadata(*I0);
2278 for (auto *I : Insts) {
2279 if (!I->isSameOperationAs(I0, Instruction::CompareUsingIntersectedAttrs))
2280 return false;
2281
2282 // Treat MMRAs conservatively. This pass can be quite aggressive and
2283 // could drop a lot of MMRAs otherwise.
2284 if (MMRAMetadata(*I) != I0MMRA)
2285 return false;
2286 }
2287
2288 // Uses must be consistent: If I0 is used in a phi node in the sink target,
2289 // then the other phi operands must match the instructions from Insts. This
2290 // also has to hold true for any phi nodes that would be created as a result
2291 // of sinking. Both of these cases are represented by PhiOperands.
2292 for (const Use &U : I0->uses()) {
2293 auto It = PHIOperands.find(&U);
2294 if (It == PHIOperands.end())
2295 // There may be uses in other blocks when sinking into a loop header.
2296 return false;
2297 if (!equal(Insts, It->second))
2298 return false;
2299 }
2300
2301 // For calls to be sinkable, they must all be indirect, or have same callee.
2302 // I.e. if we have two direct calls to different callees, we don't want to
2303 // turn that into an indirect call. Likewise, if we have an indirect call,
2304 // and a direct call, we don't actually want to have a single indirect call.
2305 if (isa<CallBase>(I0)) {
2306 auto IsIndirectCall = [](const Instruction *I) {
2307 return cast<CallBase>(I)->isIndirectCall();
2308 };
2309 bool HaveIndirectCalls = any_of(Insts, IsIndirectCall);
2310 bool AllCallsAreIndirect = all_of(Insts, IsIndirectCall);
2311 if (HaveIndirectCalls) {
2312 if (!AllCallsAreIndirect)
2313 return false;
2314 } else {
2315 // All callees must be identical.
2316 Value *Callee = nullptr;
2317 for (const Instruction *I : Insts) {
2318 Value *CurrCallee = cast<CallBase>(I)->getCalledOperand();
2319 if (!Callee)
2320 Callee = CurrCallee;
2321 else if (Callee != CurrCallee)
2322 return false;
2323 }
2324 }
2325 }
2326
2327 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
2328 Value *Op = I0->getOperand(OI);
2329 auto SameAsI0 = [&I0, OI](const Instruction *I) {
2330 assert(I->getNumOperands() == I0->getNumOperands());
2331 return I->getOperand(OI) == I0->getOperand(OI);
2332 };
2333 if (!all_of(Insts, SameAsI0)) {
2334 auto CanReplaceOperand = [OI](const Instruction *I) {
2335 return canReplaceOperandWithVariable(I, OI);
2336 };
2338 !all_of(Insts, CanReplaceOperand))
2339 // We can't create a PHI from this operand.
2340 return false;
2341 auto &Ops = PHIOperands[&I0->getOperandUse(OI)];
2342 for (auto *I : Insts)
2343 Ops.push_back(I->getOperand(OI));
2344 }
2345 }
2346 return true;
2347}
2348
2349// Assuming canSinkInstructions(Blocks) has returned true, sink the last
2350// instruction of every block in Blocks to their common successor, commoning
2351// into one instruction.
2353 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
2354
2355 // canSinkInstructions returning true guarantees that every block has at
2356 // least one non-terminator instruction.
2358 for (auto *BB : Blocks) {
2359 Instruction *I = BB->getTerminator();
2360 I = I->getPrevNode();
2361 Insts.push_back(I);
2362 }
2363
2364 // We don't need to do any more checking here; canSinkInstructions should
2365 // have done it all for us.
2366 SmallVector<Value*, 4> NewOperands;
2367 Instruction *I0 = Insts.front();
2368 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
2369 // This check is different to that in canSinkInstructions. There, we
2370 // cared about the global view once simplifycfg (and instcombine) have
2371 // completed - it takes into account PHIs that become trivially
2372 // simplifiable. However here we need a more local view; if an operand
2373 // differs we create a PHI and rely on instcombine to clean up the very
2374 // small mess we may make.
2375 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
2376 return I->getOperand(O) != I0->getOperand(O);
2377 });
2378 if (!NeedPHI) {
2379 NewOperands.push_back(I0->getOperand(O));
2380 continue;
2381 }
2382
2383 // Create a new PHI in the successor block and populate it.
2384 auto *Op = I0->getOperand(O);
2385 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
2386 auto *PN =
2387 PHINode::Create(Op->getType(), Insts.size(), Op->getName() + ".sink");
2388 PN->insertBefore(BBEnd->begin());
2389 for (auto *I : Insts)
2390 PN->addIncoming(I->getOperand(O), I->getParent());
2391 NewOperands.push_back(PN);
2392 }
2393
2394 // Arbitrarily use I0 as the new "common" instruction; remap its operands
2395 // and move it to the start of the successor block.
2396 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
2397 I0->getOperandUse(O).set(NewOperands[O]);
2398
2399 I0->moveBefore(*BBEnd, BBEnd->getFirstInsertionPt());
2400
2401 // Update metadata and IR flags, and merge debug locations.
2402 for (auto *I : Insts)
2403 if (I != I0) {
2404 // The debug location for the "common" instruction is the merged locations
2405 // of all the commoned instructions. We start with the original location
2406 // of the "common" instruction and iteratively merge each location in the
2407 // loop below.
2408 // This is an N-way merge, which will be inefficient if I0 is a CallInst.
2409 // However, as N-way merge for CallInst is rare, so we use simplified API
2410 // instead of using complex API for N-way merge.
2411 I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
2412 combineMetadataForCSE(I0, I, true);
2413 // We mark branch weights explicitly unknown for select instructions as we
2414 // might be sinking through control flow with conditions not independent
2415 // of the select condition, or pulling multiple conditions together
2416 // through a phi node.
2417 if (auto *SI = dyn_cast<SelectInst>(I0))
2419 I0->andIRFlags(I);
2420 if (auto *CB = dyn_cast<CallBase>(I0)) {
2421 bool Success = CB->tryIntersectAttributes(cast<CallBase>(I));
2422 assert(Success && "We should not be trying to sink callbases "
2423 "with non-intersectable attributes");
2424 // For NDEBUG Compile.
2425 (void)Success;
2426 }
2427 }
2428
2429 for (User *U : make_early_inc_range(I0->users())) {
2430 // canSinkLastInstruction checked that all instructions are only used by
2431 // phi nodes in a way that allows replacing the phi node with the common
2432 // instruction.
2433 auto *PN = cast<PHINode>(U);
2434 PN->replaceAllUsesWith(I0);
2435 PN->eraseFromParent();
2436 }
2437
2438 // Finally nuke all instructions apart from the common instruction.
2439 for (auto *I : Insts) {
2440 if (I == I0)
2441 continue;
2442 // The remaining uses are debug users, replace those with the common inst.
2443 // In most (all?) cases this just introduces a use-before-def.
2444 assert(I->user_empty() && "Inst unexpectedly still has non-dbg users");
2445 I->replaceAllUsesWith(I0);
2446 I->eraseFromParent();
2447 }
2448}
2449
2450/// Check whether BB's predecessors end with unconditional branches. If it is
2451/// true, sink any common code from the predecessors to BB.
2453 DomTreeUpdater *DTU) {
2454 // We support two situations:
2455 // (1) all incoming arcs are unconditional
2456 // (2) there are non-unconditional incoming arcs
2457 //
2458 // (2) is very common in switch defaults and
2459 // else-if patterns;
2460 //
2461 // if (a) f(1);
2462 // else if (b) f(2);
2463 //
2464 // produces:
2465 //
2466 // [if]
2467 // / \
2468 // [f(1)] [if]
2469 // | | \
2470 // | | |
2471 // | [f(2)]|
2472 // \ | /
2473 // [ end ]
2474 //
2475 // [end] has two unconditional predecessor arcs and one conditional. The
2476 // conditional refers to the implicit empty 'else' arc. This conditional
2477 // arc can also be caused by an empty default block in a switch.
2478 //
2479 // In this case, we attempt to sink code from all *unconditional* arcs.
2480 // If we can sink instructions from these arcs (determined during the scan
2481 // phase below) we insert a common successor for all unconditional arcs and
2482 // connect that to [end], to enable sinking:
2483 //
2484 // [if]
2485 // / \
2486 // [x(1)] [if]
2487 // | | \
2488 // | | \
2489 // | [x(2)] |
2490 // \ / |
2491 // [sink.split] |
2492 // \ /
2493 // [ end ]
2494 //
2495 SmallVector<BasicBlock*,4> UnconditionalPreds;
2496 bool HaveNonUnconditionalPredecessors = false;
2497 for (auto *PredBB : predecessors(BB)) {
2498 auto *PredBr = dyn_cast<UncondBrInst>(PredBB->getTerminator());
2499 if (PredBr)
2500 UnconditionalPreds.push_back(PredBB);
2501 else
2502 HaveNonUnconditionalPredecessors = true;
2503 }
2504 if (UnconditionalPreds.size() < 2)
2505 return false;
2506
2507 // We take a two-step approach to tail sinking. First we scan from the end of
2508 // each block upwards in lockstep. If the n'th instruction from the end of each
2509 // block can be sunk, those instructions are added to ValuesToSink and we
2510 // carry on. If we can sink an instruction but need to PHI-merge some operands
2511 // (because they're not identical in each instruction) we add these to
2512 // PHIOperands.
2513 // We prepopulate PHIOperands with the phis that already exist in BB.
2515 for (PHINode &PN : BB->phis()) {
2517 for (const Use &U : PN.incoming_values())
2518 IncomingVals.insert({PN.getIncomingBlock(U), &U});
2519 auto &Ops = PHIOperands[IncomingVals[UnconditionalPreds[0]]];
2520 for (BasicBlock *Pred : UnconditionalPreds)
2521 Ops.push_back(*IncomingVals[Pred]);
2522 }
2523
2524 int ScanIdx = 0;
2525 SmallPtrSet<Value*,4> InstructionsToSink;
2526 LockstepReverseIterator<true> LRI(UnconditionalPreds);
2527 while (LRI.isValid() &&
2528 canSinkInstructions(*LRI, PHIOperands)) {
2529 LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
2530 << "\n");
2531 InstructionsToSink.insert_range(*LRI);
2532 ++ScanIdx;
2533 --LRI;
2534 }
2535
2536 // If no instructions can be sunk, early-return.
2537 if (ScanIdx == 0)
2538 return false;
2539
2540 bool followedByDeoptOrUnreachable = IsBlockFollowedByDeoptOrUnreachable(BB);
2541
2542 if (!followedByDeoptOrUnreachable) {
2543 // Check whether this is the pointer operand of a load/store.
2544 auto IsMemOperand = [](Use &U) {
2545 auto *I = cast<Instruction>(U.getUser());
2546 if (isa<LoadInst>(I))
2547 return U.getOperandNo() == LoadInst::getPointerOperandIndex();
2548 if (isa<StoreInst>(I))
2549 return U.getOperandNo() == StoreInst::getPointerOperandIndex();
2550 return false;
2551 };
2552
2553 // Okay, we *could* sink last ScanIdx instructions. But how many can we
2554 // actually sink before encountering instruction that is unprofitable to
2555 // sink?
2556 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator<true> &LRI) {
2557 unsigned NumPHIInsts = 0;
2558 for (Use &U : (*LRI)[0]->operands()) {
2559 auto It = PHIOperands.find(&U);
2560 if (It != PHIOperands.end() && !all_of(It->second, [&](Value *V) {
2561 return InstructionsToSink.contains(V);
2562 })) {
2563 ++NumPHIInsts;
2564 // Do not separate a load/store from the gep producing the address.
2565 // The gep can likely be folded into the load/store as an addressing
2566 // mode. Additionally, a load of a gep is easier to analyze than a
2567 // load of a phi.
2568 if (IsMemOperand(U) &&
2569 any_of(It->second, [](Value *V) { return isa<GEPOperator>(V); }))
2570 return false;
2571 // FIXME: this check is overly optimistic. We may end up not sinking
2572 // said instruction, due to the very same profitability check.
2573 // See @creating_too_many_phis in sink-common-code.ll.
2574 }
2575 }
2576 LLVM_DEBUG(dbgs() << "SINK: #phi insts: " << NumPHIInsts << "\n");
2577 return NumPHIInsts <= 1;
2578 };
2579
2580 // We've determined that we are going to sink last ScanIdx instructions,
2581 // and recorded them in InstructionsToSink. Now, some instructions may be
2582 // unprofitable to sink. But that determination depends on the instructions
2583 // that we are going to sink.
2584
2585 // First, forward scan: find the first instruction unprofitable to sink,
2586 // recording all the ones that are profitable to sink.
2587 // FIXME: would it be better, after we detect that not all are profitable.
2588 // to either record the profitable ones, or erase the unprofitable ones?
2589 // Maybe we need to choose (at runtime) the one that will touch least
2590 // instrs?
2591 LRI.reset();
2592 int Idx = 0;
2593 SmallPtrSet<Value *, 4> InstructionsProfitableToSink;
2594 while (Idx < ScanIdx) {
2595 if (!ProfitableToSinkInstruction(LRI)) {
2596 // Too many PHIs would be created.
2597 LLVM_DEBUG(
2598 dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
2599 break;
2600 }
2601 InstructionsProfitableToSink.insert_range(*LRI);
2602 --LRI;
2603 ++Idx;
2604 }
2605
2606 // If no instructions can be sunk, early-return.
2607 if (Idx == 0)
2608 return false;
2609
2610 // Did we determine that (only) some instructions are unprofitable to sink?
2611 if (Idx < ScanIdx) {
2612 // Okay, some instructions are unprofitable.
2613 ScanIdx = Idx;
2614 InstructionsToSink = InstructionsProfitableToSink;
2615
2616 // But, that may make other instructions unprofitable, too.
2617 // So, do a backward scan, do any earlier instructions become
2618 // unprofitable?
2619 assert(
2620 !ProfitableToSinkInstruction(LRI) &&
2621 "We already know that the last instruction is unprofitable to sink");
2622 ++LRI;
2623 --Idx;
2624 while (Idx >= 0) {
2625 // If we detect that an instruction becomes unprofitable to sink,
2626 // all earlier instructions won't be sunk either,
2627 // so preemptively keep InstructionsProfitableToSink in sync.
2628 // FIXME: is this the most performant approach?
2629 for (auto *I : *LRI)
2630 InstructionsProfitableToSink.erase(I);
2631 if (!ProfitableToSinkInstruction(LRI)) {
2632 // Everything starting with this instruction won't be sunk.
2633 ScanIdx = Idx;
2634 InstructionsToSink = InstructionsProfitableToSink;
2635 }
2636 ++LRI;
2637 --Idx;
2638 }
2639 }
2640
2641 // If no instructions can be sunk, early-return.
2642 if (ScanIdx == 0)
2643 return false;
2644 }
2645
2646 bool Changed = false;
2647
2648 if (HaveNonUnconditionalPredecessors) {
2649 if (!followedByDeoptOrUnreachable) {
2650 // It is always legal to sink common instructions from unconditional
2651 // predecessors. However, if not all predecessors are unconditional,
2652 // this transformation might be pessimizing. So as a rule of thumb,
2653 // don't do it unless we'd sink at least one non-speculatable instruction.
2654 // See https://bugs.llvm.org/show_bug.cgi?id=30244
2655 LRI.reset();
2656 int Idx = 0;
2657 bool Profitable = false;
2658 while (Idx < ScanIdx) {
2659 if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
2660 Profitable = true;
2661 break;
2662 }
2663 --LRI;
2664 ++Idx;
2665 }
2666 if (!Profitable)
2667 return false;
2668 }
2669
2670 LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
2671 // We have a conditional edge and we're going to sink some instructions.
2672 // Insert a new block postdominating all blocks we're going to sink from.
2673 if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split", DTU))
2674 // Edges couldn't be split.
2675 return false;
2676 Changed = true;
2677 }
2678
2679 // Now that we've analyzed all potential sinking candidates, perform the
2680 // actual sink. We iteratively sink the last non-terminator of the source
2681 // blocks into their common successor unless doing so would require too
2682 // many PHI instructions to be generated (currently only one PHI is allowed
2683 // per sunk instruction).
2684 //
2685 // We can use InstructionsToSink to discount values needing PHI-merging that will
2686 // actually be sunk in a later iteration. This allows us to be more
2687 // aggressive in what we sink. This does allow a false positive where we
2688 // sink presuming a later value will also be sunk, but stop half way through
2689 // and never actually sink it which means we produce more PHIs than intended.
2690 // This is unlikely in practice though.
2691 int SinkIdx = 0;
2692 for (; SinkIdx != ScanIdx; ++SinkIdx) {
2693 LLVM_DEBUG(dbgs() << "SINK: Sink: "
2694 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
2695 << "\n");
2696
2697 // Because we've sunk every instruction in turn, the current instruction to
2698 // sink is always at index 0.
2699 LRI.reset();
2700
2701 sinkLastInstruction(UnconditionalPreds);
2702 NumSinkCommonInstrs++;
2703 Changed = true;
2704 }
2705 if (SinkIdx != 0)
2706 ++NumSinkCommonCode;
2707 return Changed;
2708}
2709
2710namespace {
2711
2712struct CompatibleSets {
2713 using SetTy = SmallVector<InvokeInst *, 2>;
2714
2716
2717 static bool shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes);
2718
2719 SetTy &getCompatibleSet(InvokeInst *II);
2720
2721 void insert(InvokeInst *II);
2722};
2723
2724CompatibleSets::SetTy &CompatibleSets::getCompatibleSet(InvokeInst *II) {
2725 // Perform a linear scan over all the existing sets, see if the new `invoke`
2726 // is compatible with any particular set. Since we know that all the `invokes`
2727 // within a set are compatible, only check the first `invoke` in each set.
2728 // WARNING: at worst, this has quadratic complexity.
2729 for (CompatibleSets::SetTy &Set : Sets) {
2730 if (CompatibleSets::shouldBelongToSameSet({Set.front(), II}))
2731 return Set;
2732 }
2733
2734 // Otherwise, we either had no sets yet, or this invoke forms a new set.
2735 return Sets.emplace_back();
2736}
2737
2738void CompatibleSets::insert(InvokeInst *II) {
2739 getCompatibleSet(II).emplace_back(II);
2740}
2741
2742bool CompatibleSets::shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes) {
2743 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2744
2745 // Can we theoretically merge these `invoke`s?
2746 auto IsIllegalToMerge = [](InvokeInst *II) {
2747 return II->cannotMerge() || II->isInlineAsm();
2748 };
2749 if (any_of(Invokes, IsIllegalToMerge))
2750 return false;
2751
2752 // Either both `invoke`s must be direct,
2753 // or both `invoke`s must be indirect.
2754 auto IsIndirectCall = [](InvokeInst *II) { return II->isIndirectCall(); };
2755 bool HaveIndirectCalls = any_of(Invokes, IsIndirectCall);
2756 bool AllCallsAreIndirect = all_of(Invokes, IsIndirectCall);
2757 if (HaveIndirectCalls) {
2758 if (!AllCallsAreIndirect)
2759 return false;
2760 } else {
2761 // All callees must be identical.
2762 Value *Callee = nullptr;
2763 for (InvokeInst *II : Invokes) {
2764 Value *CurrCallee = II->getCalledOperand();
2765 assert(CurrCallee && "There is always a called operand.");
2766 if (!Callee)
2767 Callee = CurrCallee;
2768 else if (Callee != CurrCallee)
2769 return false;
2770 }
2771 }
2772
2773 // Either both `invoke`s must not have a normal destination,
2774 // or both `invoke`s must have a normal destination,
2775 auto HasNormalDest = [](InvokeInst *II) {
2776 return !isa<UnreachableInst>(II->getNormalDest()->getFirstNonPHIIt());
2777 };
2778 if (any_of(Invokes, HasNormalDest)) {
2779 // Do not merge `invoke` that does not have a normal destination with one
2780 // that does have a normal destination, even though doing so would be legal.
2781 if (!all_of(Invokes, HasNormalDest))
2782 return false;
2783
2784 // All normal destinations must be identical.
2785 BasicBlock *NormalBB = nullptr;
2786 for (InvokeInst *II : Invokes) {
2787 BasicBlock *CurrNormalBB = II->getNormalDest();
2788 assert(CurrNormalBB && "There is always a 'continue to' basic block.");
2789 if (!NormalBB)
2790 NormalBB = CurrNormalBB;
2791 else if (NormalBB != CurrNormalBB)
2792 return false;
2793 }
2794
2795 // In the normal destination, the incoming values for these two `invoke`s
2796 // must be compatible.
2797 SmallPtrSet<Value *, 16> EquivalenceSet(llvm::from_range, Invokes);
2799 NormalBB, {Invokes[0]->getParent(), Invokes[1]->getParent()},
2800 &EquivalenceSet))
2801 return false;
2802 }
2803
2804#ifndef NDEBUG
2805 // All unwind destinations must be identical.
2806 // We know that because we have started from said unwind destination.
2807 BasicBlock *UnwindBB = nullptr;
2808 for (InvokeInst *II : Invokes) {
2809 BasicBlock *CurrUnwindBB = II->getUnwindDest();
2810 assert(CurrUnwindBB && "There is always an 'unwind to' basic block.");
2811 if (!UnwindBB)
2812 UnwindBB = CurrUnwindBB;
2813 else
2814 assert(UnwindBB == CurrUnwindBB && "Unexpected unwind destination.");
2815 }
2816#endif
2817
2818 // In the unwind destination, the incoming values for these two `invoke`s
2819 // must be compatible.
2821 Invokes.front()->getUnwindDest(),
2822 {Invokes[0]->getParent(), Invokes[1]->getParent()}))
2823 return false;
2824
2825 // Ignoring arguments, these `invoke`s must be identical,
2826 // including operand bundles.
2827 const InvokeInst *II0 = Invokes.front();
2828 for (auto *II : Invokes.drop_front())
2829 if (!II->isSameOperationAs(II0, Instruction::CompareUsingIntersectedAttrs))
2830 return false;
2831
2832 // Can we theoretically form the data operands for the merged `invoke`?
2833 auto IsIllegalToMergeArguments = [](auto Ops) {
2834 Use &U0 = std::get<0>(Ops);
2835 Use &U1 = std::get<1>(Ops);
2836 if (U0 == U1)
2837 return false;
2839 U0.getOperandNo());
2840 };
2841 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2842 if (any_of(zip(Invokes[0]->data_ops(), Invokes[1]->data_ops()),
2843 IsIllegalToMergeArguments))
2844 return false;
2845
2846 return true;
2847}
2848
2849} // namespace
2850
2851// Merge all invokes in the provided set, all of which are compatible
2852// as per the `CompatibleSets::shouldBelongToSameSet()`.
2854 DomTreeUpdater *DTU) {
2855 assert(Invokes.size() >= 2 && "Must have at least two invokes to merge.");
2856
2858 if (DTU)
2859 Updates.reserve(2 + 3 * Invokes.size());
2860
2861 bool HasNormalDest =
2862 !isa<UnreachableInst>(Invokes[0]->getNormalDest()->getFirstNonPHIIt());
2863
2864 // Clone one of the invokes into a new basic block.
2865 // Since they are all compatible, it doesn't matter which invoke is cloned.
2866 InvokeInst *MergedInvoke = [&Invokes, HasNormalDest]() {
2867 InvokeInst *II0 = Invokes.front();
2868 BasicBlock *II0BB = II0->getParent();
2869 BasicBlock *InsertBeforeBlock =
2870 II0->getParent()->getIterator()->getNextNode();
2871 Function *Func = II0BB->getParent();
2872 LLVMContext &Ctx = II0->getContext();
2873
2874 BasicBlock *MergedInvokeBB = BasicBlock::Create(
2875 Ctx, II0BB->getName() + ".invoke", Func, InsertBeforeBlock);
2876
2877 auto *MergedInvoke = cast<InvokeInst>(II0->clone());
2878 // NOTE: all invokes have the same attributes, so no handling needed.
2879 MergedInvoke->insertInto(MergedInvokeBB, MergedInvokeBB->end());
2880
2881 if (!HasNormalDest) {
2882 // This set does not have a normal destination,
2883 // so just form a new block with unreachable terminator.
2884 BasicBlock *MergedNormalDest = BasicBlock::Create(
2885 Ctx, II0BB->getName() + ".cont", Func, InsertBeforeBlock);
2886 auto *UI = new UnreachableInst(Ctx, MergedNormalDest);
2887 UI->setDebugLoc(DebugLoc::getTemporary());
2888 MergedInvoke->setNormalDest(MergedNormalDest);
2889 }
2890
2891 // The unwind destination, however, remainds identical for all invokes here.
2892
2893 return MergedInvoke;
2894 }();
2895
2896 if (DTU) {
2897 // Predecessor blocks that contained these invokes will now branch to
2898 // the new block that contains the merged invoke, ...
2899 for (InvokeInst *II : Invokes)
2900 Updates.push_back(
2901 {DominatorTree::Insert, II->getParent(), MergedInvoke->getParent()});
2902
2903 // ... which has the new `unreachable` block as normal destination,
2904 // or unwinds to the (same for all `invoke`s in this set) `landingpad`,
2905 for (BasicBlock *SuccBBOfMergedInvoke : successors(MergedInvoke))
2906 Updates.push_back({DominatorTree::Insert, MergedInvoke->getParent(),
2907 SuccBBOfMergedInvoke});
2908
2909 // Since predecessor blocks now unconditionally branch to a new block,
2910 // they no longer branch to their original successors.
2911 for (InvokeInst *II : Invokes)
2912 for (BasicBlock *SuccOfPredBB : successors(II->getParent()))
2913 Updates.push_back(
2914 {DominatorTree::Delete, II->getParent(), SuccOfPredBB});
2915 }
2916
2917 bool IsIndirectCall = Invokes[0]->isIndirectCall();
2918
2919 // Form the merged operands for the merged invoke.
2920 for (Use &U : MergedInvoke->operands()) {
2921 // Only PHI together the indirect callees and data operands.
2922 if (MergedInvoke->isCallee(&U)) {
2923 if (!IsIndirectCall)
2924 continue;
2925 } else if (!MergedInvoke->isDataOperand(&U))
2926 continue;
2927
2928 // Don't create trivial PHI's with all-identical incoming values.
2929 bool NeedPHI = any_of(Invokes, [&U](InvokeInst *II) {
2930 return II->getOperand(U.getOperandNo()) != U.get();
2931 });
2932 if (!NeedPHI)
2933 continue;
2934
2935 // Form a PHI out of all the data ops under this index.
2937 U->getType(), /*NumReservedValues=*/Invokes.size(), "", MergedInvoke->getIterator());
2938 for (InvokeInst *II : Invokes)
2939 PN->addIncoming(II->getOperand(U.getOperandNo()), II->getParent());
2940
2941 U.set(PN);
2942 }
2943
2944 // We've ensured that each PHI node has compatible (identical) incoming values
2945 // when coming from each of the `invoke`s in the current merge set,
2946 // so update the PHI nodes accordingly.
2947 for (BasicBlock *Succ : successors(MergedInvoke))
2948 addPredecessorToBlock(Succ, /*NewPred=*/MergedInvoke->getParent(),
2949 /*ExistPred=*/Invokes.front()->getParent());
2950
2951 // And finally, replace the original `invoke`s with an unconditional branch
2952 // to the block with the merged `invoke`. Also, give that merged `invoke`
2953 // the merged debugloc of all the original `invoke`s.
2954 DILocation *MergedDebugLoc = nullptr;
2955 for (InvokeInst *II : Invokes) {
2956 // Compute the debug location common to all the original `invoke`s.
2957 if (!MergedDebugLoc)
2958 MergedDebugLoc = II->getDebugLoc();
2959 else
2960 MergedDebugLoc =
2961 DebugLoc::getMergedLocation(MergedDebugLoc, II->getDebugLoc());
2962
2963 // And replace the old `invoke` with an unconditionally branch
2964 // to the block with the merged `invoke`.
2965 for (BasicBlock *OrigSuccBB : successors(II->getParent()))
2966 OrigSuccBB->removePredecessor(II->getParent());
2967 auto *BI = UncondBrInst::Create(MergedInvoke->getParent(), II->getParent());
2968 // The unconditional branch is part of the replacement for the original
2969 // invoke, so should use its DebugLoc.
2970 BI->setDebugLoc(II->getDebugLoc());
2971 bool Success = MergedInvoke->tryIntersectAttributes(II);
2972 assert(Success && "Merged invokes with incompatible attributes");
2973 // For NDEBUG Compile
2974 (void)Success;
2975 II->replaceAllUsesWith(MergedInvoke);
2976 II->eraseFromParent();
2977 ++NumInvokesMerged;
2978 }
2979 MergedInvoke->setDebugLoc(MergedDebugLoc);
2980 ++NumInvokeSetsFormed;
2981
2982 if (DTU)
2983 DTU->applyUpdates(Updates);
2984}
2985
2986/// If this block is a `landingpad` exception handling block, categorize all
2987/// the predecessor `invoke`s into sets, with all `invoke`s in each set
2988/// being "mergeable" together, and then merge invokes in each set together.
2989///
2990/// This is a weird mix of hoisting and sinking. Visually, it goes from:
2991/// [...] [...]
2992/// | |
2993/// [invoke0] [invoke1]
2994/// / \ / \
2995/// [cont0] [landingpad] [cont1]
2996/// to:
2997/// [...] [...]
2998/// \ /
2999/// [invoke]
3000/// / \
3001/// [cont] [landingpad]
3002///
3003/// But of course we can only do that if the invokes share the `landingpad`,
3004/// edges invoke0->cont0 and invoke1->cont1 are "compatible",
3005/// and the invoked functions are "compatible".
3008 return false;
3009
3010 bool Changed = false;
3011
3012 // FIXME: generalize to all exception handling blocks?
3013 if (!BB->isLandingPad())
3014 return Changed;
3015
3016 CompatibleSets Grouper;
3017
3018 // Record all the predecessors of this `landingpad`. As per verifier,
3019 // the only allowed predecessor is the unwind edge of an `invoke`.
3020 // We want to group "compatible" `invokes` into the same set to be merged.
3021 for (BasicBlock *PredBB : predecessors(BB))
3022 Grouper.insert(cast<InvokeInst>(PredBB->getTerminator()));
3023
3024 // And now, merge `invoke`s that were grouped togeter.
3025 for (ArrayRef<InvokeInst *> Invokes : Grouper.Sets) {
3026 if (Invokes.size() < 2)
3027 continue;
3028 Changed = true;
3029 mergeCompatibleInvokesImpl(Invokes, DTU);
3030 }
3031
3032 return Changed;
3033}
3034
3035namespace {
3036/// Track ephemeral values, which should be ignored for cost-modelling
3037/// purposes. Requires walking instructions in reverse order.
3038class EphemeralValueTracker {
3039 SmallPtrSet<const Instruction *, 32> EphValues;
3040
3041 bool isEphemeral(const Instruction *I) {
3042 if (isa<AssumeInst>(I))
3043 return true;
3044 return !I->mayHaveSideEffects() && !I->isTerminator() &&
3045 all_of(I->users(), [&](const User *U) {
3046 return EphValues.count(cast<Instruction>(U));
3047 });
3048 }
3049
3050public:
3051 bool track(const Instruction *I) {
3052 if (isEphemeral(I)) {
3053 EphValues.insert(I);
3054 return true;
3055 }
3056 return false;
3057 }
3058
3059 bool contains(const Instruction *I) const { return EphValues.contains(I); }
3060};
3061} // namespace
3062
3063/// Determine if we can hoist sink a sole store instruction out of a
3064/// conditional block.
3065///
3066/// We are looking for code like the following:
3067/// BrBB:
3068/// store i32 %add, i32* %arrayidx2
3069/// ... // No other stores or function calls (we could be calling a memory
3070/// ... // function).
3071/// %cmp = icmp ult %x, %y
3072/// br i1 %cmp, label %EndBB, label %ThenBB
3073/// ThenBB:
3074/// store i32 %add5, i32* %arrayidx2
3075/// br label EndBB
3076/// EndBB:
3077/// ...
3078/// We are going to transform this into:
3079/// BrBB:
3080/// store i32 %add, i32* %arrayidx2
3081/// ... //
3082/// %cmp = icmp ult %x, %y
3083/// %add.add5 = select i1 %cmp, i32 %add, %add5
3084/// store i32 %add.add5, i32* %arrayidx2
3085/// ...
3086///
3087/// \return The value from the previous access if the store can be hoisted into
3088/// the predecessor block. PreviousAccess is set to that access. Return
3089/// null otherwise.
3091 BasicBlock *StoreBB, BasicBlock *EndBB,
3092 Instruction *&PreviousAccess) {
3093 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
3094 if (!StoreToHoist)
3095 return nullptr;
3096
3097 // Volatile or atomic.
3098 if (!StoreToHoist->isSimple())
3099 return nullptr;
3100
3101 Value *StorePtr = StoreToHoist->getPointerOperand();
3102 Type *StoreTy = StoreToHoist->getValueOperand()->getType();
3103
3104 // Look for a store to the same pointer in BrBB.
3105 unsigned MaxNumInstToLookAt = 9;
3106 // Skip pseudo probe intrinsic calls which are not really killing any memory
3107 // accesses.
3108 for (Instruction &CurI : reverse(*BrBB)) {
3109 if (!MaxNumInstToLookAt)
3110 break;
3111 --MaxNumInstToLookAt;
3112
3113 if (isa<PseudoProbeInst>(CurI))
3114 continue;
3115
3116 // Could be calling an instruction that affects memory like free().
3117 if (CurI.mayWriteToMemory() && !isa<StoreInst>(CurI))
3118 return nullptr;
3119
3120 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
3121 // Found the previous store to same location and type. Make sure it is
3122 // simple, to avoid introducing a spurious non-atomic write after an
3123 // atomic write.
3124 if (SI->getPointerOperand() == StorePtr &&
3125 SI->getValueOperand()->getType() == StoreTy && SI->isSimple() &&
3126 SI->getAlign() >= StoreToHoist->getAlign()) {
3127 // Found the previous store, return its value operand.
3128 PreviousAccess = SI;
3129 return SI->getValueOperand();
3130 }
3131 return nullptr; // Unknown store.
3132 }
3133
3134 if (auto *LI = dyn_cast<LoadInst>(&CurI)) {
3135 if (LI->getPointerOperand() == StorePtr && LI->getType() == StoreTy &&
3136 LI->isSimple() && LI->getAlign() >= StoreToHoist->getAlign()) {
3137 Value *Obj = getUnderlyingObject(StorePtr);
3138 bool ExplicitlyDereferenceableOnly;
3139 // The dereferenceability query here is only required to satisfy the
3140 // writable contract, actual dereferenceability is proven by the
3141 // presence of an access. As such, we can ignore frees.
3142 if (isWritableObject(Obj, ExplicitlyDereferenceableOnly) &&
3145 .WithoutRet) &&
3146 (!ExplicitlyDereferenceableOnly ||
3147 isDereferenceablePointer(StorePtr, StoreTy, LI->getDataLayout(),
3148 /*IgnoreFree=*/true))) {
3149 // Found a previous load, return it.
3150 PreviousAccess = LI;
3151 return LI;
3152 }
3153 }
3154 // The load didn't work out, but we may still find a store.
3155 }
3156 }
3157
3158 return nullptr;
3159}
3160
3161/// Estimate the cost of the insertion(s) and check that the PHI nodes can be
3162/// converted to selects.
3164 BasicBlock *EndBB,
3165 unsigned &SpeculatedInstructions,
3166 InstructionCost &Cost,
3167 const TargetTransformInfo &TTI) {
3169 BB->getParent()->hasMinSize()
3172
3173 bool HaveRewritablePHIs = false;
3174 for (PHINode &PN : EndBB->phis()) {
3175 Value *OrigV = PN.getIncomingValueForBlock(BB);
3176 Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
3177
3178 // FIXME: Try to remove some of the duplication with
3179 // hoistCommonCodeFromSuccessors. Skip PHIs which are trivial.
3180 if (ThenV == OrigV)
3181 continue;
3182
3183 Cost += TTI.getCmpSelInstrCost(Instruction::Select, PN.getType(),
3184 Type::getInt1Ty(PN.getContext()),
3185 CmpInst::BAD_ICMP_PREDICATE, CostKind);
3186
3187 // Don't convert to selects if we could remove undefined behavior instead.
3188 if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
3190 return false;
3191
3192 HaveRewritablePHIs = true;
3193 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
3194 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
3195 if (!OrigCE && !ThenCE)
3196 continue; // Known cheap (FIXME: Maybe not true for aggregates).
3197
3198 InstructionCost OrigCost = OrigCE ? computeSpeculationCost(OrigCE, TTI) : 0;
3199 InstructionCost ThenCost = ThenCE ? computeSpeculationCost(ThenCE, TTI) : 0;
3200 InstructionCost MaxCost =
3202 if (OrigCost + ThenCost > MaxCost)
3203 return false;
3204
3205 // Account for the cost of an unfolded ConstantExpr which could end up
3206 // getting expanded into Instructions.
3207 // FIXME: This doesn't account for how many operations are combined in the
3208 // constant expression.
3209 ++SpeculatedInstructions;
3210 if (SpeculatedInstructions > 1)
3211 return false;
3212 }
3213
3214 return HaveRewritablePHIs;
3215}
3216
3218 std::optional<bool> Invert,
3219 const TargetTransformInfo &TTI) {
3220 // If the branch is non-unpredictable, and is predicted to *not* branch to
3221 // the `then` block, then avoid speculating it.
3222 if (BI->getMetadata(LLVMContext::MD_unpredictable))
3223 return true;
3224
3225 uint64_t TWeight, FWeight;
3226 if (!extractBranchWeights(*BI, TWeight, FWeight) || (TWeight + FWeight) == 0)
3227 return true;
3228
3229 if (!Invert.has_value())
3230 return false;
3231
3232 uint64_t EndWeight = *Invert ? TWeight : FWeight;
3233 BranchProbability BIEndProb =
3234 BranchProbability::getBranchProbability(EndWeight, TWeight + FWeight);
3235 BranchProbability Likely = TTI.getPredictableBranchThreshold();
3236 return BIEndProb < Likely;
3237}
3238
3239/// Speculate a conditional basic block flattening the CFG.
3240///
3241/// Note that this is a very risky transform currently. Speculating
3242/// instructions like this is most often not desirable. Instead, there is an MI
3243/// pass which can do it with full awareness of the resource constraints.
3244/// However, some cases are "obvious" and we should do directly. An example of
3245/// this is speculating a single, reasonably cheap instruction.
3246///
3247/// There is only one distinct advantage to flattening the CFG at the IR level:
3248/// it makes very common but simplistic optimizations such as are common in
3249/// instcombine and the DAG combiner more powerful by removing CFG edges and
3250/// modeling their effects with easier to reason about SSA value graphs.
3251///
3252///
3253/// An illustration of this transform is turning this IR:
3254/// \code
3255/// BB:
3256/// %cmp = icmp ult %x, %y
3257/// br i1 %cmp, label %EndBB, label %ThenBB
3258/// ThenBB:
3259/// %sub = sub %x, %y
3260/// br label BB2
3261/// EndBB:
3262/// %phi = phi [ %sub, %ThenBB ], [ 0, %BB ]
3263/// ...
3264/// \endcode
3265///
3266/// Into this IR:
3267/// \code
3268/// BB:
3269/// %cmp = icmp ult %x, %y
3270/// %sub = sub %x, %y
3271/// %cond = select i1 %cmp, 0, %sub
3272/// ...
3273/// \endcode
3274///
3275/// \returns true if the conditional block is removed.
3276bool SimplifyCFGOpt::speculativelyExecuteBB(CondBrInst *BI,
3277 BasicBlock *ThenBB) {
3278 if (!Options.SpeculateBlocks)
3279 return false;
3280
3281 BasicBlock *BB = BI->getParent();
3282 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
3283 InstructionCost Budget =
3285
3286 // If ThenBB is actually on the false edge of the conditional branch, remember
3287 // to swap the select operands later.
3288 bool Invert = false;
3289 if (ThenBB != BI->getSuccessor(0)) {
3290 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
3291 Invert = true;
3292 }
3293 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
3294
3295 if (!isProfitableToSpeculate(BI, Invert, TTI))
3296 return false;
3297
3298 // Keep a count of how many times instructions are used within ThenBB when
3299 // they are candidates for sinking into ThenBB. Specifically:
3300 // - They are defined in BB, and
3301 // - They have no side effects, and
3302 // - All of their uses are in ThenBB.
3303 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
3304
3305 SmallVector<Instruction *, 4> SpeculatedPseudoProbes;
3306
3307 unsigned SpeculatedInstructions = 0;
3308 bool HoistLoadsStores = Options.HoistLoadsStoresWithCondFaulting;
3309 SmallVector<Instruction *, 2> SpeculatedConditionalLoadsStores;
3310 Value *SpeculatedStoreValue = nullptr;
3311 StoreInst *SpeculatedStore = nullptr;
3312 Instruction *PreviousStoreAccess = nullptr;
3313 EphemeralValueTracker EphTracker;
3314 for (Instruction &I : reverse(drop_end(*ThenBB))) {
3315 // Skip pseudo probes. The consequence is we lose track of the branch
3316 // probability for ThenBB, which is fine since the optimization here takes
3317 // place regardless of the branch probability.
3318 if (isa<PseudoProbeInst>(I)) {
3319 // The probe should be deleted so that it will not be over-counted when
3320 // the samples collected on the non-conditional path are counted towards
3321 // the conditional path. We leave it for the counts inference algorithm to
3322 // figure out a proper count for an unknown probe.
3323 SpeculatedPseudoProbes.push_back(&I);
3324 continue;
3325 }
3326
3327 // Ignore ephemeral values, they will be dropped by the transform.
3328 if (EphTracker.track(&I))
3329 continue;
3330
3331 // Only speculatively execute a single instruction (not counting the
3332 // terminator) for now.
3333 bool IsSafeCheapLoadStore = HoistLoadsStores &&
3335 SpeculatedConditionalLoadsStores.size() <
3337 // Not count load/store into cost if target supports conditional faulting
3338 // b/c it's cheap to speculate it.
3339 if (IsSafeCheapLoadStore)
3340 SpeculatedConditionalLoadsStores.push_back(&I);
3341 else
3342 ++SpeculatedInstructions;
3343
3344 if (SpeculatedInstructions > 1)
3345 return false;
3346
3347 // Don't hoist the instruction if it's unsafe or expensive.
3348 if (!IsSafeCheapLoadStore &&
3350 !(HoistCondStores && !SpeculatedStoreValue &&
3351 (SpeculatedStoreValue = isSafeToSpeculateStore(&I, BB, ThenBB, EndBB,
3352 PreviousStoreAccess))))
3353 return false;
3354 if (!IsSafeCheapLoadStore && !SpeculatedStoreValue &&
3357 return false;
3358
3359 // Store the store speculation candidate.
3360 if (!SpeculatedStore && SpeculatedStoreValue)
3361 SpeculatedStore = cast<StoreInst>(&I);
3362
3363 // Do not hoist the instruction if any of its operands are defined but not
3364 // used in BB. The transformation will prevent the operand from
3365 // being sunk into the use block.
3366 for (Use &Op : I.operands()) {
3368 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
3369 continue; // Not a candidate for sinking.
3370
3371 ++SinkCandidateUseCounts[OpI];
3372 }
3373 }
3374
3375 // Consider any sink candidates which are only used in ThenBB as costs for
3376 // speculation. Note, while we iterate over a DenseMap here, we are summing
3377 // and so iteration order isn't significant.
3378 for (const auto &[Inst, Count] : SinkCandidateUseCounts)
3379 if (Inst->hasNUses(Count)) {
3380 ++SpeculatedInstructions;
3381 if (SpeculatedInstructions > 1)
3382 return false;
3383 }
3384
3385 // Check that we can insert the selects and that it's not too expensive to do
3386 // so.
3387 bool Convert =
3388 SpeculatedStore != nullptr || !SpeculatedConditionalLoadsStores.empty();
3390 Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB,
3391 SpeculatedInstructions, Cost, TTI);
3392 if (!Convert || Cost > Budget)
3393 return false;
3394
3395 // If we get here, we can hoist the instruction and if-convert.
3396 LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
3397
3398 Instruction *Sel = nullptr;
3399 Value *BrCond = BI->getCondition();
3400 // Insert a select of the value of the speculated store.
3401 if (SpeculatedStoreValue) {
3402 IRBuilder<NoFolder> Builder(BI);
3403 Value *OrigV = SpeculatedStore->getValueOperand();
3404 Value *TrueV = SpeculatedStore->getValueOperand();
3405 Value *FalseV = SpeculatedStoreValue;
3406 if (Invert)
3407 std::swap(TrueV, FalseV);
3408 Value *S = Builder.CreateSelect(
3409 BrCond, TrueV, FalseV, "spec.store.select", BI);
3410 Sel = cast<Instruction>(S);
3411 SpeculatedStore->setOperand(0, S);
3412 SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
3413 SpeculatedStore->getDebugLoc());
3414 // The value stored is still conditional, but the store itself is now
3415 // unconditionally executed, so we must be sure that any linked dbg.assign
3416 // intrinsics are tracking the new stored value (the result of the
3417 // select). If we don't, and the store were to be removed by another pass
3418 // (e.g. DSE), then we'd eventually end up emitting a location describing
3419 // the conditional value, unconditionally.
3420 //
3421 // === Before this transformation ===
3422 // pred:
3423 // store %one, %x.dest, !DIAssignID !1
3424 // dbg.assign %one, "x", ..., !1, ...
3425 // br %cond if.then
3426 //
3427 // if.then:
3428 // store %two, %x.dest, !DIAssignID !2
3429 // dbg.assign %two, "x", ..., !2, ...
3430 //
3431 // === After this transformation ===
3432 // pred:
3433 // store %one, %x.dest, !DIAssignID !1
3434 // dbg.assign %one, "x", ..., !1
3435 /// ...
3436 // %merge = select %cond, %two, %one
3437 // store %merge, %x.dest, !DIAssignID !2
3438 // dbg.assign %merge, "x", ..., !2
3439 for (DbgVariableRecord *DbgAssign :
3440 at::getDVRAssignmentMarkers(SpeculatedStore))
3441 if (llvm::is_contained(DbgAssign->location_ops(), OrigV))
3442 DbgAssign->replaceVariableLocationOp(OrigV, S);
3443 }
3444
3445 // Metadata can be dependent on the condition we are hoisting above.
3446 // Strip all UB-implying metadata on the instruction. Drop the debug loc
3447 // to avoid making it appear as if the condition is a constant, which would
3448 // be misleading while debugging.
3449 // Similarly strip attributes that maybe dependent on condition we are
3450 // hoisting above.
3451 for (auto &I : make_early_inc_range(*ThenBB)) {
3452 if (!SpeculatedStoreValue || &I != SpeculatedStore) {
3453 I.dropLocation();
3454 I.dropUBImplyingAttrsAndMetadata();
3455 } else {
3456 assert(PreviousStoreAccess && "Missing previous store access");
3457 AAMDNodes MergedAA = SpeculatedStore->getAAMetadata().merge(
3458 PreviousStoreAccess->getAAMetadata());
3459 I.dropUBImplyingAttrsAndMetadata();
3460 I.setAAMetadata(MergedAA);
3461 }
3462
3463 // Drop ephemeral values.
3464 if (EphTracker.contains(&I)) {
3465 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
3466 I.eraseFromParent();
3467 }
3468 }
3469
3470 // Hoist the instructions.
3471 // Drop DbgVariableRecords attached to these instructions.
3472 for (auto &It : *ThenBB)
3473 for (DbgRecord &DR : make_early_inc_range(It.getDbgRecordRange()))
3474 // Drop all records except assign-kind DbgVariableRecords (dbg.assign
3475 // equivalent).
3476 if (DbgVariableRecord *DVR = dyn_cast<DbgVariableRecord>(&DR);
3477 !DVR || !DVR->isDbgAssign())
3478 It.dropOneDbgRecord(&DR);
3479 BB->splice(BI->getIterator(), ThenBB, ThenBB->begin(),
3480 std::prev(ThenBB->end()));
3481
3482 if (!SpeculatedConditionalLoadsStores.empty())
3483 hoistConditionalLoadsStores(BI, SpeculatedConditionalLoadsStores, Invert,
3484 Sel);
3485
3486 // Insert selects and rewrite the PHI operands.
3487 IRBuilder<NoFolder> Builder(BI);
3488 for (PHINode &PN : EndBB->phis()) {
3489 unsigned OrigI = PN.getBasicBlockIndex(BB);
3490 unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
3491 Value *OrigV = PN.getIncomingValue(OrigI);
3492 Value *ThenV = PN.getIncomingValue(ThenI);
3493
3494 // Skip PHIs which are trivial.
3495 if (OrigV == ThenV)
3496 continue;
3497
3498 // Create a select whose true value is the speculatively executed value and
3499 // false value is the pre-existing value. Swap them if the branch
3500 // destinations were inverted.
3501 Value *TrueV = ThenV, *FalseV = OrigV;
3502 if (Invert)
3503 std::swap(TrueV, FalseV);
3504 // Propagate fast-math flags from the phi node to the replacement select.
3505 Value *V = Builder.CreateSelectFMF(
3506 BrCond, TrueV, FalseV, PN.getFastMathFlagsOrNone(), "spec.select", BI);
3507 PN.setIncomingValue(OrigI, V);
3508 PN.setIncomingValue(ThenI, V);
3509 }
3510
3511 // Remove speculated pseudo probes.
3512 for (Instruction *I : SpeculatedPseudoProbes)
3513 I->eraseFromParent();
3514
3515 ++NumSpeculations;
3516 return true;
3517}
3518
3520
3521// Return false if number of blocks searched is too much.
3522static bool findReaching(BasicBlock *BB, BasicBlock *DefBB,
3523 BlocksSet &ReachesNonLocalUses) {
3524 if (BB == DefBB)
3525 return true;
3526 if (!ReachesNonLocalUses.insert(BB).second)
3527 return true;
3528
3529 if (ReachesNonLocalUses.size() > MaxJumpThreadingLiveBlocks)
3530 return false;
3531 for (BasicBlock *Pred : predecessors(BB))
3532 if (!findReaching(Pred, DefBB, ReachesNonLocalUses))
3533 return false;
3534 return true;
3535}
3536
3537/// Return true if we can thread a branch across this block.
3539 BlocksSet &NonLocalUseBlocks) {
3540 int Size = 0;
3541 EphemeralValueTracker EphTracker;
3542
3543 // Walk the loop in reverse so that we can identify ephemeral values properly
3544 // (values only feeding assumes).
3545 for (Instruction &I : reverse(*BB)) {
3546 // Can't fold blocks that contain noduplicate or convergent calls.
3547 if (CallInst *CI = dyn_cast<CallInst>(&I))
3548 if (CI->cannotDuplicate() || CI->isConvergent())
3549 return false;
3550
3551 // Ignore ephemeral values which are deleted during codegen.
3552 // We will delete Phis while threading, so Phis should not be accounted in
3553 // block's size.
3554 if (!EphTracker.track(&I) && !isa<PHINode>(I)) {
3555 if (Size++ > MaxSmallBlockSize)
3556 return false; // Don't clone large BB's.
3557 }
3558
3559 // Record blocks with non-local uses of values defined in the current basic
3560 // block.
3561 for (User *U : I.users()) {
3563 BasicBlock *UsedInBB = UI->getParent();
3564 if (UsedInBB == BB) {
3565 if (isa<PHINode>(UI))
3566 return false;
3567 } else
3568 NonLocalUseBlocks.insert(UsedInBB);
3569 }
3570
3571 // Looks ok, continue checking.
3572 }
3573
3574 return true;
3575}
3576
3578 BasicBlock *To) {
3579 // Don't look past the block defining the value, we might get the value from
3580 // a previous loop iteration.
3581 auto *I = dyn_cast<Instruction>(V);
3582 if (I && I->getParent() == To)
3583 return nullptr;
3584
3585 // We know the value if the From block branches on it.
3586 auto *BI = dyn_cast<CondBrInst>(From->getTerminator());
3587 if (BI && BI->getCondition() == V &&
3588 BI->getSuccessor(0) != BI->getSuccessor(1))
3589 return BI->getSuccessor(0) == To ? ConstantInt::getTrue(BI->getContext())
3591
3592 return nullptr;
3593}
3594
3596 return CB->isConvergent() && !isa<ConvergenceControlInst>(CB) &&
3598}
3599
3601 BasicBlock *StopBB) {
3602 static constexpr unsigned MaxInstructionsToScan = 512;
3603
3604 // Walk predecessors of StopBB to find blocks that can reach it. Only
3605 // convergent calls on a cycle with StopBB matter - a convergent call on a
3606 // path to function exit cannot have its dynamic instance changed by
3607 // threading.
3608 SmallPtrSet<BasicBlock *, 8> CanReachStop;
3609 SmallPtrSet<BasicBlock *, 8> BlocksWithUncontrolledConvergentCalls;
3611 for (BasicBlock *Pred : predecessors(StopBB))
3612 Worklist.push_back(Pred);
3613
3614 // Cache blocks with relevant calls while building CanReachStop. This keeps
3615 // the instruction scan bounded without a separate block limit.
3616 unsigned NumScannedInstructions = 0;
3617 while (!Worklist.empty()) {
3618 BasicBlock *BB = Worklist.pop_back_val();
3619 if (BB == StopBB)
3620 continue;
3621 if (!CanReachStop.insert(BB).second)
3622 continue;
3623
3624 for (Instruction &I : *BB) {
3625 if (++NumScannedInstructions > MaxInstructionsToScan)
3626 return true;
3627 auto *CB = dyn_cast<CallBase>(&I);
3628 if (CB && isUncontrolledConvergentCall(CB)) {
3629 BlocksWithUncontrolledConvergentCalls.insert(BB);
3630 break;
3631 }
3632 }
3633
3634 append_range(Worklist, predecessors(BB));
3635 }
3636
3637 if (!CanReachStop.contains(From))
3638 return false;
3639
3641 Worklist.push_back(From);
3642
3643 while (!Worklist.empty()) {
3644 BasicBlock *BB = Worklist.pop_back_val();
3645 if (BB == StopBB || !CanReachStop.contains(BB))
3646 continue;
3647
3648 if (!Visited.insert(BB).second)
3649 continue;
3650
3651 if (BlocksWithUncontrolledConvergentCalls.contains(BB))
3652 return true;
3653
3654 append_range(Worklist, successors(BB));
3655 }
3656
3657 return false;
3658}
3659
3660/// If we have a conditional branch on something for which we know the constant
3661/// value in predecessors (e.g. a phi node in the current block), thread edges
3662/// from the predecessor to their ultimate destination.
3665 AssumptionCache *AC, const DataLayout &DL) {
3667 BasicBlock *BB = BI->getParent();
3668 Value *Cond = BI->getCondition();
3670 if (PN && PN->getParent() == BB) {
3671 // Degenerate case of a single entry PHI.
3672 if (PN->getNumIncomingValues() == 1) {
3674 return true;
3675 }
3676
3677 for (Use &U : PN->incoming_values())
3678 if (auto *CB = dyn_cast<ConstantInt>(U))
3679 KnownValues[CB].insert(PN->getIncomingBlock(U));
3680 } else {
3681 for (BasicBlock *Pred : predecessors(BB)) {
3682 if (ConstantInt *CB = getKnownValueOnEdge(Cond, Pred, BB))
3683 KnownValues[CB].insert(Pred);
3684 }
3685 }
3686
3687 if (KnownValues.empty())
3688 return false;
3689
3690 // Now we know that this block has multiple preds and two succs.
3691 // Check that the block is small enough and record which non-local blocks use
3692 // values defined in the block.
3693
3694 BlocksSet NonLocalUseBlocks;
3695 BlocksSet ReachesNonLocalUseBlocks;
3696 if (!blockIsSimpleEnoughToThreadThrough(BB, NonLocalUseBlocks))
3697 return false;
3698
3699 // Jump-threading can only be done to destinations where no values defined
3700 // in BB are live.
3701
3702 // Quickly check if both destinations have uses. If so, jump-threading cannot
3703 // be done.
3704 if (NonLocalUseBlocks.contains(BI->getSuccessor(0)) &&
3705 NonLocalUseBlocks.contains(BI->getSuccessor(1)))
3706 return false;
3707
3708 // Search backward from NonLocalUseBlocks to find which blocks
3709 // reach non-local uses.
3710 for (BasicBlock *UseBB : NonLocalUseBlocks)
3711 // Give up if too many blocks are searched.
3712 if (!findReaching(UseBB, BB, ReachesNonLocalUseBlocks))
3713 return false;
3714
3715 for (const auto &Pair : KnownValues) {
3716 ConstantInt *CB = Pair.first;
3717 ArrayRef<BasicBlock *> PredBBs = Pair.second.getArrayRef();
3718 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
3719
3720 // Okay, we now know that all edges from PredBB should be revectored to
3721 // branch to RealDest.
3722 if (RealDest == BB)
3723 continue; // Skip self loops.
3724
3725 // Skip if the predecessor's terminator is an indirect branch.
3726 if (any_of(PredBBs, [](BasicBlock *PredBB) {
3727 return isa<IndirectBrInst>(PredBB->getTerminator());
3728 }))
3729 continue;
3730
3731 // Only revector to RealDest if no values defined in BB are live.
3732 if (ReachesNonLocalUseBlocks.contains(RealDest))
3733 continue;
3734
3735 // Threading through a branch can bypass a reconvergence point. If the
3736 // destination can execute an uncontrolled convergent operation before
3737 // returning to this block, this may change the dynamic instance of that
3738 // operation.
3739 if (TTI.hasBranchDivergence(BB->getParent()) &&
3741 continue;
3742
3743 LLVM_DEBUG({
3744 dbgs() << "Condition " << *Cond << " in " << BB->getName()
3745 << " has value " << *Pair.first << " in predecessors:\n";
3746 for (const BasicBlock *PredBB : Pair.second)
3747 dbgs() << " " << PredBB->getName() << "\n";
3748 dbgs() << "Threading to destination " << RealDest->getName() << ".\n";
3749 });
3750
3751 // Split the predecessors we are threading into a new edge block. We'll
3752 // clone the instructions into this block, and then redirect it to RealDest.
3753 BasicBlock *EdgeBB = SplitBlockPredecessors(BB, PredBBs, ".critedge", DTU);
3754 if (!EdgeBB)
3755 continue;
3756
3757 // TODO: These just exist to reduce test diff, we can drop them if we like.
3758 EdgeBB->setName(RealDest->getName() + ".critedge");
3759 EdgeBB->moveBefore(RealDest);
3760
3761 // Update PHI nodes.
3762 addPredecessorToBlock(RealDest, EdgeBB, BB);
3763
3764 // BB may have instructions that are being threaded over. Clone these
3765 // instructions into EdgeBB. We know that there will be no uses of the
3766 // cloned instructions outside of EdgeBB.
3767 BasicBlock::iterator InsertPt = EdgeBB->getFirstInsertionPt();
3768 ValueToValueMapTy TranslateMap; // Track translated values.
3769 TranslateMap[Cond] = CB;
3770
3771 // RemoveDIs: track instructions that we optimise away while folding, so
3772 // that we can copy DbgVariableRecords from them later.
3773 BasicBlock::iterator SrcDbgCursor = BB->begin();
3774 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
3775 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
3776 TranslateMap[PN] = PN->getIncomingValueForBlock(EdgeBB);
3777 continue;
3778 }
3779 // Clone the instruction.
3780 Instruction *N = BBI->clone();
3781 // Insert the new instruction into its new home.
3782 N->insertInto(EdgeBB, InsertPt);
3783
3784 if (BBI->hasName())
3785 N->setName(BBI->getName() + ".c");
3786
3787 // Update operands due to translation.
3788 // Key Instructions: Remap all the atom groups.
3789 if (const DebugLoc &DL = BBI->getDebugLoc())
3790 mapAtomInstance(DL, TranslateMap);
3791 RemapInstruction(N, TranslateMap,
3793
3794 // Check for trivial simplification.
3795 if (Value *V = simplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
3796 if (!BBI->use_empty())
3797 TranslateMap[&*BBI] = V;
3798 if (!N->mayHaveSideEffects()) {
3799 N->eraseFromParent(); // Instruction folded away, don't need actual
3800 // inst
3801 N = nullptr;
3802 }
3803 } else {
3804 if (!BBI->use_empty())
3805 TranslateMap[&*BBI] = N;
3806 }
3807 if (N) {
3808 // Copy all debug-info attached to instructions from the last we
3809 // successfully clone, up to this instruction (they might have been
3810 // folded away).
3811 for (; SrcDbgCursor != BBI; ++SrcDbgCursor)
3812 N->cloneDebugInfoFrom(&*SrcDbgCursor);
3813 SrcDbgCursor = std::next(BBI);
3814 // Clone debug-info on this instruction too.
3815 N->cloneDebugInfoFrom(&*BBI);
3816
3817 // Register the new instruction with the assumption cache if necessary.
3818 if (auto *Assume = dyn_cast<AssumeInst>(N))
3819 if (AC)
3820 AC->registerAssumption(Assume);
3821 }
3822 }
3823
3824 for (; &*SrcDbgCursor != BI; ++SrcDbgCursor)
3825 InsertPt->cloneDebugInfoFrom(&*SrcDbgCursor);
3826 InsertPt->cloneDebugInfoFrom(BI);
3827
3828 BB->removePredecessor(EdgeBB);
3829 UncondBrInst *EdgeBI = cast<UncondBrInst>(EdgeBB->getTerminator());
3830 EdgeBI->setSuccessor(0, RealDest);
3831 EdgeBI->setDebugLoc(BI->getDebugLoc());
3832
3833 if (DTU) {
3835 Updates.push_back({DominatorTree::Delete, EdgeBB, BB});
3836 Updates.push_back({DominatorTree::Insert, EdgeBB, RealDest});
3837 DTU->applyUpdates(Updates);
3838 }
3839
3840 // For simplicity, we created a separate basic block for the edge. Merge
3841 // it back into the predecessor if possible. This not only avoids
3842 // unnecessary SimplifyCFG iterations, but also makes sure that we don't
3843 // bypass the check for trivial cycles above.
3844 MergeBlockIntoPredecessor(EdgeBB, DTU);
3845
3846 // Signal repeat, simplifying any other constants.
3847 return std::nullopt;
3848 }
3849
3850 return false;
3851}
3852
3853bool SimplifyCFGOpt::foldCondBranchOnValueKnownInPredecessor(CondBrInst *BI) {
3854 // Note: If BB is a loop header then there is a risk that threading introduces
3855 // a non-canonical loop by moving a back edge. So we avoid this optimization
3856 // for loop headers if NeedCanonicalLoop is set.
3857 if (Options.NeedCanonicalLoop && is_contained(LoopHeaders, BI->getParent()))
3858 return false;
3859
3860 std::optional<bool> Result;
3861 bool EverChanged = false;
3862 do {
3863 // Note that None means "we changed things, but recurse further."
3865 Options.AC, DL);
3866 EverChanged |= Result == std::nullopt || *Result;
3867 } while (Result == std::nullopt);
3868 return EverChanged;
3869}
3870
3871/// Given a BB that starts with the specified two-entry PHI node,
3872/// see if we can eliminate it.
3875 const DataLayout &DL,
3876 bool SpeculateUnpredictables) {
3877 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
3878 // statement", which has a very simple dominance structure. Basically, we
3879 // are trying to find the condition that is being branched on, which
3880 // subsequently causes this merge to happen. We really want control
3881 // dependence information for this check, but simplifycfg can't keep it up
3882 // to date, and this catches most of the cases we care about anyway.
3883 BasicBlock *BB = PN->getParent();
3884
3885 BasicBlock *IfTrue, *IfFalse;
3886 CondBrInst *DomBI = GetIfCondition(BB, IfTrue, IfFalse);
3887 if (!DomBI)
3888 return false;
3889 Value *IfCond = DomBI->getCondition();
3890 // Don't bother if the branch will be constant folded trivially.
3891 if (isa<ConstantInt>(IfCond))
3892 return false;
3893
3894 BasicBlock *DomBlock = DomBI->getParent();
3896 llvm::copy_if(PN->blocks(), std::back_inserter(IfBlocks),
3897 [](BasicBlock *IfBlock) {
3898 return isa<UncondBrInst>(IfBlock->getTerminator());
3899 });
3900 assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) &&
3901 "Will have either one or two blocks to speculate.");
3902
3903 // If the branch is non-unpredictable, see if we either predictably jump to
3904 // the merge bb (if we have only a single 'then' block), or if we predictably
3905 // jump to one specific 'then' block (if we have two of them).
3906 // It isn't beneficial to speculatively execute the code
3907 // from the block that we know is predictably not entered.
3908 bool IsUnpredictable = DomBI->getMetadata(LLVMContext::MD_unpredictable);
3909 if (!IsUnpredictable) {
3910 uint64_t TWeight, FWeight;
3911 if (extractBranchWeights(*DomBI, TWeight, FWeight) &&
3912 (TWeight + FWeight) != 0) {
3913 BranchProbability BITrueProb =
3914 BranchProbability::getBranchProbability(TWeight, TWeight + FWeight);
3915 BranchProbability Likely = TTI.getPredictableBranchThreshold();
3916 BranchProbability BIFalseProb = BITrueProb.getCompl();
3917 if (IfBlocks.size() == 1) {
3918 BranchProbability BIBBProb =
3919 DomBI->getSuccessor(0) == BB ? BITrueProb : BIFalseProb;
3920 if (BIBBProb >= Likely)
3921 return false;
3922 } else {
3923 if (BITrueProb >= Likely || BIFalseProb >= Likely)
3924 return false;
3925 }
3926 }
3927 }
3928
3929 // Don't try to fold an unreachable block. For example, the phi node itself
3930 // can't be the candidate if-condition for a select that we want to form.
3931 if (auto *IfCondPhiInst = dyn_cast<PHINode>(IfCond))
3932 if (IfCondPhiInst->getParent() == BB)
3933 return false;
3934
3935 // Okay, we found that we can merge this two-entry phi node into a select.
3936 // Doing so would require us to fold *all* two entry phi nodes in this block.
3937 // At some point this becomes non-profitable (particularly if the target
3938 // doesn't support cmov's). Only do this transformation if there are two or
3939 // fewer PHI nodes in this block.
3940 unsigned NumPhis = 0;
3941 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
3942 if (NumPhis > 2)
3943 return false;
3944
3945 // Loop over the PHI's seeing if we can promote them all to select
3946 // instructions. While we are at it, keep track of the instructions
3947 // that need to be moved to the dominating block.
3948 SmallPtrSet<Instruction *, 4> AggressiveInsts;
3949 SmallPtrSet<Instruction *, 2> ZeroCostInstructions;
3950 InstructionCost Cost = 0;
3951 InstructionCost Budget =
3953 if (SpeculateUnpredictables && IsUnpredictable)
3954 Budget += TTI.getBranchMispredictPenalty();
3955
3956 bool Changed = false;
3957 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
3958 PHINode *PN = cast<PHINode>(II++);
3959 if (Value *V = simplifyInstruction(PN, {DL, PN})) {
3960 PN->replaceAllUsesWith(V);
3961 PN->eraseFromParent();
3962 Changed = true;
3963 continue;
3964 }
3965
3966 if (!dominatesMergePoint(PN->getIncomingValue(0), BB, DomBI,
3967 AggressiveInsts, Cost, Budget, TTI, AC,
3968 ZeroCostInstructions) ||
3969 !dominatesMergePoint(PN->getIncomingValue(1), BB, DomBI,
3970 AggressiveInsts, Cost, Budget, TTI, AC,
3971 ZeroCostInstructions))
3972 return Changed;
3973 }
3974
3975 // If we folded the first phi, PN dangles at this point. Refresh it. If
3976 // we ran out of PHIs then we simplified them all.
3977 PN = dyn_cast<PHINode>(BB->begin());
3978 if (!PN)
3979 return true;
3980
3981 // Don't fold i1 branches on PHIs which contain binary operators or
3982 // (possibly inverted) select form of or/ands if their parameters are
3983 // an equality test.
3984 auto IsBinOpOrAndEq = [](Value *V) {
3985 CmpPredicate Pred;
3986 if (match(V, m_CombineOr(
3988 m_BinOp(m_Cmp(Pred, m_Value(), m_Value()), m_Value()),
3989 m_BinOp(m_Value(), m_Cmp(Pred, m_Value(), m_Value()))),
3991 m_Cmp(Pred, m_Value(), m_Value()))))) {
3992 return CmpInst::isEquality(Pred);
3993 }
3994 return false;
3995 };
3996 if (PN->getType()->isIntegerTy(1) &&
3997 (IsBinOpOrAndEq(PN->getIncomingValue(0)) ||
3998 IsBinOpOrAndEq(PN->getIncomingValue(1)) || IsBinOpOrAndEq(IfCond)))
3999 return Changed;
4000
4001 // If all PHI nodes are promotable, check to make sure that all instructions
4002 // in the predecessor blocks can be promoted as well. If not, we won't be able
4003 // to get rid of the control flow, so it's not worth promoting to select
4004 // instructions.
4005 for (BasicBlock *IfBlock : IfBlocks)
4006 for (BasicBlock::iterator I = IfBlock->begin(); !I->isTerminator(); ++I)
4007 if (!AggressiveInsts.count(&*I) && !isa<PseudoProbeInst>(I)) {
4008 // This is not an aggressive instruction that we can promote.
4009 // Because of this, we won't be able to get rid of the control flow, so
4010 // the xform is not worth it.
4011 return Changed;
4012 }
4013
4014 // If either of the blocks has it's address taken, we can't do this fold.
4015 if (any_of(IfBlocks,
4016 [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); }))
4017 return Changed;
4018
4019 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond;
4020 if (IsUnpredictable) dbgs() << " (unpredictable)";
4021 dbgs() << " T: " << IfTrue->getName()
4022 << " F: " << IfFalse->getName() << "\n");
4023
4024 // If we can still promote the PHI nodes after this gauntlet of tests,
4025 // do all of the PHI's now.
4026
4027 // Move all 'aggressive' instructions, which are defined in the
4028 // conditional parts of the if's up to the dominating block.
4029 for (BasicBlock *IfBlock : IfBlocks)
4030 hoistAllInstructionsInto(DomBlock, DomBI, IfBlock);
4031
4032 IRBuilder<NoFolder> Builder(DomBI);
4033 // Propagate fast-math-flags from phi nodes to replacement selects.
4034 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
4035 // Change the PHI node into a select instruction.
4036 Value *TrueVal = PN->getIncomingValueForBlock(IfTrue);
4037 Value *FalseVal = PN->getIncomingValueForBlock(IfFalse);
4038
4039 Value *Sel = Builder.CreateSelectFMF(IfCond, TrueVal, FalseVal,
4040 isa<FPMathOperator>(PN) ? PN : nullptr,
4041 "", DomBI);
4042 PN->replaceAllUsesWith(Sel);
4043 Sel->takeName(PN);
4044 PN->eraseFromParent();
4045 }
4046
4047 // At this point, all IfBlocks are empty, so our if statement
4048 // has been flattened. Change DomBlock to jump directly to our new block to
4049 // avoid other simplifycfg's kicking in on the diamond.
4050 Builder.CreateBr(BB);
4051
4053 if (DTU) {
4054 Updates.push_back({DominatorTree::Insert, DomBlock, BB});
4055 for (auto *Successor : successors(DomBlock))
4056 Updates.push_back({DominatorTree::Delete, DomBlock, Successor});
4057 }
4058
4059 DomBI->eraseFromParent();
4060 if (DTU)
4061 DTU->applyUpdates(Updates);
4062
4063 return true;
4064}
4065
4068 Value *RHS, const Twine &Name = "") {
4069 // Try to relax logical op to binary op.
4070 if (impliesPoison(RHS, LHS))
4071 return Builder.CreateBinOp(Opc, LHS, RHS, Name);
4072 if (Opc == Instruction::And)
4073 return Builder.CreateLogicalAnd(LHS, RHS, Name);
4074 if (Opc == Instruction::Or)
4075 return Builder.CreateLogicalOr(LHS, RHS, Name);
4076 llvm_unreachable("Invalid logical opcode");
4077}
4078
4079/// Return true if either PBI or BI has branch weight available, and store
4080/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
4081/// not have branch weight, use 1:1 as its weight.
4083 uint64_t &PredTrueWeight,
4084 uint64_t &PredFalseWeight,
4085 uint64_t &SuccTrueWeight,
4086 uint64_t &SuccFalseWeight) {
4087 bool PredHasWeights =
4088 extractBranchWeights(*PBI, PredTrueWeight, PredFalseWeight);
4089 bool SuccHasWeights =
4090 extractBranchWeights(*BI, SuccTrueWeight, SuccFalseWeight);
4091 if (PredHasWeights || SuccHasWeights) {
4092 if (!PredHasWeights)
4093 PredTrueWeight = PredFalseWeight = 1;
4094 if (!SuccHasWeights)
4095 SuccTrueWeight = SuccFalseWeight = 1;
4096 return true;
4097 } else {
4098 return false;
4099 }
4100}
4101
4102/// Determine if the two branches share a common destination and deduce a glue
4103/// that joins the branches' conditions to arrive at the common destination if
4104/// that would be profitable.
4105static std::optional<std::tuple<BasicBlock *, Instruction::BinaryOps, bool>>
4107 const TargetTransformInfo *TTI) {
4108 assert(BI && PBI && "Both blocks must end with a conditional branches.");
4110 "PredBB must be a predecessor of BB.");
4111
4112 // We have the potential to fold the conditions together, but if the
4113 // predecessor branch is predictable, we may not want to merge them.
4114 uint64_t PTWeight, PFWeight;
4115 BranchProbability PBITrueProb, Likely;
4116 if (TTI && !PBI->getMetadata(LLVMContext::MD_unpredictable) &&
4117 extractBranchWeights(*PBI, PTWeight, PFWeight) &&
4118 (PTWeight + PFWeight) != 0) {
4119 PBITrueProb =
4120 BranchProbability::getBranchProbability(PTWeight, PTWeight + PFWeight);
4121 Likely = TTI->getPredictableBranchThreshold();
4122 }
4123
4124 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4125 // Speculate the 2nd condition unless the 1st is probably true.
4126 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
4127 return {{BI->getSuccessor(0), Instruction::Or, false}};
4128 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4129 // Speculate the 2nd condition unless the 1st is probably false.
4130 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
4131 return {{BI->getSuccessor(1), Instruction::And, false}};
4132 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4133 // Speculate the 2nd condition unless the 1st is probably true.
4134 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
4135 return {{BI->getSuccessor(1), Instruction::And, true}};
4136 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4137 // Speculate the 2nd condition unless the 1st is probably false.
4138 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
4139 return {{BI->getSuccessor(0), Instruction::Or, true}};
4140 }
4141 return std::nullopt;
4142}
4143
4145 DomTreeUpdater *DTU,
4146 MemorySSAUpdater *MSSAU,
4147 const TargetTransformInfo *TTI) {
4148 BasicBlock *BB = BI->getParent();
4149 BasicBlock *PredBlock = PBI->getParent();
4150
4151 // Determine if the two branches share a common destination.
4152 BasicBlock *CommonSucc;
4154 bool InvertPredCond;
4155 std::tie(CommonSucc, Opc, InvertPredCond) =
4157
4158 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
4159
4161 *BB->getModule(), ConstantFolder{},
4163 // The builder is used to create instructions to eliminate the branch in
4164 // BB. If BB's terminator has !annotation metadata, add it to the new
4165 // instructions.
4166 I->copyMetadata(*BB->getTerminator(), LLVMContext::MD_annotation);
4167 }));
4168 Builder.SetInsertPoint(PBI);
4169
4170 // If we need to invert the condition in the pred block to match, do so now.
4171 if (InvertPredCond) {
4172 InvertBranch(PBI, Builder);
4173 }
4174
4175 BasicBlock *UniqueSucc =
4176 PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1);
4177
4178 // Before cloning instructions, notify the successor basic block that it
4179 // is about to have a new predecessor. This will update PHI nodes,
4180 // which will allow us to update live-out uses of bonus instructions.
4181 addPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU);
4182
4183 // Try to update branch weights.
4184 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4185 SmallVector<uint64_t, 2> MDWeights;
4186 if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4187 SuccTrueWeight, SuccFalseWeight)) {
4188
4189 if (PBI->getSuccessor(0) == BB) {
4190 // PBI: br i1 %x, BB, FalseDest
4191 // BI: br i1 %y, UniqueSucc, FalseDest
4192 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
4193 MDWeights.push_back(PredTrueWeight * SuccTrueWeight);
4194 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
4195 // TrueWeight for PBI * FalseWeight for BI.
4196 // We assume that total weights of a CondBrInst can fit into 32 bits.
4197 // Therefore, we will not have overflow using 64-bit arithmetic.
4198 MDWeights.push_back(PredFalseWeight * (SuccFalseWeight + SuccTrueWeight) +
4199 PredTrueWeight * SuccFalseWeight);
4200 } else {
4201 // PBI: br i1 %x, TrueDest, BB
4202 // BI: br i1 %y, TrueDest, UniqueSucc
4203 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
4204 // FalseWeight for PBI * TrueWeight for BI.
4205 MDWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) +
4206 PredFalseWeight * SuccTrueWeight);
4207 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
4208 MDWeights.push_back(PredFalseWeight * SuccFalseWeight);
4209 }
4210
4211 setFittedBranchWeights(*PBI, MDWeights, /*IsExpected=*/false,
4212 /*ElideAllZero=*/true);
4213
4214 // TODO: If BB is reachable from all paths through PredBlock, then we
4215 // could replace PBI's branch probabilities with BI's.
4216 } else {
4217 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
4219 }
4220
4221 // Now, update the CFG.
4222 PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc);
4223
4224 if (DTU)
4225 DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc},
4226 {DominatorTree::Delete, PredBlock, BB}});
4227
4228 // If BI was a loop latch, it may have had associated loop metadata.
4229 // We need to copy it to the new latch, that is, PBI.
4230 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
4231 PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
4232
4233 ValueToValueMapTy VMap; // maps original values to cloned values
4235
4236 Module *M = BB->getModule();
4237
4238 PredBlock->getTerminator()->cloneDebugInfoFrom(BB->getTerminator());
4239 for (DbgVariableRecord &DVR :
4241 RemapDbgRecord(M, &DVR, VMap,
4243 }
4244
4245 // Now that the Cond was cloned into the predecessor basic block,
4246 // or/and the two conditions together.
4247 Value *BICond = VMap[BI->getCondition()];
4248 PBI->setCondition(
4249 createLogicalOp(Builder, Opc, PBI->getCondition(), BICond, "or.cond"));
4250 if (auto *SI = dyn_cast<SelectInst>(PBI->getCondition())) {
4251 if (!MDWeights.empty()) {
4252 assert(isSelectInRoleOfConjunctionOrDisjunction(SI));
4253 setFittedBranchWeights(*SI, {MDWeights[0], MDWeights[1]},
4254 /*IsExpected=*/false, /*ElideAllZero=*/true);
4255 } else {
4257 }
4258 }
4259
4260 ++NumFoldBranchToCommonDest;
4261 return true;
4262}
4263
4264/// Return if an instruction's type or any of its operands' types are a vector
4265/// type.
4266static bool isVectorOp(Instruction &I) {
4267 return I.getType()->isVectorTy() || any_of(I.operands(), [](Use &U) {
4268 return U->getType()->isVectorTy();
4269 });
4270}
4271
4272/// If this basic block is simple enough, and if a predecessor branches to us
4273/// and one of our successors, fold the block into the predecessor and use
4274/// logical operations to pick the right destination.
4276 MemorySSAUpdater *MSSAU,
4277 const TargetTransformInfo *TTI,
4278 AssumptionCache *AC,
4279 unsigned BonusInstThreshold) {
4280 BasicBlock *BB = BI->getParent();
4284
4286
4288 Cond->getParent() != BB || !Cond->hasOneUse())
4289 return false;
4290
4291 // Finally, don't infinitely unroll conditional loops.
4292 if (is_contained(successors(BB), BB))
4293 return false;
4294
4295 // With which predecessors will we want to deal with?
4297 for (BasicBlock *PredBlock : predecessors(BB)) {
4298 CondBrInst *PBI = dyn_cast<CondBrInst>(PredBlock->getTerminator());
4299
4300 // Check that we have two conditional branches. If there is a PHI node in
4301 // the common successor, verify that the same value flows in from both
4302 // blocks.
4303 if (!PBI || !safeToMergeTerminators(BI, PBI))
4304 continue;
4305
4306 // Determine if the two branches share a common destination.
4307 BasicBlock *CommonSucc;
4309 bool InvertPredCond;
4310 if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI))
4311 std::tie(CommonSucc, Opc, InvertPredCond) = *Recipe;
4312 else
4313 continue;
4314
4315 // Check the cost of inserting the necessary logic before performing the
4316 // transformation.
4317 if (TTI) {
4318 Type *Ty = BI->getCondition()->getType();
4319 InstructionCost Cost = TTI->getArithmeticInstrCost(Opc, Ty, CostKind);
4320 if (InvertPredCond && (!PBI->getCondition()->hasOneUse() ||
4321 !isa<CmpInst>(PBI->getCondition())))
4322 Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind);
4323
4325 continue;
4326 }
4327
4328 // Ok, we do want to deal with this predecessor. Record it.
4329 Preds.emplace_back(PredBlock);
4330 }
4331
4332 // If there aren't any predecessors into which we can fold,
4333 // don't bother checking the cost.
4334 if (Preds.empty())
4335 return false;
4336
4337 // Only allow this transformation if computing the condition doesn't involve
4338 // too many instructions and these involved instructions can be executed
4339 // unconditionally. We denote all involved instructions except the condition
4340 // as "bonus instructions", and only allow this transformation when the
4341 // number of the bonus instructions we'll need to create when cloning into
4342 // each predecessor does not exceed a certain threshold.
4343 unsigned NumBonusInsts = 0;
4344 bool SawVectorOp = false;
4345 const unsigned PredCount = Preds.size();
4346 // Speculated instructions will be inserted before the terminator of the
4347 // predecessor. Only handle the simple case of one predecessor.
4348 const Instruction *CtxI =
4349 PredCount == 1 ? Preds[0]->getTerminator() : nullptr;
4350 for (Instruction &I : *BB) {
4351 // Don't check the branch condition comparison itself.
4352 if (&I == Cond)
4353 continue;
4354 // Ignore the terminator.
4356 continue;
4357 // Pseudo probes aren't speculatable but can be dropped on fold.
4359 continue;
4360 // I must be safe to execute unconditionally.
4361 if (!isSafeToSpeculativelyExecute(&I, CtxI, AC))
4362 return false;
4363 SawVectorOp |= isVectorOp(I);
4364
4365 // Account for the cost of duplicating this instruction into each
4366 // predecessor. Ignore free instructions.
4367 if (!TTI || TTI->getInstructionCost(&I, CostKind) !=
4369 NumBonusInsts += PredCount;
4370
4371 // Early exits once we reach the limit.
4372 if (NumBonusInsts >
4373 BonusInstThreshold * BranchFoldToCommonDestVectorMultiplier)
4374 return false;
4375 }
4376
4377 auto IsBCSSAUse = [BB, &I](Use &U) {
4378 auto *UI = cast<Instruction>(U.getUser());
4379 if (auto *PN = dyn_cast<PHINode>(UI))
4380 return PN->getIncomingBlock(U) == BB;
4381 return UI->getParent() == BB && I.comesBefore(UI);
4382 };
4383
4384 // Does this instruction require rewriting of uses?
4385 if (!all_of(I.uses(), IsBCSSAUse))
4386 return false;
4387 }
4388 if (NumBonusInsts >
4389 BonusInstThreshold *
4390 (SawVectorOp ? BranchFoldToCommonDestVectorMultiplier : 1))
4391 return false;
4392
4393 // Ok, we have the budget. Perform the transformation.
4394 for (BasicBlock *PredBlock : Preds) {
4395 auto *PBI = cast<CondBrInst>(PredBlock->getTerminator());
4396 return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI);
4397 }
4398 return false;
4399}
4400
4401// If there is only one store in BB1 and BB2, return it, otherwise return
4402// nullptr.
4404 StoreInst *S = nullptr;
4405 for (auto *BB : {BB1, BB2}) {
4406 if (!BB)
4407 continue;
4408 for (auto &I : *BB)
4409 if (auto *SI = dyn_cast<StoreInst>(&I)) {
4410 if (S)
4411 // Multiple stores seen.
4412 return nullptr;
4413 else
4414 S = SI;
4415 }
4416 }
4417 return S;
4418}
4419
4421 Value *AlternativeV = nullptr) {
4422 // PHI is going to be a PHI node that allows the value V that is defined in
4423 // BB to be referenced in BB's only successor.
4424 //
4425 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
4426 // doesn't matter to us what the other operand is (it'll never get used). We
4427 // could just create a new PHI with an undef incoming value, but that could
4428 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
4429 // other PHI. So here we directly look for some PHI in BB's successor with V
4430 // as an incoming operand. If we find one, we use it, else we create a new
4431 // one.
4432 //
4433 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
4434 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
4435 // where OtherBB is the single other predecessor of BB's only successor.
4436 PHINode *PHI = nullptr;
4437 BasicBlock *Succ = BB->getSingleSuccessor();
4438
4439 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
4440 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
4441 PHI = cast<PHINode>(I);
4442 if (!AlternativeV)
4443 break;
4444
4445 assert(Succ->hasNPredecessors(2));
4446 auto PredI = pred_begin(Succ);
4447 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
4448 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
4449 break;
4450 PHI = nullptr;
4451 }
4452 if (PHI)
4453 return PHI;
4454
4455 // If V is not an instruction defined in BB, just return it.
4456 if (!AlternativeV &&
4457 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
4458 return V;
4459
4460 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge");
4461 PHI->insertBefore(Succ->begin());
4462 PHI->addIncoming(V, BB);
4463 for (BasicBlock *PredBB : predecessors(Succ))
4464 if (PredBB != BB)
4465 PHI->addIncoming(
4466 AlternativeV ? AlternativeV : PoisonValue::get(V->getType()), PredBB);
4467 return PHI;
4468}
4469
4471 BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB,
4472 BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond,
4473 DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) {
4474 // For every pointer, there must be exactly two stores, one coming from
4475 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
4476 // store (to any address) in PTB,PFB or QTB,QFB.
4477 // FIXME: We could relax this restriction with a bit more work and performance
4478 // testing.
4479 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
4480 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
4481 if (!PStore || !QStore)
4482 return false;
4483
4484 // Now check the stores are compatible.
4485 if (!QStore->isUnordered() || !PStore->isUnordered() ||
4486 PStore->getOrdering() != QStore->getOrdering() ||
4487 PStore->getSyncScopeID() != QStore->getSyncScopeID() ||
4488 PStore->getValueOperand()->getType() !=
4489 QStore->getValueOperand()->getType())
4490 return false;
4491
4492 // Check that sinking the store won't cause program behavior changes. Sinking
4493 // the store out of the Q blocks won't change any behavior as we're sinking
4494 // from a block to its unconditional successor. But we're moving a store from
4495 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
4496 // So we need to check that there are no aliasing loads or stores in
4497 // QBI, QTB and QFB. We also need to check there are no conflicting memory
4498 // operations between PStore and the end of its parent block.
4499 //
4500 // The ideal way to do this is to query AliasAnalysis, but we don't
4501 // preserve AA currently so that is dangerous. Be super safe and just
4502 // check there are no other memory operations at all.
4503 for (auto &I : *QFB->getSinglePredecessor())
4504 if (I.mayReadOrWriteMemory())
4505 return false;
4506 for (auto &I : *QFB)
4507 if (&I != QStore && I.mayReadOrWriteMemory())
4508 return false;
4509 if (QTB)
4510 for (auto &I : *QTB)
4511 if (&I != QStore && I.mayReadOrWriteMemory())
4512 return false;
4513 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
4514 I != E; ++I)
4515 if (&*I != PStore && I->mayReadOrWriteMemory())
4516 return false;
4517
4518 // If we're not in aggressive mode, we only optimize if we have some
4519 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
4520 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
4521 if (!BB)
4522 return true;
4523 // Heuristic: if the block can be if-converted/phi-folded and the
4524 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
4525 // thread this store.
4526 InstructionCost Cost = 0;
4527 InstructionCost Budget =
4529 for (auto &I : *BB) {
4530 // Consider terminator instruction to be free.
4531 if (I.isTerminator())
4532 continue;
4533 // If this is one the stores that we want to speculate out of this BB,
4534 // then don't count it's cost, consider it to be free.
4535 if (auto *S = dyn_cast<StoreInst>(&I))
4536 if (llvm::find(FreeStores, S))
4537 continue;
4538 // Else, we have a white-list of instructions that we are ak speculating.
4540 return false; // Not in white-list - not worthwhile folding.
4541 // And finally, if this is a non-free instruction that we are okay
4542 // speculating, ensure that we consider the speculation budget.
4543 Cost +=
4544 TTI.getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
4545 if (Cost > Budget)
4546 return false; // Eagerly refuse to fold as soon as we're out of budget.
4547 }
4548 assert(Cost <= Budget &&
4549 "When we run out of budget we will eagerly return from within the "
4550 "per-instruction loop.");
4551 return true;
4552 };
4553
4554 const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
4556 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
4557 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
4558 return false;
4559
4560 // If PostBB has more than two predecessors, we need to split it so we can
4561 // sink the store.
4562 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
4563 // We know that QFB's only successor is PostBB. And QFB has a single
4564 // predecessor. If QTB exists, then its only successor is also PostBB.
4565 // If QTB does not exist, then QFB's only predecessor has a conditional
4566 // branch to QFB and PostBB.
4567 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
4568 BasicBlock *NewBB =
4569 SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU);
4570 if (!NewBB)
4571 return false;
4572 PostBB = NewBB;
4573 }
4574
4575 // OK, we're going to sink the stores to PostBB. The store has to be
4576 // conditional though, so first create the predicate.
4577 CondBrInst *PBranch =
4579 CondBrInst *QBranch =
4581 Value *PCond = PBranch->getCondition();
4582 Value *QCond = QBranch->getCondition();
4583
4585 PStore->getParent());
4587 QStore->getParent(), PPHI);
4588
4589 IRBuilder<> QB(PostBB->getFirstInsertionPt());
4590
4591 InvertPCond ^= (PStore->getParent() != PTB);
4592 InvertQCond ^= (QStore->getParent() != QTB);
4593 Value *PPred = InvertPCond ? QB.CreateNot(PCond) : PCond;
4594 Value *QPred = InvertQCond ? QB.CreateNot(QCond) : QCond;
4595
4596 Value *CombinedPred = QB.CreateOr(PPred, QPred);
4597
4598 BasicBlock::iterator InsertPt = QB.GetInsertPoint();
4599 auto *T = SplitBlockAndInsertIfThen(CombinedPred, InsertPt,
4600 /*Unreachable=*/false,
4601 /*BranchWeights=*/nullptr, DTU);
4602 if (hasBranchWeightMD(*PBranch) && hasBranchWeightMD(*QBranch)) {
4603 SmallVector<uint32_t, 2> PWeights, QWeights;
4604 extractBranchWeights(*PBranch, PWeights);
4605 extractBranchWeights(*QBranch, QWeights);
4606 if (InvertPCond)
4607 std::swap(PWeights[0], PWeights[1]);
4608 if (InvertQCond)
4609 std::swap(QWeights[0], QWeights[1]);
4610 auto CombinedWeights = getDisjunctionWeights(PWeights, QWeights);
4612 {CombinedWeights[0], CombinedWeights[1]},
4613 /*IsExpected=*/false, /*ElideAllZero=*/true);
4614 }
4615
4616 QB.SetInsertPoint(T);
4617 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
4618 combineMetadataForCSE(QStore, PStore, true);
4619 SI->copyMetadata(*QStore);
4620 // Update any dbg.assign intrinsics to track the merged value (QPHI) instead
4621 // of the original constant values, likely making these identical.
4622 for (auto *DbgAssign : at::getDVRAssignmentMarkers(SI)) {
4623 if (llvm::is_contained(DbgAssign->location_ops(),
4624 PStore->getValueOperand()))
4625 DbgAssign->replaceVariableLocationOp(PStore->getValueOperand(), QPHI);
4626 if (llvm::is_contained(DbgAssign->location_ops(),
4627 QStore->getValueOperand()))
4628 DbgAssign->replaceVariableLocationOp(QStore->getValueOperand(), QPHI);
4629 }
4630
4631 // Choose the minimum alignment. If we could prove both stores execute, we
4632 // could use biggest one. In this case, though, we only know that one of the
4633 // stores executes. And we don't know it's safe to take the alignment from a
4634 // store that doesn't execute.
4635 SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign()));
4636
4637 if (QStore->isAtomic())
4638 SI->setAtomic(QStore->getOrdering(), QStore->getSyncScopeID());
4639
4640 QStore->eraseFromParent();
4641 PStore->eraseFromParent();
4642
4643 return true;
4644}
4645
4647 DomTreeUpdater *DTU, const DataLayout &DL,
4648 const TargetTransformInfo &TTI) {
4649 // The intention here is to find diamonds or triangles (see below) where each
4650 // conditional block contains a store to the same address. Both of these
4651 // stores are conditional, so they can't be unconditionally sunk. But it may
4652 // be profitable to speculatively sink the stores into one merged store at the
4653 // end, and predicate the merged store on the union of the two conditions of
4654 // PBI and QBI.
4655 //
4656 // This can reduce the number of stores executed if both of the conditions are
4657 // true, and can allow the blocks to become small enough to be if-converted.
4658 // This optimization will also chain, so that ladders of test-and-set
4659 // sequences can be if-converted away.
4660 //
4661 // We only deal with simple diamonds or triangles:
4662 //
4663 // PBI or PBI or a combination of the two
4664 // / \ | \
4665 // PTB PFB | PFB
4666 // \ / | /
4667 // QBI QBI
4668 // / \ | \
4669 // QTB QFB | QFB
4670 // \ / | /
4671 // PostBB PostBB
4672 //
4673 // We model triangles as a type of diamond with a nullptr "true" block.
4674 // Triangles are canonicalized so that the fallthrough edge is represented by
4675 // a true condition, as in the diagram above.
4676 BasicBlock *PTB = PBI->getSuccessor(0);
4677 BasicBlock *PFB = PBI->getSuccessor(1);
4678 BasicBlock *QTB = QBI->getSuccessor(0);
4679 BasicBlock *QFB = QBI->getSuccessor(1);
4680 BasicBlock *PostBB = QFB->getSingleSuccessor();
4681
4682 // Make sure we have a good guess for PostBB. If QTB's only successor is
4683 // QFB, then QFB is a better PostBB.
4684 if (QTB->getSingleSuccessor() == QFB)
4685 PostBB = QFB;
4686
4687 // If we couldn't find a good PostBB, stop.
4688 if (!PostBB)
4689 return false;
4690
4691 bool InvertPCond = false, InvertQCond = false;
4692 // Canonicalize fallthroughs to the true branches.
4693 if (PFB == QBI->getParent()) {
4694 std::swap(PFB, PTB);
4695 InvertPCond = true;
4696 }
4697 if (QFB == PostBB) {
4698 std::swap(QFB, QTB);
4699 InvertQCond = true;
4700 }
4701
4702 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
4703 // and QFB may not. Model fallthroughs as a nullptr block.
4704 if (PTB == QBI->getParent())
4705 PTB = nullptr;
4706 if (QTB == PostBB)
4707 QTB = nullptr;
4708
4709 // Legality bailouts. We must have at least the non-fallthrough blocks and
4710 // the post-dominating block, and the non-fallthroughs must only have one
4711 // predecessor.
4712 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
4713 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
4714 };
4715 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
4716 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
4717 return false;
4718 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
4719 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
4720 return false;
4721 if (!QBI->getParent()->hasNUses(2))
4722 return false;
4723
4724 // OK, this is a sequence of two diamonds or triangles.
4725 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
4726 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
4727 for (auto *BB : {PTB, PFB}) {
4728 if (!BB)
4729 continue;
4730 for (auto &I : *BB)
4732 PStoreAddresses.insert(SI->getPointerOperand());
4733 }
4734 for (auto *BB : {QTB, QFB}) {
4735 if (!BB)
4736 continue;
4737 for (auto &I : *BB)
4739 QStoreAddresses.insert(SI->getPointerOperand());
4740 }
4741
4742 set_intersect(PStoreAddresses, QStoreAddresses);
4743 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
4744 // clear what it contains.
4745 auto &CommonAddresses = PStoreAddresses;
4746
4747 bool Changed = false;
4748 for (auto *Address : CommonAddresses)
4749 Changed |=
4750 mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address,
4751 InvertPCond, InvertQCond, DTU, DL, TTI);
4752 return Changed;
4753}
4754
4755/// If the previous block ended with a widenable branch, determine if reusing
4756/// the target block is profitable and legal. This will have the effect of
4757/// "widening" PBI, but doesn't require us to reason about hosting safety.
4759 DomTreeUpdater *DTU) {
4760 // TODO: This can be generalized in two important ways:
4761 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
4762 // values from the PBI edge.
4763 // 2) We can sink side effecting instructions into BI's fallthrough
4764 // successor provided they doesn't contribute to computation of
4765 // BI's condition.
4766 BasicBlock *IfTrueBB = PBI->getSuccessor(0);
4767 BasicBlock *IfFalseBB = PBI->getSuccessor(1);
4768 if (!isWidenableBranch(PBI) || IfTrueBB != BI->getParent() ||
4769 !BI->getParent()->getSinglePredecessor())
4770 return false;
4771 if (!IfFalseBB->phis().empty())
4772 return false; // TODO
4773 // This helps avoid infinite loop with SimplifyCondBranchToCondBranch which
4774 // may undo the transform done here.
4775 // TODO: There might be a more fine-grained solution to this.
4776 if (!llvm::succ_empty(IfFalseBB))
4777 return false;
4778 // Use lambda to lazily compute expensive condition after cheap ones.
4779 auto NoSideEffects = [](BasicBlock &BB) {
4780 return llvm::none_of(BB, [](const Instruction &I) {
4781 return I.mayWriteToMemory() || I.mayHaveSideEffects();
4782 });
4783 };
4784 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
4785 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
4786 NoSideEffects(*BI->getParent())) {
4787 auto *OldSuccessor = BI->getSuccessor(1);
4788 OldSuccessor->removePredecessor(BI->getParent());
4789 BI->setSuccessor(1, IfFalseBB);
4790 if (DTU)
4791 DTU->applyUpdates(
4792 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4793 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4794 return true;
4795 }
4796 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
4797 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
4798 NoSideEffects(*BI->getParent())) {
4799 auto *OldSuccessor = BI->getSuccessor(0);
4800 OldSuccessor->removePredecessor(BI->getParent());
4801 BI->setSuccessor(0, IfFalseBB);
4802 if (DTU)
4803 DTU->applyUpdates(
4804 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4805 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4806 return true;
4807 }
4808 return false;
4809}
4810
4811/// If we have a conditional branch as a predecessor of another block,
4812/// this function tries to simplify it. We know
4813/// that PBI and BI are both conditional branches, and BI is in one of the
4814/// successor blocks of PBI - PBI branches to BI.
4816 DomTreeUpdater *DTU,
4817 const DataLayout &DL,
4818 const TargetTransformInfo &TTI) {
4819 BasicBlock *BB = BI->getParent();
4820
4821 // If this block ends with a branch instruction, and if there is a
4822 // predecessor that ends on a branch of the same condition, make
4823 // this conditional branch redundant.
4824 if (PBI->getCondition() == BI->getCondition() &&
4825 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
4826 // Okay, the outcome of this conditional branch is statically
4827 // knowable. If this block had a single pred, handle specially, otherwise
4828 // foldCondBranchOnValueKnownInPredecessor() will handle it.
4829 if (BB->getSinglePredecessor()) {
4830 // Turn this into a branch on constant.
4831 bool CondIsTrue = PBI->getSuccessor(0) == BB;
4832 BI->setCondition(
4833 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
4834 return true; // Nuke the branch on constant.
4835 }
4836 }
4837
4838 // If the previous block ended with a widenable branch, determine if reusing
4839 // the target block is profitable and legal. This will have the effect of
4840 // "widening" PBI, but doesn't require us to reason about hosting safety.
4841 if (tryWidenCondBranchToCondBranch(PBI, BI, DTU))
4842 return true;
4843
4844 // If both branches are conditional and both contain stores to the same
4845 // address, remove the stores from the conditionals and create a conditional
4846 // merged store at the end.
4847 if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI))
4848 return true;
4849
4850 // If this is a conditional branch in an empty block, and if any
4851 // predecessors are a conditional branch to one of our destinations,
4852 // fold the conditions into logical ops and one cond br.
4853
4854 // Ignore dbg intrinsics.
4855 if (&*BB->begin() != BI)
4856 return false;
4857
4858 int PBIOp, BIOp;
4859 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4860 PBIOp = 0;
4861 BIOp = 0;
4862 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4863 PBIOp = 0;
4864 BIOp = 1;
4865 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4866 PBIOp = 1;
4867 BIOp = 0;
4868 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4869 PBIOp = 1;
4870 BIOp = 1;
4871 } else {
4872 return false;
4873 }
4874
4875 // Check to make sure that the other destination of this branch
4876 // isn't BB itself. If so, this is an infinite loop that will
4877 // keep getting unwound.
4878 if (PBI->getSuccessor(PBIOp) == BB)
4879 return false;
4880
4881 // If predecessor's branch probability to BB is too low don't merge branches.
4882 SmallVector<uint32_t, 2> PredWeights;
4883 if (!PBI->getMetadata(LLVMContext::MD_unpredictable) &&
4884 extractBranchWeights(*PBI, PredWeights) &&
4885 (static_cast<uint64_t>(PredWeights[0]) + PredWeights[1]) != 0) {
4886
4888 PredWeights[PBIOp],
4889 static_cast<uint64_t>(PredWeights[0]) + PredWeights[1]);
4890
4891 BranchProbability Likely = TTI.getPredictableBranchThreshold();
4892 if (CommonDestProb >= Likely)
4893 return false;
4894 }
4895
4896 // Do not perform this transformation if it would require
4897 // insertion of a large number of select instructions. For targets
4898 // without predication/cmovs, this is a big pessimization.
4899
4900 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
4901 BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1);
4902 unsigned NumPhis = 0;
4903 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
4904 ++II, ++NumPhis) {
4905 if (NumPhis > 2) // Disable this xform.
4906 return false;
4907 }
4908
4909 // Finally, if everything is ok, fold the branches to logical ops.
4910 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
4911
4912 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
4913 << "AND: " << *BI->getParent());
4914
4916
4917 // If OtherDest *is* BB, then BB is a basic block with a single conditional
4918 // branch in it, where one edge (OtherDest) goes back to itself but the other
4919 // exits. We don't *know* that the program avoids the infinite loop
4920 // (even though that seems likely). If we do this xform naively, we'll end up
4921 // recursively unpeeling the loop. Since we know that (after the xform is
4922 // done) that the block *is* infinite if reached, we just make it an obviously
4923 // infinite loop with no cond branch.
4924 if (OtherDest == BB) {
4925 // Insert it at the end of the function, because it's either code,
4926 // or it won't matter if it's hot. :)
4927 BasicBlock *InfLoopBlock =
4928 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
4929 UncondBrInst::Create(InfLoopBlock, InfLoopBlock);
4930 if (DTU)
4931 Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
4932 OtherDest = InfLoopBlock;
4933 }
4934
4935 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4936
4937 // BI may have other predecessors. Because of this, we leave
4938 // it alone, but modify PBI.
4939
4940 // Make sure we get to CommonDest on True&True directions.
4941 Value *PBICond = PBI->getCondition();
4942 IRBuilder<NoFolder> Builder(PBI);
4943 if (PBIOp)
4944 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
4945
4946 Value *BICond = BI->getCondition();
4947 if (BIOp)
4948 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
4949
4950 // Merge the conditions.
4951 Value *Cond =
4952 createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge");
4953
4954 // Modify PBI to branch on the new condition to the new dests.
4955 PBI->setCondition(Cond);
4956 PBI->setSuccessor(0, CommonDest);
4957 PBI->setSuccessor(1, OtherDest);
4958
4959 if (DTU) {
4960 Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest});
4961 Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest});
4962
4963 DTU->applyUpdates(Updates);
4964 }
4965
4966 // Update branch weight for PBI.
4967 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4968 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
4969 bool HasWeights =
4970 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4971 SuccTrueWeight, SuccFalseWeight);
4972 if (HasWeights) {
4973 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4974 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4975 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4976 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4977 // The weight to CommonDest should be PredCommon * SuccTotal +
4978 // PredOther * SuccCommon.
4979 // The weight to OtherDest should be PredOther * SuccOther.
4980 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
4981 PredOther * SuccCommon,
4982 PredOther * SuccOther};
4983
4984 setFittedBranchWeights(*PBI, NewWeights, /*IsExpected=*/false,
4985 /*ElideAllZero=*/true);
4986 // Cond may be a select instruction with the first operand set to "true", or
4987 // the second to "false" (see how createLogicalOp works for `and` and `or`)
4988 if (auto *SI = dyn_cast<SelectInst>(Cond)) {
4989 assert(isSelectInRoleOfConjunctionOrDisjunction(SI));
4990 // The select is predicated on PBICond
4991 assert(SI->getCondition() == PBICond);
4992 // The corresponding probabilities are what was referred to above as
4993 // PredCommon and PredOther.
4994 setFittedBranchWeights(*SI, {PredCommon, PredOther},
4995 /*IsExpected=*/false, /*ElideAllZero=*/true);
4996 }
4997 }
4998
4999 // OtherDest may have phi nodes. If so, add an entry from PBI's
5000 // block that are identical to the entries for BI's block.
5001 addPredecessorToBlock(OtherDest, PBI->getParent(), BB);
5002
5003 // We know that the CommonDest already had an edge from PBI to
5004 // it. If it has PHIs though, the PHIs may have different
5005 // entries for BB and PBI's BB. If so, insert a select to make
5006 // them agree.
5007 for (PHINode &PN : CommonDest->phis()) {
5008 Value *BIV = PN.getIncomingValueForBlock(BB);
5009 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
5010 Value *PBIV = PN.getIncomingValue(PBBIdx);
5011 if (BIV != PBIV) {
5012 // Insert a select in PBI to pick the right value.
5014 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
5015 PN.setIncomingValue(PBBIdx, NV);
5016 // The select has the same condition as PBI, in the same BB. The
5017 // probabilities don't change.
5018 if (HasWeights) {
5019 uint64_t TrueWeight = PBIOp ? PredFalseWeight : PredTrueWeight;
5020 uint64_t FalseWeight = PBIOp ? PredTrueWeight : PredFalseWeight;
5021 setFittedBranchWeights(*NV, {TrueWeight, FalseWeight},
5022 /*IsExpected=*/false, /*ElideAllZero=*/true);
5023 }
5024 }
5025 }
5026
5027 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
5028 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
5029
5030 // This basic block is probably dead. We know it has at least
5031 // one fewer predecessor.
5032 return true;
5033}
5034
5035// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
5036// true or to FalseBB if Cond is false.
5037// Takes care of updating the successors and removing the old terminator.
5038// Also makes sure not to introduce new successors by assuming that edges to
5039// non-successor TrueBBs and FalseBBs aren't reachable.
5040bool SimplifyCFGOpt::simplifyTerminatorOnSelect(Instruction *OldTerm,
5041 Value *Cond, BasicBlock *TrueBB,
5042 BasicBlock *FalseBB,
5043 uint32_t TrueWeight,
5044 uint32_t FalseWeight) {
5045 auto *BB = OldTerm->getParent();
5046 // Remove any superfluous successor edges from the CFG.
5047 // First, figure out which successors to preserve.
5048 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
5049 // successor.
5050 BasicBlock *KeepEdge1 = TrueBB;
5051 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
5052
5053 SmallSetVector<BasicBlock *, 2> RemovedSuccessors;
5054
5055 // Then remove the rest.
5056 for (BasicBlock *Succ : successors(OldTerm)) {
5057 // Make sure only to keep exactly one copy of each edge.
5058 if (Succ == KeepEdge1)
5059 KeepEdge1 = nullptr;
5060 else if (Succ == KeepEdge2)
5061 KeepEdge2 = nullptr;
5062 else {
5063 Succ->removePredecessor(BB,
5064 /*KeepOneInputPHIs=*/true);
5065
5066 if (Succ != TrueBB && Succ != FalseBB)
5067 RemovedSuccessors.insert(Succ);
5068 }
5069 }
5070
5071 IRBuilder<> Builder(OldTerm);
5072 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
5073
5074 // Insert an appropriate new terminator.
5075 if (!KeepEdge1 && !KeepEdge2) {
5076 if (TrueBB == FalseBB) {
5077 // We were only looking for one successor, and it was present.
5078 // Create an unconditional branch to it.
5079 Builder.CreateBr(TrueBB);
5080 } else {
5081 // We found both of the successors we were looking for.
5082 // Create a conditional branch sharing the condition of the select.
5083 CondBrInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
5084 setBranchWeights(*NewBI, {TrueWeight, FalseWeight},
5085 /*IsExpected=*/false, /*ElideAllZero=*/true);
5086 }
5087 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
5088 // Neither of the selected blocks were successors, so this
5089 // terminator must be unreachable.
5090 new UnreachableInst(OldTerm->getContext(), OldTerm->getIterator());
5091 } else {
5092 // One of the selected values was a successor, but the other wasn't.
5093 // Insert an unconditional branch to the one that was found;
5094 // the edge to the one that wasn't must be unreachable.
5095 if (!KeepEdge1) {
5096 // Only TrueBB was found.
5097 Builder.CreateBr(TrueBB);
5098 } else {
5099 // Only FalseBB was found.
5100 Builder.CreateBr(FalseBB);
5101 }
5102 }
5103
5105
5106 if (DTU) {
5107 SmallVector<DominatorTree::UpdateType, 2> Updates;
5108 Updates.reserve(RemovedSuccessors.size());
5109 for (auto *RemovedSuccessor : RemovedSuccessors)
5110 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
5111 DTU->applyUpdates(Updates);
5112 }
5113
5114 return true;
5115}
5116
5117// Folds switch(select(icmp eq X, C, K, X)) into switch(X), retargeting
5118// (or adding) the case for C to wherever K currently dispatches to:
5119// %cmp = icmp eq T %x, C
5120// %key = select i1 %cmp, T K, T %x
5121// switch T %key, label %default [ T K, label %case_k ... ]
5122// becomes
5123// switch T %x, label %default [ T C, label %case_k
5124// T K, label %case_k ... ]
5125bool SimplifyCFGOpt::simplifySwitchOnSelectRemap(SwitchInst *SI,
5126 SelectInst *Select, Value *X,
5127 ConstantInt *C, bool Negate) {
5128 Value *TrueVal = Select->getTrueValue();
5129 Value *FalseVal = Select->getFalseValue();
5130 if (Negate)
5131 std::swap(TrueVal, FalseVal);
5132 if (FalseVal != X)
5133 return false;
5134 auto *K = dyn_cast<ConstantInt>(TrueVal);
5135 if (!K)
5136 return false;
5137
5138 BasicBlock *DestFork = SI->findCaseValue(K)->getCaseSuccessor();
5139 auto CaseC = SI->findCaseValue(C);
5140 bool IsDefault = CaseC == SI->case_default();
5141 // Save before setSuccessor()/addCase() change it.
5142 BasicBlock *OldDest = CaseC->getCaseSuccessor();
5143 BasicBlock *BB = SI->getParent();
5144
5145 // Switch on X first: removePredecessor() below may fold X away if it is a
5146 // PHI in OldDest, and the RAUW must update the switch condition too.
5147 SI->setCondition(X);
5148
5149 if (OldDest != DestFork) {
5150 if (!IsDefault)
5151 OldDest->removePredecessor(BB);
5152 if (IsDefault)
5153 SI->addCase(C, DestFork);
5154 else
5155 CaseC->setSuccessor(DestFork);
5156 // Not a new edge (BB->DestFork exists via K), just adding the PHI
5157 // entry.
5158 addPredecessorToBlock(DestFork, BB, BB);
5159
5160 if (!IsDefault) {
5161 // Edge to OldDest is gone only if nothing else still uses it.
5162 bool OldDestStillTargeted = any_of(
5163 successors(SI), [&](BasicBlock *Succ) { return Succ == OldDest; });
5164 if (DTU && !OldDestStillTargeted)
5165 DTU->applyUpdates({{DominatorTree::Delete, BB, OldDest}});
5166 }
5167
5168 // Update the profile information on the switch if we had a profile
5169 // for both it and the select instruction.
5170 SmallVector<uint32_t> SwitchWeights;
5171 bool SwitchHasBranchWeights = extractBranchWeights(*SI, SwitchWeights);
5172 // If we add a case, ensure the length of the branch weights list matches
5173 // to make iterating over them easier later.
5174 if (IsDefault)
5175 SwitchWeights.push_back(0);
5178 bool SelectHasBranchWeights =
5180 uint64_t SelectTotalWeight = SelectTrueWeight + SelectFalseWeight;
5181 if (Negate)
5183 if (SwitchHasBranchWeights && SelectHasBranchWeights &&
5185 // We update the branch weights by subtracting P(x=C) from the probability
5186 // of case K in the switch (what C redirect to before the transformation),
5187 // plugging the probability for case C into the switch (which we derive
5188 // from the select), and ensuring everything is scaled to have a common
5189 // denominator.
5190 uint64_t SwitchTotalWeight = sum_of(SwitchWeights, uint64_t{0});
5191 SmallVector<uint64_t> NewSwitchWeights;
5192 NewSwitchWeights.reserve(SwitchWeights.size());
5193 NewSwitchWeights.push_back(SwitchWeights[0] * SelectTotalWeight);
5194 for (const auto &[SwitchCase, SwitchWeight] :
5195 zip(SI->cases(), drop_begin(SwitchWeights))) {
5196 if (SwitchCase.getCaseValue() == C) {
5197 NewSwitchWeights.push_back(SwitchTotalWeight * SelectTrueWeight);
5198 } else if (SwitchCase.getCaseValue() == K) {
5199 // In reality, P(key=K) > P(x=C) should always hold, but explicitly
5200 // guard against bad profiles here to prevent underflow by saturating
5201 // to zero.
5202 uint64_t ProbabilityKeyEqualsK = SwitchWeight * SelectTotalWeight;
5203 uint64_t ProbabilityXEqualsC = SelectTrueWeight * SwitchTotalWeight;
5204 uint64_t ProbabilityXEqualsK =
5205 ProbabilityKeyEqualsK > ProbabilityXEqualsC
5206 ? ProbabilityKeyEqualsK - ProbabilityXEqualsC
5207 : 0;
5208 NewSwitchWeights.push_back(ProbabilityXEqualsK);
5209 } else {
5210 NewSwitchWeights.push_back(SwitchWeight * SelectTotalWeight);
5211 }
5212 }
5213 setFittedBranchWeights(*SI, NewSwitchWeights, /*IsExpected=*/false);
5214 } else if (SwitchHasBranchWeights) {
5215 // If we only have branch weights on the switch, we cannot reconstruct
5216 // branch weights correctly, so mark them as unknown if the function has
5217 // a profile count. Reset the branch weights first to ensure we remove
5218 // the now invalid branch weights if the function is not otherwise
5219 // profiled.
5220 SI->setMetadata(LLVMContext::MD_prof, nullptr);
5222 }
5223 }
5224
5225 // The compare/select are now dead.
5227 return true;
5228}
5229
5230// Replaces
5231// (switch (select cond, X, Y)) on constant X, Y
5232// with a branch - conditional if X and Y lead to distinct BBs,
5233// unconditional otherwise.
5234bool SimplifyCFGOpt::simplifySwitchOnSelect(SwitchInst *SI,
5235 SelectInst *Select) {
5236 CmpPredicate Pred;
5237 Value *X;
5238 ConstantInt *C;
5239 if (Select->hasOneUse() &&
5240 match(Select->getCondition(),
5241 m_ICmp(Pred, m_Value(X), m_ConstantInt(C))) &&
5242 ICmpInst::isEquality(Pred) &&
5243 simplifySwitchOnSelectRemap(SI, Select, X, C, Pred == ICmpInst::ICMP_NE))
5244 return true;
5245
5246 // Check for constant integer values in the select.
5247 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
5248 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
5249 if (!TrueVal || !FalseVal)
5250 return false;
5251
5252 // Find the relevant condition and destinations.
5253 Value *Condition = Select->getCondition();
5254 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
5255 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
5256
5257 // Get weight for TrueBB and FalseBB.
5258 uint32_t TrueWeight = 0, FalseWeight = 0;
5259 SmallVector<uint64_t, 8> Weights;
5260 bool HasWeights = hasBranchWeightMD(*SI);
5261 if (HasWeights) {
5262 getBranchWeights(SI, Weights);
5263 if (Weights.size() == 1 + SI->getNumCases()) {
5264 TrueWeight =
5265 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
5266 FalseWeight =
5267 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
5268 }
5269 }
5270
5271 // Perform the actual simplification.
5272 return simplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
5273 FalseWeight);
5274}
5275
5276// Replaces
5277// (indirectbr (select cond, blockaddress(@fn, BlockA),
5278// blockaddress(@fn, BlockB)))
5279// with
5280// (br cond, BlockA, BlockB).
5281bool SimplifyCFGOpt::simplifyIndirectBrOnSelect(IndirectBrInst *IBI,
5282 SelectInst *SI) {
5283 // Check that both operands of the select are block addresses.
5284 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
5285 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
5286 if (!TBA || !FBA)
5287 return false;
5288
5289 // Extract the actual blocks.
5290 BasicBlock *TrueBB = TBA->getBasicBlock();
5291 BasicBlock *FalseBB = FBA->getBasicBlock();
5292
5293 // The select's profile becomes the profile of the conditional branch that
5294 // replaces the indirect branch.
5295 SmallVector<uint32_t> SelectBranchWeights(2);
5296 extractBranchWeights(*SI, SelectBranchWeights);
5297 // Perform the actual simplification.
5298 return simplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
5299 SelectBranchWeights[0],
5300 SelectBranchWeights[1]);
5301}
5302
5303/// This is called when we find an icmp instruction
5304/// (a seteq/setne with a constant) as the only instruction in a
5305/// block that ends with an uncond branch. We are looking for a very specific
5306/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
5307/// this case, we merge the first two "or's of icmp" into a switch, but then the
5308/// default value goes to an uncond block with a seteq in it, we get something
5309/// like:
5310///
5311/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
5312/// DEFAULT:
5313/// %tmp = icmp eq i8 %A, 92
5314/// br label %end
5315/// end:
5316/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
5317///
5318/// We prefer to split the edge to 'end' so that there is a true/false entry to
5319/// the PHI, merging the third icmp into the switch.
5320bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
5321 ICmpInst *ICI, IRBuilder<> &Builder) {
5322 // Select == nullptr means we assume that there is a hidden no-op select
5323 // instruction of `_ = select %icmp, true, false` after `%icmp = icmp ...`
5324 return tryToSimplifyUncondBranchWithICmpSelectInIt(ICI, nullptr, Builder);
5325}
5326
5327/// Similar to tryToSimplifyUncondBranchWithICmpInIt, but handle a more generic
5328/// case. This is called when we find an icmp instruction (a seteq/setne with a
5329/// constant) and its following select instruction as the only TWO instructions
5330/// in a block that ends with an uncond branch. We are looking for a very
5331/// specific pattern that occurs when "
5332/// if (A == 1) return C1;
5333/// if (A == 2) return C2;
5334/// if (A < 3) return C3;
5335/// return C4;
5336/// " gets simplified. In this case, we merge the first two "branches of icmp"
5337/// into a switch, but then the default value goes to an uncond block with a lt
5338/// icmp and select in it, as InstCombine can not simplify "A < 3" as "A == 2".
5339/// After SimplifyCFG and other subsequent optimizations (e.g., SCCP), we might
5340/// get something like:
5341///
5342/// case1:
5343/// switch i8 %A, label %DEFAULT [ i8 0, label %end i8 1, label %case2 ]
5344/// case2:
5345/// br label %end
5346/// DEFAULT:
5347/// %tmp = icmp eq i8 %A, 2
5348/// %val = select i1 %tmp, i8 C3, i8 C4
5349/// br label %end
5350/// end:
5351/// _ = phi i8 [ C1, %case1 ], [ C2, %case2 ], [ %val, %DEFAULT ]
5352///
5353/// We prefer to split the edge to 'end' so that there are TWO entries of V3/V4
5354/// to the PHI, merging the icmp & select into the switch, as follows:
5355///
5356/// case1:
5357/// switch i8 %A, label %DEFAULT [
5358/// i8 0, label %end
5359/// i8 1, label %case2
5360/// i8 2, label %case3
5361/// ]
5362/// case2:
5363/// br label %end
5364/// case3:
5365/// br label %end
5366/// DEFAULT:
5367/// br label %end
5368/// end:
5369/// _ = phi i8 [ C1, %case1 ], [ C2, %case2 ], [ C3, %case2 ], [ C4, %DEFAULT]
5370bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpSelectInIt(
5371 ICmpInst *ICI, SelectInst *Select, IRBuilder<> &Builder) {
5372 BasicBlock *BB = ICI->getParent();
5373
5374 // If the block has any PHIs in it or the icmp/select has multiple uses, it is
5375 // too complex.
5376 /// TODO: support multi-phis in succ BB of select's BB.
5377 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse() ||
5378 (Select && !Select->hasOneUse()))
5379 return false;
5380
5381 // The pattern we're looking for is where our only predecessor is a switch on
5382 // 'V' and this block is the default case for the switch. In this case we can
5383 // fold the compared value into the switch to simplify things.
5384 BasicBlock *Pred = BB->getSinglePredecessor();
5385 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
5386 return false;
5387
5388 Value *IcmpCond;
5389 ConstantInt *NewCaseVal;
5390 CmpPredicate Predicate;
5391
5392 // Match icmp X, C
5393 if (!match(ICI,
5394 m_ICmp(Predicate, m_Value(IcmpCond), m_ConstantInt(NewCaseVal))))
5395 return false;
5396
5397 Value *SelectCond, *SelectTrueVal, *SelectFalseVal;
5399 if (!Select) {
5400 // If Select == nullptr, we can assume that there is a hidden no-op select
5401 // just after icmp
5402 SelectCond = ICI;
5403 SelectTrueVal = Builder.getTrue();
5404 SelectFalseVal = Builder.getFalse();
5405 User = ICI->user_back();
5406 } else {
5407 SelectCond = Select->getCondition();
5408 // Check if the select condition is the same as the icmp condition.
5409 if (SelectCond != ICI)
5410 return false;
5411 SelectTrueVal = Select->getTrueValue();
5412 SelectFalseVal = Select->getFalseValue();
5413 User = Select->user_back();
5414 }
5415
5416 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
5417 if (SI->getCondition() != IcmpCond)
5418 return false;
5419
5420 // If BB is reachable on a non-default case, then we simply know the value of
5421 // V in this block. Substitute it and constant fold the icmp instruction
5422 // away.
5423 if (SI->getDefaultDest() != BB) {
5424 ConstantInt *VVal = SI->findCaseDest(BB);
5425 assert(VVal && "Should have a unique destination value");
5426 ICI->setOperand(0, VVal);
5427
5428 if (Value *V = simplifyInstruction(ICI, {DL, ICI})) {
5429 ICI->replaceAllUsesWith(V);
5430 ICI->eraseFromParent();
5431 }
5432 // BB is now empty, so it is likely to simplify away.
5433 return requestResimplify();
5434 }
5435
5436 // Ok, the block is reachable from the default dest. If the constant we're
5437 // comparing exists in one of the other edges, then we can constant fold ICI
5438 // and zap it.
5439 if (SI->findCaseValue(NewCaseVal) != SI->case_default()) {
5440 Value *V;
5441 if (Predicate == ICmpInst::ICMP_EQ)
5443 else
5445
5446 ICI->replaceAllUsesWith(V);
5447 ICI->eraseFromParent();
5448 // BB is now empty, so it is likely to simplify away.
5449 return requestResimplify();
5450 }
5451
5452 // The use of the select has to be in the 'end' block, by the only PHI node in
5453 // the block.
5454 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
5455 PHINode *PHIUse = dyn_cast<PHINode>(User);
5456 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
5458 return false;
5459
5460 // If the icmp is a SETEQ, then the default dest gets SelectFalseVal, the new
5461 // edge gets SelectTrueVal in the PHI.
5462 Value *DefaultCst = SelectFalseVal;
5463 Value *NewCst = SelectTrueVal;
5464
5465 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
5466 std::swap(DefaultCst, NewCst);
5467
5468 // Replace Select (which is used by the PHI for the default value) with
5469 // SelectFalseVal or SelectTrueVal depending on if ICI is EQ or NE.
5470 if (Select) {
5471 Select->replaceAllUsesWith(DefaultCst);
5472 Select->eraseFromParent();
5473 } else {
5474 ICI->replaceAllUsesWith(DefaultCst);
5475 }
5476 ICI->eraseFromParent();
5477
5478 SmallVector<DominatorTree::UpdateType, 2> Updates;
5479
5480 // Okay, the switch goes to this block on a default value. Add an edge from
5481 // the switch to the merge point on the compared value.
5482 BasicBlock *NewBB =
5483 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
5484 {
5485 SwitchInstProfUpdateWrapper SIW(*SI);
5486 auto W0 = SIW.getSuccessorWeight(0);
5488 if (W0) {
5489 NewW = ((uint64_t(*W0) + 1) >> 1);
5490 SIW.setSuccessorWeight(0, *NewW);
5491 }
5492 SIW.addCase(NewCaseVal, NewBB, NewW);
5493 if (DTU)
5494 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
5495 }
5496
5497 // NewBB branches to the phi block, add the uncond branch and the phi entry.
5498 Builder.SetInsertPoint(NewBB);
5499 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
5500 Builder.CreateBr(SuccBlock);
5501 PHIUse->addIncoming(NewCst, NewBB);
5502 if (DTU) {
5503 Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock});
5504 DTU->applyUpdates(Updates);
5505 }
5506 return true;
5507}
5508
5509/// Check to see if it is branching on an or/and chain of icmp instructions, and
5510/// fold it into a switch instruction if so.
5511bool SimplifyCFGOpt::simplifyBranchOnICmpChain(CondBrInst *BI,
5512 IRBuilder<> &Builder,
5513 const DataLayout &DL) {
5515 if (!Cond)
5516 return false;
5517
5518 // Change br (X == 0 | X == 1), T, F into a switch instruction.
5519 // If this is a bunch of seteq's or'd together, or if it's a bunch of
5520 // 'setne's and'ed together, collect them.
5521
5522 // Try to gather values from a chain of and/or to be turned into a switch
5523 ConstantComparesGatherer ConstantCompare(Cond, DL);
5524 // Unpack the result
5525 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
5526 Value *CompVal = ConstantCompare.CompValue;
5527 unsigned UsedICmps = ConstantCompare.UsedICmps;
5528 Value *ExtraCase = ConstantCompare.Extra;
5529 bool TrueWhenEqual = ConstantCompare.IsEq;
5530
5531 // If we didn't have a multiply compared value, fail.
5532 if (!CompVal)
5533 return false;
5534
5535 // Avoid turning single icmps into a switch.
5536 if (UsedICmps <= 1)
5537 return false;
5538
5539 // There might be duplicate constants in the list, which the switch
5540 // instruction can't handle, remove them now.
5542 Values.erase(llvm::unique(Values), Values.end());
5543
5544 // If Extra was used, we require at least two switch values to do the
5545 // transformation. A switch with one value is just a conditional branch.
5546 if (ExtraCase && Values.size() < 2)
5547 return false;
5548
5549 SmallVector<uint32_t> BranchWeights;
5550 const bool HasProfile = extractBranchWeights(*BI, BranchWeights);
5551
5552 // Figure out which block is which destination.
5553 BasicBlock *DefaultBB = BI->getSuccessor(1);
5554 BasicBlock *EdgeBB = BI->getSuccessor(0);
5555 if (!TrueWhenEqual) {
5556 std::swap(DefaultBB, EdgeBB);
5557 if (HasProfile)
5558 std::swap(BranchWeights[0], BranchWeights[1]);
5559 }
5560
5561 BasicBlock *BB = BI->getParent();
5562
5563 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
5564 << " cases into SWITCH. BB is:\n"
5565 << *BB);
5566
5567 SmallVector<DominatorTree::UpdateType, 2> Updates;
5568
5569 // If there are any extra values that couldn't be folded into the switch
5570 // then we evaluate them with an explicit branch first. Split the block
5571 // right before the condbr to handle it.
5572 if (ExtraCase) {
5573 BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr,
5574 /*MSSAU=*/nullptr, "switch.early.test");
5575
5576 // Remove the uncond branch added to the old block.
5577 Instruction *OldTI = BB->getTerminator();
5578 Builder.SetInsertPoint(OldTI);
5579
5580 // There can be an unintended UB if extra values are Poison. Before the
5581 // transformation, extra values may not be evaluated according to the
5582 // condition, and it will not raise UB. But after transformation, we are
5583 // evaluating extra values before checking the condition, and it will raise
5584 // UB. It can be solved by adding freeze instruction to extra values.
5585 AssumptionCache *AC = Options.AC;
5586
5587 if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr))
5588 ExtraCase = Builder.CreateFreeze(ExtraCase);
5589
5590 // We don't have any info about this condition.
5591 auto *Br = TrueWhenEqual ? Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB)
5592 : Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
5594
5595 OldTI->eraseFromParent();
5596
5597 if (DTU)
5598 Updates.push_back({DominatorTree::Insert, BB, EdgeBB});
5599
5600 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
5601 // for the edge we just added.
5602 addPredecessorToBlock(EdgeBB, BB, NewBB);
5603
5604 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
5605 << "\nEXTRABB = " << *BB);
5606 BB = NewBB;
5607 }
5608
5609 Builder.SetInsertPoint(BI);
5610 // Convert pointer to int before we switch.
5611 if (CompVal->getType()->isPointerTy()) {
5612 assert(!DL.hasUnstableRepresentation(CompVal->getType()) &&
5613 "Should not end up here with unstable pointers");
5614 CompVal = Builder.CreatePtrToInt(
5615 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
5616 }
5617
5618 // Check if we can represent the values as a contiguous range. If so, we use a
5619 // range check + conditional branch instead of a switch.
5620 if (Values.front()->getValue() - Values.back()->getValue() ==
5621 Values.size() - 1) {
5622 ConstantRange RangeToCheck = ConstantRange::getNonEmpty(
5623 Values.back()->getValue(), Values.front()->getValue() + 1);
5624 APInt Offset, RHS;
5625 ICmpInst::Predicate Pred;
5626 RangeToCheck.getEquivalentICmp(Pred, RHS, Offset);
5627 Value *X = CompVal;
5628 if (!Offset.isZero())
5629 X = Builder.CreateAdd(X, ConstantInt::get(CompVal->getType(), Offset));
5630 Value *Cond =
5631 Builder.CreateICmp(Pred, X, ConstantInt::get(CompVal->getType(), RHS));
5632 CondBrInst *NewBI = Builder.CreateCondBr(Cond, EdgeBB, DefaultBB);
5633 if (HasProfile)
5634 setBranchWeights(*NewBI, BranchWeights, /*IsExpected=*/false);
5635 else
5637 if (MDNode *Unpredictable = BI->getMetadata(LLVMContext::MD_unpredictable))
5638 NewBI->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
5639 // We don't need to update PHI nodes since we don't add any new edges.
5640 } else {
5641 // Create the new switch instruction now.
5642 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
5643 if (MDNode *Unpredictable = BI->getMetadata(LLVMContext::MD_unpredictable))
5644 New->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
5645 if (HasProfile) {
5646 // We know the weight of the default case. We don't know the weight of the
5647 // other cases, but rather than completely lose profiling info, we split
5648 // the remaining probability equally over them.
5649 SmallVector<uint32_t> NewWeights(Values.size() + 1);
5650 NewWeights[0] = BranchWeights[1]; // this is the default, and we swapped
5651 // if TrueWhenEqual.
5652 for (auto &V : drop_begin(NewWeights))
5653 V = BranchWeights[0] / Values.size();
5654 setBranchWeights(*New, NewWeights, /*IsExpected=*/false);
5655 } else {
5657 }
5658
5659 // Add all of the 'cases' to the switch instruction.
5660 for (ConstantInt *Val : Values)
5661 New->addCase(Val, EdgeBB);
5662
5663 // We added edges from PI to the EdgeBB. As such, if there were any
5664 // PHI nodes in EdgeBB, they need entries to be added corresponding to
5665 // the number of edges added.
5666 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
5667 PHINode *PN = cast<PHINode>(BBI);
5668 Value *InVal = PN->getIncomingValueForBlock(BB);
5669 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
5670 PN->addIncoming(InVal, BB);
5671 }
5672 }
5673
5674 // Erase the old branch instruction.
5676 if (DTU)
5677 DTU->applyUpdates(Updates);
5678
5679 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
5680 return true;
5681}
5682
5683bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
5684 if (isa<PHINode>(RI->getValue()))
5685 return simplifyCommonResume(RI);
5686 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHIIt()) &&
5687 RI->getValue() == &*RI->getParent()->getFirstNonPHIIt())
5688 // The resume must unwind the exception that caused control to branch here.
5689 return simplifySingleResume(RI);
5690
5691 return false;
5692}
5693
5694// Check if cleanup block is empty
5696 for (Instruction &I : R) {
5697 auto *II = dyn_cast<IntrinsicInst>(&I);
5698 if (!II || II->getIntrinsicID() != Intrinsic::lifetime_end)
5699 return false;
5700 }
5701 return true;
5702}
5703
5704// Simplify resume that is shared by several landing pads (phi of landing pad).
5705bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
5706 BasicBlock *BB = RI->getParent();
5707
5708 // Check that there are no other instructions except for debug and lifetime
5709 // intrinsics between the phi's and resume instruction.
5710 if (!isCleanupBlockEmpty(make_range(RI->getParent()->getFirstNonPHIIt(),
5711 BB->getTerminator()->getIterator())))
5712 return false;
5713
5714 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
5715 auto *PhiLPInst = cast<PHINode>(RI->getValue());
5716
5717 // Check incoming blocks to see if any of them are trivial.
5718 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
5719 Idx++) {
5720 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
5721 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
5722
5723 // If the block has other successors, we can not delete it because
5724 // it has other dependents.
5725 if (IncomingBB->getUniqueSuccessor() != BB)
5726 continue;
5727
5728 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHIIt());
5729 // Not the landing pad that caused the control to branch here.
5730 if (IncomingValue != LandingPad)
5731 continue;
5732
5734 make_range(LandingPad->getNextNode(), IncomingBB->getTerminator())))
5735 TrivialUnwindBlocks.insert(IncomingBB);
5736 }
5737
5738 // If no trivial unwind blocks, don't do any simplifications.
5739 if (TrivialUnwindBlocks.empty())
5740 return false;
5741
5742 // Turn all invokes that unwind here into calls.
5743 for (auto *TrivialBB : TrivialUnwindBlocks) {
5744 // Blocks that will be simplified should be removed from the phi node.
5745 // Note there could be multiple edges to the resume block, and we need
5746 // to remove them all.
5747 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
5748 BB->removePredecessor(TrivialBB, true);
5749
5750 for (BasicBlock *Pred :
5752 removeUnwindEdge(Pred, DTU);
5753 ++NumInvokes;
5754 }
5755
5756 // In each SimplifyCFG run, only the current processed block can be erased.
5757 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
5758 // of erasing TrivialBB, we only remove the branch to the common resume
5759 // block so that we can later erase the resume block since it has no
5760 // predecessors.
5761 TrivialBB->getTerminator()->eraseFromParent();
5762 new UnreachableInst(RI->getContext(), TrivialBB);
5763 if (DTU)
5764 DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}});
5765 }
5766
5767 // Delete the resume block if all its predecessors have been removed.
5768 if (pred_empty(BB))
5769 DeleteDeadBlock(BB, DTU);
5770
5771 return !TrivialUnwindBlocks.empty();
5772}
5773
5774// Simplify resume that is only used by a single (non-phi) landing pad.
5775bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
5776 BasicBlock *BB = RI->getParent();
5777 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHIIt());
5778 assert(RI->getValue() == LPInst &&
5779 "Resume must unwind the exception that caused control to here");
5780
5781 // Check that there are no other instructions except for debug intrinsics.
5783 make_range<Instruction *>(LPInst->getNextNode(), RI)))
5784 return false;
5785
5786 // Turn all invokes that unwind here into calls and delete the basic block.
5787 for (BasicBlock *Pred : llvm::make_early_inc_range(predecessors(BB))) {
5788 removeUnwindEdge(Pred, DTU);
5789 ++NumInvokes;
5790 }
5791
5792 // The landingpad is now unreachable. Zap it.
5793 DeleteDeadBlock(BB, DTU);
5794 return true;
5795}
5796
5798 // If this is a trivial cleanup pad that executes no instructions, it can be
5799 // eliminated. If the cleanup pad continues to the caller, any predecessor
5800 // that is an EH pad will be updated to continue to the caller and any
5801 // predecessor that terminates with an invoke instruction will have its invoke
5802 // instruction converted to a call instruction. If the cleanup pad being
5803 // simplified does not continue to the caller, each predecessor will be
5804 // updated to continue to the unwind destination of the cleanup pad being
5805 // simplified.
5806 BasicBlock *BB = RI->getParent();
5807 CleanupPadInst *CPInst = RI->getCleanupPad();
5808 if (CPInst->getParent() != BB)
5809 // This isn't an empty cleanup.
5810 return false;
5811
5812 // We cannot kill the pad if it has multiple uses. This typically arises
5813 // from unreachable basic blocks.
5814 if (!CPInst->hasOneUse())
5815 return false;
5816
5817 // Check that there are no other instructions except for benign intrinsics.
5819 make_range<Instruction *>(CPInst->getNextNode(), RI)))
5820 return false;
5821
5822 // If the cleanup return we are simplifying unwinds to the caller, this will
5823 // set UnwindDest to nullptr.
5824 BasicBlock *UnwindDest = RI->getUnwindDest();
5825
5826 // We're about to remove BB from the control flow. Before we do, sink any
5827 // PHINodes into the unwind destination. Doing this before changing the
5828 // control flow avoids some potentially slow checks, since we can currently
5829 // be certain that UnwindDest and BB have no common predecessors (since they
5830 // are both EH pads).
5831 if (UnwindDest) {
5832 // First, go through the PHI nodes in UnwindDest and update any nodes that
5833 // reference the block we are removing
5834 for (PHINode &DestPN : UnwindDest->phis()) {
5835 int Idx = DestPN.getBasicBlockIndex(BB);
5836 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
5837 assert(Idx != -1);
5838 // This PHI node has an incoming value that corresponds to a control
5839 // path through the cleanup pad we are removing. If the incoming
5840 // value is in the cleanup pad, it must be a PHINode (because we
5841 // verified above that the block is otherwise empty). Otherwise, the
5842 // value is either a constant or a value that dominates the cleanup
5843 // pad being removed.
5844 //
5845 // Because BB and UnwindDest are both EH pads, all of their
5846 // predecessors must unwind to these blocks, and since no instruction
5847 // can have multiple unwind destinations, there will be no overlap in
5848 // incoming blocks between SrcPN and DestPN.
5849 Value *SrcVal = DestPN.getIncomingValue(Idx);
5850 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
5851
5852 bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB;
5853 for (auto *Pred : predecessors(BB)) {
5854 Value *Incoming =
5855 NeedPHITranslation ? SrcPN->getIncomingValueForBlock(Pred) : SrcVal;
5856 DestPN.addIncoming(Incoming, Pred);
5857 }
5858 }
5859
5860 // Sink any remaining PHI nodes directly into UnwindDest.
5861 BasicBlock::iterator InsertPt = UnwindDest->getFirstNonPHIIt();
5862 for (PHINode &PN : make_early_inc_range(BB->phis())) {
5863 if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB))
5864 // If the PHI node has no uses or all of its uses are in this basic
5865 // block (meaning they are debug or lifetime intrinsics), just leave
5866 // it. It will be erased when we erase BB below.
5867 continue;
5868
5869 // Otherwise, sink this PHI node into UnwindDest.
5870 // Any predecessors to UnwindDest which are not already represented
5871 // must be back edges which inherit the value from the path through
5872 // BB. In this case, the PHI value must reference itself.
5873 for (auto *pred : predecessors(UnwindDest))
5874 if (pred != BB)
5875 PN.addIncoming(&PN, pred);
5876 PN.moveBefore(InsertPt);
5877 // Also, add a dummy incoming value for the original BB itself,
5878 // so that the PHI is well-formed until we drop said predecessor.
5879 PN.addIncoming(PoisonValue::get(PN.getType()), BB);
5880 }
5881 }
5882
5883 std::vector<DominatorTree::UpdateType> Updates;
5884
5885 // We use make_early_inc_range here because we will remove all predecessors.
5887 if (UnwindDest == nullptr) {
5888 if (DTU) {
5889 DTU->applyUpdates(Updates);
5890 Updates.clear();
5891 }
5892 removeUnwindEdge(PredBB, DTU);
5893 ++NumInvokes;
5894 } else {
5895 BB->removePredecessor(PredBB);
5896 Instruction *TI = PredBB->getTerminator();
5897 TI->replaceUsesOfWith(BB, UnwindDest);
5898 if (DTU) {
5899 Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest});
5900 Updates.push_back({DominatorTree::Delete, PredBB, BB});
5901 }
5902 }
5903 }
5904
5905 if (DTU)
5906 DTU->applyUpdates(Updates);
5907
5908 DeleteDeadBlock(BB, DTU);
5909
5910 return true;
5911}
5912
5913// Try to merge two cleanuppads together.
5915 // Skip any cleanuprets which unwind to caller, there is nothing to merge
5916 // with.
5917 BasicBlock *UnwindDest = RI->getUnwindDest();
5918 if (!UnwindDest)
5919 return false;
5920
5921 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
5922 // be safe to merge without code duplication.
5923 if (UnwindDest->getSinglePredecessor() != RI->getParent())
5924 return false;
5925
5926 // Verify that our cleanuppad's unwind destination is another cleanuppad.
5927 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
5928 if (!SuccessorCleanupPad)
5929 return false;
5930
5931 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
5932 // Replace any uses of the successor cleanupad with the predecessor pad
5933 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
5934 // funclet bundle operands.
5935 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
5936 // Remove the old cleanuppad.
5937 SuccessorCleanupPad->eraseFromParent();
5938 // Now, we simply replace the cleanupret with a branch to the unwind
5939 // destination.
5940 UncondBrInst::Create(UnwindDest, RI->getParent());
5941 RI->eraseFromParent();
5942
5943 return true;
5944}
5945
5946bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
5947 // It is possible to transiantly have an undef cleanuppad operand because we
5948 // have deleted some, but not all, dead blocks.
5949 // Eventually, this block will be deleted.
5950 if (isa<UndefValue>(RI->getOperand(0)))
5951 return false;
5952
5953 if (mergeCleanupPad(RI))
5954 return true;
5955
5956 if (removeEmptyCleanup(RI, DTU))
5957 return true;
5958
5959 return false;
5960}
5961
5962// WARNING: keep in sync with InstCombinerImpl::visitUnreachableInst()!
5963bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
5964 BasicBlock *BB = UI->getParent();
5965
5966 bool Changed = false;
5967
5968 // Ensure that any debug-info records that used to occur after the Unreachable
5969 // are moved to in front of it -- otherwise they'll "dangle" at the end of
5970 // the block.
5972
5973 // Debug-info records on the unreachable inst itself should be deleted, as
5974 // below we delete everything past the final executable instruction.
5975 UI->dropDbgRecords();
5976
5977 // If there are any instructions immediately before the unreachable that can
5978 // be removed, do so.
5979 while (UI->getIterator() != BB->begin()) {
5981 --BBI;
5982
5984 break; // Can not drop any more instructions. We're done here.
5985 // Otherwise, this instruction can be freely erased,
5986 // even if it is not side-effect free.
5987
5988 // Note that deleting EH's here is in fact okay, although it involves a bit
5989 // of subtle reasoning. If this inst is an EH, all the predecessors of this
5990 // block will be the unwind edges of Invoke/CatchSwitch/CleanupReturn,
5991 // and we can therefore guarantee this block will be erased.
5992
5993 // If we're deleting this, we're deleting any subsequent debug info, so
5994 // delete DbgRecords.
5995 BBI->dropDbgRecords();
5996
5997 // Delete this instruction (any uses are guaranteed to be dead)
5998 BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
5999 BBI->eraseFromParent();
6000 Changed = true;
6001 }
6002
6003 // If the unreachable instruction is the first in the block, take a gander
6004 // at all of the predecessors of this instruction, and simplify them.
6005 if (&BB->front() != UI)
6006 return Changed;
6007
6008 std::vector<DominatorTree::UpdateType> Updates;
6009
6010 SmallSetVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
6011 for (BasicBlock *Predecessor : Preds) {
6012 Instruction *TI = Predecessor->getTerminator();
6013 IRBuilder<> Builder(TI);
6014 if (isa<UncondBrInst>(TI)) {
6015 new UnreachableInst(TI->getContext(), TI->getIterator());
6016 TI->eraseFromParent();
6017 Changed = true;
6018 if (DTU)
6019 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6020 } else if (auto *BI = dyn_cast<CondBrInst>(TI)) {
6021 // We could either have a proper unconditional branch,
6022 // or a degenerate conditional branch with matching destinations.
6023 if (BI->getSuccessor(0) == BI->getSuccessor(1)) {
6024 new UnreachableInst(TI->getContext(), TI->getIterator());
6025 TI->eraseFromParent();
6026 Changed = true;
6027 } else {
6028 Value* Cond = BI->getCondition();
6029 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
6030 "The destinations are guaranteed to be different here.");
6031 CallInst *Assumption;
6032 if (BI->getSuccessor(0) == BB) {
6033 Assumption = Builder.CreateAssumption(Builder.CreateNot(Cond));
6034 Builder.CreateBr(BI->getSuccessor(1));
6035 } else {
6036 assert(BI->getSuccessor(1) == BB && "Incorrect CFG");
6037 Assumption = Builder.CreateAssumption(Cond);
6038 Builder.CreateBr(BI->getSuccessor(0));
6039 }
6040 if (Options.AC)
6041 Options.AC->registerAssumption(cast<AssumeInst>(Assumption));
6042
6044 Changed = true;
6045 }
6046 if (DTU)
6047 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6048 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
6049 SwitchInstProfUpdateWrapper SU(*SI);
6050 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
6051 if (i->getCaseSuccessor() != BB) {
6052 ++i;
6053 continue;
6054 }
6055 BB->removePredecessor(SU->getParent());
6056 i = SU.removeCase(i);
6057 e = SU->case_end();
6058 Changed = true;
6059 }
6060 // Note that the default destination can't be removed!
6061 if (DTU && SI->getDefaultDest() != BB)
6062 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6063 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
6064 if (II->getUnwindDest() == BB) {
6065 if (DTU) {
6066 DTU->applyUpdates(Updates);
6067 Updates.clear();
6068 }
6069 auto *CI = cast<CallInst>(removeUnwindEdge(TI->getParent(), DTU));
6070 if (!CI->doesNotThrow())
6071 CI->setDoesNotThrow();
6072 Changed = true;
6073 }
6074 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
6075 if (CSI->getUnwindDest() == BB) {
6076 if (DTU) {
6077 DTU->applyUpdates(Updates);
6078 Updates.clear();
6079 }
6080 removeUnwindEdge(TI->getParent(), DTU);
6081 Changed = true;
6082 continue;
6083 }
6084
6085 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
6086 E = CSI->handler_end();
6087 I != E; ++I) {
6088 if (*I == BB) {
6089 CSI->removeHandler(I);
6090 --I;
6091 --E;
6092 Changed = true;
6093 }
6094 }
6095 if (DTU)
6096 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6097 if (CSI->getNumHandlers() == 0) {
6098 if (CSI->hasUnwindDest()) {
6099 // Redirect all predecessors of the block containing CatchSwitchInst
6100 // to instead branch to the CatchSwitchInst's unwind destination.
6101 if (DTU) {
6102 for (auto *PredecessorOfPredecessor : predecessors(Predecessor)) {
6103 Updates.push_back({DominatorTree::Insert,
6104 PredecessorOfPredecessor,
6105 CSI->getUnwindDest()});
6106 Updates.push_back({DominatorTree::Delete,
6107 PredecessorOfPredecessor, Predecessor});
6108 }
6109 }
6110 Predecessor->replaceAllUsesWith(CSI->getUnwindDest());
6111 } else {
6112 // Rewrite all preds to unwind to caller (or from invoke to call).
6113 if (DTU) {
6114 DTU->applyUpdates(Updates);
6115 Updates.clear();
6116 }
6117 SmallVector<BasicBlock *, 8> EHPreds(predecessors(Predecessor));
6118 for (BasicBlock *EHPred : EHPreds)
6119 removeUnwindEdge(EHPred, DTU);
6120 }
6121 // The catchswitch is no longer reachable.
6122 new UnreachableInst(CSI->getContext(), CSI->getIterator());
6123 CSI->eraseFromParent();
6124 Changed = true;
6125 }
6126 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
6127 (void)CRI;
6128 assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB &&
6129 "Expected to always have an unwind to BB.");
6130 if (DTU)
6131 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6132 new UnreachableInst(TI->getContext(), TI->getIterator());
6133 TI->eraseFromParent();
6134 Changed = true;
6135 }
6136 }
6137
6138 if (DTU)
6139 DTU->applyUpdates(Updates);
6140
6141 // If this block is now dead, remove it.
6142 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
6143 DeleteDeadBlock(BB, DTU);
6144 return true;
6145 }
6146
6147 return Changed;
6148}
6149
6158
6159static std::optional<ContiguousCasesResult>
6162 BasicBlock *Dest, BasicBlock *OtherDest) {
6163 assert(Cases.size() >= 1);
6164
6166 const APInt &Min = Cases.back()->getValue();
6167 const APInt &Max = Cases.front()->getValue();
6168 APInt Offset = Max - Min;
6169 size_t ContiguousOffset = Cases.size() - 1;
6170 if (Offset == ContiguousOffset) {
6171 return ContiguousCasesResult{
6172 /*Min=*/Cases.back(),
6173 /*Max=*/Cases.front(),
6174 /*Dest=*/Dest,
6175 /*OtherDest=*/OtherDest,
6176 /*Cases=*/&Cases,
6177 /*OtherCases=*/&OtherCases,
6178 };
6179 }
6180 ConstantRange CR = computeConstantRange(Condition, /*ForSigned=*/false,
6181 SimplifyQuery(Dest->getDataLayout()));
6182 // If this is a wrapping contiguous range, that is, [Min, OtherMin] +
6183 // [OtherMax, Max] (also [OtherMax, OtherMin]), [OtherMin+1, OtherMax-1] is a
6184 // contiguous range for the other destination. N.B. If CR is not a full range,
6185 // Max+1 is not equal to Min. It's not continuous in arithmetic.
6186 if (Max == CR.getUnsignedMax() && Min == CR.getUnsignedMin()) {
6187 assert(Cases.size() >= 2);
6188 auto *It =
6189 std::adjacent_find(Cases.begin(), Cases.end(), [](auto L, auto R) {
6190 return L->getValue() != R->getValue() + 1;
6191 });
6192 if (It == Cases.end())
6193 return std::nullopt;
6194 auto [OtherMax, OtherMin] = std::make_pair(*It, *std::next(It));
6195 if ((Max - OtherMax->getValue()) + (OtherMin->getValue() - Min) ==
6196 Cases.size() - 2) {
6197 return ContiguousCasesResult{
6198 /*Min=*/cast<ConstantInt>(
6199 ConstantInt::get(OtherMin->getType(), OtherMin->getValue() + 1)),
6200 /*Max=*/
6202 ConstantInt::get(OtherMax->getType(), OtherMax->getValue() - 1)),
6203 /*Dest=*/OtherDest,
6204 /*OtherDest=*/Dest,
6205 /*Cases=*/&OtherCases,
6206 /*OtherCases=*/&Cases,
6207 };
6208 }
6209 }
6210 return std::nullopt;
6211}
6212
6214 DomTreeUpdater *DTU,
6215 bool RemoveOrigDefaultBlock = true) {
6216 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
6217 auto *BB = Switch->getParent();
6218 auto *OrigDefaultBlock = Switch->getDefaultDest();
6219 if (RemoveOrigDefaultBlock)
6220 OrigDefaultBlock->removePredecessor(BB);
6221 BasicBlock *NewDefaultBlock = BasicBlock::Create(
6222 BB->getContext(), BB->getName() + ".unreachabledefault", BB->getParent(),
6223 OrigDefaultBlock);
6224 auto *UI = new UnreachableInst(Switch->getContext(), NewDefaultBlock);
6226 Switch->setDefaultDest(&*NewDefaultBlock);
6227 if (DTU) {
6229 Updates.push_back({DominatorTree::Insert, BB, &*NewDefaultBlock});
6230 if (RemoveOrigDefaultBlock &&
6231 !is_contained(successors(BB), OrigDefaultBlock))
6232 Updates.push_back({DominatorTree::Delete, BB, &*OrigDefaultBlock});
6233 DTU->applyUpdates(Updates);
6234 }
6235}
6236
6237/// Turn a switch into an integer range comparison and branch.
6238/// Switches with more than 2 destinations are ignored.
6239/// Switches with 1 destination are also ignored.
6240bool SimplifyCFGOpt::turnSwitchRangeIntoICmp(SwitchInst *SI,
6241 IRBuilder<> &Builder) {
6242 assert(SI->getNumCases() > 1 && "Degenerate switch?");
6243
6244 bool HasDefault = !SI->defaultDestUnreachable();
6245
6246 auto *BB = SI->getParent();
6247 // Partition the cases into two sets with different destinations.
6248 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
6249 BasicBlock *DestB = nullptr;
6252
6253 for (auto Case : SI->cases()) {
6254 BasicBlock *Dest = Case.getCaseSuccessor();
6255 if (!DestA)
6256 DestA = Dest;
6257 if (Dest == DestA) {
6258 CasesA.push_back(Case.getCaseValue());
6259 continue;
6260 }
6261 if (!DestB)
6262 DestB = Dest;
6263 if (Dest == DestB) {
6264 CasesB.push_back(Case.getCaseValue());
6265 continue;
6266 }
6267 return false; // More than two destinations.
6268 }
6269 if (!DestB)
6270 return false; // All destinations are the same and the default is unreachable
6271
6272 assert(DestA && DestB &&
6273 "Single-destination switch should have been folded.");
6274 assert(DestA != DestB);
6275 assert(DestB != SI->getDefaultDest());
6276 assert(!CasesB.empty() && "There must be non-default cases.");
6277 assert(!CasesA.empty() || HasDefault);
6278
6279 // Figure out if one of the sets of cases form a contiguous range.
6280 std::optional<ContiguousCasesResult> ContiguousCases;
6281
6282 // Only one icmp is needed when there is only one case.
6283 if (!HasDefault && CasesA.size() == 1)
6284 ContiguousCases = ContiguousCasesResult{
6285 /*Min=*/CasesA[0],
6286 /*Max=*/CasesA[0],
6287 /*Dest=*/DestA,
6288 /*OtherDest=*/DestB,
6289 /*Cases=*/&CasesA,
6290 /*OtherCases=*/&CasesB,
6291 };
6292 else if (CasesB.size() == 1)
6293 ContiguousCases = ContiguousCasesResult{
6294 /*Min=*/CasesB[0],
6295 /*Max=*/CasesB[0],
6296 /*Dest=*/DestB,
6297 /*OtherDest=*/DestA,
6298 /*Cases=*/&CasesB,
6299 /*OtherCases=*/&CasesA,
6300 };
6301 // Correctness: Cases to the default destination cannot be contiguous cases.
6302 else if (!HasDefault)
6303 ContiguousCases =
6304 findContiguousCases(SI->getCondition(), CasesA, CasesB, DestA, DestB);
6305
6306 if (!ContiguousCases)
6307 ContiguousCases =
6308 findContiguousCases(SI->getCondition(), CasesB, CasesA, DestB, DestA);
6309
6310 if (!ContiguousCases)
6311 return false;
6312
6313 auto [Min, Max, Dest, OtherDest, Cases, OtherCases] = *ContiguousCases;
6314
6315 // Start building the compare and branch.
6316
6318 Constant *NumCases = ConstantInt::get(Offset->getType(),
6319 Max->getValue() - Min->getValue() + 1);
6320 Instruction *NewBI;
6321 if (NumCases->isOneValue()) {
6322 assert(Max->getValue() == Min->getValue());
6323 Value *Cmp = Builder.CreateICmpEQ(SI->getCondition(), Min);
6324 NewBI = Builder.CreateCondBr(Cmp, Dest, OtherDest);
6325 }
6326 // If NumCases overflowed, then all possible values jump to the successor.
6327 else if (NumCases->isNullValue() && !Cases->empty()) {
6328 NewBI = Builder.CreateBr(Dest);
6329 } else {
6330 Value *Sub = SI->getCondition();
6331 if (!Offset->isNullValue())
6332 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
6333 Value *Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
6334 NewBI = Builder.CreateCondBr(Cmp, Dest, OtherDest);
6335 }
6336
6337 // Update weight for the newly-created conditional branch.
6338 if (hasBranchWeightMD(*SI) && isa<CondBrInst>(NewBI)) {
6339 SmallVector<uint64_t, 8> Weights;
6340 getBranchWeights(SI, Weights);
6341 if (Weights.size() == 1 + SI->getNumCases()) {
6342 uint64_t TrueWeight = 0;
6343 uint64_t FalseWeight = 0;
6344 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
6345 if (SI->getSuccessor(I) == Dest)
6346 TrueWeight += Weights[I];
6347 else
6348 FalseWeight += Weights[I];
6349 }
6350 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
6351 TrueWeight /= 2;
6352 FalseWeight /= 2;
6353 }
6354 setFittedBranchWeights(*NewBI, {TrueWeight, FalseWeight},
6355 /*IsExpected=*/false, /*ElideAllZero=*/true);
6356 }
6357 }
6358
6359 // Prune obsolete incoming values off the successors' PHI nodes.
6360 for (auto &PHI : make_early_inc_range(Dest->phis())) {
6361 unsigned PreviousEdges = Cases->size();
6362 if (Dest == SI->getDefaultDest())
6363 ++PreviousEdges;
6364 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
6365 PHI.removeIncomingValue(SI->getParent());
6366 }
6367 for (auto &PHI : make_early_inc_range(OtherDest->phis())) {
6368 unsigned PreviousEdges = OtherCases->size();
6369 if (OtherDest == SI->getDefaultDest())
6370 ++PreviousEdges;
6371 unsigned E = PreviousEdges - 1;
6372 // Remove all incoming values from OtherDest if OtherDest is unreachable.
6373 if (isa<UncondBrInst>(NewBI))
6374 ++E;
6375 for (unsigned I = 0; I != E; ++I)
6376 PHI.removeIncomingValue(SI->getParent());
6377 }
6378
6379 // Clean up the default block.
6380 SmallVector<DominatorTree::UpdateType, 2> Updates;
6381 if (!HasDefault) {
6382 BasicBlock *OrigDefaultBlock = SI->getDefaultDest();
6383 OrigDefaultBlock->removePredecessor(BB);
6384 Updates.push_back({DominatorTree::Delete, BB, OrigDefaultBlock});
6385 }
6386
6387 // Drop the switch.
6388 SI->eraseFromParent();
6389
6390 if (isa<UncondBrInst>(NewBI))
6391 Updates.push_back({DominatorTree::Delete, BB, OtherDest});
6392
6393 if (DTU)
6394 DTU->applyUpdates(Updates);
6395 return true;
6396}
6397
6398/// Compute masked bits for the condition of a switch
6399/// and use it to remove dead cases.
6401 AssumptionCache *AC,
6402 const DataLayout &DL) {
6403 Value *Cond = SI->getCondition();
6406 bool IsKnownValuesValid = collectPossibleValues(Cond, KnownValues, 4);
6407
6408 // We can also eliminate cases by determining that their values are outside of
6409 // the limited range of the condition based on how many significant (non-sign)
6410 // bits are in the condition value.
6411 unsigned MaxSignificantBitsInCond =
6413
6414 // Gather dead cases.
6416 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
6417 SmallVector<BasicBlock *, 8> UniqueSuccessors;
6418 for (const auto &Case : SI->cases()) {
6419 auto *Successor = Case.getCaseSuccessor();
6420 if (DTU) {
6421 auto [It, Inserted] = NumPerSuccessorCases.try_emplace(Successor);
6422 if (Inserted)
6423 UniqueSuccessors.push_back(Successor);
6424 ++It->second;
6425 }
6426 ConstantInt *CaseC = Case.getCaseValue();
6427 const APInt &CaseVal = CaseC->getValue();
6428 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
6429 (CaseVal.getSignificantBits() > MaxSignificantBitsInCond) ||
6430 (IsKnownValuesValid && !KnownValues.contains(CaseC))) {
6431 DeadCases.push_back(CaseC);
6432 if (DTU)
6433 --NumPerSuccessorCases[Successor];
6434 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
6435 << " is dead.\n");
6436 } else if (IsKnownValuesValid)
6437 KnownValues.erase(CaseC);
6438 }
6439
6440 // If we can prove that the cases must cover all possible values, the
6441 // default destination becomes dead and we can remove it. If we know some
6442 // of the bits in the value, we can use that to more precisely compute the
6443 // number of possible unique case values.
6444 bool HasDefault = !SI->defaultDestUnreachable();
6445 const unsigned NumUnknownBits =
6446 Known.getBitWidth() - (Known.Zero | Known.One).popcount();
6447 assert(NumUnknownBits <= Known.getBitWidth());
6448 if (HasDefault && DeadCases.empty()) {
6449 if (IsKnownValuesValid && all_of(KnownValues, IsaPred<UndefValue>)) {
6451 return true;
6452 }
6453
6454 if (NumUnknownBits < 64 /* avoid overflow */) {
6455 uint64_t AllNumCases = 1ULL << NumUnknownBits;
6456 if (SI->getNumCases() == AllNumCases) {
6458 return true;
6459 }
6460 // When only one case value is missing, replace default with that case.
6461 // Eliminating the default branch will provide more opportunities for
6462 // optimization, such as lookup tables.
6463 if (SI->getNumCases() == AllNumCases - 1) {
6464 assert(NumUnknownBits > 1 && "Should be canonicalized to a branch");
6465 IntegerType *CondTy = cast<IntegerType>(Cond->getType());
6466 if (CondTy->getIntegerBitWidth() > 64 ||
6467 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
6468 return false;
6469
6470 uint64_t MissingCaseVal = 0;
6471 for (const auto &Case : SI->cases())
6472 MissingCaseVal ^= Case.getCaseValue()->getValue().getLimitedValue();
6473 auto *MissingCase = cast<ConstantInt>(
6474 ConstantInt::get(Cond->getType(), MissingCaseVal));
6476 SIW.addCase(MissingCase, SI->getDefaultDest(),
6477 SIW.getSuccessorWeight(0));
6479 /*RemoveOrigDefaultBlock*/ false);
6480 SIW.setSuccessorWeight(0, 0);
6481 return true;
6482 }
6483 }
6484 }
6485
6486 if (DeadCases.empty())
6487 return false;
6488
6490 for (ConstantInt *DeadCase : DeadCases) {
6491 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
6492 assert(CaseI != SI->case_default() &&
6493 "Case was not found. Probably mistake in DeadCases forming.");
6494 // Prune unused values from PHI nodes.
6495 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
6496 SIW.removeCase(CaseI);
6497 }
6498
6499 if (DTU) {
6500 std::vector<DominatorTree::UpdateType> Updates;
6501 for (auto *Successor : UniqueSuccessors)
6502 if (NumPerSuccessorCases[Successor] == 0)
6503 Updates.push_back({DominatorTree::Delete, SI->getParent(), Successor});
6504 DTU->applyUpdates(Updates);
6505 }
6506
6507 return true;
6508}
6509
6510/// If BB would be eligible for simplification by
6511/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
6512/// by an unconditional branch), look at the phi node for BB in the successor
6513/// block and see if the incoming value is equal to CaseValue. If so, return
6514/// the phi node, and set PhiIndex to BB's index in the phi node.
6516 BasicBlock *BB, int *PhiIndex) {
6517 if (&*BB->getFirstNonPHIIt() != BB->getTerminator())
6518 return nullptr; // BB must be empty to be a candidate for simplification.
6519 if (!BB->getSinglePredecessor())
6520 return nullptr; // BB must be dominated by the switch.
6521
6523 if (!Branch)
6524 return nullptr; // Terminator must be unconditional branch.
6525
6526 BasicBlock *Succ = Branch->getSuccessor();
6527
6528 for (PHINode &PHI : Succ->phis()) {
6529 int Idx = PHI.getBasicBlockIndex(BB);
6530 assert(Idx >= 0 && "PHI has no entry for predecessor?");
6531
6532 Value *InValue = PHI.getIncomingValue(Idx);
6533 if (InValue != CaseValue)
6534 continue;
6535
6536 *PhiIndex = Idx;
6537 return &PHI;
6538 }
6539
6540 return nullptr;
6541}
6542
6543/// Try to forward the condition of a switch instruction to a phi node
6544/// dominated by the switch, if that would mean that some of the destination
6545/// blocks of the switch can be folded away. Return true if a change is made.
6547 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
6548
6549 ForwardingNodesMap ForwardingNodes;
6550 BasicBlock *SwitchBlock = SI->getParent();
6551 bool Changed = false;
6552 for (const auto &Case : SI->cases()) {
6553 ConstantInt *CaseValue = Case.getCaseValue();
6554 BasicBlock *CaseDest = Case.getCaseSuccessor();
6555
6556 // Replace phi operands in successor blocks that are using the constant case
6557 // value rather than the switch condition variable:
6558 // switchbb:
6559 // switch i32 %x, label %default [
6560 // i32 17, label %succ
6561 // ...
6562 // succ:
6563 // %r = phi i32 ... [ 17, %switchbb ] ...
6564 // -->
6565 // %r = phi i32 ... [ %x, %switchbb ] ...
6566
6567 for (PHINode &Phi : CaseDest->phis()) {
6568 // This only works if there is exactly 1 incoming edge from the switch to
6569 // a phi. If there is >1, that means multiple cases of the switch map to 1
6570 // value in the phi, and that phi value is not the switch condition. Thus,
6571 // this transform would not make sense (the phi would be invalid because
6572 // a phi can't have different incoming values from the same block).
6573 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
6574 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
6575 count(Phi.blocks(), SwitchBlock) == 1) {
6576 Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
6577 Changed = true;
6578 }
6579 }
6580
6581 // Collect phi nodes that are indirectly using this switch's case constants.
6582 int PhiIdx;
6583 if (auto *Phi = findPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
6584 ForwardingNodes[Phi].push_back(PhiIdx);
6585 }
6586
6587 for (auto &ForwardingNode : ForwardingNodes) {
6588 PHINode *Phi = ForwardingNode.first;
6589 SmallVectorImpl<int> &Indexes = ForwardingNode.second;
6590 // Check if it helps to fold PHI.
6591 if (Indexes.size() < 2 && !llvm::is_contained(Phi->incoming_values(), SI->getCondition()))
6592 continue;
6593
6594 for (int Index : Indexes)
6595 Phi->setIncomingValue(Index, SI->getCondition());
6596 Changed = true;
6597 }
6598
6599 return Changed;
6600}
6601
6602/// Return true if the backend will be able to handle
6603/// initializing an array of constants like C.
6605 if (C->isThreadDependent())
6606 return false;
6607 if (C->isDLLImportDependent())
6608 return false;
6609
6612 return false;
6613
6614 // Globals cannot contain scalable types.
6615 if (C->getType()->isScalableTy())
6616 return false;
6617
6619 // Pointer casts and in-bounds GEPs will not prohibit the backend from
6620 // materializing the array of constants.
6621 Constant *StrippedC = cast<Constant>(CE->stripInBoundsConstantOffsets());
6622 if (StrippedC == C || !validLookupTableConstant(StrippedC, TTI))
6623 return false;
6624 }
6625
6626 if (!TTI.shouldBuildLookupTablesForConstant(C))
6627 return false;
6628
6629 return true;
6630}
6631
6632/// If V is a Constant, return it. Otherwise, try to look up
6633/// its constant value in ConstantPool, returning 0 if it's not there.
6634static Constant *
6637 if (Constant *C = dyn_cast<Constant>(V))
6638 return C;
6639 return ConstantPool.lookup(V);
6640}
6641
6642/// Try to fold instruction I into a constant. This works for
6643/// simple instructions such as binary operations where both operands are
6644/// constant or can be replaced by constants from the ConstantPool. Returns the
6645/// resulting constant on success, 0 otherwise.
6646static Constant *
6650 Constant *A = lookupConstant(Select->getCondition(), ConstantPool);
6651 if (!A)
6652 return nullptr;
6653 if (A->isAllOnesValue())
6654 return lookupConstant(Select->getTrueValue(), ConstantPool);
6655 if (A->isNullValue())
6656 return lookupConstant(Select->getFalseValue(), ConstantPool);
6657 return nullptr;
6658 }
6659
6661 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
6662 if (Constant *A = lookupConstant(I->getOperand(N), ConstantPool))
6663 COps.push_back(A);
6664 else
6665 return nullptr;
6666 }
6667
6668 return ConstantFoldInstOperands(I, COps, DL);
6669}
6670
6671/// Try to determine the resulting constant values in phi nodes
6672/// at the common destination basic block, *CommonDest, for one of the case
6673/// destinations CaseDest corresponding to value CaseVal (nullptr for the
6674/// default case), of a switch instruction SI.
6675static bool
6677 BasicBlock **CommonDest,
6678 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
6679 const DataLayout &DL) {
6680 // The block from which we enter the common destination.
6681 BasicBlock *Pred = SI->getParent();
6682
6683 // If CaseDest is empty except for some side-effect free instructions through
6684 // which we can constant-propagate the CaseVal, continue to its successor.
6686 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
6687 for (Instruction &I : *CaseDest) {
6688 if (I.isTerminator()) {
6689 // If the terminator is a simple branch, continue to the next block.
6690 if (I.getNumSuccessors() != 1 || I.isSpecialTerminator())
6691 return false;
6692 Pred = CaseDest;
6693 CaseDest = I.getSuccessor(0);
6694 } else if (Constant *C = constantFold(&I, DL, ConstantPool)) {
6695 // Instruction is side-effect free and constant.
6696
6697 // If the instruction has uses outside this block or a phi node slot for
6698 // the block, it is not safe to bypass the instruction since it would then
6699 // no longer dominate all its uses.
6700 for (auto &Use : I.uses()) {
6701 User *User = Use.getUser();
6703 if (I->getParent() == CaseDest)
6704 continue;
6705 if (PHINode *Phi = dyn_cast<PHINode>(User))
6706 if (Phi->getIncomingBlock(Use) == CaseDest)
6707 continue;
6708 return false;
6709 }
6710
6711 ConstantPool.insert(std::make_pair(&I, C));
6712 } else {
6713 break;
6714 }
6715 }
6716
6717 // If we did not have a CommonDest before, use the current one.
6718 if (!*CommonDest)
6719 *CommonDest = CaseDest;
6720 // If the destination isn't the common one, abort.
6721 if (CaseDest != *CommonDest)
6722 return false;
6723
6724 // Get the values for this case from phi nodes in the destination block.
6725 for (PHINode &PHI : (*CommonDest)->phis()) {
6726 int Idx = PHI.getBasicBlockIndex(Pred);
6727 if (Idx == -1)
6728 continue;
6729
6730 Constant *ConstVal =
6731 lookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
6732 if (!ConstVal)
6733 return false;
6734
6735 Res.push_back(std::make_pair(&PHI, ConstVal));
6736 }
6737
6738 return Res.size() > 0;
6739}
6740
6741// Helper function used to add CaseVal to the list of cases that generate
6742// Result. Returns the updated number of cases that generate this result.
6743static size_t mapCaseToResult(ConstantInt *CaseVal,
6744 SwitchCaseResultVectorTy &UniqueResults,
6745 Constant *Result) {
6746 for (auto &I : UniqueResults) {
6747 if (I.first == Result) {
6748 I.second.push_back(CaseVal);
6749 return I.second.size();
6750 }
6751 }
6752 UniqueResults.push_back(
6753 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
6754 return 1;
6755}
6756
6757// Helper function that initializes a map containing
6758// results for the PHI node of the common destination block for a switch
6759// instruction. Returns false if multiple PHI nodes have been found or if
6760// there is not a common destination block for the switch.
6762 BasicBlock *&CommonDest,
6763 SwitchCaseResultVectorTy &UniqueResults,
6764 Constant *&DefaultResult,
6765 const DataLayout &DL,
6766 uintptr_t MaxUniqueResults) {
6767 for (const auto &I : SI->cases()) {
6768 ConstantInt *CaseVal = I.getCaseValue();
6769
6770 // Resulting value at phi nodes for this case value.
6771 SwitchCaseResultsTy Results;
6772 if (!getCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
6773 DL))
6774 return false;
6775
6776 // Only one value per case is permitted.
6777 if (Results.size() > 1)
6778 return false;
6779
6780 // Add the case->result mapping to UniqueResults.
6781 const size_t NumCasesForResult =
6782 mapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
6783
6784 // Early out if there are too many cases for this result.
6785 if (NumCasesForResult > MaxSwitchCasesPerResult)
6786 return false;
6787
6788 // Early out if there are too many unique results.
6789 if (UniqueResults.size() > MaxUniqueResults)
6790 return false;
6791
6792 // Check the PHI consistency.
6793 if (!PHI)
6794 PHI = Results[0].first;
6795 else if (PHI != Results[0].first)
6796 return false;
6797 }
6798 // Find the default result value.
6800 getCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
6801 DL);
6802 // If the default value is not found abort unless the default destination
6803 // is unreachable.
6804 DefaultResult =
6805 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
6806
6807 return DefaultResult || SI->defaultDestUnreachable();
6808}
6809
6810// Helper function that checks if it is possible to transform a switch with only
6811// two cases (or two cases + default) that produces a result into a select.
6812// TODO: Handle switches with more than 2 cases that map to the same result.
6813// The branch weights correspond to the provided Condition (i.e. if Condition is
6814// modified from the original SwitchInst, the caller must adjust the weights)
6815static Value *foldSwitchToSelect(const SwitchCaseResultVectorTy &ResultVector,
6816 Constant *DefaultResult, Value *Condition,
6817 IRBuilder<> &Builder, const DataLayout &DL,
6818 ArrayRef<uint32_t> BranchWeights) {
6819 // If we are selecting between only two cases transform into a simple
6820 // select or a two-way select if default is possible.
6821 // Example:
6822 // switch (a) { %0 = icmp eq i32 %a, 10
6823 // case 10: return 42; %1 = select i1 %0, i32 42, i32 4
6824 // case 20: return 2; ----> %2 = icmp eq i32 %a, 20
6825 // default: return 4; %3 = select i1 %2, i32 2, i32 %1
6826 // }
6827
6828 const bool HasBranchWeights = !BranchWeights.empty();
6829
6830 if (ResultVector.size() == 2 && ResultVector[0].second.size() == 1 &&
6831 ResultVector[1].second.size() == 1) {
6832 ConstantInt *FirstCase = ResultVector[0].second[0];
6833 ConstantInt *SecondCase = ResultVector[1].second[0];
6834 Value *SelectValue = ResultVector[1].first;
6835 if (DefaultResult) {
6836 Value *ValueCompare =
6837 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
6838 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
6839 DefaultResult, "switch.select");
6840 if (auto *SI = dyn_cast<SelectInst>(SelectValue);
6841 SI && HasBranchWeights) {
6842 // We start with 3 probabilities, where the numerator is the
6843 // corresponding BranchWeights[i], and the denominator is the sum over
6844 // BranchWeights. We want the probability and negative probability of
6845 // Condition == SecondCase.
6846 assert(BranchWeights.size() == 3);
6848 *SI, {BranchWeights[2], BranchWeights[0] + BranchWeights[1]},
6849 /*IsExpected=*/false, /*ElideAllZero=*/true);
6850 }
6851 }
6852 Value *ValueCompare =
6853 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
6854 Value *Ret = Builder.CreateSelect(ValueCompare, ResultVector[0].first,
6855 SelectValue, "switch.select");
6856 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6857 // We may have had a DefaultResult. Base the position of the first and
6858 // second's branch weights accordingly. Also the proability that Condition
6859 // != FirstCase needs to take that into account.
6860 assert(BranchWeights.size() >= 2);
6861 size_t FirstCasePos = (Condition != nullptr);
6862 size_t SecondCasePos = FirstCasePos + 1;
6863 uint32_t DefaultCase = (Condition != nullptr) ? BranchWeights[0] : 0;
6865 {BranchWeights[FirstCasePos],
6866 DefaultCase + BranchWeights[SecondCasePos]},
6867 /*IsExpected=*/false, /*ElideAllZero=*/true);
6868 }
6869 return Ret;
6870 }
6871
6872 // Handle the degenerate case where two cases have the same result value.
6873 if (ResultVector.size() == 1 && DefaultResult) {
6874 ArrayRef<ConstantInt *> CaseValues = ResultVector[0].second;
6875 unsigned CaseCount = CaseValues.size();
6876 // n bits group cases map to the same result:
6877 // case 0,4 -> Cond & 0b1..1011 == 0 ? result : default
6878 // case 0,2,4,6 -> Cond & 0b1..1001 == 0 ? result : default
6879 // case 0,2,8,10 -> Cond & 0b1..0101 == 0 ? result : default
6880 if (isPowerOf2_32(CaseCount)) {
6881 ConstantInt *MinCaseVal = CaseValues[0];
6882 // If there are bits that are set exclusively by CaseValues, we
6883 // can transform the switch into a select if the conjunction of
6884 // all the values uniquely identify CaseValues.
6885 APInt AndMask = APInt::getAllOnes(MinCaseVal->getBitWidth());
6886
6887 // Find the minimum value and compute the and of all the case values.
6888 for (auto *Case : CaseValues) {
6889 if (Case->getValue().slt(MinCaseVal->getValue()))
6890 MinCaseVal = Case;
6891 AndMask &= Case->getValue();
6892 }
6893 KnownBits Known = computeKnownBits(Condition, DL);
6894
6895 if (!AndMask.isZero() && Known.getMaxValue().uge(AndMask)) {
6896 // Compute the number of bits that are free to vary.
6897 unsigned FreeBits = Known.countMaxActiveBits() - AndMask.popcount();
6898
6899 // Check if the number of values covered by the mask is equal
6900 // to the number of cases.
6901 if (FreeBits == Log2_32(CaseCount)) {
6902 Value *And = Builder.CreateAnd(Condition, AndMask);
6903 Value *Cmp = Builder.CreateICmpEQ(
6904 And, Constant::getIntegerValue(And->getType(), AndMask));
6905 Value *Ret =
6906 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6907 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6908 // We know there's a Default case. We base the resulting branch
6909 // weights off its probability.
6910 assert(BranchWeights.size() >= 2);
6912 *SI,
6913 {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6914 /*IsExpected=*/false, /*ElideAllZero=*/true);
6915 }
6916 return Ret;
6917 }
6918 }
6919
6920 // Mark the bits case number touched.
6921 APInt BitMask = APInt::getZero(MinCaseVal->getBitWidth());
6922 for (auto *Case : CaseValues)
6923 BitMask |= (Case->getValue() - MinCaseVal->getValue());
6924
6925 // Check if cases with the same result can cover all number
6926 // in touched bits.
6927 if (BitMask.popcount() == Log2_32(CaseCount)) {
6928 if (!MinCaseVal->isNullValue())
6929 Condition = Builder.CreateSub(Condition, MinCaseVal);
6930 Value *And = Builder.CreateAnd(Condition, ~BitMask, "switch.and");
6931 Value *Cmp = Builder.CreateICmpEQ(
6932 And, Constant::getNullValue(And->getType()), "switch.selectcmp");
6933 Value *Ret =
6934 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6935 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6936 assert(BranchWeights.size() >= 2);
6938 *SI,
6939 {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6940 /*IsExpected=*/false, /*ElideAllZero=*/true);
6941 }
6942 return Ret;
6943 }
6944 }
6945
6946 // Handle the degenerate case where two cases have the same value.
6947 if (CaseValues.size() == 2) {
6948 Value *Cmp1 = Builder.CreateICmpEQ(Condition, CaseValues[0],
6949 "switch.selectcmp.case1");
6950 Value *Cmp2 = Builder.CreateICmpEQ(Condition, CaseValues[1],
6951 "switch.selectcmp.case2");
6952 Value *Cmp = Builder.CreateOr(Cmp1, Cmp2, "switch.selectcmp");
6953 Value *Ret =
6954 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6955 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6956 assert(BranchWeights.size() >= 2);
6958 *SI, {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6959 /*IsExpected=*/false, /*ElideAllZero=*/true);
6960 }
6961 return Ret;
6962 }
6963 }
6964
6965 return nullptr;
6966}
6967
6968// Helper function to cleanup a switch instruction that has been converted into
6969// a select, fixing up PHI nodes and basic blocks.
6971 Value *SelectValue,
6972 IRBuilder<> &Builder,
6973 DomTreeUpdater *DTU) {
6974 std::vector<DominatorTree::UpdateType> Updates;
6975
6976 BasicBlock *SelectBB = SI->getParent();
6977 BasicBlock *DestBB = PHI->getParent();
6978
6979 if (DTU && !is_contained(predecessors(DestBB), SelectBB))
6980 Updates.push_back({DominatorTree::Insert, SelectBB, DestBB});
6981 Builder.CreateBr(DestBB);
6982
6983 // Remove the switch.
6984
6985 PHI->removeIncomingValueIf(
6986 [&](unsigned Idx) { return PHI->getIncomingBlock(Idx) == SelectBB; });
6987 PHI->addIncoming(SelectValue, SelectBB);
6988
6989 SmallPtrSet<BasicBlock *, 4> RemovedSuccessors;
6990 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
6991 BasicBlock *Succ = SI->getSuccessor(i);
6992
6993 if (Succ == DestBB)
6994 continue;
6995 Succ->removePredecessor(SelectBB);
6996 if (DTU && RemovedSuccessors.insert(Succ).second)
6997 Updates.push_back({DominatorTree::Delete, SelectBB, Succ});
6998 }
6999 SI->eraseFromParent();
7000 if (DTU)
7001 DTU->applyUpdates(Updates);
7002}
7003
7004/// If a switch is only used to initialize one or more phi nodes in a common
7005/// successor block with only two different constant values, try to replace the
7006/// switch with a select. Returns true if the fold was made.
7008 DomTreeUpdater *DTU, const DataLayout &DL) {
7009 Value *const Cond = SI->getCondition();
7010 PHINode *PHI = nullptr;
7011 BasicBlock *CommonDest = nullptr;
7012 Constant *DefaultResult;
7013 SwitchCaseResultVectorTy UniqueResults;
7014 // Collect all the cases that will deliver the same value from the switch.
7015 if (!initializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
7016 DL, /*MaxUniqueResults*/ 2))
7017 return false;
7018
7019 assert(PHI != nullptr && "PHI for value select not found");
7020 Builder.SetInsertPoint(SI);
7021 SmallVector<uint32_t, 4> BranchWeights;
7022 [[maybe_unused]] auto HasWeights =
7024 assert(!HasWeights == (BranchWeights.empty()));
7025 assert(BranchWeights.empty() ||
7026 (BranchWeights.size() >=
7027 UniqueResults.size() + (DefaultResult != nullptr)));
7028
7029 Value *SelectValue = foldSwitchToSelect(UniqueResults, DefaultResult, Cond,
7030 Builder, DL, BranchWeights);
7031 if (!SelectValue)
7032 return false;
7033
7034 removeSwitchAfterSelectFold(SI, PHI, SelectValue, Builder, DTU);
7035 return true;
7036}
7037
7038namespace {
7039
7040/// This class finds alternatives for switches to ultimately
7041/// replace the switch.
7042class SwitchReplacement {
7043public:
7044 /// Create a helper for optimizations to use as a switch replacement.
7045 /// Find a better representation for the content of Values,
7046 /// using DefaultValue to fill any holes in the table.
7047 /// If no representation is possible, isValid() returns false.
7048 SwitchReplacement(
7049 Module &M, uint64_t TableSize, ConstantInt *Offset,
7050 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
7051 Constant *DefaultValue, const DataLayout &DL,
7052 const TargetTransformInfo &TTI, const StringRef &FuncName);
7053
7054 /// Build instructions with Builder to retrieve values using Index
7055 /// and replace the switch.
7056 Value *replaceSwitch(Value *Index, IRBuilder<> &Builder, const DataLayout &DL,
7057 Function *Func);
7058
7059 /// Return true if a table with TableSize elements of
7060 /// type ElementType would fit in a target-legal register.
7061 static bool wouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
7062 Type *ElementType);
7063
7064 /// Return the default value of the switch.
7065 Constant *getDefaultValue();
7066
7067 /// Return true if the replacement is a lookup table.
7068 bool isLookupTable();
7069
7070 /// Return true if the replacement is a bit map.
7071 bool isBitMap();
7072
7073 /// Return true if a suitable switch replacement was found.
7074 bool isValid() const { return Kind != InvalidKind; }
7075
7076private:
7077 // Depending on the switch, there are different alternatives.
7078 enum {
7079 // No suitable replacement was found.
7080 InvalidKind,
7081
7082 // For switches where each case contains the same value, we just have to
7083 // store that single value and return it for each lookup.
7084 SingleValueKind,
7085
7086 // For switches where there is a linear relationship between table index
7087 // and values. We calculate the result with a simple multiplication
7088 // and addition instead of a table lookup.
7089 LinearMapKind,
7090
7091 // For small tables with integer elements, we can pack them into a bitmap
7092 // that fits into a target-legal register. Values are retrieved by
7093 // shift and mask operations.
7094 BitMapKind,
7095
7096 // The table is stored as an array of values. Values are retrieved by load
7097 // instructions from the table.
7098 LookupTableKind
7099 } Kind;
7100
7101 // The default value of the switch.
7102 Constant *DefaultValue;
7103
7104 // The type of the output values.
7105 Type *ValueType;
7106
7107 // For SingleValueKind, this is the single value.
7108 Constant *SingleValue = nullptr;
7109
7110 // For BitMapKind, this is the bitmap.
7111 ConstantInt *BitMap = nullptr;
7112 IntegerType *BitMapElementTy = nullptr;
7113
7114 // For LinearMapKind, these are the constants used to derive the value.
7115 ConstantInt *LinearOffset = nullptr;
7116 ConstantInt *LinearMultiplier = nullptr;
7117 bool LinearMapValWrapped = false;
7118
7119 // For LookupTableKind, this is the table.
7120 Constant *Initializer = nullptr;
7121};
7122
7123} // end anonymous namespace
7124
7125SwitchReplacement::SwitchReplacement(
7126 Module &M, uint64_t TableSize, ConstantInt *Offset,
7127 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
7128 Constant *DefaultValue, const DataLayout &DL,
7129 const TargetTransformInfo &TTI, const StringRef &FuncName)
7130 : DefaultValue(DefaultValue) {
7131 assert(Values.size() && "Can't build lookup table without values!");
7132 assert(TableSize >= Values.size() && "Can't fit values in table!");
7133
7134 // If all values in the table are equal, this is that value.
7135 SingleValue = Values.begin()->second;
7136
7137 ValueType = Values.begin()->second->getType();
7138
7139 // Build up the table contents.
7140 SmallVector<Constant *, 64> TableContents(TableSize);
7141 for (const auto &[CaseVal, CaseRes] : Values) {
7142 assert(CaseRes->getType() == ValueType);
7143
7144 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
7145 TableContents[Idx] = CaseRes;
7146
7147 if (SingleValue && !isa<PoisonValue>(CaseRes) && CaseRes != SingleValue)
7148 SingleValue = isa<PoisonValue>(SingleValue) ? CaseRes : nullptr;
7149 }
7150
7151 // Fill in any holes in the table with the default result.
7152 if (Values.size() < TableSize) {
7153 assert(DefaultValue &&
7154 "Need a default value to fill the lookup table holes.");
7155 assert(DefaultValue->getType() == ValueType);
7156 for (uint64_t I = 0; I < TableSize; ++I) {
7157 if (!TableContents[I])
7158 TableContents[I] = DefaultValue;
7159 }
7160
7161 // If the default value is poison, all the holes are poison.
7162 bool DefaultValueIsPoison = isa<PoisonValue>(DefaultValue);
7163
7164 if (DefaultValue != SingleValue && !DefaultValueIsPoison)
7165 SingleValue = nullptr;
7166 }
7167
7168 // If each element in the table contains the same value, we only need to store
7169 // that single value.
7170 if (SingleValue) {
7171 Kind = SingleValueKind;
7172 return;
7173 }
7174
7175 // Check if we can derive the value with a linear transformation from the
7176 // table index.
7178 bool LinearMappingPossible = true;
7179 APInt PrevVal;
7180 APInt DistToPrev;
7181 // When linear map is monotonic and signed overflow doesn't happen on
7182 // maximum index, we can attach nsw on Add and Mul.
7183 bool NonMonotonic = false;
7184 assert(TableSize >= 2 && "Should be a SingleValue table.");
7185 // Check if there is the same distance between two consecutive values.
7186 for (uint64_t I = 0; I < TableSize; ++I) {
7187 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
7188
7189 if (!ConstVal && isa<PoisonValue>(TableContents[I])) {
7190 // This is an poison, so it's (probably) a lookup table hole.
7191 // To prevent any regressions from before we switched to using poison as
7192 // the default value, holes will fall back to using the first value.
7193 // This can be removed once we add proper handling for poisons in lookup
7194 // tables.
7195 ConstVal = dyn_cast<ConstantInt>(Values[0].second);
7196 }
7197
7198 if (!ConstVal) {
7199 // We only handle literal integers when checking for a linear mapping.
7200 LinearMappingPossible = false;
7201 break;
7202 }
7203 const APInt &Val = ConstVal->getValue();
7204 if (I != 0) {
7205 APInt Dist = Val - PrevVal;
7206 if (I == 1) {
7207 DistToPrev = Dist;
7208 } else if (Dist != DistToPrev) {
7209 LinearMappingPossible = false;
7210 break;
7211 }
7212 NonMonotonic |=
7213 Dist.isStrictlyPositive() ? Val.sle(PrevVal) : Val.sgt(PrevVal);
7214 }
7215 PrevVal = Val;
7216 }
7217 if (LinearMappingPossible) {
7218 LinearOffset = cast<ConstantInt>(TableContents[0]);
7219 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
7220 APInt M = LinearMultiplier->getValue();
7221 bool MayWrap = true;
7222 if (isIntN(M.getBitWidth(), TableSize - 1))
7223 (void)M.smul_ov(APInt(M.getBitWidth(), TableSize - 1), MayWrap);
7224 LinearMapValWrapped = NonMonotonic || MayWrap;
7225 Kind = LinearMapKind;
7226 return;
7227 }
7228 }
7229
7230 // If the values are integer constants and the table fits in a register,
7231 // build a bitmap.
7232 if (wouldFitInRegister(DL, TableSize, ValueType) &&
7233 all_of(TableContents, IsaPred<ConstantInt, UndefValue>)) {
7235 APInt TableInt(TableSize * IT->getBitWidth(), 0);
7236 for (uint64_t I = TableSize; I > 0; --I) {
7237 TableInt <<= IT->getBitWidth();
7238 // Insert values into the bitmap. Undef values are set to zero.
7239 if (!isa<UndefValue>(TableContents[I - 1])) {
7240 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
7241 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
7242 }
7243 }
7244 BitMap = ConstantInt::get(M.getContext(), TableInt);
7245 BitMapElementTy = IT;
7246 Kind = BitMapKind;
7247 return;
7248 }
7249
7250 // The remaining representation needs a global initializer.
7251 if (!all_of(TableContents,
7252 [&](Constant *C) { return validLookupTableConstant(C, TTI); })) {
7253 Kind = InvalidKind;
7254 return;
7255 }
7256
7257 if (auto *IT = dyn_cast<IntegerType>(ValueType)) {
7258 ConstantRange Range(IT->getBitWidth(), false);
7259 for (Constant *Value : TableContents)
7260 if (!isa<UndefValue>(Value))
7261 Range = Range.unionWith(cast<ConstantInt>(Value)->getValue());
7262 // TODO: handle sign extension as well?
7263 unsigned NeededBitWidth =
7264 std::max(TTI.getMinimumLookupTableEntryBitWidth(),
7265 unsigned(PowerOf2Ceil(Range.getActiveBits())));
7266 if (NeededBitWidth < IT->getBitWidth()) {
7267 IntegerType *DstTy = IntegerType::get(IT->getContext(), NeededBitWidth);
7268 for (Constant *&Value : TableContents)
7269 Value = ConstantFoldCastInstruction(Instruction::Trunc, Value, DstTy);
7270 }
7271 }
7272
7273 // Store the table in an array.
7274 auto *TableTy = ArrayType::get(TableContents[0]->getType(), TableSize);
7275 Initializer = ConstantArray::get(TableTy, TableContents);
7276
7277 Kind = LookupTableKind;
7278}
7279
7280Value *SwitchReplacement::replaceSwitch(Value *Index, IRBuilder<> &Builder,
7281 const DataLayout &DL, Function *Func) {
7282 switch (Kind) {
7283 case InvalidKind:
7284 llvm_unreachable("Cannot use an invalid switch replacement");
7285 case SingleValueKind:
7286 return SingleValue;
7287 case LinearMapKind: {
7288 ++NumLinearMaps;
7289 // Derive the result value from the input value.
7290 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
7291 false, "switch.idx.cast");
7292 if (!LinearMultiplier->isOne())
7293 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult",
7294 /*HasNUW = */ false,
7295 /*HasNSW = */ !LinearMapValWrapped);
7296
7297 if (!LinearOffset->isZero())
7298 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset",
7299 /*HasNUW = */ false,
7300 /*HasNSW = */ !LinearMapValWrapped);
7301 return Result;
7302 }
7303 case BitMapKind: {
7304 ++NumBitMaps;
7305 // Type of the bitmap (e.g. i59).
7306 IntegerType *MapTy = BitMap->getIntegerType();
7307
7308 // Cast Index to the same type as the bitmap.
7309 // Note: The Index is <= the number of elements in the table, so
7310 // truncating it to the width of the bitmask is safe.
7311 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
7312
7313 // Multiply the shift amount by the element width. NUW/NSW can always be
7314 // set, because wouldFitInRegister guarantees Index * ShiftAmt is in
7315 // BitMap's bit width.
7316 ShiftAmt = Builder.CreateMul(
7317 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
7318 "switch.shiftamt",/*HasNUW =*/true,/*HasNSW =*/true);
7319
7320 // Shift down.
7321 Value *DownShifted =
7322 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
7323 // Mask off.
7324 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
7325 }
7326 case LookupTableKind: {
7327 ++NumLookupTables;
7328 auto *Table =
7329 new GlobalVariable(*Func->getParent(), Initializer->getType(),
7330 /*isConstant=*/true, GlobalVariable::PrivateLinkage,
7331 Initializer, "switch.table." + Func->getName());
7332 Table->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
7333 // Set the alignment to that of an array items. We will be only loading one
7334 // value out of it.
7335 Table->setAlignment(DL.getPrefTypeAlign(ValueType));
7336 Type *IndexTy = DL.getIndexType(Table->getType());
7337 auto *ArrayTy = cast<ArrayType>(Table->getValueType());
7338
7339 if (Index->getType() != IndexTy) {
7340 unsigned OldBitWidth = Index->getType()->getIntegerBitWidth();
7341 Index = Builder.CreateZExtOrTrunc(Index, IndexTy);
7342 if (auto *Zext = dyn_cast<ZExtInst>(Index))
7343 Zext->setNonNeg(
7344 isUIntN(OldBitWidth - 1, ArrayTy->getNumElements() - 1));
7345 }
7346
7347 Value *GEPIndices[] = {ConstantInt::get(IndexTy, 0), Index};
7348 Value *GEP =
7349 Builder.CreateInBoundsGEP(ArrayTy, Table, GEPIndices, "switch.gep");
7350 Value *Load =
7351 Builder.CreateLoad(ArrayTy->getElementType(), GEP, "switch.load");
7352 if (Load->getType() == ValueType)
7353 return Load;
7354 return Builder.CreateZExt(Load, ValueType, "switch.ext");
7355 }
7356 }
7357 llvm_unreachable("Unknown helper kind!");
7358}
7359
7360bool SwitchReplacement::wouldFitInRegister(const DataLayout &DL,
7361 uint64_t TableSize,
7362 Type *ElementType) {
7363 auto *IT = dyn_cast<IntegerType>(ElementType);
7364 if (!IT)
7365 return false;
7366 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
7367 // are <= 15, we could try to narrow the type.
7368
7369 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
7370 if (TableSize >= UINT_MAX / IT->getBitWidth())
7371 return false;
7372 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
7373}
7374
7376 const DataLayout &DL) {
7377 // Allow any legal type.
7378 if (TTI.isTypeLegal(Ty))
7379 return true;
7380
7381 auto *IT = dyn_cast<IntegerType>(Ty);
7382 if (!IT)
7383 return false;
7384
7385 // Also allow power of 2 integer types that have at least 8 bits and fit in
7386 // a register. These types are common in frontend languages and targets
7387 // usually support loads of these types.
7388 // TODO: We could relax this to any integer that fits in a register and rely
7389 // on ABI alignment and padding in the table to allow the load to be widened.
7390 // Or we could widen the constants and truncate the load.
7391 unsigned BitWidth = IT->getBitWidth();
7392 return BitWidth >= 8 && isPowerOf2_32(BitWidth) &&
7393 DL.fitsInLegalInteger(IT->getBitWidth());
7394}
7395
7396Constant *SwitchReplacement::getDefaultValue() { return DefaultValue; }
7397
7398bool SwitchReplacement::isLookupTable() { return Kind == LookupTableKind; }
7399
7400bool SwitchReplacement::isBitMap() { return Kind == BitMapKind; }
7401
7402static bool isSwitchDense(uint64_t NumCases, uint64_t CaseRange, bool OptSize) {
7403 // 40% is the default density for building a jump table in optsize/minsize
7404 // mode, 10% is the default density for jump tables. See also
7405 // TargetLoweringBase::isSuitableForJumpTable(), which this function was based
7406 // on.
7407 const uint64_t MinDensity = OptSize ? 40 : 10;
7408
7409 if (CaseRange >= UINT64_MAX / 100)
7410 return false; // Avoid multiplication overflows below.
7411
7412 return NumCases * 100 >= CaseRange * MinDensity;
7413}
7414
7415static bool isSwitchDense(ArrayRef<int64_t> Values, bool OptSize) {
7416 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
7417 uint64_t Range = Diff + 1;
7418 if (Range < Diff)
7419 return false; // Overflow.
7420
7421 return isSwitchDense(Values.size(), Range, OptSize);
7422}
7423
7424static std::optional<unsigned>
7426 bool OptSize) {
7427 assert(Values.size() > 1 && "expected multiple switch cases");
7428 if (!llvm::all_of(Values, [Base](int64_t V) { return V >= Base; }))
7429 return std::nullopt;
7430
7431 // First, transform the values by subtracting Base.
7432 SmallVector<int64_t, 4> ReducedValues(Values);
7433 uint64_t ReducedValuesOr = 0;
7434 for (auto &V : ReducedValues) {
7435 uint64_t Reduced = (uint64_t)V - (uint64_t)Base;
7436 ReducedValuesOr |= Reduced;
7437 V = (int64_t)Reduced;
7438 }
7439
7440 // Conceptually, the reduced values are non-negative distances from Base.
7441 // Since the rest of the transform is bitwise only, treat them as unsigned
7442 // bit patterns from here.
7443
7444 // countr_zero(0) returns 64. As Values is guaranteed to have more than
7445 // one element and LLVM disallows duplicate cases, ReducedValuesOr will
7446 // have at least one bit set, so Shift will be less than 64.
7447 unsigned Shift = llvm::countr_zero(ReducedValuesOr);
7448 assert(Shift < 64);
7449 if (Shift > 0)
7450 for (auto &V : ReducedValues)
7451 V = (int64_t)((uint64_t)V >> Shift);
7452
7453 if (!isSwitchDense(ReducedValues, OptSize))
7454 return std::nullopt;
7455
7456 return Shift;
7457}
7458
7459/// Determine whether a lookup table should be built for this switch, based on
7460/// the number of cases, size of the table, and the types of the results.
7461// TODO: We could support larger than legal types by limiting based on the
7462// number of loads required and/or table size. If the constants are small we
7463// could use smaller table entries and extend after the load.
7465 const TargetTransformInfo &TTI,
7466 const DataLayout &DL,
7467 const SmallVector<Type *> &ResultTypes) {
7468 if (SI->getNumCases() > TableSize)
7469 return false; // TableSize overflowed.
7470
7471 bool AllTablesFitInRegister = true;
7472 bool HasIllegalType = false;
7473 for (const auto &Ty : ResultTypes) {
7474 // Saturate this flag to true.
7475 HasIllegalType = HasIllegalType || !isTypeLegalForLookupTable(Ty, TTI, DL);
7476
7477 // Saturate this flag to false.
7478 AllTablesFitInRegister =
7479 AllTablesFitInRegister &&
7480 SwitchReplacement::wouldFitInRegister(DL, TableSize, Ty);
7481
7482 // If both flags saturate, we're done. NOTE: This *only* works with
7483 // saturating flags, and all flags have to saturate first due to the
7484 // non-deterministic behavior of iterating over a dense map.
7485 if (HasIllegalType && !AllTablesFitInRegister)
7486 break;
7487 }
7488
7489 // If each table would fit in a register, we should build it anyway.
7490 if (AllTablesFitInRegister)
7491 return true;
7492
7493 // Don't build a table that doesn't fit in-register if it has illegal types.
7494 if (HasIllegalType)
7495 return false;
7496
7497 return isSwitchDense(SI->getNumCases(), TableSize,
7498 SI->getFunction()->hasOptSize());
7499}
7500
7502 ConstantInt &MinCaseVal, const ConstantInt &MaxCaseVal,
7503 bool HasDefaultResults, const SmallVector<Type *> &ResultTypes,
7504 const DataLayout &DL, const TargetTransformInfo &TTI) {
7505 if (MinCaseVal.isNullValue())
7506 return true;
7507 if (MinCaseVal.isNegative() ||
7508 MaxCaseVal.getLimitedValue() == std::numeric_limits<uint64_t>::max() ||
7509 !HasDefaultResults)
7510 return false;
7511 return all_of(ResultTypes, [&](const auto &ResultType) {
7512 return SwitchReplacement::wouldFitInRegister(
7513 DL, MaxCaseVal.getLimitedValue() + 1 /* TableSize */, ResultType);
7514 });
7515}
7516
7517/// Try to reuse the switch table index compare. Following pattern:
7518/// \code
7519/// if (idx < tablesize)
7520/// r = table[idx]; // table does not contain default_value
7521/// else
7522/// r = default_value;
7523/// if (r != default_value)
7524/// ...
7525/// \endcode
7526/// Is optimized to:
7527/// \code
7528/// cond = idx < tablesize;
7529/// if (cond)
7530/// r = table[idx];
7531/// else
7532/// r = default_value;
7533/// if (cond)
7534/// ...
7535/// \endcode
7536/// Jump threading will then eliminate the second if(cond).
7538 User *PhiUser, BasicBlock *PhiBlock, CondBrInst *RangeCheckBranch,
7539 Constant *DefaultValue,
7540 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
7542 if (!CmpInst)
7543 return;
7544
7545 // We require that the compare is in the same block as the phi so that jump
7546 // threading can do its work afterwards.
7547 if (CmpInst->getParent() != PhiBlock)
7548 return;
7549
7551 if (!CmpOp1)
7552 return;
7553
7554 Value *RangeCmp = RangeCheckBranch->getCondition();
7555 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
7556 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
7557
7558 // Check if the compare with the default value is constant true or false.
7559 const DataLayout &DL = PhiBlock->getDataLayout();
7561 CmpInst->getPredicate(), DefaultValue, CmpOp1, DL);
7562 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
7563 return;
7564
7565 // Check if the compare with the case values is distinct from the default
7566 // compare result.
7567 for (auto ValuePair : Values) {
7569 CmpInst->getPredicate(), ValuePair.second, CmpOp1, DL);
7570 if (!CaseConst || CaseConst == DefaultConst ||
7571 (CaseConst != TrueConst && CaseConst != FalseConst))
7572 return;
7573 }
7574
7575 // Check if the branch instruction dominates the phi node. It's a simple
7576 // dominance check, but sufficient for our needs.
7577 // Although this check is invariant in the calling loops, it's better to do it
7578 // at this late stage. Practically we do it at most once for a switch.
7579 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
7580 for (BasicBlock *Pred : predecessors(PhiBlock)) {
7581 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
7582 return;
7583 }
7584
7585 if (DefaultConst == FalseConst) {
7586 // The compare yields the same result. We can replace it.
7587 CmpInst->replaceAllUsesWith(RangeCmp);
7588 ++NumTableCmpReuses;
7589 } else {
7590 // The compare yields the same result, just inverted. We can replace it.
7591 Value *InvertedTableCmp = BinaryOperator::CreateXor(
7592 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
7593 RangeCheckBranch->getIterator());
7594 CmpInst->replaceAllUsesWith(InvertedTableCmp);
7595 ++NumTableCmpReuses;
7596 }
7597}
7598
7599/// If the switch is only used to initialize one or more phi nodes in a common
7600/// successor block with different constant values, replace the switch with
7601/// lookup tables.
7603 DomTreeUpdater *DTU, const DataLayout &DL,
7604 const TargetTransformInfo &TTI,
7605 bool ConvertSwitchToLookupTable) {
7606 assert(SI->getNumCases() > 1 && "Degenerate switch?");
7607
7608 BasicBlock *BB = SI->getParent();
7609 Function *Fn = BB->getParent();
7610
7611 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
7612 // split off a dense part and build a lookup table for that.
7613
7614 // FIXME: This creates arrays of GEPs to constant strings, which means each
7615 // GEP needs a runtime relocation in PIC code. We should just build one big
7616 // string and lookup indices into that.
7617
7618 // Ignore switches with less than three cases. Lookup tables will not make
7619 // them faster, so we don't analyze them.
7620 if (SI->getNumCases() < 3)
7621 return false;
7622
7623 // Figure out the corresponding result for each case value and phi node in the
7624 // common destination, as well as the min and max case values.
7625 assert(!SI->cases().empty());
7626 SwitchInst::CaseIt CI = SI->case_begin();
7627 ConstantInt *MinCaseVal = CI->getCaseValue();
7628 ConstantInt *MaxCaseVal = CI->getCaseValue();
7629
7630 BasicBlock *CommonDest = nullptr;
7631
7632 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
7634
7636 SmallVector<Type *> ResultTypes;
7638
7639 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
7640 ConstantInt *CaseVal = CI->getCaseValue();
7641 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
7642 MinCaseVal = CaseVal;
7643 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
7644 MaxCaseVal = CaseVal;
7645
7646 // Resulting value at phi nodes for this case value.
7648 ResultsTy Results;
7649 if (!getCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
7650 Results, DL))
7651 return false;
7652
7653 // Append the result and result types from this case to the list for each
7654 // phi.
7655 for (const auto &I : Results) {
7656 PHINode *PHI = I.first;
7657 Constant *Value = I.second;
7658 auto [It, Inserted] = ResultLists.try_emplace(PHI);
7659 if (Inserted)
7660 PHIs.push_back(PHI);
7661 It->second.push_back(std::make_pair(CaseVal, Value));
7662 ResultTypes.push_back(PHI->getType());
7663 }
7664 }
7665
7666 // If the table has holes, we need a constant result for the default case
7667 // or a bitmask that fits in a register.
7668 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
7669 bool HasDefaultResults = getCaseResults(SI, nullptr, SI->getDefaultDest(),
7670 &CommonDest, DefaultResultsList, DL);
7671 for (const auto &I : DefaultResultsList) {
7672 PHINode *PHI = I.first;
7673 Constant *Result = I.second;
7674 DefaultResults[PHI] = Result;
7675 }
7676
7677 bool UseSwitchConditionAsTableIndex = shouldUseSwitchConditionAsTableIndex(
7678 *MinCaseVal, *MaxCaseVal, HasDefaultResults, ResultTypes, DL, TTI);
7679 uint64_t TableSize;
7680 ConstantInt *TableIndexOffset;
7681 if (UseSwitchConditionAsTableIndex) {
7682 TableSize = MaxCaseVal->getLimitedValue() + 1;
7683 TableIndexOffset = ConstantInt::get(MaxCaseVal->getIntegerType(), 0);
7684 } else {
7685 TableSize =
7686 (MaxCaseVal->getValue() - MinCaseVal->getValue()).getLimitedValue() + 1;
7687
7688 TableIndexOffset = MinCaseVal;
7689 }
7690
7691 // If the default destination is unreachable, or if the lookup table covers
7692 // all values of the conditional variable, branch directly to the lookup table
7693 // BB. Otherwise, check that the condition is within the case range.
7694 uint64_t NumResults = ResultLists[PHIs[0]].size();
7695 bool DefaultIsReachable = !SI->defaultDestUnreachable();
7696
7697 bool TableHasHoles = (NumResults < TableSize);
7698
7699 // If the table has holes but the default destination doesn't produce any
7700 // constant results, the lookup table entries corresponding to the holes will
7701 // contain poison.
7702 bool AllHolesArePoison = TableHasHoles && !HasDefaultResults;
7703
7704 // If the default destination doesn't produce a constant result but is still
7705 // reachable, and the lookup table has holes, we need to use a mask to
7706 // determine if the current index should load from the lookup table or jump
7707 // to the default case.
7708 // The mask is unnecessary if the table has holes but the default destination
7709 // is unreachable, as in that case the holes must also be unreachable.
7710 bool NeedMask = AllHolesArePoison && DefaultIsReachable;
7711 if (NeedMask) {
7712 // As an extra penalty for the validity test we require more cases.
7713 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
7714 return false;
7715 if (!DL.fitsInLegalInteger(TableSize))
7716 return false;
7717 }
7718
7719 if (!shouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
7720 return false;
7721
7722 // Compute the table index value.
7723 Value *TableIndex;
7724 if (UseSwitchConditionAsTableIndex) {
7725 TableIndex = SI->getCondition();
7726 if (HasDefaultResults) {
7727 // Grow the table to cover all possible index values to avoid the range
7728 // check. It will use the default result to fill in the table hole later,
7729 // so make sure it exist.
7730 ConstantRange CR = computeConstantRange(TableIndex, /*ForSigned=*/false,
7731 SimplifyQuery(DL));
7732 // Grow the table shouldn't have any size impact by checking
7733 // wouldFitInRegister.
7734 // TODO: Consider growing the table also when it doesn't fit in a register
7735 // if no optsize is specified.
7736 const uint64_t UpperBound = CR.getUpper().getLimitedValue();
7737 if (!CR.isUpperWrapped() &&
7738 all_of(ResultTypes, [&](const auto &ResultType) {
7739 return SwitchReplacement::wouldFitInRegister(DL, UpperBound,
7740 ResultType);
7741 })) {
7742 // There may be some case index larger than the UpperBound (unreachable
7743 // case), so make sure the table size does not get smaller.
7744 TableSize = std::max(UpperBound, TableSize);
7745 // The default branch is unreachable after we enlarge the lookup table.
7746 // Adjust DefaultIsReachable to reuse code path.
7747 DefaultIsReachable = false;
7748 }
7749 }
7750 }
7751
7752 // Keep track of the switch replacement for each phi
7754 for (PHINode *PHI : PHIs) {
7755 const auto &ResultList = ResultLists[PHI];
7756
7757 Type *ResultType = ResultList.begin()->second->getType();
7758 // Use any value to fill the lookup table holes.
7759 Constant *DefaultVal =
7760 AllHolesArePoison ? PoisonValue::get(ResultType) : DefaultResults[PHI];
7761 StringRef FuncName = Fn->getName();
7762 SwitchReplacement Replacement(*Fn->getParent(), TableSize, TableIndexOffset,
7763 ResultList, DefaultVal, DL, TTI, FuncName);
7764 if (!Replacement.isValid())
7765 return false;
7766 PhiToReplacementMap.insert({PHI, Replacement});
7767 }
7768
7769 bool AnyLookupTables = any_of(
7770 PhiToReplacementMap, [](auto &KV) { return KV.second.isLookupTable(); });
7771 bool AnyBitMaps = any_of(PhiToReplacementMap,
7772 [](auto &KV) { return KV.second.isBitMap(); });
7773
7774 // A few conditions prevent the generation of lookup tables:
7775 // 1. The target does not support lookup tables.
7776 // 2. The "no-jump-tables" function attribute is set.
7777 // However, these objections do not apply to other switch replacements, like
7778 // the bitmap, so we only stop here if any of these conditions are met and we
7779 // want to create a LUT. Otherwise, continue with the switch replacement.
7780 if (AnyLookupTables &&
7781 (!TTI.shouldBuildLookupTables() ||
7782 Fn->getFnAttribute("no-jump-tables").getValueAsBool()))
7783 return false;
7784
7785 // In the early optimization pipeline, disable formation of lookup tables,
7786 // bit maps and mask checks, as they may inhibit further optimization.
7787 if (!ConvertSwitchToLookupTable &&
7788 (AnyLookupTables || AnyBitMaps || NeedMask))
7789 return false;
7790
7791 Builder.SetInsertPoint(SI);
7792 // TableIndex is the switch condition - TableIndexOffset if we don't
7793 // use the condition directly
7794 if (!UseSwitchConditionAsTableIndex) {
7795 // If the default is unreachable, all case values are s>= MinCaseVal. Then
7796 // we can try to attach nsw.
7797 bool MayWrap = true;
7798 if (!DefaultIsReachable) {
7799 APInt Res =
7800 MaxCaseVal->getValue().ssub_ov(MinCaseVal->getValue(), MayWrap);
7801 (void)Res;
7802 }
7803 TableIndex = Builder.CreateSub(SI->getCondition(), TableIndexOffset,
7804 "switch.tableidx", /*HasNUW =*/false,
7805 /*HasNSW =*/!MayWrap);
7806 }
7807
7808 std::vector<DominatorTree::UpdateType> Updates;
7809
7810 // Compute the maximum table size representable by the integer type we are
7811 // switching upon.
7812 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
7813 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
7814 assert(MaxTableSize >= TableSize &&
7815 "It is impossible for a switch to have more entries than the max "
7816 "representable value of its input integer type's size.");
7817
7818 // Create the BB that does the lookups.
7819 Module &Mod = *CommonDest->getParent()->getParent();
7820 BasicBlock *LookupBB = BasicBlock::Create(
7821 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
7822
7823 CondBrInst *RangeCheckBranch = nullptr;
7824 CondBrInst *CondBranch = nullptr;
7825
7826 Builder.SetInsertPoint(SI);
7827 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
7828 const bool IsFullyCoveredLookupTable =
7829 !DefaultIsReachable || GeneratingCoveredLookupTable;
7830 if (IsFullyCoveredLookupTable) {
7831 Builder.CreateBr(LookupBB);
7832 if (DTU)
7833 Updates.push_back({DominatorTree::Insert, BB, LookupBB});
7834 // Note: We call removeProdecessor later since we need to be able to get the
7835 // PHI value for the default case in case we're using a bit mask.
7836 } else {
7837 Value *Cmp = Builder.CreateICmpULT(
7838 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
7839 RangeCheckBranch =
7840 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
7841 CondBranch = RangeCheckBranch;
7842 if (DTU)
7843 Updates.push_back({DominatorTree::Insert, BB, LookupBB});
7844 }
7845
7846 // Populate the BB that does the lookups.
7847 Builder.SetInsertPoint(LookupBB);
7848
7849 if (NeedMask) {
7850 // Before doing the lookup, we do the hole check. The LookupBB is therefore
7851 // re-purposed to do the hole check, and we create a new LookupBB.
7852 BasicBlock *MaskBB = LookupBB;
7853 MaskBB->setName("switch.hole_check");
7854 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
7855 CommonDest->getParent(), CommonDest);
7856
7857 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
7858 // unnecessary illegal types.
7859 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
7860 APInt MaskInt(TableSizePowOf2, 0);
7861 APInt One(TableSizePowOf2, 1);
7862 // Build bitmask; fill in a 1 bit for every case.
7863 const ResultListTy &ResultList = ResultLists[PHIs[0]];
7864 for (const auto &Result : ResultList) {
7865 uint64_t Idx = (Result.first->getValue() - TableIndexOffset->getValue())
7866 .getLimitedValue();
7867 MaskInt |= One << Idx;
7868 }
7869 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
7870
7871 // Get the TableIndex'th bit of the bitmask.
7872 // If this bit is 0 (meaning hole) jump to the default destination,
7873 // else continue with table lookup.
7874 IntegerType *MapTy = TableMask->getIntegerType();
7875 Value *MaskIndex =
7876 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
7877 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
7878 Value *LoBit = Builder.CreateTrunc(
7879 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
7880 if (!IsFullyCoveredLookupTable)
7882 CondBranch = Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
7883 if (DTU) {
7884 Updates.push_back({DominatorTree::Insert, MaskBB, LookupBB});
7885 Updates.push_back({DominatorTree::Insert, MaskBB, SI->getDefaultDest()});
7886 }
7887 Builder.SetInsertPoint(LookupBB);
7888 addPredecessorToBlock(SI->getDefaultDest(), MaskBB, BB);
7889 }
7890
7891 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
7892 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
7893 // do not delete PHINodes here.
7894 SI->getDefaultDest()->removePredecessor(BB,
7895 /*KeepOneInputPHIs=*/true);
7896 if (DTU)
7897 Updates.push_back({DominatorTree::Delete, BB, SI->getDefaultDest()});
7898 }
7899
7900 for (PHINode *PHI : PHIs) {
7901 const ResultListTy &ResultList = ResultLists[PHI];
7902 auto Replacement = PhiToReplacementMap.at(PHI);
7903 auto *Result = Replacement.replaceSwitch(TableIndex, Builder, DL, Fn);
7904 // Do a small peephole optimization: re-use the switch table compare if
7905 // possible.
7906 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
7907 BasicBlock *PhiBlock = PHI->getParent();
7908 // Search for compare instructions which use the phi.
7909 for (auto *User : PHI->users()) {
7910 reuseTableCompare(User, PhiBlock, RangeCheckBranch,
7911 Replacement.getDefaultValue(), ResultList);
7912 }
7913 }
7914
7915 PHI->addIncoming(Result, LookupBB);
7916 }
7917
7918 Builder.CreateBr(CommonDest);
7919 if (DTU)
7920 Updates.push_back({DominatorTree::Insert, LookupBB, CommonDest});
7921
7922 SmallVector<uint32_t> BranchWeights;
7923 const bool HasBranchWeights =
7924 CondBranch && extractBranchWeights(*SI, BranchWeights);
7925 uint64_t ToLookupWeight = 0;
7926 uint64_t ToDefaultWeight = 0;
7927
7928 // Remove the switch.
7929 SmallPtrSet<BasicBlock *, 8> RemovedSuccessors;
7930 for (unsigned I = 0, E = SI->getNumSuccessors(); I < E; ++I) {
7931 BasicBlock *Succ = SI->getSuccessor(I);
7932
7933 if (Succ == SI->getDefaultDest()) {
7934 if (HasBranchWeights)
7935 ToDefaultWeight += BranchWeights[I];
7936 continue;
7937 }
7938 Succ->removePredecessor(BB);
7939 if (DTU && RemovedSuccessors.insert(Succ).second)
7940 Updates.push_back({DominatorTree::Delete, BB, Succ});
7941 if (HasBranchWeights)
7942 ToLookupWeight += BranchWeights[I];
7943 }
7944 SI->eraseFromParent();
7945 // In the case where we do not have a fully covered lookup table (i.e., we
7946 // need a range check), and we need a mask check, we split the default case
7947 // into two different cases for which we cannot infer branch weights.
7948 // Otherwise we have a single branch for which we can infer branch weights.
7949 if ((NeedMask && !IsFullyCoveredLookupTable) &&
7952 else if (HasBranchWeights)
7953 setFittedBranchWeights(*CondBranch, {ToLookupWeight, ToDefaultWeight},
7954 /*IsExpected=*/false);
7955 if (DTU)
7956 DTU->applyUpdates(Updates);
7957
7958 if (NeedMask)
7959 ++NumLookupTablesHoles;
7960 return true;
7961}
7962
7963/// Try to transform a switch that has "holes" in it to a contiguous sequence
7964/// of cases.
7965///
7966/// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
7967/// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
7968///
7969/// This converts a sparse switch into a dense switch which allows better
7970/// lowering and could also allow transforming into a lookup table.
7972 const DataLayout &DL,
7973 const TargetTransformInfo &TTI) {
7974 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
7975 if (CondTy->getIntegerBitWidth() > 64 ||
7976 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
7977 return false;
7978 // Only bother with this optimization if there are more than 3 switch cases;
7979 // SDAG will only bother creating jump tables for 4 or more cases.
7980 if (SI->getNumCases() < 4)
7981 return false;
7982
7983 // This transform is agnostic to the signedness of the input or case values. We
7984 // can treat the case values as signed or unsigned. We can optimize more common
7985 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
7986 // as signed.
7988 for (const auto &C : SI->cases())
7989 Values.push_back(C.getCaseValue()->getValue().getSExtValue());
7991
7992 // If the switch is already dense, there's nothing useful to do here.
7993 bool OptSize = SI->getFunction()->hasOptSize();
7994 if (isSwitchDense(Values, OptSize))
7995 return false;
7996
7997 // Find a Base and corresponding Shift that results in a dense switch range.
7998 // Values[0] is the local minimum.
7999 int64_t Base = Values[0];
8000 std::optional<unsigned> Shift;
8001 // Prefer Base=0 when shifting out common low zero bits still produces a dense
8002 // range, as this avoids an unnecessary `(condition - local_min)` expression.
8003 // However, avoiding the subtract can leave a wider reduced range than using
8004 // the local minimum, so require Base=0 to satisfy the stricter optsize
8005 // density threshold before falling back to the normal density policy for
8006 // local-min.
8007 if ((Shift = getDenseSwitchRangeReductionShift(Values, /*Base=*/0,
8008 /*OptSize=*/true)))
8009 Base = 0;
8010 else if (Base != 0)
8012
8013 if (!Shift)
8014 return false;
8015
8016 // The obvious transform is to shift the switch condition right and emit a
8017 // check that the condition actually cleanly divided by GCD, i.e.
8018 // C & (1 << Shift - 1) == 0
8019 // inserting a new CFG edge to handle the case where it didn't divide cleanly.
8020 //
8021 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
8022 // shift and puts the shifted-off bits in the uppermost bits. If any of these
8023 // are nonzero then the switch condition will be very large and will hit the
8024 // default case.
8025 //
8026 // This transform can be done speculatively because it is so cheap - it
8027 // results in a single rotate operation being inserted.
8028
8029 auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
8030 Builder.SetInsertPoint(SI);
8031 Value *Sub = SI->getCondition();
8032 if (Base != 0)
8033 Sub = Builder.CreateSub(Sub, ConstantInt::getSigned(Ty, Base));
8034 Value *Rot = Builder.CreateIntrinsic(
8035 Ty, Intrinsic::fshl,
8036 {Sub, Sub, ConstantInt::get(Ty, Ty->getBitWidth() - *Shift)});
8037 SI->replaceUsesOfWith(SI->getCondition(), Rot);
8038
8039 for (auto Case : SI->cases()) {
8040 auto *Orig = Case.getCaseValue();
8041 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base, true);
8042 Case.setValue(cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(*Shift))));
8043 }
8044 return true;
8045}
8046
8047/// Tries to transform the switch when the condition is umin with a constant.
8048/// In that case, the default branch can be replaced by the constant's branch.
8049/// This method also removes dead cases when the simplification cannot replace
8050/// the default branch.
8051///
8052/// For example:
8053/// switch(umin(a, 3)) {
8054/// case 0:
8055/// case 1:
8056/// case 2:
8057/// case 3:
8058/// case 4:
8059/// // ...
8060/// default:
8061/// unreachable
8062/// }
8063///
8064/// Transforms into:
8065///
8066/// switch(a) {
8067/// case 0:
8068/// case 1:
8069/// case 2:
8070/// default:
8071/// // This is case 3
8072/// }
8074 Value *A;
8076
8077 if (!match(SI->getCondition(), m_UMin(m_Value(A), m_ConstantInt(Constant))))
8078 return false;
8079
8082 BasicBlock *BB = SIW->getParent();
8083
8084 // Dead cases are removed even when the simplification fails.
8085 // A case is dead when its value is higher than the Constant.
8086 for (auto I = SI->case_begin(), E = SI->case_end(); I != E;) {
8087 if (!I->getCaseValue()->getValue().ugt(Constant->getValue())) {
8088 ++I;
8089 continue;
8090 }
8091 BasicBlock *DeadCaseBB = I->getCaseSuccessor();
8092 DeadCaseBB->removePredecessor(BB);
8093 I = SIW.removeCase(I);
8094 E = SIW->case_end();
8095 if (!is_contained(successors(BB), DeadCaseBB))
8096 Updates.push_back({DominatorTree::Delete, BB, DeadCaseBB});
8097 }
8098
8099 auto Case = SI->findCaseValue(Constant);
8100 // If the case value is not found, `findCaseValue` returns the default case.
8101 // In this scenario, since there is no explicit `case 3:`, the simplification
8102 // fails. The simplification also fails when the switch’s default destination
8103 // is reachable.
8104 if (!SI->defaultDestUnreachable() || Case == SI->case_default()) {
8105 if (DTU)
8106 DTU->applyUpdates(Updates);
8107 return !Updates.empty();
8108 }
8109
8110 BasicBlock *Unreachable = SI->getDefaultDest();
8111 SIW.replaceDefaultDest(Case);
8112 SIW.removeCase(Case);
8113 SIW->setCondition(A);
8114
8115 Updates.push_back({DominatorTree::Delete, BB, Unreachable});
8116
8117 if (DTU)
8118 DTU->applyUpdates(Updates);
8119
8120 return true;
8121}
8122
8124 const DataLayout &DL,
8125 AssumptionCache *AC) {
8126 assert(SI);
8127 if (SI->defaultDestUnreachable())
8128 return false;
8129
8130 // If it can be proved that the switch condition takes some concrete value
8131 // in the default block, we can make some nice simplifications to the
8132 // switch.
8133 BasicBlock *Default = SI->getDefaultDest();
8134 const Instruction *CtxI = &*Default->getFirstNonPHIIt();
8136 SI->getCondition(),
8137 SimplifyQuery(DL, /*DT=*/nullptr, AC, CtxI).allowEphemerals(true));
8138 if (!Known.isConstant())
8139 return false;
8140
8141 // At this point, we know that only one value can be mapped to the
8142 // default block. So, if a case doesn't exist for it already, we
8143 // can create one pointing to the default block.
8144 ConstantInt *CaseVal =
8145 ConstantInt::get(SI->getContext(), Known.getConstant());
8146 const llvm::SwitchInst::CaseIt CaseIt = SI->findCaseValue(CaseVal);
8147 if (CaseIt == SI->case_default()) {
8149 SIW.addCase(CaseVal, Default, SIW.getSuccessorWeight(0));
8150 SIW.setSuccessorWeight(0, 0);
8151 }
8152 // If there is a pre-existing case for the constant, the default branch
8153 // will be removed rather than being moved. Thus, we are removing an edge
8154 // in the CFG, and need to update any PHIs in the default block.
8155 createUnreachableSwitchDefault(SI, DTU, /*RemoveOrigDefaultBlock=*/CaseIt !=
8156 SI->case_default());
8157
8158 assert(SI->getNumCases() > 0 && "Switch should have at least one case");
8159 assert(SI->findCaseValue(CaseVal) != SI->case_default() &&
8160 "Proven value should have a dedicated case");
8161 assert(SI->defaultDestUnreachable());
8162 return true;
8163}
8164
8165/// Tries to transform switch of powers of two to reduce switch range.
8166/// For example, switch like:
8167/// switch (C) { case 1: case 2: case 64: case 128: }
8168/// will be transformed to:
8169/// switch (count_trailing_zeros(C)) { case 0: case 1: case 6: case 7: }
8170///
8171/// This transformation allows better lowering and may transform the switch
8172/// instruction into a sequence of bit manipulation and a smaller
8173/// log2(C)-indexed value table (instead of traditionally emitting a load of the
8174/// address of the jump target, and indirectly jump to it).
8176 DomTreeUpdater *DTU,
8177 const DataLayout &DL,
8178 const TargetTransformInfo &TTI) {
8179 Value *Condition = SI->getCondition();
8180 LLVMContext &Context = SI->getContext();
8181 auto *CondTy = cast<IntegerType>(Condition->getType());
8182
8183 if (CondTy->getIntegerBitWidth() > 64 ||
8184 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
8185 return false;
8186
8187 // Ensure trailing zeroes count intrinsic emission is not too expensive.
8188 IntrinsicCostAttributes Attrs(Intrinsic::cttz, CondTy,
8189 {Condition, ConstantInt::getTrue(Context)});
8190 if (TTI.getIntrinsicInstrCost(Attrs, TTI::TCK_SizeAndLatency) >
8191 TTI::TCC_Basic * 2)
8192 return false;
8193
8194 // Only bother with this optimization if there are more than 3 switch cases.
8195 // SDAG will start emitting jump tables for 4 or more cases.
8196 if (SI->getNumCases() < 4)
8197 return false;
8198
8199 // Check that switch cases are powers of two.
8201 for (const auto &Case : SI->cases()) {
8202 uint64_t CaseValue = Case.getCaseValue()->getValue().getZExtValue();
8203 if (llvm::has_single_bit(CaseValue))
8204 Values.push_back(CaseValue);
8205 else
8206 return false;
8207 }
8208
8209 // isSwichDense requires case values to be sorted.
8211 if (!isSwitchDense(Values.size(),
8212 llvm::countr_zero(Values.back()) -
8213 llvm::countr_zero(Values.front()) + 1,
8214 SI->getFunction()->hasOptSize()))
8215 // Transform is unable to generate dense switch.
8216 return false;
8217
8218 Builder.SetInsertPoint(SI);
8219
8220 if (!SI->defaultDestUnreachable()) {
8221 // Let non-power-of-two inputs jump to the default case, when the latter is
8222 // reachable.
8223 auto *PopC = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Condition);
8224 auto *IsPow2 = Builder.CreateICmpEQ(PopC, ConstantInt::get(CondTy, 1));
8225
8226 auto *OrigBB = SI->getParent();
8227 auto *DefaultCaseBB = SI->getDefaultDest();
8228 BasicBlock *SplitBB = SplitBlock(OrigBB, SI, DTU);
8229 auto It = OrigBB->getTerminator()->getIterator();
8230 SmallVector<uint32_t> Weights;
8231 auto HasWeights = extractBranchWeights(*SI, Weights);
8232 auto *BI = CondBrInst::Create(IsPow2, SplitBB, DefaultCaseBB, It);
8233 if (HasWeights && any_of(Weights, not_equal_to(0))) {
8234 // IsPow2 covers a subset of the cases in which we'd go to the default
8235 // label. The other is those powers of 2 that don't appear in the case
8236 // statement. We don't know the distribution of the values coming in, so
8237 // the safest is to split 50-50 the original probability to `default`.
8238 uint64_t OrigDenominator =
8240 SmallVector<uint64_t> NewWeights(2);
8241 NewWeights[1] = Weights[0] / 2;
8242 NewWeights[0] = OrigDenominator - NewWeights[1];
8243 setFittedBranchWeights(*BI, NewWeights, /*IsExpected=*/false);
8244 // The probability of executing the default block stays constant. It was
8245 // p_d = Weights[0] / OrigDenominator
8246 // we rewrite as W/D
8247 // We want to find the probability of the default branch of the switch
8248 // statement. Let's call it X. We have W/D = W/2D + X * (1-W/2D)
8249 // i.e. the original probability is the probability we go to the default
8250 // branch from the BI branch, or we take the default branch on the SI.
8251 // Meaning X = W / (2D - W), or (W/2) / (D - W/2)
8252 // This matches using W/2 for the default branch probability numerator and
8253 // D-W/2 as the denominator.
8254 Weights[0] = NewWeights[1];
8255 uint64_t CasesDenominator = OrigDenominator - Weights[0];
8256 for (auto &W : drop_begin(Weights))
8257 W = NewWeights[0] * static_cast<double>(W) / CasesDenominator;
8258
8259 setBranchWeights(*SI, Weights, /*IsExpected=*/false);
8260 }
8261 // BI is handling the default case for SI, and so should share its DebugLoc.
8262 BI->setDebugLoc(SI->getDebugLoc());
8263 It->eraseFromParent();
8264
8265 addPredecessorToBlock(DefaultCaseBB, OrigBB, SplitBB);
8266 if (DTU)
8267 DTU->applyUpdates({{DominatorTree::Insert, OrigBB, DefaultCaseBB}});
8268 }
8269
8270 // Replace each case with its trailing zeros number.
8271 for (auto &Case : SI->cases()) {
8272 auto *OrigValue = Case.getCaseValue();
8273 Case.setValue(ConstantInt::get(OrigValue->getIntegerType(),
8274 OrigValue->getValue().countr_zero()));
8275 }
8276
8277 // Replace condition with its trailing zeros number.
8278 auto *ConditionTrailingZeros = Builder.CreateIntrinsic(
8279 Intrinsic::cttz, {CondTy}, {Condition, ConstantInt::getTrue(Context)});
8280
8281 SI->setCondition(ConditionTrailingZeros);
8282
8283 return true;
8284}
8285
8286/// Fold switch over ucmp/scmp intrinsic to br if two of the switch arms have
8287/// the same destination.
8289 DomTreeUpdater *DTU) {
8290 auto *Cmp = dyn_cast<CmpIntrinsic>(SI->getCondition());
8291 if (!Cmp || !Cmp->hasOneUse())
8292 return false;
8293
8295 bool HasWeights = extractBranchWeights(getBranchWeightMDNode(*SI), Weights);
8296 if (!HasWeights)
8297 Weights.resize(4); // Avoid checking HasWeights everywhere.
8298
8299 // Normalize to [us]cmp == Res ? Succ : OtherSucc.
8300 int64_t Res;
8301 BasicBlock *Succ, *OtherSucc;
8302 uint32_t SuccWeight = 0, OtherSuccWeight = 0;
8303 BasicBlock *Unreachable = nullptr;
8304
8305 if (SI->getNumCases() == 2) {
8306 // Find which of 1, 0 or -1 is missing (handled by default dest).
8307 SmallSet<int64_t, 3> Missing;
8308 Missing.insert(1);
8309 Missing.insert(0);
8310 Missing.insert(-1);
8311
8312 Succ = SI->getDefaultDest();
8313 SuccWeight = Weights[0];
8314 OtherSucc = nullptr;
8315 for (auto &Case : SI->cases()) {
8316 std::optional<int64_t> Val =
8317 Case.getCaseValue()->getValue().trySExtValue();
8318 if (!Val)
8319 return false;
8320 if (!Missing.erase(*Val))
8321 return false;
8322 if (OtherSucc && OtherSucc != Case.getCaseSuccessor())
8323 return false;
8324 OtherSucc = Case.getCaseSuccessor();
8325 OtherSuccWeight += Weights[Case.getSuccessorIndex()];
8326 }
8327
8328 assert(Missing.size() == 1 && "Should have one case left");
8329 Res = *Missing.begin();
8330 } else if (SI->getNumCases() == 3 && SI->defaultDestUnreachable()) {
8331 // Normalize so that Succ is taken once and OtherSucc twice.
8332 Unreachable = SI->getDefaultDest();
8333 Succ = OtherSucc = nullptr;
8334 for (auto &Case : SI->cases()) {
8335 BasicBlock *NewSucc = Case.getCaseSuccessor();
8336 uint32_t Weight = Weights[Case.getSuccessorIndex()];
8337 if (!OtherSucc || OtherSucc == NewSucc) {
8338 OtherSucc = NewSucc;
8339 OtherSuccWeight += Weight;
8340 } else if (!Succ) {
8341 Succ = NewSucc;
8342 SuccWeight = Weight;
8343 } else if (Succ == NewSucc) {
8344 std::swap(Succ, OtherSucc);
8345 std::swap(SuccWeight, OtherSuccWeight);
8346 } else
8347 return false;
8348 }
8349 for (auto &Case : SI->cases()) {
8350 std::optional<int64_t> Val =
8351 Case.getCaseValue()->getValue().trySExtValue();
8352 if (!Val || (Val != 1 && Val != 0 && Val != -1))
8353 return false;
8354 if (Case.getCaseSuccessor() == Succ) {
8355 Res = *Val;
8356 break;
8357 }
8358 }
8359 } else {
8360 return false;
8361 }
8362
8363 // Determine predicate for the missing case.
8365 switch (Res) {
8366 case 1:
8367 Pred = ICmpInst::ICMP_UGT;
8368 break;
8369 case 0:
8370 Pred = ICmpInst::ICMP_EQ;
8371 break;
8372 case -1:
8373 Pred = ICmpInst::ICMP_ULT;
8374 break;
8375 }
8376 if (Cmp->isSigned())
8377 Pred = ICmpInst::getSignedPredicate(Pred);
8378
8379 MDNode *NewWeights = nullptr;
8380 if (HasWeights)
8381 NewWeights = MDBuilder(SI->getContext())
8382 .createBranchWeights(SuccWeight, OtherSuccWeight);
8383
8384 BasicBlock *BB = SI->getParent();
8385 Builder.SetInsertPoint(SI->getIterator());
8386 Value *ICmp = Builder.CreateICmp(Pred, Cmp->getLHS(), Cmp->getRHS());
8387 Builder.CreateCondBr(ICmp, Succ, OtherSucc, NewWeights,
8388 SI->getMetadata(LLVMContext::MD_unpredictable));
8389 OtherSucc->removePredecessor(BB);
8390 if (Unreachable)
8391 Unreachable->removePredecessor(BB);
8392 SI->eraseFromParent();
8393 Cmp->eraseFromParent();
8394 if (DTU && Unreachable)
8395 DTU->applyUpdates({{DominatorTree::Delete, BB, Unreachable}});
8396 return true;
8397}
8398
8399/// Checking whether two BBs are equal depends on the contents of the
8400/// BasicBlock and the incoming values of their successor PHINodes.
8401/// PHINode::getIncomingValueForBlock is O(|Preds|), so we'd like to avoid
8402/// calling this function on each BasicBlock every time isEqual is called,
8403/// especially since the same BasicBlock may be passed as an argument multiple
8404/// times. To do this, we can precompute a map of PHINode -> Pred BasicBlock ->
8405/// IncomingValue and add it in the Wrapper so isEqual can do O(1) checking
8406/// of the incoming values.
8409
8410 // One Phi usually has < 8 incoming values.
8414
8415 // We only merge the identical non-entry BBs with
8416 // - terminator unconditional br to Succ (pending relaxation),
8417 // - does not have address taken / weird control.
8418 static bool canBeMerged(const BasicBlock *BB) {
8419 assert(BB && "Expected non-null BB");
8420 // Entry block cannot be eliminated or have predecessors.
8421 if (BB->isEntryBlock())
8422 return false;
8423
8424 // Single successor and must be Succ.
8425 // FIXME: Relax that the terminator is a BranchInst by checking for equality
8426 // on other kinds of terminators. We decide to only support unconditional
8427 // branches for now for compile time reasons.
8428 auto *BI = dyn_cast<UncondBrInst>(BB->getTerminator());
8429 if (!BI)
8430 return false;
8431
8432 // Avoid blocks that are "address-taken" (blockaddress) or have unusual
8433 // uses.
8434 if (BB->hasAddressTaken() || BB->isEHPad())
8435 return false;
8436
8437 // TODO: relax this condition to merge equal blocks with >1 instructions?
8438 // Here, we use a O(1) form of the O(n) comparison of `size() != 1`.
8439 if (&BB->front() != &BB->back())
8440 return false;
8441
8442 // The BB must have at least one predecessor.
8443 if (pred_empty(BB))
8444 return false;
8445
8446 return true;
8447 }
8448};
8449
8451 static unsigned getHashValue(const EqualBBWrapper *EBW) {
8452 BasicBlock *BB = EBW->BB;
8454 assert(BB->size() == 1 && "Expected just a single branch in the BB");
8455
8456 // Since we assume the BB is just a single UncondBrInst with a single
8457 // successor, we hash as the BB and the incoming Values of its successor
8458 // PHIs. Initially, we tried to just use the successor BB as the hash, but
8459 // including the incoming PHI values leads to better performance.
8460 // We also tried to build a map from BB -> Succs.IncomingValues ahead of
8461 // time and passing it in EqualBBWrapper, but this slowed down the average
8462 // compile time without having any impact on the worst case compile time.
8463 BasicBlock *Succ = BI->getSuccessor();
8464 auto PhiValsForBB = map_range(Succ->phis(), [&](PHINode &Phi) {
8465 return (*EBW->PhiPredIVs)[&Phi][BB];
8466 });
8467 return hash_combine(Succ, hash_combine_range(PhiValsForBB));
8468 }
8469 static bool isEqual(const EqualBBWrapper *LHS, const EqualBBWrapper *RHS) {
8470 BasicBlock *A = LHS->BB;
8471 BasicBlock *B = RHS->BB;
8472
8473 // FIXME: we checked that the size of A and B are both 1 in
8474 // mergeIdenticalUncondBBs to make the Case list smaller to
8475 // improve performance. If we decide to support BasicBlocks with more
8476 // than just a single instruction, we need to check that A.size() ==
8477 // B.size() here, and we need to check more than just the BranchInsts
8478 // for equality.
8479
8480 UncondBrInst *ABI = cast<UncondBrInst>(A->getTerminator());
8481 UncondBrInst *BBI = cast<UncondBrInst>(B->getTerminator());
8482 if (ABI->getSuccessor() != BBI->getSuccessor())
8483 return false;
8484
8485 // Need to check that PHIs in successor have matching values.
8486 BasicBlock *Succ = ABI->getSuccessor();
8487 auto IfPhiIVMatch = [&](PHINode &Phi) {
8488 // Replace O(|Pred|) Phi.getIncomingValueForBlock with this O(1) hashmap
8489 // query.
8490 auto &PredIVs = (*LHS->PhiPredIVs)[&Phi];
8491 return PredIVs[A] == PredIVs[B];
8492 };
8493 return all_of(Succ->phis(), IfPhiIVMatch);
8494 }
8495};
8496
8497// Merge identical BBs into one of them.
8499 DomTreeUpdater *DTU) {
8500 if (Candidates.size() < 2)
8501 return false;
8502
8503 // Build Cases. Skip BBs that are not candidates for simplification. Mark
8504 // PHINodes which need to be processed into PhiPredIVs. We decide to process
8505 // an entire PHI at once after the loop, opposed to calling
8506 // getIncomingValueForBlock inside this loop, since each call to
8507 // getIncomingValueForBlock is O(|Preds|).
8508 EqualBBWrapper::Phi2IVsMap PhiPredIVs;
8510 BBs2Merge.reserve(Candidates.size());
8512
8513 for (BasicBlock *BB : Candidates) {
8514 BasicBlock *Succ = BB->getSingleSuccessor();
8515 assert(Succ && "Expected unconditional BB");
8516 BBs2Merge.emplace_back(EqualBBWrapper{BB, &PhiPredIVs});
8517 Phis.insert_range(make_pointer_range(Succ->phis()));
8518 }
8519
8520 // Precompute a data structure to improve performance of isEqual for
8521 // EqualBBWrapper.
8522 PhiPredIVs.reserve(Phis.size());
8523 for (PHINode *Phi : Phis) {
8524 auto &IVs =
8525 PhiPredIVs.try_emplace(Phi, Phi->getNumIncomingValues()).first->second;
8526 // Pre-fill all incoming for O(1) lookup as Phi.getIncomingValueForBlock is
8527 // O(|Pred|).
8528 for (auto &IV : Phi->incoming_values())
8529 IVs.insert({Phi->getIncomingBlock(IV), IV.get()});
8530 }
8531
8532 // Group duplicates using DenseSet with custom equality/hashing.
8533 // Build a set such that if the EqualBBWrapper exists in the set and another
8534 // EqualBBWrapper isEqual, then the equivalent EqualBBWrapper which is not in
8535 // the set should be replaced with the one in the set. If the EqualBBWrapper
8536 // is not in the set, then it should be added to the set so other
8537 // EqualBBWrapper can check against it in the same manner. We use
8538 // EqualBBWrapper instead of just BasicBlock because we'd like to pass around
8539 // information to isEquality, getHashValue, and when doing the replacement
8540 // with better performance.
8542 Keep.reserve(BBs2Merge.size());
8543
8545 Updates.reserve(BBs2Merge.size() * 2);
8546
8547 bool MadeChange = false;
8548
8549 // Helper: redirect all edges X -> DeadPred to X -> LivePred.
8550 auto RedirectIncomingEdges = [&](BasicBlock *Dead, BasicBlock *Live) {
8553 if (DTU) {
8554 // All predecessors of DeadPred (except the common predecessor) will be
8555 // moved to LivePred.
8556 Updates.reserve(Updates.size() + DeadPreds.size() * 2);
8558 predecessors(Live));
8559 for (BasicBlock *PredOfDead : DeadPreds) {
8560 // Do not modify those common predecessors of DeadPred and LivePred.
8561 if (!LivePreds.contains(PredOfDead))
8562 Updates.push_back({DominatorTree::Insert, PredOfDead, Live});
8563 Updates.push_back({DominatorTree::Delete, PredOfDead, Dead});
8564 }
8565 }
8566 LLVM_DEBUG(dbgs() << "Replacing duplicate pred BB ";
8567 Dead->printAsOperand(dbgs()); dbgs() << " with pred ";
8568 Live->printAsOperand(dbgs()); dbgs() << " for ";
8569 Live->getSingleSuccessor()->printAsOperand(dbgs());
8570 dbgs() << "\n");
8571 // Replace successors in all predecessors of DeadPred.
8572 for (BasicBlock *PredOfDead : DeadPreds) {
8573 Instruction *T = PredOfDead->getTerminator();
8574 T->replaceSuccessorWith(Dead, Live);
8575 }
8576 };
8577
8578 // Try to eliminate duplicate predecessors.
8579 for (const auto &EBW : BBs2Merge) {
8580 // EBW is a candidate for simplification. If we find a duplicate BB,
8581 // replace it.
8582 const auto &[It, Inserted] = Keep.insert(&EBW);
8583 if (Inserted)
8584 continue;
8585
8586 // Found duplicate: merge P into canonical predecessor It->Pred.
8587 BasicBlock *KeepBB = (*It)->BB;
8588 BasicBlock *DeadBB = EBW.BB;
8589
8590 // Avoid merging a BB with itself.
8591 if (KeepBB == DeadBB)
8592 continue;
8593
8594 // Redirect all edges into DeadPred to KeepPred.
8595 RedirectIncomingEdges(DeadBB, KeepBB);
8596
8597 // Now DeadBB should become unreachable; leave DCE to later,
8598 // but we can try to simplify it if it only branches to Succ.
8599 // (We won't erase here to keep the routine simple and DT-safe.)
8600 assert(pred_empty(DeadBB) && "DeadBB should be unreachable.");
8601 MadeChange = true;
8602 }
8603
8604 if (DTU && !Updates.empty())
8605 DTU->applyUpdates(Updates);
8606
8607 return MadeChange;
8608}
8609
8610bool SimplifyCFGOpt::simplifyDuplicateSwitchArms(SwitchInst *SI,
8611 DomTreeUpdater *DTU) {
8612 // Collect candidate switch-arms top-down.
8613 SmallSetVector<BasicBlock *, 16> FilteredArms(
8616 return mergeIdenticalBBs(FilteredArms.getArrayRef(), DTU);
8617}
8618
8619bool SimplifyCFGOpt::simplifyDuplicatePredecessors(BasicBlock *BB,
8620 DomTreeUpdater *DTU) {
8621 // Need at least 2 predecessors to do anything.
8622 if (!BB || !BB->hasNPredecessorsOrMore(2))
8623 return false;
8624
8625 // Compilation time consideration: retain the canonical loop, otherwise, we
8626 // require more time in the later loop canonicalization.
8627 if (Options.NeedCanonicalLoop && is_contained(LoopHeaders, BB))
8628 return false;
8629
8630 // Collect candidate predecessors bottom-up.
8631 SmallSetVector<BasicBlock *, 8> FilteredPreds(
8634 return mergeIdenticalBBs(FilteredPreds.getArrayRef(), DTU);
8635}
8636
8637bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
8638 BasicBlock *BB = SI->getParent();
8639
8640 if (isValueEqualityComparison(SI)) {
8641 // If we only have one predecessor, and if it is a branch on this value,
8642 // see if that predecessor totally determines the outcome of this switch.
8643 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
8644 if (simplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
8645 return requestResimplify();
8646
8647 Value *Cond = SI->getCondition();
8648 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
8649 if (simplifySwitchOnSelect(SI, Select))
8650 return requestResimplify();
8651
8652 // If the block only contains the switch, see if we can fold the block
8653 // away into any preds.
8654 if (SI == &*BB->begin())
8655 if (foldValueComparisonIntoPredecessors(SI, Builder))
8656 return requestResimplify();
8657 }
8658
8659 // Try to transform the switch into an icmp and a branch.
8660 // The conversion from switch to comparison may lose information on
8661 // impossible switch values, so disable it early in the pipeline.
8662 if (Options.ConvertSwitchRangeToICmp && turnSwitchRangeIntoICmp(SI, Builder))
8663 return requestResimplify();
8664
8665 // Remove unreachable cases.
8666 if (eliminateDeadSwitchCases(SI, DTU, Options.AC, DL))
8667 return requestResimplify();
8668
8669 if (simplifySwitchOfCmpIntrinsic(SI, Builder, DTU))
8670 return requestResimplify();
8671
8672 if (trySwitchToSelect(SI, Builder, DTU, DL))
8673 return requestResimplify();
8674
8675 if (Options.ForwardSwitchCondToPhi && forwardSwitchConditionToPHI(SI))
8676 return requestResimplify();
8677
8678 // The conversion of switches to arithmetic or lookup table is disabled in
8679 // the early optimization pipeline, as it may lose information or make the
8680 // resulting code harder to analyze.
8681 if (Options.ConvertSwitchToArithmetic || Options.ConvertSwitchToLookupTable)
8682 if (simplifySwitchLookup(SI, Builder, DTU, DL, TTI,
8683 Options.ConvertSwitchToLookupTable))
8684 return requestResimplify();
8685
8686 if (simplifySwitchOfPowersOfTwo(SI, Builder, DTU, DL, TTI))
8687 return requestResimplify();
8688
8689 if (reduceSwitchRange(SI, Builder, DL, TTI))
8690 return requestResimplify();
8691
8692 if (HoistCommon &&
8693 hoistCommonCodeFromSuccessors(SI, !Options.HoistCommonInsts))
8694 return requestResimplify();
8695
8696 // We can merge identical switch arms early to enhance more aggressive
8697 // optimization on switch.
8698 if (simplifyDuplicateSwitchArms(SI, DTU))
8699 return requestResimplify();
8700
8701 if (simplifySwitchWhenUMin(SI, DTU))
8702 return requestResimplify();
8703
8704 if (simplifySwitchDefaultBranch(SI, DTU, DL, Options.AC))
8705 return requestResimplify();
8706
8707 return false;
8708}
8709
8710bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) {
8711 BasicBlock *BB = IBI->getParent();
8712 bool Changed = false;
8713 SmallVector<uint32_t> BranchWeights;
8714 const bool HasBranchWeights = extractBranchWeights(*IBI, BranchWeights);
8715
8716 DenseMap<const BasicBlock *, uint64_t> TargetWeight;
8717 if (HasBranchWeights)
8718 for (size_t I = 0, E = IBI->getNumDestinations(); I < E; ++I)
8719 TargetWeight[IBI->getDestination(I)] += BranchWeights[I];
8720
8721 // Eliminate redundant destinations.
8722 SmallPtrSet<Value *, 8> Succs;
8723 SmallSetVector<BasicBlock *, 8> RemovedSuccs;
8724 for (unsigned I = 0, E = IBI->getNumDestinations(); I != E; ++I) {
8725 BasicBlock *Dest = IBI->getDestination(I);
8726 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
8727 if (!Dest->hasAddressTaken())
8728 RemovedSuccs.insert(Dest);
8729 Dest->removePredecessor(BB);
8730 IBI->removeDestination(I);
8731 --I;
8732 --E;
8733 Changed = true;
8734 }
8735 }
8736
8737 if (DTU) {
8738 std::vector<DominatorTree::UpdateType> Updates;
8739 Updates.reserve(RemovedSuccs.size());
8740 for (auto *RemovedSucc : RemovedSuccs)
8741 Updates.push_back({DominatorTree::Delete, BB, RemovedSucc});
8742 DTU->applyUpdates(Updates);
8743 }
8744
8745 if (IBI->getNumDestinations() == 0) {
8746 // If the indirectbr has no successors, change it to unreachable.
8747 new UnreachableInst(IBI->getContext(), IBI->getIterator());
8749 return true;
8750 }
8751
8752 if (IBI->getNumDestinations() == 1) {
8753 // If the indirectbr has one successor, change it to a direct branch.
8756 return true;
8757 }
8758 if (HasBranchWeights) {
8759 SmallVector<uint64_t> NewBranchWeights(IBI->getNumDestinations());
8760 for (size_t I = 0, E = IBI->getNumDestinations(); I < E; ++I)
8761 NewBranchWeights[I] += TargetWeight.find(IBI->getDestination(I))->second;
8762 setFittedBranchWeights(*IBI, NewBranchWeights, /*IsExpected=*/false);
8763 }
8764 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
8765 if (simplifyIndirectBrOnSelect(IBI, SI))
8766 return requestResimplify();
8767 }
8768 return Changed;
8769}
8770
8771/// Given an block with only a single landing pad and a unconditional branch
8772/// try to find another basic block which this one can be merged with. This
8773/// handles cases where we have multiple invokes with unique landing pads, but
8774/// a shared handler.
8775///
8776/// We specifically choose to not worry about merging non-empty blocks
8777/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
8778/// practice, the optimizer produces empty landing pad blocks quite frequently
8779/// when dealing with exception dense code. (see: instcombine, gvn, if-else
8780/// sinking in this file)
8781///
8782/// This is primarily a code size optimization. We need to avoid performing
8783/// any transform which might inhibit optimization (such as our ability to
8784/// specialize a particular handler via tail commoning). We do this by not
8785/// merging any blocks which require us to introduce a phi. Since the same
8786/// values are flowing through both blocks, we don't lose any ability to
8787/// specialize. If anything, we make such specialization more likely.
8788///
8789/// Phis in the successor are allowed if both blocks pass the same value, or
8790/// each passes its own landing pad value and that is its only use: the merged
8791/// block's landing pad then carries the value for both edges.
8793 BasicBlock *BB, DomTreeUpdater *DTU) {
8794 auto Succ = BB->getUniqueSuccessor();
8795 assert(Succ);
8796
8797 for (BasicBlock *OtherPred : predecessors(Succ)) {
8798 if (BB == OtherPred)
8799 continue;
8800 BasicBlock::iterator I = OtherPred->begin();
8802 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
8803 continue;
8804 ++I;
8806 if (!BI2 || !BI2->isIdenticalTo(BI))
8807 continue;
8808
8809 // Merging must not require a new phi in the merged landing pad block.
8810 if (!all_of(Succ->phis(), [&](PHINode &PN) {
8811 Value *V = PN.getIncomingValueForBlock(BB);
8812 Value *V2 = PN.getIncomingValueForBlock(OtherPred);
8813 return V == V2 || (V == LPad && V2 == LPad2);
8814 }))
8815 continue;
8816
8817 // Those phis must be the only uses of the landing pads. Otherwise, with a
8818 // loop through Succ, a use would be clobbered when the merged pad is
8819 // re-entered.
8820 unsigned NumLPadPhis = count_if(Succ->phis(), [&](PHINode &PN) {
8821 return PN.getIncomingValueForBlock(BB) == LPad;
8822 });
8823 if (!LPad->hasNUses(NumLPadPhis) || !LPad2->hasNUses(NumLPadPhis))
8824 continue;
8825
8826 std::vector<DominatorTree::UpdateType> Updates;
8827
8828 // We've found an identical block. Update our predecessors to take that
8829 // path instead and make ourselves dead.
8831 for (BasicBlock *Pred : UniquePreds) {
8832 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
8833 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
8834 "unexpected successor");
8835 II->setUnwindDest(OtherPred);
8836 if (DTU) {
8837 Updates.push_back({DominatorTree::Insert, Pred, OtherPred});
8838 Updates.push_back({DominatorTree::Delete, Pred, BB});
8839 }
8840 }
8841
8843 for (BasicBlock *Succ : UniqueSuccs) {
8844 Succ->removePredecessor(BB);
8845 if (DTU)
8846 Updates.push_back({DominatorTree::Delete, BB, Succ});
8847 }
8848
8849 IRBuilder<> Builder(BI);
8850 Builder.CreateUnreachable();
8851 BI->eraseFromParent();
8852 if (DTU)
8853 DTU->applyUpdates(Updates);
8854 return true;
8855 }
8856 return false;
8857}
8858
8859bool SimplifyCFGOpt::simplifyUncondBranch(UncondBrInst *BI,
8860 IRBuilder<> &Builder) {
8861 BasicBlock *BB = BI->getParent();
8862 BasicBlock *Succ = BI->getSuccessor(0);
8863
8864 // If the Terminator is the only non-phi instruction, simplify the block.
8865 // If LoopHeader is provided, check if the block or its successor is a loop
8866 // header. (This is for early invocations before loop simplify and
8867 // vectorization to keep canonical loop forms for nested loops. These blocks
8868 // can be eliminated when the pass is invoked later in the back-end.)
8869 // Note that if BB has only one predecessor then we do not introduce new
8870 // backedge, so we can eliminate BB.
8871 bool NeedCanonicalLoop =
8872 Options.NeedCanonicalLoop &&
8873 (!LoopHeaders.empty() && BB->hasNPredecessorsOrMore(2) &&
8874 (is_contained(LoopHeaders, BB) || is_contained(LoopHeaders, Succ)));
8876 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
8877 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB, DTU))
8878 return true;
8879
8880 // If the only instruction in the block is a seteq/setne comparison against a
8881 // constant, try to simplify the block.
8882 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
8883 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
8884 ++I;
8885 if (I->isTerminator() &&
8886 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
8887 return true;
8888 if (isa<SelectInst>(I) && I->getNextNode()->isTerminator() &&
8889 tryToSimplifyUncondBranchWithICmpSelectInIt(ICI, cast<SelectInst>(I),
8890 Builder))
8891 return true;
8892 }
8893 }
8894
8895 // See if we can merge an empty landing pad block with another which is
8896 // equivalent.
8897 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
8898 ++I;
8899 if (I->isTerminator() && tryToMergeLandingPad(LPad, BI, BB, DTU))
8900 return true;
8901 }
8902
8903 return false;
8904}
8905
8907 BasicBlock *PredPred = nullptr;
8908 for (auto *P : predecessors(BB)) {
8909 BasicBlock *PPred = P->getSinglePredecessor();
8910 if (!PPred || (PredPred && PredPred != PPred))
8911 return nullptr;
8912 PredPred = PPred;
8913 }
8914 return PredPred;
8915}
8916
8917/// Fold the following pattern:
8918/// bb0:
8919/// br i1 %cond1, label %bb1, label %bb2
8920/// bb1:
8921/// br i1 %cond2, label %bb3, label %bb4
8922/// bb2:
8923/// br i1 %cond2, label %bb4, label %bb3
8924/// bb3:
8925/// ...
8926/// bb4:
8927/// ...
8928/// into
8929/// bb0:
8930/// %cond = xor i1 %cond1, %cond2
8931/// br i1 %cond, label %bb4, label %bb3
8932/// bb3:
8933/// ...
8934/// bb4:
8935/// ...
8936/// NOTE: %cond2 always dominates the terminator of bb0.
8938 BasicBlock *BB = BI->getParent();
8939 BasicBlock *BB1 = BI->getSuccessor(0);
8940 BasicBlock *BB2 = BI->getSuccessor(1);
8941 auto IsSimpleSuccessor = [BB](BasicBlock *Succ, CondBrInst *&SuccBI) {
8942 if (Succ == BB)
8943 return false;
8944 if (&Succ->front() != Succ->getTerminator())
8945 return false;
8946 SuccBI = dyn_cast<CondBrInst>(Succ->getTerminator());
8947 if (!SuccBI)
8948 return false;
8949 BasicBlock *Succ1 = SuccBI->getSuccessor(0);
8950 BasicBlock *Succ2 = SuccBI->getSuccessor(1);
8951 return Succ1 != Succ && Succ2 != Succ && Succ1 != BB && Succ2 != BB &&
8952 !isa<PHINode>(Succ1->front()) && !isa<PHINode>(Succ2->front());
8953 };
8954 CondBrInst *BB1BI, *BB2BI;
8955 if (!IsSimpleSuccessor(BB1, BB1BI) || !IsSimpleSuccessor(BB2, BB2BI))
8956 return false;
8957
8958 if (BB1BI->getCondition() != BB2BI->getCondition() ||
8959 BB1BI->getSuccessor(0) != BB2BI->getSuccessor(1) ||
8960 BB1BI->getSuccessor(1) != BB2BI->getSuccessor(0))
8961 return false;
8962
8963 BasicBlock *BB3 = BB1BI->getSuccessor(0);
8964 BasicBlock *BB4 = BB1BI->getSuccessor(1);
8965 // Bail out on trivial cases to avoid bothering to handle the special case in
8966 // the code below.
8967 if (BB3 == BB4)
8968 return false;
8969 IRBuilder<> Builder(BI);
8970 BI->setCondition(
8971 Builder.CreateXor(BI->getCondition(), BB1BI->getCondition()));
8972 BB1->removePredecessor(BB);
8973 BI->setSuccessor(0, BB4);
8974 BB2->removePredecessor(BB);
8975 BI->setSuccessor(1, BB3);
8976 if (DTU) {
8978 Updates.push_back({DominatorTree::Delete, BB, BB1});
8979 Updates.push_back({DominatorTree::Insert, BB, BB4});
8980 Updates.push_back({DominatorTree::Delete, BB, BB2});
8981 Updates.push_back({DominatorTree::Insert, BB, BB3});
8982
8983 DTU->applyUpdates(Updates);
8984 }
8985 bool HasWeight = false;
8986 uint64_t BBTWeight, BBFWeight;
8987 if (extractBranchWeights(*BI, BBTWeight, BBFWeight))
8988 HasWeight = true;
8989 else
8990 BBTWeight = BBFWeight = 1;
8991 uint64_t BB1TWeight, BB1FWeight;
8992 if (extractBranchWeights(*BB1BI, BB1TWeight, BB1FWeight))
8993 HasWeight = true;
8994 else
8995 BB1TWeight = BB1FWeight = 1;
8996 uint64_t BB2TWeight, BB2FWeight;
8997 if (extractBranchWeights(*BB2BI, BB2TWeight, BB2FWeight))
8998 HasWeight = true;
8999 else
9000 BB2TWeight = BB2FWeight = 1;
9001 if (HasWeight) {
9002 uint64_t Weights[2] = {BBTWeight * BB1FWeight + BBFWeight * BB2TWeight,
9003 BBTWeight * BB1TWeight + BBFWeight * BB2FWeight};
9004 setFittedBranchWeights(*BI, Weights, /*IsExpected=*/false,
9005 /*ElideAllZero=*/true);
9006 }
9007 return true;
9008}
9009
9010bool SimplifyCFGOpt::simplifyCondBranch(CondBrInst *BI, IRBuilder<> &Builder) {
9011 assert(
9013 BI->getSuccessor(0) != BI->getSuccessor(1) &&
9014 "Tautological conditional branch should have been eliminated already.");
9015
9016 BasicBlock *BB = BI->getParent();
9017 if (!Options.SimplifyCondBranch ||
9018 BI->getFunction()->hasFnAttribute(Attribute::OptForFuzzing))
9019 return false;
9020
9021 // Conditional branch
9022 if (isValueEqualityComparison(BI)) {
9023 // If we only have one predecessor, and if it is a branch on this value,
9024 // see if that predecessor totally determines the outcome of this
9025 // switch.
9026 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
9027 if (simplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
9028 return requestResimplify();
9029
9030 // This block must be empty, except for the setcond inst, if it exists.
9031 // Ignore pseudo intrinsics.
9032 for (auto &I : *BB) {
9033 if (isa<PseudoProbeInst>(I) ||
9034 &I == cast<Instruction>(BI->getCondition()))
9035 continue;
9036 if (&I == BI)
9037 if (foldValueComparisonIntoPredecessors(BI, Builder))
9038 return requestResimplify();
9039 break;
9040 }
9041 }
9042
9043 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
9044 if (simplifyBranchOnICmpChain(BI, Builder, DL))
9045 return true;
9046
9047 // If this basic block has dominating predecessor blocks and the dominating
9048 // blocks' conditions imply BI's condition, we know the direction of BI.
9049 std::optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
9050 if (Imp) {
9051 // Turn this into a branch on constant.
9052 auto *OldCond = BI->getCondition();
9053 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
9054 : ConstantInt::getFalse(BB->getContext());
9055 BI->setCondition(TorF);
9057 return requestResimplify();
9058 }
9059
9060 // If this basic block is ONLY a compare and a branch, and if a predecessor
9061 // branches to us and one of our successors, fold the comparison into the
9062 // predecessor and use logical operations to pick the right destination.
9063 if (Options.SpeculateBlocks &&
9064 foldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI, Options.AC,
9065 Options.BonusInstThreshold))
9066 return requestResimplify();
9067
9068 // We have a conditional branch to two blocks that are only reachable
9069 // from BI. We know that the condbr dominates the two blocks, so see if
9070 // there is any identical code in the "then" and "else" blocks. If so, we
9071 // can hoist it up to the branching block.
9072 if (BI->getSuccessor(0)->getSinglePredecessor()) {
9073 if (BI->getSuccessor(1)->getSinglePredecessor()) {
9074 if (HoistCommon &&
9075 hoistCommonCodeFromSuccessors(BI, !Options.HoistCommonInsts))
9076 return requestResimplify();
9077
9078 if (BI && Options.HoistLoadsStoresWithCondFaulting &&
9079 isProfitableToSpeculate(BI, std::nullopt, TTI)) {
9080 SmallVector<Instruction *, 2> SpeculatedConditionalLoadsStores;
9081 auto CanSpeculateConditionalLoadsStores = [&]() {
9082 for (auto *Succ : successors(BB)) {
9083 for (Instruction &I : *Succ) {
9084 if (I.isTerminator()) {
9085 if (I.getNumSuccessors() > 1)
9086 return false;
9087 continue;
9088 } else if (!isSafeCheapLoadStore(&I, TTI) ||
9089 SpeculatedConditionalLoadsStores.size() ==
9091 return false;
9092 }
9093 SpeculatedConditionalLoadsStores.push_back(&I);
9094 }
9095 }
9096 return !SpeculatedConditionalLoadsStores.empty();
9097 };
9098
9099 if (CanSpeculateConditionalLoadsStores()) {
9100 hoistConditionalLoadsStores(BI, SpeculatedConditionalLoadsStores,
9101 std::nullopt, nullptr);
9102 return requestResimplify();
9103 }
9104 }
9105 } else {
9106 // If Successor #1 has multiple preds, we may be able to conditionally
9107 // execute Successor #0 if it branches to Successor #1.
9108 Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
9109 if (Succ0TI->getNumSuccessors() == 1 &&
9110 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
9111 if (speculativelyExecuteBB(BI, BI->getSuccessor(0)))
9112 return requestResimplify();
9113 }
9114 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
9115 // If Successor #0 has multiple preds, we may be able to conditionally
9116 // execute Successor #1 if it branches to Successor #0.
9117 Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
9118 if (Succ1TI->getNumSuccessors() == 1 &&
9119 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
9120 if (speculativelyExecuteBB(BI, BI->getSuccessor(1)))
9121 return requestResimplify();
9122 }
9123
9124 // If this is a branch on something for which we know the constant value in
9125 // predecessors (e.g. a phi node in the current block), thread control
9126 // through this block.
9127 if (foldCondBranchOnValueKnownInPredecessor(BI))
9128 return requestResimplify();
9129
9130 // Scan predecessor blocks for conditional branches.
9131 for (BasicBlock *Pred : predecessors(BB))
9132 if (CondBrInst *PBI = dyn_cast<CondBrInst>(Pred->getTerminator()))
9133 if (PBI != BI)
9134 if (SimplifyCondBranchToCondBranch(PBI, BI, DTU, DL, TTI))
9135 return requestResimplify();
9136
9137 // Look for diamond patterns.
9138 if (MergeCondStores)
9139 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
9140 if (CondBrInst *PBI = dyn_cast<CondBrInst>(PrevBB->getTerminator()))
9141 if (PBI != BI)
9142 if (mergeConditionalStores(PBI, BI, DTU, DL, TTI))
9143 return requestResimplify();
9144
9145 // Look for nested conditional branches.
9146 if (mergeNestedCondBranch(BI, DTU))
9147 return requestResimplify();
9148
9149 return false;
9150}
9151
9152/// Check if passing a value to an instruction will cause undefined behavior.
9153static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified) {
9154 assert(V->getType() == I->getType() && "Mismatched types");
9156 if (!C)
9157 return false;
9158
9159 if (I->use_empty())
9160 return false;
9161
9162 if (C->isNullValue() || isa<UndefValue>(C)) {
9163 // Find the first same-block use with a UB-triggering opcode, skipping
9164 // cross-block or before-I uses.
9165 auto FindUse = llvm::find_if(I->uses(), [I](auto &U) {
9166 auto *Use = cast<Instruction>(U.getUser());
9167 // Only same-block uses after I can witness UB at I's program point.
9168 // Self-uses and before-I uses can occur when I is a PHI node.
9169 if (Use->getParent() != I->getParent() || Use == I || Use->comesBefore(I))
9170 return false;
9171 // Change this list when we want to add new instructions.
9172 switch (Use->getOpcode()) {
9173 default:
9174 return false;
9175 case Instruction::GetElementPtr:
9176 case Instruction::Ret:
9177 case Instruction::BitCast:
9178 case Instruction::Load:
9179 case Instruction::Store:
9180 case Instruction::Call:
9181 case Instruction::CallBr:
9182 case Instruction::Invoke:
9183 case Instruction::UDiv:
9184 case Instruction::URem:
9185 // Note: signed div/rem of INT_MIN / -1 is also immediate UB, not
9186 // implemented to avoid code complexity as it is unclear how useful such
9187 // logic is.
9188 case Instruction::SDiv:
9189 case Instruction::SRem:
9190 return true;
9191 }
9192 });
9193 if (FindUse == I->use_end())
9194 return false;
9195 auto &Use = *FindUse;
9196 auto *User = cast<Instruction>(Use.getUser());
9197
9198 // Now make sure that there are no instructions in between that can alter
9199 // control flow (eg. calls)
9200 auto InstrRange =
9201 make_range(std::next(I->getIterator()), User->getIterator());
9202 if (any_of(InstrRange, [](Instruction &I) {
9204 }))
9205 return false;
9206
9207 // Look through GEPs. A load from a GEP derived from NULL is still undefined
9209 if (GEP->getPointerOperand() == I) {
9210 // The type of GEP may differ from the type of base pointer.
9211 // Bail out on vector GEPs, as they are not handled by other checks.
9212 if (GEP->getType()->isVectorTy())
9213 return false;
9214 // The current base address is null, there are four cases to consider:
9215 // getelementptr (TY, null, 0) -> null
9216 // getelementptr (TY, null, not zero) -> may be modified
9217 // getelementptr inbounds (TY, null, 0) -> null
9218 // getelementptr inbounds (TY, null, not zero) -> poison iff null is
9219 // undefined?
9220 if (!GEP->hasAllZeroIndices() &&
9221 (!GEP->isInBounds() ||
9222 NullPointerIsDefined(GEP->getFunction(),
9223 GEP->getPointerAddressSpace())))
9224 PtrValueMayBeModified = true;
9225 return passingValueIsAlwaysUndefined(V, GEP, PtrValueMayBeModified);
9226 }
9227
9228 // Look through return.
9229 if (ReturnInst *Ret = dyn_cast<ReturnInst>(User)) {
9230 bool HasNoUndefAttr =
9231 Ret->getFunction()->hasRetAttribute(Attribute::NoUndef);
9232 // Return undefined to a noundef return value is undefined.
9233 if (isa<UndefValue>(C) && HasNoUndefAttr)
9234 return true;
9235 // Return null to a nonnull+noundef return value is undefined.
9236 if (C->isNullValue() && HasNoUndefAttr &&
9237 Ret->getFunction()->hasRetAttribute(Attribute::NonNull)) {
9238 return !PtrValueMayBeModified;
9239 }
9240 }
9241
9242 // Load from null is undefined.
9243 if (LoadInst *LI = dyn_cast<LoadInst>(User))
9244 if (!LI->isVolatile())
9245 return !NullPointerIsDefined(LI->getFunction(),
9246 LI->getPointerAddressSpace());
9247
9248 // Store to null is undefined.
9250 if (!SI->isVolatile())
9251 return (!NullPointerIsDefined(SI->getFunction(),
9252 SI->getPointerAddressSpace())) &&
9253 SI->getPointerOperand() == I;
9254
9255 // llvm.assume(false/undef) always triggers immediate UB.
9256 if (auto *Assume = dyn_cast<AssumeInst>(User)) {
9257 // Ignore assume operand bundles.
9258 if (I == Assume->getArgOperand(0))
9259 return true;
9260 }
9261
9262 if (auto *CB = dyn_cast<CallBase>(User)) {
9263 if (C->isNullValue() && NullPointerIsDefined(CB->getFunction()))
9264 return false;
9265 // A call to null is undefined.
9266 if (CB->getCalledOperand() == I)
9267 return true;
9268
9269 if (CB->isArgOperand(&Use)) {
9270 unsigned ArgIdx = CB->getArgOperandNo(&Use);
9271 // Passing null to a nonnnull+noundef argument is undefined.
9272 if (isa<ConstantPointerNull>(C) && C->getType()->isPointerTy() &&
9273 CB->paramHasNonNullAttr(ArgIdx, /*AllowUndefOrPoison=*/false))
9274 return !PtrValueMayBeModified;
9275 // Passing undef to a noundef argument is undefined.
9276 if (isa<UndefValue>(C) && CB->isPassingUndefUB(ArgIdx))
9277 return true;
9278 }
9279 }
9280 // Div/Rem by zero is immediate UB
9281 if (match(User, m_BinOp(m_Value(), m_Specific(I))) && User->isIntDivRem())
9282 return true;
9283 }
9284 return false;
9285}
9286
9287/// If BB has an incoming value that will always trigger undefined behavior
9288/// (eg. null pointer dereference), remove the branch leading here.
9290 DomTreeUpdater *DTU,
9291 AssumptionCache *AC) {
9292 for (PHINode &PHI : BB->phis())
9293 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
9294 if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
9295 BasicBlock *Predecessor = PHI.getIncomingBlock(i);
9296 Instruction *T = Predecessor->getTerminator();
9297 IRBuilder<> Builder(T);
9298 if (isa<UncondBrInst>(T)) {
9299 BB->removePredecessor(Predecessor);
9300 // Turn unconditional branches into unreachables.
9301 Builder.CreateUnreachable();
9302 T->eraseFromParent();
9303 if (DTU)
9304 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
9305 return true;
9306 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(T)) {
9307 BB->removePredecessor(Predecessor);
9308 // Handle degenerate conditional branches.
9309 if (BI->getSuccessor(0) == BI->getSuccessor(1)) {
9310 // The only difference from the UncondBrInst path above is that it
9311 // has two edges in CFG.
9312 BB->removePredecessor(Predecessor);
9313 // Turn unconditional branches into unreachables.
9314 Builder.CreateUnreachable();
9315 } else {
9316 // Preserve guarding condition in assume, because it might not be
9317 // inferrable from any dominating condition.
9318 Value *Cond = BI->getCondition();
9319 CallInst *Assumption;
9320 if (BI->getSuccessor(0) == BB)
9321 Assumption = Builder.CreateAssumption(Builder.CreateNot(Cond));
9322 else
9323 Assumption = Builder.CreateAssumption(Cond);
9324 if (AC)
9325 AC->registerAssumption(cast<AssumeInst>(Assumption));
9326 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
9327 : BI->getSuccessor(0));
9328 }
9329 BI->eraseFromParent();
9330 if (DTU)
9331 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
9332 return true;
9333 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
9334 // Redirect all branches leading to UB into
9335 // a newly created unreachable block.
9336 BasicBlock *Unreachable = BasicBlock::Create(
9337 Predecessor->getContext(), "unreachable", BB->getParent(), BB);
9338 Builder.SetInsertPoint(Unreachable);
9339 // The new block contains only one instruction: Unreachable
9340 Builder.CreateUnreachable();
9341 for (const auto &Case : SI->cases())
9342 if (Case.getCaseSuccessor() == BB) {
9343 BB->removePredecessor(Predecessor);
9344 Case.setSuccessor(Unreachable);
9345 }
9346 if (SI->getDefaultDest() == BB) {
9347 BB->removePredecessor(Predecessor);
9348 SI->setDefaultDest(Unreachable);
9349 }
9350
9351 if (DTU)
9352 DTU->applyUpdates(
9353 { { DominatorTree::Insert, Predecessor, Unreachable },
9354 { DominatorTree::Delete, Predecessor, BB } });
9355 return true;
9356 }
9357 }
9358
9359 return false;
9360}
9361
9362bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
9363 bool Changed = false;
9364
9365 assert(BB && BB->getParent() && "Block not embedded in function!");
9366 assert(BB->hasTerminator() && "Degenerate basic block encountered!");
9367
9368 // Remove basic blocks that have no predecessors (except the entry block)...
9369 // or that just have themself as a predecessor. These are unreachable.
9370 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
9371 BB->getSinglePredecessor() == BB) {
9372 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
9373 DeleteDeadBlock(BB, DTU);
9374 return true;
9375 }
9376
9377 // Check to see if we can constant propagate this terminator instruction
9378 // away...
9379 Changed |= ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true,
9380 /*TLI=*/nullptr, DTU);
9381
9382 // Check for and eliminate duplicate PHI nodes in this block.
9384
9385 // Check for and remove branches that will always cause undefined behavior.
9387 return requestResimplify();
9388
9389 // Merge basic blocks into their predecessor if there is only one distinct
9390 // pred, and if there is only one distinct successor of the predecessor, and
9391 // if there are no PHI nodes.
9392 if (MergeBlockIntoPredecessor(BB, DTU))
9393 return true;
9394
9395 if (SinkCommon && Options.SinkCommonInsts) {
9396 if (sinkCommonCodeFromPredecessors(BB, DTU) ||
9397 mergeCompatibleInvokes(BB, DTU)) {
9398 // sinkCommonCodeFromPredecessors() does not automatically CSE PHI's,
9399 // so we may now have duplicate PHI's.
9400 // Let's rerun EliminateDuplicatePHINodes() first,
9401 // before foldTwoEntryPHINode() potentially converts them into select's,
9402 // after which we'd need a whole EarlyCSE pass run to cleanup them.
9403 return true;
9404 }
9405 // Merge identical predecessors of this block.
9406 if (simplifyDuplicatePredecessors(BB, DTU))
9407 return true;
9408 }
9409
9410 if (Options.SpeculateBlocks &&
9411 !BB->getParent()->hasFnAttribute(Attribute::OptForFuzzing)) {
9412 // If there is a trivial two-entry PHI node in this basic block, and we can
9413 // eliminate it, do so now.
9414 if (auto *PN = dyn_cast<PHINode>(BB->begin()))
9415 if (PN->getNumIncomingValues() == 2)
9416 if (foldTwoEntryPHINode(PN, TTI, DTU, Options.AC, DL,
9417 Options.SpeculateUnpredictables))
9418 return true;
9419 }
9420
9421 IRBuilder<> Builder(BB);
9423 Builder.SetInsertPoint(Terminator);
9424 switch (Terminator->getOpcode()) {
9425 case Instruction::UncondBr:
9426 Changed |= simplifyUncondBranch(cast<UncondBrInst>(Terminator), Builder);
9427 break;
9428 case Instruction::CondBr:
9429 Changed |= simplifyCondBranch(cast<CondBrInst>(Terminator), Builder);
9430 break;
9431 case Instruction::Resume:
9432 Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder);
9433 break;
9434 case Instruction::CleanupRet:
9435 Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator));
9436 break;
9437 case Instruction::Switch:
9438 Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder);
9439 break;
9440 case Instruction::Unreachable:
9441 Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator));
9442 break;
9443 case Instruction::IndirectBr:
9444 Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator));
9445 break;
9446 }
9447
9448 return Changed;
9449}
9450
9451bool SimplifyCFGOpt::run(BasicBlock *BB) {
9452 bool Changed = false;
9453
9454 // Repeated simplify BB as long as resimplification is requested.
9455 do {
9456 Resimplify = false;
9457
9458 // Perform one round of simplifcation. Resimplify flag will be set if
9459 // another iteration is requested.
9460 Changed |= simplifyOnce(BB);
9461 } while (Resimplify);
9462
9463 return Changed;
9464}
9465
9468 ArrayRef<WeakVH> LoopHeaders) {
9469 return SimplifyCFGOpt(TTI, DTU, BB->getDataLayout(), LoopHeaders,
9470 Options)
9471 .run(BB);
9472}
#define Fail
#define Success
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t 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:665
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...
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.
static cl::opt< uint32_t > SelectFalseWeight("profcheck-default-select-false-weight", cl::init(3U), cl::desc("When annotating `select` instructions, this value will be used " "for the second ('false') case."))
static cl::opt< uint32_t > SelectTrueWeight("profcheck-default-select-true-weight", cl::init(2U), cl::desc("When annotating `select` instructions, this value will be used " "for the first ('true') case."))
SmallVector< MachineOperand, 4 > Cond
int64_t C1
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
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:480
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 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 getCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, BasicBlock **CommonDest, SmallVectorImpl< std::pair< PHINode *, Constant * > > &Res, const DataLayout &DL)
Try to determine the resulting constant values in phi nodes at the common destination basic block,...
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 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 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 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 bool initializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest, SwitchCaseResultVectorTy &UniqueResults, Constant *&DefaultResult, const DataLayout &DL, uintptr_t MaxUniqueResults)
static Value * isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, BasicBlock *StoreBB, BasicBlock *EndBB, Instruction *&PreviousAccess)
Determine if we can hoist sink a sole store instruction out of a conditional block.
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 trySwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder, DomTreeUpdater *DTU, const DataLayout &DL)
If a switch is only used to initialize one or more phi nodes in a common successor block with only tw...
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:230
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1551
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
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:471
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1998
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
Definition APInt.h:1594
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1979
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:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:509
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 hasTerminator() const LLVM_READONLY
Returns whether the block has a terminator.
Definition BasicBlock.h:232
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:666
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 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:463
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 InstListType::const_iterator getFirstNonPHIOrPseudoProbe() const
Returns an iterator to the first instruction in this block that is not a PHINode or a pseudo operatio...
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:461
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:638
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
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.
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
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.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
This is an important base class in LLVM.
Definition Constant.h:44
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:65
LLVM_ABI bool isOneValue() const
Returns true if the value is one.
Definition Constants.cpp:83
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:250
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:186
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:173
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
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:811
void reserve(size_type NumEntries)
Grow the DenseMap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:721
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
const BasicBlock & getEntryBlock() const
Definition Function.h:794
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2398
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2139
CondBrInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition IRBuilder.h:1212
LLVM_ABI Value * CreateSelectFMF(Value *C, Value *True, Value *False, FMFSource FMFSource, const Twine &Name="", Instruction *MDFrom=nullptr)
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition IRBuilder.h:445
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
BasicBlock::iterator GetInsertPoint() const
Definition IRBuilder.h:176
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition IRBuilder.h:2735
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:228
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1528
LLVM_ABI CallInst * CreateAssumption(Value *Cond)
Create an assume intrinsic call that allows the optimizer to assume that the provided condition will ...
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition IRBuilder.h:2019
UncondBrInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition IRBuilder.h:1206
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1850
SwitchInst * CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases=10, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a switch instruction with the specified value, default dest, and with a hint for the number of...
Definition IRBuilder.h:1235
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2382
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1907
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2121
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1925
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1418
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2233
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:450
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition IRBuilder.h:2107
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition IRBuilder.h:2323
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:196
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2492
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1588
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1452
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
Definition IRBuilder.h:74
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
Indirect Branch Instruction.
BasicBlock * getDestination(unsigned i)
Return the specified destination.
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
LLVM_ABI void removeDestination(unsigned i)
This method removes the specified successor from the indirectbr instruction.
LLVM_ABI void dropUBImplyingAttrsAndMetadata(ArrayRef< unsigned > Keep={})
Drop any attributes or metadata that can cause immediate undefined behavior.
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI iterator_range< simple_ilist< DbgRecord >::iterator > cloneDebugInfoFrom(const Instruction *From, std::optional< simple_ilist< DbgRecord >::iterator > FromHere=std::nullopt, bool InsertAtHead=false)
Clone any debug-info attached to From onto this instruction.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange() const
Return a range over the DbgRecords attached to this instruction.
LLVM_ABI void dropLocation()
Drop the instruction's debug location.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
bool isTerminator() const
iterator_range< user_iterator > users()
LLVM_ABI bool isUsedOutsideOfBlock(const BasicBlock *BB) const LLVM_READONLY
Return true if there are any uses of this instruction in blocks other than the specified block.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
@ CompareUsingIntersectedAttrs
Check for equivalence with intersected callbase attrs.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
LLVM_ABI bool isIdenticalTo(const Instruction *I) const LLVM_READONLY
Return true if the specified instruction is exactly identical to the current one.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI void applyMergedLocation(DebugLoc LocA, DebugLoc LocB)
Merge 2 debug locations and apply it to the Instruction.
LLVM_ABI void dropDbgRecords()
Erase any DbgRecords attached to this instruction.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Invoke instruction.
void setNormalDest(BasicBlock *B)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
The landingpad instruction holds all of the information necessary to generate correct exception handl...
An instruction for reading from memory.
static unsigned getPointerOperandIndex()
Iterates through instructions in a set of blocks in reverse order from the first non-terminator.
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
Metadata node.
Definition Metadata.h:1081
Helper class to manipulate !mmra metadata nodes.
bool empty() const
Definition MapVector.h:79
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
size_type size() const
Definition MapVector.h:58
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Value * getValue() const
Convenience accessor.
Return a value (possibly void), from a function.
This class represents the LLVM 'select' instruction.
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void insert_range(Range &&R)
Definition SetVector.h:182
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this store instruction.
Align getAlign() const
bool isSimple() const
Value * getValueOperand()
bool isUnordered() const
static unsigned getPointerOperandIndex()
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this store instruction.
Value * getPointerOperand()
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
A wrapper class to simplify modification of SwitchInst cases along with their prof branch_weights met...
LLVM_ABI void setSuccessorWeight(unsigned idx, CaseWeightOpt W)
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W)
Delegate the call to the underlying SwitchInst::addCase() and set the specified branch weight for the...
LLVM_ABI CaseWeightOpt getSuccessorWeight(unsigned idx)
LLVM_ABI void replaceDefaultDest(SwitchInst::CaseIt I)
Replace the default destination by given case.
std::optional< uint32_t > CaseWeightOpt
LLVM_ABI SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I)
Delegate the call to the underlying SwitchInst::removeCase() and remove correspondent branch weight.
Multiway switch.
CaseIt case_end()
Returns a read/write iterator that points one past the last in the SwitchInst.
BasicBlock * getSuccessor(unsigned idx) const
void setCondition(Value *V)
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
CaseIteratorImpl< CaseHandle > CaseIt
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
unsigned getNumSuccessors() const
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
TargetCostKind
The kind of cost model.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCC_Free
Expected to fold away in lowering.
@ TCC_Basic
The cost of a typical 'add' instruction.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
Unconditional Branch instruction.
void setSuccessor(BasicBlock *NewSucc)
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i=0) const
'undef' values are things that do not have specified contents.
Definition Constants.h:1657
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
LLVM_ABI void set(Value *Val)
Definition Value.h:876
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
const Use & getOperandUse(unsigned i) const
Definition User.h:220
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
static constexpr uint64_t MaximumAlignment
Definition Value.h:801
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:50
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition Value.cpp:143
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
Represents an op.with.overflow intrinsic.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
A range adaptor for a pair of iterators.
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
NoWrapTrunc_match< OpTy, TruncInst::NoUnsignedWrap > m_NUWTrunc(const OpTy &Op)
Matches trunc nuw.
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
SmallVector< DbgVariableRecord * > getDVRAssignmentMarkers(const Instruction *Inst)
Return a range of dbg_assign records for which Inst performs the assignment they encode.
Definition DebugInfo.h:209
LLVM_ABI void deleteAssignmentMarkers(const Instruction *Inst)
Delete the llvm.dbg.assign intrinsics linked to Inst.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
constexpr double e
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
constexpr auto not_equal_to(T &&Arg)
Functor variant of std::not_equal_to that can be used as a UnaryPredicate in functional algorithms li...
Definition STLExtras.h:2196
LLVM_ABI bool foldBranchToCommonDest(CondBrInst *BI, llvm::DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, const TargetTransformInfo *TTI=nullptr, AssumptionCache *AC=nullptr, unsigned BonusInstThreshold=1)
If this basic block is ONLY a setcc and a branch, and if a predecessor branches to us and one of our ...
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:61
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:522
bool succ_empty(const Instruction *I)
Definition CFG.h:141
LLVM_ABI bool IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB)
Check if we can prove that all paths starting from this block converge to a block that either has a @...
LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Definition Local.cpp:133
static cl::opt< unsigned > MaxSwitchCasesPerResult("max-switch-cases-per-result", cl::Hidden, cl::init(16), cl::desc("Limit cases to analyze when converting a switch to select"))
InstructionCost Cost
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
static cl::opt< bool > SpeculateOneExpensiveInst("speculate-one-expensive-inst", cl::Hidden, cl::init(true), cl::desc("Allow exactly one expensive instruction to be speculatively " "executed"))
@ Known
Known to have no common set bits.
@ Dead
Unused definition.
auto pred_end(const MachineBasicBlock *BB)
void set_intersect(S1Ty &S1, const S2Ty &S2)
set_intersect(A, B) - Compute A := A ^ B Identical to set_intersection, except that it works on set<>...
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
auto accumulate(R &&Range, E &&Init)
Wrapper for std::accumulate.
Definition STLExtras.h:1718
constexpr from_range_t from_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI MDNode * getBranchWeightMDNode(const Instruction &I)
Get the branch weights metadata node.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
static cl::opt< unsigned > MaxSpeculationDepth("max-speculation-depth", cl::Hidden, cl::init(10), cl::desc("Limit maximum recursion depth when calculating costs of " "speculatively executed instructions"))
OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P)
Provide wrappers to std::copy_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1807
static cl::opt< unsigned > PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2), cl::desc("Control the amount of phi node folding to perform (default = 2)"))
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
static cl::opt< bool > MergeCondStoresAggressively("simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false), cl::desc("When merging conditional stores, do so even if the resultant " "basic blocks are unlikely to be if-converted as a result"))
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
static cl::opt< unsigned > BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden, cl::init(2), cl::desc("Maximum cost of combining conditions when " "folding branches"))
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:380
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
static cl::opt< bool > SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), cl::desc("Sink common instructions down to the end block"))
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2216
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
static cl::opt< bool > HoistStoresWithCondFaulting("simplifycfg-hoist-stores-with-cond-faulting", cl::Hidden, cl::init(true), cl::desc("Hoist stores if the target supports conditional faulting"))
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
constexpr detail::StaticCastFunc< To > StaticCastTo
Function objects corresponding to the Cast types defined above.
Definition Casting.h:882
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI CondBrInst * GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, BasicBlock *&IfFalse)
Check whether BB is the merge point of a if-region.
LLVM_ABI bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes,...
Definition Local.cpp:1147
void RemapDbgRecordRange(Module *M, iterator_range< DbgRecordIterator > Range, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecords Range using the value map VM.
LLVM_ABI void InvertBranch(CondBrInst *PBI, IRBuilderBase &Builder)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
static cl::opt< bool > EnableMergeCompatibleInvokes("simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(true), cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"))
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition ValueMapper.h:98
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition ValueMapper.h:80
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
LLVM_ABI Instruction * removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
Replace 'BB's terminator with one that does not have an unwind successor block.
Definition Local.cpp:2873
auto succ_size(const MachineBasicBlock *BB)
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:552
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
static cl::opt< unsigned > MaxJumpThreadingLiveBlocks("max-jump-threading-live-blocks", cl::Hidden, cl::init(24), cl::desc("Limit number of blocks a define in a threaded block is allowed " "to be live in"))
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition Local.cpp:3126
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
static cl::opt< int > MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden, cl::init(10), cl::desc("Max size of a block which is still considered " "small enough to thread through"))
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
LLVM_ABI bool isWidenableBranch(const User *U)
Returns true iff U is a widenable branch (that is, extractWidenableCondition returns widenable condit...
@ Other
Any other memory.
Definition ModRef.h:68
TargetTransformInfo TTI
static cl::opt< unsigned > HoistCommonSkipLimit("simplifycfg-hoist-common-skip-limit", cl::Hidden, cl::init(20), cl::desc("Allow reordering across at most this many " "instructions when hoisting"))
LLVM_ABI cl::opt< bool > RequireAndPreserveDomTree
This function is used to do simplification of a CFG.
static cl::opt< bool > MergeCondStores("simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true), cl::desc("Hoist conditional stores even if an unconditional store does not " "precede - hoist multiple conditional stores into a single " "predicated store"))
static cl::opt< unsigned > BranchFoldToCommonDestVectorMultiplier("simplifycfg-branch-fold-common-dest-vector-multiplier", cl::Hidden, cl::init(2), cl::desc("Multiplier to apply to threshold when determining whether or not " "to fold branch to common destination when vector operations are " "present"))
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
LLVM_ABI void hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt, BasicBlock *BB)
Hoist all of the instructions in the IfBlock to the dominant block DomBlock, by moving its instructio...
Definition Local.cpp:3405
@ Sub
Subtraction of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
IntPtrTy
Definition InstrProf.h:82
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
LLVM_ABI bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant value?
Definition Local.cpp:3911
DWARFExpression::Operation Op
LLVM_ABI bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, unsigned MaxUsesToExplore=0)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
LLVM_ABI bool FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
void RemapDbgRecord(Module *M, DbgRecord *DR, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecord DR using the value map VM.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
auto sum_of(R &&Range, E Init=E{0})
Returns the sum of all values in Range with Init initial value.
Definition STLExtras.h:1733
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
static cl::opt< bool > HoistCondStores("simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), cl::desc("Hoist conditional stores if an unconditional store precedes"))
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
LLVM_ABI bool simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, DomTreeUpdater *DTU=nullptr, const SimplifyCFGOptions &Options={}, ArrayRef< WeakVH > LoopHeaders={})
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
auto predecessors(const MachineBasicBlock *BB)
static cl::opt< unsigned > HoistLoadsStoresWithCondFaultingThreshold("hoist-loads-stores-with-cond-faulting-threshold", cl::Hidden, cl::init(6), cl::desc("Control the maximal conditional load/store that we are willing " "to speculatively execute to eliminate conditional branch " "(default = 6)"))
static cl::opt< bool > HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true), cl::desc("Hoist common instructions up to the parent block"))
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
static cl::opt< unsigned > TwoEntryPHINodeFoldingThreshold("two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4), cl::desc("Control the maximal total instruction cost that we are willing " "to speculatively execute to fold a 2-entry PHI node into a " "select (default = 4)"))
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
SmallVector< uint64_t, 2 > getDisjunctionWeights(const SmallVector< T1, 2 > &B1, const SmallVector< T2, 2 > &B2)
Get the branch weights of a branch conditioned on b1 || b2, where b1 and b2 are 2 booleans that are t...
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition STLExtras.h:1612
LLVM_ABI bool hasBranchWeightMD(const Instruction &I)
Checks if an instructions has Branch Weight Metadata.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const SimplifyQuery &Q, bool IgnoreFree=false)
Equivalent to isDereferenceableAndAlignedPointer with an alignment of 1.
Definition Loads.cpp:266
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
static cl::opt< bool > HoistLoadsWithCondFaulting("simplifycfg-hoist-loads-with-cond-faulting", cl::Hidden, cl::init(true), cl::desc("Hoist loads if the target supports conditional faulting"))
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
Definition Local.cpp:1503
@ Keep
No function return thunk.
Definition CodeGen.h:370
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI void RemapSourceAtom(Instruction *I, ValueToValueMapTy &VM)
Remap source location atom.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:287
LLVM_ABI bool isWritableObject(const Value *Object, bool &ExplicitlyDereferenceableOnly)
Return true if the Object is writable, in the sense that any location based on this pointer that can ...
LLVM_ABI void mapAtomInstance(const DebugLoc &DL, ValueToValueMapTy &VMap)
Mark a cloned instruction as a new instance so that its source loc can be updated when remapped.
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:368
LLVM_ABI void extractFromBranchWeightMD64(const MDNode *ProfileData, SmallVectorImpl< uint64_t > &Weights)
Faster version of extractBranchWeights() that skips checks and must only be called with "branch_weigh...
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
SmallVectorImpl< ConstantInt * > * Cases
SmallVectorImpl< ConstantInt * > * OtherCases
Checking whether two BBs are equal depends on the contents of the BasicBlock and the incoming values ...
SmallDenseMap< BasicBlock *, Value *, 8 > BB2ValueMap
Phi2IVsMap * PhiPredIVs
DenseMap< PHINode *, BB2ValueMap > Phi2IVsMap
static bool canBeMerged(const BasicBlock *BB)
BasicBlock * BB
LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
static bool isEqual(const EqualBBWrapper *LHS, const EqualBBWrapper *RHS)
static unsigned getHashValue(const EqualBBWrapper *EBW)
An information struct used to provide DenseMap with the various necessary components for a given valu...
Matching combinators.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342