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