LLVM 24.0.0git
SimplifyCFG.cpp
Go to the documentation of this file.
1//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Peephole optimize the CFG.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/ADT/APInt.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/MapVector.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/Sequence.h"
20#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/StringRef.h"
31#include "llvm/Analysis/Loads.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/CFG.h"
39#include "llvm/IR/Constant.h"
41#include "llvm/IR/Constants.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/DebugInfo.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/GlobalValue.h"
48#include "llvm/IR/IRBuilder.h"
49#include "llvm/IR/InstrTypes.h"
50#include "llvm/IR/Instruction.h"
53#include "llvm/IR/LLVMContext.h"
54#include "llvm/IR/MDBuilder.h"
56#include "llvm/IR/Metadata.h"
57#include "llvm/IR/Module.h"
58#include "llvm/IR/NoFolder.h"
59#include "llvm/IR/Operator.h"
62#include "llvm/IR/Type.h"
63#include "llvm/IR/Use.h"
64#include "llvm/IR/User.h"
65#include "llvm/IR/Value.h"
66#include "llvm/IR/ValueHandle.h"
70#include "llvm/Support/Debug.h"
80#include <algorithm>
81#include <cassert>
82#include <climits>
83#include <cstddef>
84#include <cstdint>
85#include <iterator>
86#include <map>
87#include <optional>
88#include <set>
89#include <tuple>
90#include <utility>
91#include <vector>
92
93using namespace llvm;
94using namespace PatternMatch;
95
96#define DEBUG_TYPE "simplifycfg"
97
98namespace llvm {
99
101 "simplifycfg-require-and-preserve-domtree", cl::Hidden,
102
103 cl::desc(
104 "Temporary development switch used to gradually uplift SimplifyCFG "
105 "into preserving DomTree,"));
106
107// Chosen as 2 so as to be cheap, but still to have enough power to fold
108// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
109// To catch this, we need to fold a compare and a select, hence '2' being the
110// minimum reasonable default.
112 "phi-node-folding-threshold", cl::Hidden, cl::init(2),
113 cl::desc(
114 "Control the amount of phi node folding to perform (default = 2)"));
115
117 "two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4),
118 cl::desc("Control the maximal total instruction cost that we are willing "
119 "to speculatively execute to fold a 2-entry PHI node into a "
120 "select (default = 4)"));
121
122static cl::opt<bool>
123 HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true),
124 cl::desc("Hoist common instructions up to the parent block"));
125
127 "simplifycfg-hoist-loads-with-cond-faulting", cl::Hidden, cl::init(true),
128 cl::desc("Hoist loads if the target supports conditional faulting"));
129
131 "simplifycfg-hoist-stores-with-cond-faulting", cl::Hidden, cl::init(true),
132 cl::desc("Hoist stores if the target supports conditional faulting"));
133
135 "hoist-loads-stores-with-cond-faulting-threshold", cl::Hidden, cl::init(6),
136 cl::desc("Control the maximal conditional load/store that we are willing "
137 "to speculatively execute to eliminate conditional branch "
138 "(default = 6)"));
139
141 HoistCommonSkipLimit("simplifycfg-hoist-common-skip-limit", cl::Hidden,
142 cl::init(20),
143 cl::desc("Allow reordering across at most this many "
144 "instructions when hoisting"));
145
146static cl::opt<bool>
147 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
148 cl::desc("Sink common instructions down to the end block"));
149
151 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
152 cl::desc("Hoist conditional stores if an unconditional store precedes"));
153
155 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
156 cl::desc("Hoist conditional stores even if an unconditional store does not "
157 "precede - hoist multiple conditional stores into a single "
158 "predicated store"));
159
161 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
162 cl::desc("When merging conditional stores, do so even if the resultant "
163 "basic blocks are unlikely to be if-converted as a result"));
164
166 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
167 cl::desc("Allow exactly one expensive instruction to be speculatively "
168 "executed"));
169
171 "max-speculation-depth", cl::Hidden, cl::init(10),
172 cl::desc("Limit maximum recursion depth when calculating costs of "
173 "speculatively executed instructions"));
174
175static cl::opt<int>
176 MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden,
177 cl::init(10),
178 cl::desc("Max size of a block which is still considered "
179 "small enough to thread through"));
180
181// Two is chosen to allow one negation and a logical combine.
183 BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden,
184 cl::init(2),
185 cl::desc("Maximum cost of combining conditions when "
186 "folding branches"));
187
189 "simplifycfg-branch-fold-common-dest-vector-multiplier", cl::Hidden,
190 cl::init(2),
191 cl::desc("Multiplier to apply to threshold when determining whether or not "
192 "to fold branch to common destination when vector operations are "
193 "present"));
194
196 "simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(true),
197 cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"));
198
200 "max-switch-cases-per-result", cl::Hidden, cl::init(16),
201 cl::desc("Limit cases to analyze when converting a switch to select"));
202
204 "max-jump-threading-live-blocks", cl::Hidden, cl::init(24),
205 cl::desc("Limit number of blocks a define in a threaded block is allowed "
206 "to be live in"));
207
209
210} // end namespace llvm
211
212STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
213STATISTIC(NumLinearMaps,
214 "Number of switch instructions turned into linear mapping");
215STATISTIC(NumLookupTables,
216 "Number of switch instructions turned into lookup tables");
218 NumLookupTablesHoles,
219 "Number of switch instructions turned into lookup tables (holes checked)");
220STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
221STATISTIC(NumFoldValueComparisonIntoPredecessors,
222 "Number of value comparisons folded into predecessor basic blocks");
223STATISTIC(NumFoldBranchToCommonDest,
224 "Number of branches folded into predecessor basic block");
226 NumHoistCommonCode,
227 "Number of common instruction 'blocks' hoisted up to the begin block");
228STATISTIC(NumHoistCommonInstrs,
229 "Number of common instructions hoisted up to the begin block");
230STATISTIC(NumSinkCommonCode,
231 "Number of common instruction 'blocks' sunk down to the end block");
232STATISTIC(NumSinkCommonInstrs,
233 "Number of common instructions sunk down to the end block");
234STATISTIC(NumSpeculations, "Number of speculative executed instructions");
235STATISTIC(NumInvokes,
236 "Number of invokes with empty resume blocks simplified into calls");
237STATISTIC(NumInvokesMerged, "Number of invokes that were merged together");
238STATISTIC(NumInvokeSetsFormed, "Number of invoke sets that were formed");
239
240namespace {
241
242// The first field contains the value that the switch produces when a certain
243// case group is selected, and the second field is a vector containing the
244// cases composing the case group.
245using SwitchCaseResultVectorTy =
247
248// The first field contains the phi node that generates a result of the switch
249// and the second field contains the value generated for a certain case in the
250// switch for that PHI.
251using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
252
253/// ValueEqualityComparisonCase - Represents a case of a switch.
254struct ValueEqualityComparisonCase {
256 BasicBlock *Dest;
257
258 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
259 : Value(Value), Dest(Dest) {}
260
261 bool operator<(ValueEqualityComparisonCase RHS) const {
262 // Comparing pointers is ok as we only rely on the order for uniquing.
263 return Value < RHS.Value;
264 }
265
266 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
267};
268
269class SimplifyCFGOpt {
270 const TargetTransformInfo &TTI;
271 DomTreeUpdater *DTU;
272 const DataLayout &DL;
273 ArrayRef<WeakVH> LoopHeaders;
274 const SimplifyCFGOptions &Options;
275 bool Resimplify;
276
277 Value *isValueEqualityComparison(Instruction *TI);
278 BasicBlock *getValueEqualityComparisonCases(
279 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
280 bool simplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
281 BasicBlock *Pred,
282 IRBuilder<> &Builder);
283 bool performValueComparisonIntoPredecessorFolding(Instruction *TI, Value *&CV,
284 Instruction *PTI,
285 IRBuilder<> &Builder);
286 bool foldValueComparisonIntoPredecessors(Instruction *TI,
287 IRBuilder<> &Builder);
288
289 bool simplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
290 bool simplifySingleResume(ResumeInst *RI);
291 bool simplifyCommonResume(ResumeInst *RI);
292 bool simplifyCleanupReturn(CleanupReturnInst *RI);
293 bool simplifyUnreachable(UnreachableInst *UI);
294 bool simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
295 bool simplifyDuplicateSwitchArms(SwitchInst *SI, DomTreeUpdater *DTU);
296 bool simplifyIndirectBr(IndirectBrInst *IBI);
297 bool simplifyUncondBranch(UncondBrInst *BI, IRBuilder<> &Builder);
298 bool simplifyCondBranch(CondBrInst *BI, IRBuilder<> &Builder);
299 bool foldCondBranchOnValueKnownInPredecessor(CondBrInst *BI);
300
301 bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
302 IRBuilder<> &Builder);
303 bool tryToSimplifyUncondBranchWithICmpSelectInIt(ICmpInst *ICI,
304 SelectInst *Select,
305 IRBuilder<> &Builder);
306 bool hoistCommonCodeFromSuccessors(Instruction *TI, bool AllInstsEqOnly);
307 bool hoistSuccIdenticalTerminatorToSwitchOrIf(
308 Instruction *TI, Instruction *I1,
309 SmallVectorImpl<Instruction *> &OtherSuccTIs,
310 ArrayRef<BasicBlock *> UniqueSuccessors);
311 bool speculativelyExecuteBB(CondBrInst *BI, BasicBlock *ThenBB);
312 bool simplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
313 BasicBlock *TrueBB, BasicBlock *FalseBB,
314 uint32_t TrueWeight, uint32_t FalseWeight);
315 bool simplifyBranchOnICmpChain(CondBrInst *BI, IRBuilder<> &Builder,
316 const DataLayout &DL);
317 bool simplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select);
318 bool simplifySwitchOnSelectRemap(SwitchInst *SI, SelectInst *Select, Value *X,
319 ConstantInt *C, bool Negate);
320 bool simplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI);
321 bool turnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder);
322 bool simplifyDuplicatePredecessors(BasicBlock *Succ, DomTreeUpdater *DTU);
323
324public:
325 SimplifyCFGOpt(const TargetTransformInfo &TTI, DomTreeUpdater *DTU,
326 const DataLayout &DL, ArrayRef<WeakVH> LoopHeaders,
327 const SimplifyCFGOptions &Opts)
328 : TTI(TTI), DTU(DTU), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {
329 assert((!DTU || !DTU->hasPostDomTree()) &&
330 "SimplifyCFG is not yet capable of maintaining validity of a "
331 "PostDomTree, so don't ask for it.");
332 }
333
334 bool simplifyOnce(BasicBlock *BB);
335 bool run(BasicBlock *BB);
336
337 // Helper to set Resimplify and return change indication.
338 bool requestResimplify() {
339 Resimplify = true;
340 return true;
341 }
342};
343
344// we synthesize a || b as select a, true, b
345// we synthesize a && b as select a, b, false
346// this function determines if SI is playing one of those roles.
347[[maybe_unused]] bool
348isSelectInRoleOfConjunctionOrDisjunction(const SelectInst *SI) {
349 return ((isa<ConstantInt>(SI->getTrueValue()) &&
350 (dyn_cast<ConstantInt>(SI->getTrueValue())->isOne())) ||
351 (isa<ConstantInt>(SI->getFalseValue()) &&
352 (dyn_cast<ConstantInt>(SI->getFalseValue())->isNullValue())));
353}
354
355} // end anonymous namespace
356
357/// Return true if all the PHI nodes in the basic block \p BB
358/// receive compatible (identical) incoming values when coming from
359/// all of the predecessor blocks that are specified in \p IncomingBlocks.
360///
361/// Note that if the values aren't exactly identical, but \p EquivalenceSet
362/// is provided, and *both* of the values are present in the set,
363/// then they are considered equal.
365 BasicBlock *BB, ArrayRef<BasicBlock *> IncomingBlocks,
366 SmallPtrSetImpl<Value *> *EquivalenceSet = nullptr) {
367 assert(IncomingBlocks.size() == 2 &&
368 "Only for a pair of incoming blocks at the time!");
369
370 // FIXME: it is okay if one of the incoming values is an `undef` value,
371 // iff the other incoming value is guaranteed to be a non-poison value.
372 // FIXME: it is okay if one of the incoming values is a `poison` value.
373 return all_of(BB->phis(), [IncomingBlocks, EquivalenceSet](PHINode &PN) {
374 Value *IV0 = PN.getIncomingValueForBlock(IncomingBlocks[0]);
375 Value *IV1 = PN.getIncomingValueForBlock(IncomingBlocks[1]);
376 if (IV0 == IV1)
377 return true;
378 if (EquivalenceSet && EquivalenceSet->contains(IV0) &&
379 EquivalenceSet->contains(IV1))
380 return true;
381 return false;
382 });
383}
384
385/// Return true if it is safe to merge these two
386/// terminator instructions together.
387static bool
389 SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
390 if (SI1 == SI2)
391 return false; // Can't merge with self!
392
393 // It is not safe to merge these two switch instructions if they have a common
394 // successor, and if that successor has a PHI node, and if *that* PHI node has
395 // conflicting incoming values from the two switch blocks.
396 BasicBlock *SI1BB = SI1->getParent();
397 BasicBlock *SI2BB = SI2->getParent();
398
400 bool Fail = false;
401 for (BasicBlock *Succ : successors(SI2BB)) {
402 if (!SI1Succs.count(Succ))
403 continue;
404 if (incomingValuesAreCompatible(Succ, {SI1BB, SI2BB}))
405 continue;
406 Fail = true;
407 if (FailBlocks)
408 FailBlocks->insert(Succ);
409 else
410 break;
411 }
412
413 return !Fail;
414}
415
416/// Update PHI nodes in Succ to indicate that there will now be entries in it
417/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
418/// will be the same as those coming in from ExistPred, an existing predecessor
419/// of Succ.
420static void addPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
421 BasicBlock *ExistPred,
422 MemorySSAUpdater *MSSAU = nullptr) {
423 for (PHINode &PN : Succ->phis())
424 PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
425 if (MSSAU)
426 if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ))
427 MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred);
428}
429
430/// Compute an abstract "cost" of speculating the given instruction,
431/// which is assumed to be safe to speculate. TCC_Free means cheap,
432/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
433/// expensive.
435 const TargetTransformInfo &TTI) {
436 return TTI.getInstructionCost(I, TargetTransformInfo::TCK_SizeAndLatency);
437}
438
439/// If we have a merge point of an "if condition" as accepted above,
440/// return true if the specified value dominates the block. We don't handle
441/// the true generality of domination here, just a special case which works
442/// well enough for us.
443///
444/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
445/// see if V (which must be an instruction) and its recursive operands
446/// that do not dominate BB have a combined cost lower than Budget and
447/// are non-trapping. If both are true, the instruction is inserted into the
448/// set and true is returned.
449///
450/// The cost for most non-trapping instructions is defined as 1 except for
451/// Select whose cost is 2.
452///
453/// After this function returns, Cost is increased by the cost of
454/// V plus its non-dominating operands. If that cost is greater than
455/// Budget, false is returned and Cost is undefined.
457 Value *V, BasicBlock *BB, Instruction *InsertPt,
458 SmallPtrSetImpl<Instruction *> &AggressiveInsts, InstructionCost &Cost,
460 SmallPtrSetImpl<Instruction *> &ZeroCostInstructions, unsigned Depth = 0) {
461 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
462 // so limit the recursion depth.
463 // TODO: While this recursion limit does prevent pathological behavior, it
464 // would be better to track visited instructions to avoid cycles.
466 return false;
467
469 if (!I) {
470 // Non-instructions dominate all instructions and can be executed
471 // unconditionally.
472 return true;
473 }
474 BasicBlock *PBB = I->getParent();
475
476 // We don't want to allow weird loops that might have the "if condition" in
477 // the bottom of this block.
478 if (PBB == BB)
479 return false;
480
481 // If this instruction is defined in a block that contains an unconditional
482 // branch to BB, then it must be in the 'conditional' part of the "if
483 // statement". If not, it definitely dominates the region.
485 if (!BI || BI->getSuccessor() != BB)
486 return true;
487
488 // If we have seen this instruction before, don't count it again.
489 if (AggressiveInsts.count(I))
490 return true;
491
492 // Okay, it looks like the instruction IS in the "condition". Check to
493 // see if it's a cheap instruction to unconditionally compute, and if it
494 // only uses stuff defined outside of the condition. If so, hoist it out.
495 if (!isSafeToSpeculativelyExecute(I, InsertPt, AC))
496 return false;
497
498 // Overflow arithmetic instruction plus extract value are usually generated
499 // when a division is being replaced. But, in this case, the zero check may
500 // still be kept in the code. In that case it would be worth to hoist these
501 // two instruction out of the basic block. Let's treat this pattern as one
502 // single cheap instruction here!
503 WithOverflowInst *OverflowInst;
504 if (match(I, m_ExtractValue<1>(m_OneUse(m_WithOverflowInst(OverflowInst))))) {
505 ZeroCostInstructions.insert(OverflowInst);
506 Cost += 1;
507 } else if (!ZeroCostInstructions.contains(I))
508 Cost += computeSpeculationCost(I, TTI);
509
510 // Allow exactly one instruction to be speculated regardless of its cost
511 // (as long as it is safe to do so).
512 // This is intended to flatten the CFG even if the instruction is a division
513 // or other expensive operation. The speculation of an expensive instruction
514 // is expected to be undone in CodeGenPrepare if the speculation has not
515 // enabled further IR optimizations.
516 if (Cost > Budget &&
517 (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0 ||
518 !Cost.isValid()))
519 return false;
520
521 // Okay, we can only really hoist these out if their operands do
522 // not take us over the cost threshold.
523 for (Use &Op : I->operands())
524 if (!dominatesMergePoint(Op, BB, InsertPt, AggressiveInsts, Cost, Budget,
525 TTI, AC, ZeroCostInstructions, Depth + 1))
526 return false;
527 // Okay, it's safe to do this! Remember this instruction.
528 AggressiveInsts.insert(I);
529 return true;
530}
531
532/// Extract ConstantInt from value, looking through IntToPtr
533/// and PointerNullValue. Return NULL if value is not a constant int.
535 // Normal constant int.
537 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
538 return CI;
539
540 // It is not safe to look through inttoptr or ptrtoint when using unstable
541 // pointer types.
542 if (DL.hasUnstableRepresentation(V->getType()))
543 return nullptr;
544
545 // This is some kind of pointer constant. Turn it into a pointer-sized
546 // ConstantInt if possible.
547 IntegerType *IntPtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
548
549 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
551 return ConstantInt::get(IntPtrTy, 0);
552
553 // IntToPtr const int, we can look through this if the semantics of
554 // inttoptr for this address space are a simple (truncating) bitcast.
556 if (CE->getOpcode() == Instruction::IntToPtr)
557 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
558 // The constant is very likely to have the right type already.
559 if (CI->getType() == IntPtrTy)
560 return CI;
561 else
562 return cast<ConstantInt>(
563 ConstantFoldIntegerCast(CI, IntPtrTy, /*isSigned=*/false, DL));
564 }
565 return nullptr;
566}
567
568namespace {
569
570/// Given a chain of or (||) or and (&&) comparison of a value against a
571/// constant, this will try to recover the information required for a switch
572/// structure.
573/// It will depth-first traverse the chain of comparison, seeking for patterns
574/// like %a == 12 or %a < 4 and combine them to produce a set of integer
575/// representing the different cases for the switch.
576/// Note that if the chain is composed of '||' it will build the set of elements
577/// that matches the comparisons (i.e. any of this value validate the chain)
578/// while for a chain of '&&' it will build the set elements that make the test
579/// fail.
580struct ConstantComparesGatherer {
581 const DataLayout &DL;
582
583 /// Value found for the switch comparison
584 Value *CompValue = nullptr;
585
586 /// Extra clause to be checked before the switch
587 Value *Extra = nullptr;
588
589 /// Set of integers to match in switch
591
592 /// Number of comparisons matched in the and/or chain
593 unsigned UsedICmps = 0;
594
595 /// If the elements in Vals matches the comparisons
596 bool IsEq = false;
597
598 // Used to check if the first matched CompValue shall be the Extra check.
599 bool IgnoreFirstMatch = false;
600 bool MultipleMatches = false;
601
602 /// Construct and compute the result for the comparison instruction Cond
603 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
604 gather(Cond);
605 if (CompValue || !MultipleMatches)
606 return;
607 Extra = nullptr;
608 Vals.clear();
609 UsedICmps = 0;
610 IgnoreFirstMatch = true;
611 gather(Cond);
612 }
613
614 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
615 ConstantComparesGatherer &
616 operator=(const ConstantComparesGatherer &) = delete;
617
618private:
619 /// Try to set the current value used for the comparison, it succeeds only if
620 /// it wasn't set before or if the new value is the same as the old one
621 bool setValueOnce(Value *NewVal) {
622 if (IgnoreFirstMatch) {
623 IgnoreFirstMatch = false;
624 return false;
625 }
626 if (CompValue && CompValue != NewVal) {
627 MultipleMatches = true;
628 return false;
629 }
630 CompValue = NewVal;
631 return true;
632 }
633
634 /// Try to match Instruction "I" as a comparison against a constant and
635 /// populates the array Vals with the set of values that match (or do not
636 /// match depending on isEQ).
637 /// Return false on failure. On success, the Value the comparison matched
638 /// against is placed in CompValue.
639 /// If CompValue is already set, the function is expected to fail if a match
640 /// is found but the value compared to is different.
641 bool matchInstruction(Instruction *I, bool isEQ) {
642 if (match(I, m_Not(m_Instruction(I))))
643 isEQ = !isEQ;
644
645 Value *Val;
646 if (match(I, m_NUWTrunc(m_Value(Val)))) {
647 // If we already have a value for the switch, it has to match!
648 if (!setValueOnce(Val))
649 return false;
650 UsedICmps++;
651 Vals.push_back(ConstantInt::get(cast<IntegerType>(Val->getType()), isEQ));
652 return true;
653 }
654 // If this is an icmp against a constant, handle this as one of the cases.
655 ICmpInst *ICI;
656 ConstantInt *C;
657 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
658 (C = getConstantInt(I->getOperand(1), DL)))) {
659 return false;
660 }
661
662 Value *RHSVal;
663 const APInt *RHSC;
664
665 // Pattern match a special case
666 // (x & ~2^z) == y --> x == y || x == y|2^z
667 // This undoes a transformation done by instcombine to fuse 2 compares.
668 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
669 // It's a little bit hard to see why the following transformations are
670 // correct. Here is a CVC3 program to verify them for 64-bit values:
671
672 /*
673 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
674 x : BITVECTOR(64);
675 y : BITVECTOR(64);
676 z : BITVECTOR(64);
677 mask : BITVECTOR(64) = BVSHL(ONE, z);
678 QUERY( (y & ~mask = y) =>
679 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
680 );
681 QUERY( (y | mask = y) =>
682 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
683 );
684 */
685
686 // Please note that each pattern must be a dual implication (<--> or
687 // iff). One directional implication can create spurious matches. If the
688 // implication is only one-way, an unsatisfiable condition on the left
689 // side can imply a satisfiable condition on the right side. Dual
690 // implication ensures that satisfiable conditions are transformed to
691 // other satisfiable conditions and unsatisfiable conditions are
692 // transformed to other unsatisfiable conditions.
693
694 // Here is a concrete example of a unsatisfiable condition on the left
695 // implying a satisfiable condition on the right:
696 //
697 // mask = (1 << z)
698 // (x & ~mask) == y --> (x == y || x == (y | mask))
699 //
700 // Substituting y = 3, z = 0 yields:
701 // (x & -2) == 3 --> (x == 3 || x == 2)
702
703 // Pattern match a special case:
704 /*
705 QUERY( (y & ~mask = y) =>
706 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
707 );
708 */
709 if (match(ICI->getOperand(0),
710 m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
711 APInt Mask = ~*RHSC;
712 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
713 // If we already have a value for the switch, it has to match!
714 if (!setValueOnce(RHSVal))
715 return false;
716
717 Vals.push_back(C);
718 Vals.push_back(
719 ConstantInt::get(C->getContext(),
720 C->getValue() | Mask));
721 UsedICmps++;
722 return true;
723 }
724 }
725
726 // Pattern match a special case:
727 /*
728 QUERY( (y | mask = y) =>
729 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
730 );
731 */
732 if (match(ICI->getOperand(0),
733 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
734 APInt Mask = *RHSC;
735 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
736 // If we already have a value for the switch, it has to match!
737 if (!setValueOnce(RHSVal))
738 return false;
739
740 Vals.push_back(C);
741 Vals.push_back(ConstantInt::get(C->getContext(),
742 C->getValue() & ~Mask));
743 UsedICmps++;
744 return true;
745 }
746 }
747
748 // If we already have a value for the switch, it has to match!
749 if (!setValueOnce(ICI->getOperand(0)))
750 return false;
751
752 UsedICmps++;
753 Vals.push_back(C);
754 return true;
755 }
756
757 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
758 ConstantRange Span =
760
761 // Shift the range if the compare is fed by an add. This is the range
762 // compare idiom as emitted by instcombine.
763 Value *CandidateVal = I->getOperand(0);
764 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
765 Span = Span.subtract(*RHSC);
766 CandidateVal = RHSVal;
767 }
768
769 // If this is an and/!= check, then we are looking to build the set of
770 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
771 // x != 0 && x != 1.
772 if (!isEQ)
773 Span = Span.inverse();
774
775 // If there are a ton of values, we don't want to make a ginormous switch.
776 if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
777 return false;
778 }
779
780 // If we already have a value for the switch, it has to match!
781 if (!setValueOnce(CandidateVal))
782 return false;
783
784 // Add all values from the range to the set
785 APInt Tmp = Span.getLower();
786 do
787 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
788 while (++Tmp != Span.getUpper());
789
790 UsedICmps++;
791 return true;
792 }
793
794 /// Given a potentially 'or'd or 'and'd together collection of icmp
795 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
796 /// the value being compared, and stick the list constants into the Vals
797 /// vector.
798 /// One "Extra" case is allowed to differ from the other.
799 void gather(Value *V) {
800 Value *Op0, *Op1;
801 if (match(V, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
802 IsEq = true;
803 else if (match(V, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
804 IsEq = false;
805 else
806 return;
807 // Keep a stack (SmallVector for efficiency) for depth-first traversal
808 SmallVector<Value *, 8> DFT{Op0, Op1};
809 SmallPtrSet<Value *, 8> Visited{V, Op0, Op1};
810
811 while (!DFT.empty()) {
812 V = DFT.pop_back_val();
813
814 if (Instruction *I = dyn_cast<Instruction>(V)) {
815 // If it is a || (or && depending on isEQ), process the operands.
816 if (IsEq ? match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1)))
817 : match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
818 if (Visited.insert(Op1).second)
819 DFT.push_back(Op1);
820 if (Visited.insert(Op0).second)
821 DFT.push_back(Op0);
822
823 continue;
824 }
825
826 // Try to match the current instruction
827 if (matchInstruction(I, IsEq))
828 // Match succeed, continue the loop
829 continue;
830 }
831
832 // One element of the sequence of || (or &&) could not be match as a
833 // comparison against the same value as the others.
834 // We allow only one "Extra" case to be checked before the switch
835 if (!Extra) {
836 Extra = V;
837 continue;
838 }
839 // Failed to parse a proper sequence, abort now
840 CompValue = nullptr;
841 break;
842 }
843 }
844};
845
846} // end anonymous namespace
847
849 MemorySSAUpdater *MSSAU = nullptr) {
850 Instruction *Cond = nullptr;
852 Cond = dyn_cast<Instruction>(SI->getCondition());
853 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
854 Cond = dyn_cast<Instruction>(BI->getCondition());
855 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
856 Cond = dyn_cast<Instruction>(IBI->getAddress());
857 }
858
859 TI->eraseFromParent();
860 if (Cond)
862}
863
864/// Return true if the specified terminator checks
865/// to see if a value is equal to constant integer value.
866Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
867 Value *CV = nullptr;
868 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
869 // Do not permit merging of large switch instructions into their
870 // predecessors unless there is only one predecessor.
871 if (!SI->getParent()->hasNPredecessorsOrMore(128 / SI->getNumSuccessors()))
872 CV = SI->getCondition();
873 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(TI))
874 if (BI->getCondition()->hasOneUse()) {
875 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
876 if (ICI->isEquality() && getConstantInt(ICI->getOperand(1), DL))
877 CV = ICI->getOperand(0);
878 } else if (auto *Trunc = dyn_cast<TruncInst>(BI->getCondition())) {
879 if (Trunc->hasNoUnsignedWrap())
880 CV = Trunc->getOperand(0);
881 }
882 }
883
884 // Unwrap any lossless ptrtoint cast (except for unstable pointers).
885 if (CV) {
886 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
887 Value *Ptr = PTII->getPointerOperand();
888 if (DL.hasUnstableRepresentation(Ptr->getType()))
889 return CV;
890 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
891 CV = Ptr;
892 }
893 }
894 return CV;
895}
896
897/// Given a value comparison instruction,
898/// decode all of the 'cases' that it represents and return the 'default' block.
899BasicBlock *SimplifyCFGOpt::getValueEqualityComparisonCases(
900 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
901 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
902 Cases.reserve(SI->getNumCases());
903 for (auto Case : SI->cases())
904 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
905 Case.getCaseSuccessor()));
906 return SI->getDefaultDest();
907 }
908
909 CondBrInst *BI = cast<CondBrInst>(TI);
910 Value *Cond = BI->getCondition();
911 ICmpInst::Predicate Pred;
912 ConstantInt *C;
913 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
914 Pred = ICI->getPredicate();
915 C = getConstantInt(ICI->getOperand(1), DL);
916 } else {
917 Pred = ICmpInst::ICMP_NE;
918 auto *Trunc = cast<TruncInst>(Cond);
919 C = ConstantInt::get(cast<IntegerType>(Trunc->getOperand(0)->getType()), 0);
920 }
921 BasicBlock *Succ = BI->getSuccessor(Pred == ICmpInst::ICMP_NE);
922 Cases.push_back(ValueEqualityComparisonCase(C, Succ));
923 return BI->getSuccessor(Pred == ICmpInst::ICMP_EQ);
924}
925
926/// Given a vector of bb/value pairs, remove any entries
927/// in the list that match the specified block.
928static void
930 std::vector<ValueEqualityComparisonCase> &Cases) {
931 llvm::erase(Cases, BB);
932}
933
934/// Return true if there are any keys in C1 that exist in C2 as well.
935static bool valuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
936 std::vector<ValueEqualityComparisonCase> &C2) {
937 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
938
939 // Make V1 be smaller than V2.
940 if (V1->size() > V2->size())
941 std::swap(V1, V2);
942
943 if (V1->empty())
944 return false;
945 if (V1->size() == 1) {
946 // Just scan V2.
947 ConstantInt *TheVal = (*V1)[0].Value;
948 for (const ValueEqualityComparisonCase &VECC : *V2)
949 if (TheVal == VECC.Value)
950 return true;
951 }
952
953 // Otherwise, just sort both lists and compare element by element.
954 array_pod_sort(V1->begin(), V1->end());
955 array_pod_sort(V2->begin(), V2->end());
956 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
957 while (i1 != e1 && i2 != e2) {
958 if ((*V1)[i1].Value == (*V2)[i2].Value)
959 return true;
960 if ((*V1)[i1].Value < (*V2)[i2].Value)
961 ++i1;
962 else
963 ++i2;
964 }
965 return false;
966}
967
968/// If TI is known to be a terminator instruction and its block is known to
969/// only have a single predecessor block, check to see if that predecessor is
970/// also a value comparison with the same value, and if that comparison
971/// determines the outcome of this comparison. If so, simplify TI. This does a
972/// very limited form of jump threading.
973bool SimplifyCFGOpt::simplifyEqualityComparisonWithOnlyPredecessor(
974 Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
975 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
976 if (!PredVal)
977 return false; // Not a value comparison in predecessor.
978
979 Value *ThisVal = isValueEqualityComparison(TI);
980 assert(ThisVal && "This isn't a value comparison!!");
981 if (ThisVal != PredVal)
982 return false; // Different predicates.
983
984 // TODO: Preserve branch weight metadata, similarly to how
985 // foldValueComparisonIntoPredecessors preserves it.
986
987 // Find out information about when control will move from Pred to TI's block.
988 std::vector<ValueEqualityComparisonCase> PredCases;
989 BasicBlock *PredDef =
990 getValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
991 eliminateBlockCases(PredDef, PredCases); // Remove default from cases.
992
993 // Find information about how control leaves this block.
994 std::vector<ValueEqualityComparisonCase> ThisCases;
995 BasicBlock *ThisDef = getValueEqualityComparisonCases(TI, ThisCases);
996 eliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
997
998 // If TI's block is the default block from Pred's comparison, potentially
999 // simplify TI based on this knowledge.
1000 if (PredDef == TI->getParent()) {
1001 // If we are here, we know that the value is none of those cases listed in
1002 // PredCases. If there are any cases in ThisCases that are in PredCases, we
1003 // can simplify TI.
1004 if (!valuesOverlap(PredCases, ThisCases))
1005 return false;
1006
1007 if (isa<CondBrInst>(TI)) {
1008 // Okay, one of the successors of this condbr is dead. Convert it to a
1009 // uncond br.
1010 assert(ThisCases.size() == 1 && "Branch can only have one case!");
1011 // Insert the new branch.
1012 Instruction *NI = Builder.CreateBr(ThisDef);
1013 (void)NI;
1014
1015 // Remove PHI node entries for the dead edge.
1016 ThisCases[0].Dest->removePredecessor(PredDef);
1017
1018 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1019 << "Through successor TI: " << *TI << "Leaving: " << *NI
1020 << "\n");
1021
1023
1024 if (DTU)
1025 DTU->applyUpdates(
1026 {{DominatorTree::Delete, PredDef, ThisCases[0].Dest}});
1027
1028 return true;
1029 }
1030
1031 SwitchInstProfUpdateWrapper SI = *cast<SwitchInst>(TI);
1032 // Okay, TI has cases that are statically dead, prune them away.
1033 SmallPtrSet<Constant *, 16> DeadCases;
1034 for (const ValueEqualityComparisonCase &Case : PredCases)
1035 DeadCases.insert(Case.Value);
1036
1037 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1038 << "Through successor TI: " << *TI);
1039
1040 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
1041 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
1042 --i;
1043 auto *Successor = i->getCaseSuccessor();
1044 if (DTU)
1045 ++NumPerSuccessorCases[Successor];
1046 if (DeadCases.count(i->getCaseValue())) {
1047 Successor->removePredecessor(PredDef);
1048 SI.removeCase(i);
1049 if (DTU)
1050 --NumPerSuccessorCases[Successor];
1051 }
1052 }
1053
1054 if (DTU) {
1055 std::vector<DominatorTree::UpdateType> Updates;
1056 for (const auto &I : NumPerSuccessorCases)
1057 if (I.second == 0)
1058 Updates.push_back({DominatorTree::Delete, PredDef, I.first});
1059 DTU->applyUpdates(Updates);
1060 }
1061
1062 LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n");
1063 return true;
1064 }
1065
1066 // Otherwise, TI's block must correspond to some matched value. Find out
1067 // which value (or set of values) this is.
1068 ConstantInt *TIV = nullptr;
1069 BasicBlock *TIBB = TI->getParent();
1070 for (const auto &[Value, Dest] : PredCases)
1071 if (Dest == TIBB) {
1072 if (TIV)
1073 return false; // Cannot handle multiple values coming to this block.
1074 TIV = Value;
1075 }
1076 assert(TIV && "No edge from pred to succ?");
1077
1078 // Okay, we found the one constant that our value can be if we get into TI's
1079 // BB. Find out which successor will unconditionally be branched to.
1080 BasicBlock *TheRealDest = nullptr;
1081 for (const auto &[Value, Dest] : ThisCases)
1082 if (Value == TIV) {
1083 TheRealDest = Dest;
1084 break;
1085 }
1086
1087 // If not handled by any explicit cases, it is handled by the default case.
1088 if (!TheRealDest)
1089 TheRealDest = ThisDef;
1090
1091 SmallPtrSet<BasicBlock *, 2> RemovedSuccs;
1092
1093 // Remove PHI node entries for dead edges.
1094 BasicBlock *CheckEdge = TheRealDest;
1095 for (BasicBlock *Succ : successors(TIBB))
1096 if (Succ != CheckEdge) {
1097 if (Succ != TheRealDest)
1098 RemovedSuccs.insert(Succ);
1099 Succ->removePredecessor(TIBB);
1100 } else
1101 CheckEdge = nullptr;
1102
1103 // Insert the new branch.
1104 Instruction *NI = Builder.CreateBr(TheRealDest);
1105 (void)NI;
1106
1107 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1108 << "Through successor TI: " << *TI << "Leaving: " << *NI
1109 << "\n");
1110
1112 if (DTU) {
1113 SmallVector<DominatorTree::UpdateType, 2> Updates;
1114 Updates.reserve(RemovedSuccs.size());
1115 for (auto *RemovedSucc : RemovedSuccs)
1116 Updates.push_back({DominatorTree::Delete, TIBB, RemovedSucc});
1117 DTU->applyUpdates(Updates);
1118 }
1119 return true;
1120}
1121
1122namespace {
1123
1124/// This class implements a stable ordering of constant
1125/// integers that does not depend on their address. This is important for
1126/// applications that sort ConstantInt's to ensure uniqueness.
1127struct ConstantIntOrdering {
1128 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1129 return LHS->getValue().ult(RHS->getValue());
1130 }
1131};
1132
1133} // end anonymous namespace
1134
1136 ConstantInt *const *P2) {
1137 const ConstantInt *LHS = *P1;
1138 const ConstantInt *RHS = *P2;
1139 if (LHS == RHS)
1140 return 0;
1141 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
1142}
1143
1144/// Get Weights of a given terminator, the default weight is at the front
1145/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
1146/// metadata.
1148 SmallVectorImpl<uint64_t> &Weights) {
1149 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
1150 assert(MD && "Invalid branch-weight metadata");
1151 extractFromBranchWeightMD64(MD, Weights);
1152
1153 // If TI is a conditional eq, the default case is the false case,
1154 // and the corresponding branch-weight data is at index 2. We swap the
1155 // default weight to be the first entry.
1156 if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
1157 assert(Weights.size() == 2);
1158 auto *ICI = dyn_cast<ICmpInst>(BI->getCondition());
1159 if (!ICI)
1160 return;
1161
1162 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1163 std::swap(Weights.front(), Weights.back());
1164 }
1165}
1166
1168 BasicBlock *BB, BasicBlock *PredBlock, ValueToValueMapTy &VMap) {
1169 Instruction *PTI = PredBlock->getTerminator();
1170
1171 // If we have bonus instructions, clone them into the predecessor block.
1172 // Note that there may be multiple predecessor blocks, so we cannot move
1173 // bonus instructions to a predecessor block.
1174 for (Instruction &BonusInst : *BB) {
1175 if (BonusInst.isTerminator())
1176 continue;
1177
1178 // Skip cloning pseudo probes into the predecessor, as it would overcount
1179 // otherwise.
1180 if (isa<PseudoProbeInst>(BonusInst))
1181 continue;
1182
1183 Instruction *NewBonusInst = BonusInst.clone();
1184 NewBonusInst->insertInto(PredBlock, PTI->getIterator());
1185
1186 if (!NewBonusInst->getDebugLoc().isSameSourceLocation(PTI->getDebugLoc())) {
1187 // Unless the instruction has the same !dbg location as the original
1188 // branch, drop it. When we fold the bonus instructions we want to make
1189 // sure we reset their debug locations in order to avoid stepping on
1190 // dead code caused by folding dead branches.
1191 NewBonusInst->dropLocation();
1192 } else if (const DebugLoc &DL = NewBonusInst->getDebugLoc()) {
1193 mapAtomInstance(DL, VMap);
1194 }
1195
1196 RemapInstruction(NewBonusInst, VMap,
1198
1199 // If we speculated an instruction, we need to drop any metadata that may
1200 // result in undefined behavior, as the metadata might have been valid
1201 // only given the branch precondition.
1202 // Similarly strip attributes on call parameters that may cause UB in
1203 // location the call is moved to.
1204 NewBonusInst->dropUBImplyingAttrsAndMetadata();
1205
1206 auto Range = NewBonusInst->cloneDebugInfoFrom(&BonusInst);
1207 RemapDbgRecordRange(NewBonusInst->getModule(), Range, VMap,
1209
1210 NewBonusInst->takeName(&BonusInst);
1211 BonusInst.setName(NewBonusInst->getName() + ".old");
1212 VMap[&BonusInst] = NewBonusInst;
1213
1214 // Update (liveout) uses of bonus instructions,
1215 // now that the bonus instruction has been cloned into predecessor.
1216 // Note that we expect to be in a block-closed SSA form for this to work!
1217 for (Use &U : make_early_inc_range(BonusInst.uses())) {
1218 auto *UI = cast<Instruction>(U.getUser());
1219 auto *PN = dyn_cast<PHINode>(UI);
1220 if (!PN) {
1221 assert(UI->getParent() == BB && BonusInst.comesBefore(UI) &&
1222 "If the user is not a PHI node, then it should be in the same "
1223 "block as, and come after, the original bonus instruction.");
1224 continue; // Keep using the original bonus instruction.
1225 }
1226 // Is this the block-closed SSA form PHI node?
1227 if (PN->getIncomingBlock(U) == BB)
1228 continue; // Great, keep using the original bonus instruction.
1229 // The only other alternative is an "use" when coming from
1230 // the predecessor block - here we should refer to the cloned bonus instr.
1231 assert(PN->getIncomingBlock(U) == PredBlock &&
1232 "Not in block-closed SSA form?");
1233 U.set(NewBonusInst);
1234 }
1235 }
1236
1237 // Key Instructions: We may have propagated atom info into the pred. If the
1238 // pred's terminator already has atom info do nothing as merging would drop
1239 // one atom group anyway. If it doesn't, propagte the remapped atom group
1240 // from BB's terminator.
1241 if (auto &PredDL = PTI->getDebugLoc()) {
1242 auto &DL = BB->getTerminator()->getDebugLoc();
1243 if (!PredDL->getAtomGroup() && DL && DL->getAtomGroup() &&
1244 PredDL.isSameSourceLocation(DL)) {
1245 PTI->setDebugLoc(DL);
1246 RemapSourceAtom(PTI, VMap);
1247 }
1248 }
1249}
1250
1251bool SimplifyCFGOpt::performValueComparisonIntoPredecessorFolding(
1252 Instruction *TI, Value *&CV, Instruction *PTI, IRBuilder<> &Builder) {
1253 BasicBlock *BB = TI->getParent();
1254 BasicBlock *Pred = PTI->getParent();
1255
1257
1258 // Figure out which 'cases' to copy from SI to PSI.
1259 std::vector<ValueEqualityComparisonCase> BBCases;
1260 BasicBlock *BBDefault = getValueEqualityComparisonCases(TI, BBCases);
1261
1262 std::vector<ValueEqualityComparisonCase> PredCases;
1263 BasicBlock *PredDefault = getValueEqualityComparisonCases(PTI, PredCases);
1264
1265 // Based on whether the default edge from PTI goes to BB or not, fill in
1266 // PredCases and PredDefault with the new switch cases we would like to
1267 // build.
1268 SmallMapVector<BasicBlock *, int, 8> NewSuccessors;
1269
1270 // Update the branch weight metadata along the way
1271 SmallVector<uint64_t, 8> Weights;
1272 bool PredHasWeights = hasBranchWeightMD(*PTI);
1273 bool SuccHasWeights = hasBranchWeightMD(*TI);
1274
1275 if (PredHasWeights) {
1276 getBranchWeights(PTI, Weights);
1277 // branch-weight metadata is inconsistent here.
1278 if (Weights.size() != 1 + PredCases.size())
1279 PredHasWeights = SuccHasWeights = false;
1280 } else if (SuccHasWeights)
1281 // If there are no predecessor weights but there are successor weights,
1282 // populate Weights with 1, which will later be scaled to the sum of
1283 // successor's weights
1284 Weights.assign(1 + PredCases.size(), 1);
1285
1286 SmallVector<uint64_t, 8> SuccWeights;
1287 if (SuccHasWeights) {
1288 getBranchWeights(TI, SuccWeights);
1289 // branch-weight metadata is inconsistent here.
1290 if (SuccWeights.size() != 1 + BBCases.size())
1291 PredHasWeights = SuccHasWeights = false;
1292 } else if (PredHasWeights)
1293 SuccWeights.assign(1 + BBCases.size(), 1);
1294
1295 if (PredDefault == BB) {
1296 // If this is the default destination from PTI, only the edges in TI
1297 // that don't occur in PTI, or that branch to BB will be activated.
1298 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1299 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1300 if (PredCases[i].Dest != BB)
1301 PTIHandled.insert(PredCases[i].Value);
1302 else {
1303 // The default destination is BB, we don't need explicit targets.
1304 std::swap(PredCases[i], PredCases.back());
1305
1306 if (PredHasWeights || SuccHasWeights) {
1307 // Increase weight for the default case.
1308 Weights[0] += Weights[i + 1];
1309 std::swap(Weights[i + 1], Weights.back());
1310 Weights.pop_back();
1311 }
1312
1313 PredCases.pop_back();
1314 --i;
1315 --e;
1316 }
1317
1318 // Reconstruct the new switch statement we will be building.
1319 if (PredDefault != BBDefault) {
1320 PredDefault->removePredecessor(Pred);
1321 if (DTU && PredDefault != BB)
1322 Updates.push_back({DominatorTree::Delete, Pred, PredDefault});
1323 PredDefault = BBDefault;
1324 ++NewSuccessors[BBDefault];
1325 }
1326
1327 unsigned CasesFromPred = Weights.size();
1328 uint64_t ValidTotalSuccWeight = 0;
1329 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1330 if (!PTIHandled.count(BBCases[i].Value) && BBCases[i].Dest != BBDefault) {
1331 PredCases.push_back(BBCases[i]);
1332 ++NewSuccessors[BBCases[i].Dest];
1333 if (SuccHasWeights || PredHasWeights) {
1334 // The default weight is at index 0, so weight for the ith case
1335 // should be at index i+1. Scale the cases from successor by
1336 // PredDefaultWeight (Weights[0]).
1337 Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1338 ValidTotalSuccWeight += SuccWeights[i + 1];
1339 }
1340 }
1341
1342 if (SuccHasWeights || PredHasWeights) {
1343 ValidTotalSuccWeight += SuccWeights[0];
1344 // Scale the cases from predecessor by ValidTotalSuccWeight.
1345 for (unsigned i = 1; i < CasesFromPred; ++i)
1346 Weights[i] *= ValidTotalSuccWeight;
1347 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1348 Weights[0] *= SuccWeights[0];
1349 }
1350 } else {
1351 // If this is not the default destination from PSI, only the edges
1352 // in SI that occur in PSI with a destination of BB will be
1353 // activated.
1354 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1355 std::map<ConstantInt *, uint64_t> WeightsForHandled;
1356 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1357 if (PredCases[i].Dest == BB) {
1358 PTIHandled.insert(PredCases[i].Value);
1359
1360 if (PredHasWeights || SuccHasWeights) {
1361 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1362 std::swap(Weights[i + 1], Weights.back());
1363 Weights.pop_back();
1364 }
1365
1366 std::swap(PredCases[i], PredCases.back());
1367 PredCases.pop_back();
1368 --i;
1369 --e;
1370 }
1371
1372 // Okay, now we know which constants were sent to BB from the
1373 // predecessor. Figure out where they will all go now.
1374 for (const ValueEqualityComparisonCase &Case : BBCases)
1375 if (PTIHandled.count(Case.Value)) {
1376 // If this is one we are capable of getting...
1377 if (PredHasWeights || SuccHasWeights)
1378 Weights.push_back(WeightsForHandled[Case.Value]);
1379 PredCases.push_back(Case);
1380 ++NewSuccessors[Case.Dest];
1381 PTIHandled.erase(Case.Value); // This constant is taken care of
1382 }
1383
1384 // If there are any constants vectored to BB that TI doesn't handle,
1385 // they must go to the default destination of TI.
1386 for (ConstantInt *I : PTIHandled) {
1387 if (PredHasWeights || SuccHasWeights)
1388 Weights.push_back(WeightsForHandled[I]);
1389 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1390 ++NewSuccessors[BBDefault];
1391 }
1392 }
1393
1394 // Okay, at this point, we know which new successor Pred will get. Make
1395 // sure we update the number of entries in the PHI nodes for these
1396 // successors.
1397 SmallPtrSet<BasicBlock *, 2> SuccsOfPred;
1398 if (DTU) {
1399 SuccsOfPred = {llvm::from_range, successors(Pred)};
1400 Updates.reserve(Updates.size() + NewSuccessors.size());
1401 }
1402 for (const std::pair<BasicBlock *, int /*Num*/> &NewSuccessor :
1403 NewSuccessors) {
1404 for (auto I : seq(NewSuccessor.second)) {
1405 (void)I;
1406 addPredecessorToBlock(NewSuccessor.first, Pred, BB);
1407 }
1408 if (DTU && !SuccsOfPred.contains(NewSuccessor.first))
1409 Updates.push_back({DominatorTree::Insert, Pred, NewSuccessor.first});
1410 }
1411
1412 Builder.SetInsertPoint(PTI);
1413 // Convert pointer to int before we switch.
1414 if (CV->getType()->isPointerTy()) {
1415 assert(!DL.hasUnstableRepresentation(CV->getType()) &&
1416 "Should not end up here with unstable pointers");
1417 CV =
1418 Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), "magicptr");
1419 }
1420
1421 // Now that the successors are updated, create the new Switch instruction.
1422 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, PredCases.size());
1423 NewSI->setDebugLoc(PTI->getDebugLoc());
1424 for (ValueEqualityComparisonCase &V : PredCases)
1425 NewSI->addCase(V.Value, V.Dest);
1426
1427 if (PredHasWeights || SuccHasWeights)
1428 setFittedBranchWeights(*NewSI, Weights, /*IsExpected=*/false,
1429 /*ElideAllZero=*/true);
1430
1431 // The new switch is only known to be unpredictable if both of the comparisons
1432 // it was built from were unpredictable.
1433 if (MDNode *Unpredictable = PTI->getMetadata(LLVMContext::MD_unpredictable))
1434 if (TI->hasMetadata(LLVMContext::MD_unpredictable))
1435 NewSI->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
1436
1438
1439 // Okay, last check. If BB is still a successor of PSI, then we must
1440 // have an infinite loop case. If so, add an infinitely looping block
1441 // to handle the case to preserve the behavior of the code.
1442 BasicBlock *InfLoopBlock = nullptr;
1443 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1444 if (NewSI->getSuccessor(i) == BB) {
1445 if (!InfLoopBlock) {
1446 // Insert it at the end of the function, because it's either code,
1447 // or it won't matter if it's hot. :)
1448 InfLoopBlock =
1449 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
1450 UncondBrInst::Create(InfLoopBlock, InfLoopBlock);
1451 if (DTU)
1452 Updates.push_back(
1453 {DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
1454 }
1455 NewSI->setSuccessor(i, InfLoopBlock);
1456 }
1457
1458 if (DTU) {
1459 if (InfLoopBlock)
1460 Updates.push_back({DominatorTree::Insert, Pred, InfLoopBlock});
1461
1462 Updates.push_back({DominatorTree::Delete, Pred, BB});
1463
1464 DTU->applyUpdates(Updates);
1465 }
1466
1467 ++NumFoldValueComparisonIntoPredecessors;
1468 return true;
1469}
1470
1471/// The specified terminator is a value equality comparison instruction
1472/// (either a switch or a branch on "X == c").
1473/// See if any of the predecessors of the terminator block are value comparisons
1474/// on the same value. If so, and if safe to do so, fold them together.
1475bool SimplifyCFGOpt::foldValueComparisonIntoPredecessors(Instruction *TI,
1476 IRBuilder<> &Builder) {
1477 BasicBlock *BB = TI->getParent();
1478 Value *CV = isValueEqualityComparison(TI); // CondVal
1479 assert(CV && "Not a comparison?");
1480
1481 bool Changed = false;
1482
1483 SmallSetVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
1484 while (!Preds.empty()) {
1485 BasicBlock *Pred = Preds.pop_back_val();
1486 Instruction *PTI = Pred->getTerminator();
1487
1488 // Don't try to fold into itself.
1489 if (Pred == BB)
1490 continue;
1491
1492 // See if the predecessor is a comparison with the same value.
1493 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
1494 if (PCV != CV)
1495 continue;
1496
1497 SmallSetVector<BasicBlock *, 4> FailBlocks;
1498 if (!safeToMergeTerminators(TI, PTI, &FailBlocks)) {
1499 for (auto *Succ : FailBlocks) {
1500 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split", DTU))
1501 return false;
1502 }
1503 }
1504
1505 performValueComparisonIntoPredecessorFolding(TI, CV, PTI, Builder);
1506 Changed = true;
1507 }
1508 return Changed;
1509}
1510
1511// If we would need to insert a select that uses the value of this invoke
1512// (comments in hoistSuccIdenticalTerminatorToSwitchOrIf explain why we would
1513// need to do this), we can't hoist the invoke, as there is nowhere to put the
1514// select in this case.
1516 Instruction *I1, Instruction *I2) {
1517 for (BasicBlock *Succ : successors(BB1)) {
1518 for (const PHINode &PN : Succ->phis()) {
1519 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1520 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1521 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1522 return false;
1523 }
1524 }
1525 }
1526 return true;
1527}
1528
1529// Get interesting characteristics of instructions that
1530// `hoistCommonCodeFromSuccessors` didn't hoist. They restrict what kind of
1531// instructions can be reordered across.
1537
1539 // Pseudo probes don't constrain reordering of other instructions.
1541 return 0;
1542 unsigned Flags = 0;
1543 if (I->mayReadFromMemory())
1544 Flags |= SkipReadMem;
1545 // We can't arbitrarily move around allocas, e.g. moving allocas (especially
1546 // inalloca) across stacksave/stackrestore boundaries.
1547 if (I->mayHaveSideEffects() || isa<AllocaInst>(I))
1548 Flags |= SkipSideEffect;
1550 Flags |= SkipImplicitControlFlow;
1551 return Flags;
1552}
1553
1554// Returns true if it is safe to reorder an instruction across preceding
1555// instructions in a basic block.
1556static bool isSafeToHoistInstr(Instruction *I, unsigned Flags) {
1557 // Don't reorder a store over a load.
1558 if ((Flags & SkipReadMem) && I->mayWriteToMemory())
1559 return false;
1560
1561 // If we have seen an instruction with side effects, it's unsafe to reorder an
1562 // instruction which reads memory or itself has side effects.
1563 if ((Flags & SkipSideEffect) &&
1564 (I->mayReadFromMemory() || I->mayHaveSideEffects() || isa<AllocaInst>(I)))
1565 return false;
1566
1567 // Reordering across an instruction which does not necessarily transfer
1568 // control to the next instruction is speculation.
1570 return false;
1571
1572 // Hoisting of llvm.deoptimize is only legal together with the next return
1573 // instruction, which this pass is not always able to do.
1574 if (auto *CB = dyn_cast<CallBase>(I))
1575 if (CB->getIntrinsicID() == Intrinsic::experimental_deoptimize)
1576 return false;
1577
1578 // It's also unsafe/illegal to hoist an instruction above its instruction
1579 // operands
1580 BasicBlock *BB = I->getParent();
1581 for (Value *Op : I->operands()) {
1582 if (auto *J = dyn_cast<Instruction>(Op))
1583 if (J->getParent() == BB)
1584 return false;
1585 }
1586
1587 return true;
1588}
1589
1590static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified = false);
1591
1592/// Helper function for hoistCommonCodeFromSuccessors. Return true if identical
1593/// instructions \p I1 and \p I2 can and should be hoisted.
1595 const TargetTransformInfo &TTI) {
1596 // If we're going to hoist a call, make sure that the two instructions
1597 // we're commoning/hoisting are both marked with musttail, or neither of
1598 // them is marked as such. Otherwise, we might end up in a situation where
1599 // we hoist from a block where the terminator is a `ret` to a block where
1600 // the terminator is a `br`, and `musttail` calls expect to be followed by
1601 // a return.
1602 auto *C1 = dyn_cast<CallInst>(I1);
1603 auto *C2 = dyn_cast<CallInst>(I2);
1604 if (C1 && C2)
1605 if (C1->isMustTailCall() != C2->isMustTailCall())
1606 return false;
1607
1608 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1609 return false;
1610
1611 // If any of the two call sites has nomerge or convergent attribute, stop
1612 // hoisting.
1613 if (const auto *CB1 = dyn_cast<CallBase>(I1))
1614 if (CB1->cannotMerge() || CB1->isConvergent())
1615 return false;
1616 if (const auto *CB2 = dyn_cast<CallBase>(I2))
1617 if (CB2->cannotMerge() || CB2->isConvergent())
1618 return false;
1619
1620 return true;
1621}
1622
1623/// Hoists DbgVariableRecords from \p I1 and \p OtherInstrs that are identical
1624/// in lock-step to \p TI. This matches how dbg.* intrinsics are hoisting in
1625/// hoistCommonCodeFromSuccessors. e.g. The input:
1626/// I1 DVRs: { x, z },
1627/// OtherInsts: { I2 DVRs: { x, y, z } }
1628/// would result in hoisting only DbgVariableRecord x.
1630 Instruction *TI, Instruction *I1,
1631 SmallVectorImpl<Instruction *> &OtherInsts) {
1632 if (!I1->hasDbgRecords())
1633 return;
1634 using CurrentAndEndIt =
1635 std::pair<DbgRecord::self_iterator, DbgRecord::self_iterator>;
1636 // Vector of {Current, End} iterators.
1638 Itrs.reserve(OtherInsts.size() + 1);
1639 // Helper lambdas for lock-step checks:
1640 // Return true if this Current == End.
1641 auto atEnd = [](const CurrentAndEndIt &Pair) {
1642 return Pair.first == Pair.second;
1643 };
1644 // Return true if all Current are identical.
1645 auto allIdentical = [](const SmallVector<CurrentAndEndIt> &Itrs) {
1646 return all_of(make_first_range(ArrayRef(Itrs).drop_front()),
1648 return Itrs[0].first->isIdenticalToWhenDefined(*I);
1649 });
1650 };
1651
1652 // Collect the iterators.
1653 Itrs.push_back(
1654 {I1->getDbgRecordRange().begin(), I1->getDbgRecordRange().end()});
1655 for (Instruction *Other : OtherInsts) {
1656 if (!Other->hasDbgRecords())
1657 return;
1658 Itrs.push_back(
1659 {Other->getDbgRecordRange().begin(), Other->getDbgRecordRange().end()});
1660 }
1661
1662 // Iterate in lock-step until any of the DbgRecord lists are exausted. If
1663 // the lock-step DbgRecord are identical, hoist all of them to TI.
1664 // This replicates the dbg.* intrinsic behaviour in
1665 // hoistCommonCodeFromSuccessors.
1666 while (none_of(Itrs, atEnd)) {
1667 bool HoistDVRs = allIdentical(Itrs);
1668 for (CurrentAndEndIt &Pair : Itrs) {
1669 // Increment Current iterator now as we may be about to move the
1670 // DbgRecord.
1671 DbgRecord &DR = *Pair.first++;
1672 if (HoistDVRs) {
1673 DR.removeFromParent();
1674 TI->getParent()->insertDbgRecordBefore(&DR, TI->getIterator());
1675 }
1676 }
1677 }
1678}
1679
1681 const Instruction *I2) {
1682 if (I1->isIdenticalToWhenDefined(I2, /*IntersectAttrs=*/true))
1683 return true;
1684
1685 if (auto *Cmp1 = dyn_cast<CmpInst>(I1))
1686 if (auto *Cmp2 = dyn_cast<CmpInst>(I2))
1687 return Cmp1->getPredicate() == Cmp2->getSwappedPredicate() &&
1688 Cmp1->getOperand(0) == Cmp2->getOperand(1) &&
1689 Cmp1->getOperand(1) == Cmp2->getOperand(0);
1690
1691 if (I1->isCommutative() && I1->isSameOperationAs(I2)) {
1692 return I1->getOperand(0) == I2->getOperand(1) &&
1693 I1->getOperand(1) == I2->getOperand(0) &&
1694 equal(drop_begin(I1->operands(), 2), drop_begin(I2->operands(), 2));
1695 }
1696
1697 return false;
1698}
1699
1700/// If the target supports conditional faulting,
1701/// we look for the following pattern:
1702/// \code
1703/// BB:
1704/// ...
1705/// %cond = icmp ult %x, %y
1706/// br i1 %cond, label %TrueBB, label %FalseBB
1707/// FalseBB:
1708/// store i32 1, ptr %q, align 4
1709/// ...
1710/// TrueBB:
1711/// %maskedloadstore = load i32, ptr %b, align 4
1712/// store i32 %maskedloadstore, ptr %p, align 4
1713/// ...
1714/// \endcode
1715///
1716/// and transform it into:
1717///
1718/// \code
1719/// BB:
1720/// ...
1721/// %cond = icmp ult %x, %y
1722/// %maskedloadstore = cload i32, ptr %b, %cond
1723/// cstore i32 %maskedloadstore, ptr %p, %cond
1724/// cstore i32 1, ptr %q, ~%cond
1725/// br i1 %cond, label %TrueBB, label %FalseBB
1726/// FalseBB:
1727/// ...
1728/// TrueBB:
1729/// ...
1730/// \endcode
1731///
1732/// where cload/cstore are represented by llvm.masked.load/store intrinsics,
1733/// e.g.
1734///
1735/// \code
1736/// %vcond = bitcast i1 %cond to <1 x i1>
1737/// %v0 = call <1 x i32> @llvm.masked.load.v1i32.p0
1738/// (ptr %b, i32 4, <1 x i1> %vcond, <1 x i32> poison)
1739/// %maskedloadstore = bitcast <1 x i32> %v0 to i32
1740/// call void @llvm.masked.store.v1i32.p0
1741/// (<1 x i32> %v0, ptr %p, i32 4, <1 x i1> %vcond)
1742/// %cond.not = xor i1 %cond, true
1743/// %vcond.not = bitcast i1 %cond.not to <1 x i>
1744/// call void @llvm.masked.store.v1i32.p0
1745/// (<1 x i32> <i32 1>, ptr %q, i32 4, <1x i1> %vcond.not)
1746/// \endcode
1747///
1748/// So we need to turn hoisted load/store into cload/cstore.
1749///
1750/// \param BI The branch instruction.
1751/// \param SpeculatedConditionalLoadsStores The load/store instructions that
1752/// will be speculated.
1753/// \param Invert indicates if speculates FalseBB. Only used in triangle CFG.
1755 CondBrInst *BI,
1756 SmallVectorImpl<Instruction *> &SpeculatedConditionalLoadsStores,
1757 std::optional<bool> Invert, Instruction *Sel) {
1758 auto &Context = BI->getParent()->getContext();
1759 auto *VCondTy = FixedVectorType::get(Type::getInt1Ty(Context), 1);
1760 auto *Cond = BI->getCondition();
1761 // Construct the condition if needed.
1762 BasicBlock *BB = BI->getParent();
1763 Value *Mask = nullptr;
1764 Value *MaskFalse = nullptr;
1765 Value *MaskTrue = nullptr;
1766 if (Invert.has_value()) {
1767 IRBuilder<> Builder(Sel ? Sel : SpeculatedConditionalLoadsStores.back());
1768 Mask = Builder.CreateBitCast(
1769 *Invert ? Builder.CreateXor(Cond, ConstantInt::getTrue(Context)) : Cond,
1770 VCondTy);
1771 } else {
1772 IRBuilder<> Builder(BI);
1773 MaskFalse = Builder.CreateBitCast(
1774 Builder.CreateXor(Cond, ConstantInt::getTrue(Context)), VCondTy);
1775 MaskTrue = Builder.CreateBitCast(Cond, VCondTy);
1776 }
1777 auto PeekThroughBitcasts = [](Value *V) {
1778 while (auto *BitCast = dyn_cast<BitCastInst>(V))
1779 V = BitCast->getOperand(0);
1780 return V;
1781 };
1782 for (auto *I : SpeculatedConditionalLoadsStores) {
1783 IRBuilder<> Builder(Invert.has_value() ? I : BI);
1784 if (!Invert.has_value())
1785 Mask = I->getParent() == BI->getSuccessor(0) ? MaskTrue : MaskFalse;
1786 // We currently assume conditional faulting load/store is supported for
1787 // scalar types only when creating new instructions. This can be easily
1788 // extended for vector types in the future.
1789 assert(!getLoadStoreType(I)->isVectorTy() && "not implemented");
1790 auto *Op0 = I->getOperand(0);
1791 CallInst *MaskedLoadStore = nullptr;
1792 if (auto *LI = dyn_cast<LoadInst>(I)) {
1793 // Handle Load.
1794 auto *Ty = I->getType();
1795 PHINode *PN = nullptr;
1796 Value *PassThru = nullptr;
1797 if (Invert.has_value())
1798 for (User *U : I->users()) {
1799 if ((PN = dyn_cast<PHINode>(U))) {
1800 PassThru = Builder.CreateBitCast(
1801 PeekThroughBitcasts(PN->getIncomingValueForBlock(BB)),
1802 FixedVectorType::get(Ty, 1));
1803 } else if (auto *Ins = cast<Instruction>(U);
1804 Sel && Ins->getParent() == BB) {
1805 // This happens when store or/and a speculative instruction between
1806 // load and store were hoisted to the BB. Make sure the masked load
1807 // inserted before its use.
1808 // We assume there's one of such use.
1809 Builder.SetInsertPoint(Ins);
1810 }
1811 }
1812 MaskedLoadStore = Builder.CreateMaskedLoad(
1813 FixedVectorType::get(Ty, 1), Op0, LI->getAlign(), Mask, PassThru);
1814 if (const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
1816 if (PassThru && !isa<PoisonValue>(PassThru)) {
1817 auto *C = dyn_cast<Constant>(PassThru);
1818 CR = C ? CR.unionWith(C->toConstantRange())
1819 : ConstantRange::getFull(CR.getBitWidth());
1820 }
1821 MaskedLoadStore->addRangeRetAttr(CR);
1822 }
1823 Value *NewLoadStore = Builder.CreateBitCast(MaskedLoadStore, Ty);
1824 if (PN)
1825 PN->setIncomingValue(PN->getBasicBlockIndex(BB), NewLoadStore);
1826 I->replaceAllUsesWith(NewLoadStore);
1827 } else {
1828 // Handle Store.
1829 auto *StoredVal = Builder.CreateBitCast(
1830 PeekThroughBitcasts(Op0), FixedVectorType::get(Op0->getType(), 1));
1831 MaskedLoadStore = Builder.CreateMaskedStore(
1832 StoredVal, I->getOperand(1), cast<StoreInst>(I)->getAlign(), Mask);
1833 }
1834 // For non-debug metadata, only !annotation, !range, !nonnull and !align are
1835 // kept when hoisting (see Instruction::dropUBImplyingAttrsAndMetadata).
1836 //
1837 // !nonnull, !align : Not support pointer type, no need to keep.
1838 // !range: Kept as a return attribute, widened over PassThru (see above).
1839 // !annotation: Not impact semantics. Keep it.
1840 I->dropUBImplyingAttrsAndUnknownMetadata({LLVMContext::MD_annotation});
1841 // FIXME: DIAssignID is not supported for masked store yet.
1842 // (Verifier::visitDIAssignIDMetadata)
1844 I->eraseMetadataIf([](unsigned MDKind, MDNode *Node) {
1845 return Node->getMetadataID() == Metadata::DIAssignIDKind;
1846 });
1847 MaskedLoadStore->copyMetadata(*I);
1848 I->eraseFromParent();
1849 }
1850}
1851
1853 const TargetTransformInfo &TTI) {
1854 // Not handle volatile or atomic.
1855 bool IsStore = false;
1856 if (auto *L = dyn_cast<LoadInst>(I)) {
1857 if (!L->isSimple() || !HoistLoadsWithCondFaulting)
1858 return false;
1859 } else if (auto *S = dyn_cast<StoreInst>(I)) {
1860 if (!S->isSimple() || !HoistStoresWithCondFaulting)
1861 return false;
1862 IsStore = true;
1863 } else
1864 return false;
1865
1866 // llvm.masked.load/store use i32 for alignment while load/store use i64.
1867 // That's why we have the alignment limitation.
1868 // FIXME: Update the prototype of the intrinsics?
1869 return TTI.hasConditionalLoadStoreForType(getLoadStoreType(I), IsStore) &&
1871}
1872
1873/// Hoist any common code in the successor blocks up into the block. This
1874/// function guarantees that BB dominates all successors. If AllInstsEqOnly is
1875/// given, only perform hoisting in case all successors blocks contain matching
1876/// instructions only. In that case, all instructions can be hoisted and the
1877/// original branch will be replaced and selects for PHIs are added.
1878bool SimplifyCFGOpt::hoistCommonCodeFromSuccessors(Instruction *TI,
1879 bool AllInstsEqOnly) {
1880 // This does very trivial matching, with limited scanning, to find identical
1881 // instructions in the two blocks. In particular, we don't want to get into
1882 // O(N1*N2*...) situations here where Ni are the sizes of these successors. As
1883 // such, we currently just scan for obviously identical instructions in an
1884 // identical order, possibly separated by the same number of non-identical
1885 // instructions.
1886 BasicBlock *BB = TI->getParent();
1887 unsigned int SuccSize = succ_size(BB);
1888 if (SuccSize < 2)
1889 return false;
1890
1891 // If either of the blocks has it's address taken, then we can't do this fold,
1892 // because the code we'd hoist would no longer run when we jump into the block
1893 // by it's address.
1894 SmallSetVector<BasicBlock *, 4> UniqueSuccessors(from_range, successors(BB));
1895 for (auto *Succ : UniqueSuccessors) {
1896 if (Succ->hasAddressTaken())
1897 return false;
1898 // Use getUniquePredecessor instead of getSinglePredecessor to support
1899 // multi-cases successors in switch.
1900 if (Succ->getUniquePredecessor())
1901 continue;
1902 // If Succ has >1 predecessors, continue to check if the Succ contains only
1903 // one `unreachable` inst. Since executing `unreachable` inst is an UB, we
1904 // can relax the condition based on the assumptiom that the program would
1905 // never enter Succ and trigger such an UB.
1906 if (isa<UnreachableInst>(*Succ->begin()))
1907 continue;
1908 return false;
1909 }
1910 // The second of pair is a SkipFlags bitmask.
1911 using SuccIterPair = std::pair<BasicBlock::iterator, unsigned>;
1912 SmallVector<SuccIterPair, 8> SuccIterPairs;
1913 for (auto *Succ : UniqueSuccessors) {
1914 BasicBlock::iterator SuccItr = Succ->begin();
1915 if (isa<PHINode>(*SuccItr))
1916 return false;
1917 SuccIterPairs.push_back(SuccIterPair(SuccItr, 0));
1918 }
1919
1920 if (AllInstsEqOnly) {
1921 // Check if all instructions in the successor blocks match. This allows
1922 // hoisting all instructions and removing the blocks we are hoisting from,
1923 // so does not add any new instructions.
1924
1925 // Check if sizes and terminators of all successors match.
1926 unsigned Size0 = UniqueSuccessors[0]->size();
1927 Instruction *Term0 = UniqueSuccessors[0]->getTerminator();
1928 bool AllSame =
1929 all_of(drop_begin(UniqueSuccessors), [Term0, Size0](BasicBlock *Succ) {
1930 return Succ->getTerminator()->isIdenticalTo(Term0) &&
1931 Succ->size() == Size0;
1932 });
1933 if (!AllSame)
1934 return false;
1935 LockstepReverseIterator<true> LRI(UniqueSuccessors.getArrayRef());
1936 while (LRI.isValid()) {
1937 Instruction *I0 = (*LRI)[0];
1938 if (any_of(*LRI, [I0](Instruction *I) {
1939 return !areIdenticalUpToCommutativity(I0, I);
1940 })) {
1941 return false;
1942 }
1943 --LRI;
1944 }
1945 // Now we know that all instructions in all successors can be hoisted. Let
1946 // the loop below handle the hoisting.
1947 }
1948
1949 // Count how many instructions were not hoisted so far. There's a limit on how
1950 // many instructions we skip, serving as a compilation time control as well as
1951 // preventing excessive increase of life ranges.
1952 unsigned NumSkipped = 0;
1953 // If we find an unreachable instruction at the beginning of a basic block, we
1954 // can still hoist instructions from the rest of the basic blocks.
1955 if (SuccIterPairs.size() > 2) {
1956 erase_if(SuccIterPairs,
1957 [](const auto &Pair) { return isa<UnreachableInst>(Pair.first); });
1958 if (SuccIterPairs.size() < 2)
1959 return false;
1960 }
1961
1962 bool Changed = false;
1963
1964 for (;;) {
1965 auto *SuccIterPairBegin = SuccIterPairs.begin();
1966 auto &BB1ItrPair = *SuccIterPairBegin++;
1967 auto OtherSuccIterPairRange =
1968 iterator_range(SuccIterPairBegin, SuccIterPairs.end());
1969 auto OtherSuccIterRange = make_first_range(OtherSuccIterPairRange);
1970
1971 Instruction *I1 = &*BB1ItrPair.first;
1972
1973 bool AllInstsAreIdentical = true;
1974 bool HasTerminator = I1->isTerminator();
1975 for (auto &SuccIter : OtherSuccIterRange) {
1976 Instruction *I2 = &*SuccIter;
1977 HasTerminator |= I2->isTerminator();
1978 if (AllInstsAreIdentical && (!areIdenticalUpToCommutativity(I1, I2) ||
1979 MMRAMetadata(*I1) != MMRAMetadata(*I2)))
1980 AllInstsAreIdentical = false;
1981 }
1982
1983 SmallVector<Instruction *, 8> OtherInsts;
1984 for (auto &SuccIter : OtherSuccIterRange)
1985 OtherInsts.push_back(&*SuccIter);
1986
1987 // If we are hoisting the terminator instruction, don't move one (making a
1988 // broken BB), instead clone it, and remove BI.
1989 if (HasTerminator) {
1990 // Even if BB, which contains only one unreachable instruction, is ignored
1991 // at the beginning of the loop, we can hoist the terminator instruction.
1992 // If any instructions remain in the block, we cannot hoist terminators.
1993 if (NumSkipped || !AllInstsAreIdentical) {
1994 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
1995 return Changed;
1996 }
1997
1998 return hoistSuccIdenticalTerminatorToSwitchOrIf(
1999 TI, I1, OtherInsts, UniqueSuccessors.getArrayRef()) ||
2000 Changed;
2001 }
2002
2003 if (AllInstsAreIdentical) {
2004 unsigned SkipFlagsBB1 = BB1ItrPair.second;
2005 AllInstsAreIdentical =
2006 isSafeToHoistInstr(I1, SkipFlagsBB1) &&
2007 all_of(OtherSuccIterPairRange, [=](const auto &Pair) {
2008 Instruction *I2 = &*Pair.first;
2009 unsigned SkipFlagsBB2 = Pair.second;
2010 // Even if the instructions are identical, it may not
2011 // be safe to hoist them if we have skipped over
2012 // instructions with side effects or their operands
2013 // weren't hoisted.
2014 return isSafeToHoistInstr(I2, SkipFlagsBB2) &&
2016 });
2017 }
2018
2019 // A musttail call must be immediately followed by a ret, so hoisting is
2020 // only legal if its ret is hoisted with it on the next iteration. That is,
2021 // no instruction has been skipped (the entire successor can be hoisted into
2022 // the predecessor) and the call is directly followed by a ret.
2023 if (auto *CI = dyn_cast<CallInst>(I1);
2024 AllInstsAreIdentical && CI && CI->isMustTailCall()) {
2025 AllInstsAreIdentical =
2026 NumSkipped == 0 && all_of(SuccIterPairs, [](const SuccIterPair &P) {
2027 return isa<ReturnInst>(*std::next(P.first));
2028 });
2029 }
2030
2031 if (AllInstsAreIdentical) {
2032 BB1ItrPair.first++;
2033 // For a normal instruction, we just move one to right before the
2034 // branch, then replace all uses of the other with the first. Finally,
2035 // we remove the now redundant second instruction.
2036 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
2037 // We've just hoisted DbgVariableRecords; move I1 after them (before TI)
2038 // and leave any that were not hoisted behind (by calling moveBefore
2039 // rather than moveBeforePreserving).
2040 I1->moveBefore(TI->getIterator());
2041 for (auto &SuccIter : OtherSuccIterRange) {
2042 Instruction *I2 = &*SuccIter++;
2043 assert(I2 != I1);
2044 if (!I2->use_empty())
2045 I2->replaceAllUsesWith(I1);
2046 I1->andIRFlags(I2);
2047 if (auto *CB = dyn_cast<CallBase>(I1)) {
2048 bool Success = CB->tryIntersectAttributes(cast<CallBase>(I2));
2049 assert(Success && "We should not be trying to hoist callbases "
2050 "with non-intersectable attributes");
2051 // For NDEBUG Compile.
2052 (void)Success;
2053 }
2054
2055 combineMetadataForCSE(I1, I2, true);
2056 // I1 and I2 are being combined into a single instruction. Its debug
2057 // location is the merged locations of the original instructions.
2058 I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
2059 I2->eraseFromParent();
2060 }
2061 // I1 now executes before the instructions we skipped.
2062 unsigned SkippedFlags = 0;
2063 for (const SuccIterPair &P : SuccIterPairs)
2064 SkippedFlags |= P.second;
2065 if (SkippedFlags & SkipImplicitControlFlow) {
2066 // One of them may throw or not return, so I1 is speculated.
2067 I1->dropUBImplyingAttrsAndMetadata();
2068 }
2069 if (!Changed)
2070 NumHoistCommonCode += SuccIterPairs.size();
2071 Changed = true;
2072 NumHoistCommonInstrs += SuccIterPairs.size();
2073 } else {
2074 if (NumSkipped >= HoistCommonSkipLimit) {
2075 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
2076 return Changed;
2077 }
2078 // We are about to skip over a pair of non-identical instructions. Record
2079 // if any have characteristics that would prevent reordering instructions
2080 // across them.
2081 for (auto &SuccIterPair : SuccIterPairs) {
2082 Instruction *I = &*SuccIterPair.first++;
2083 SuccIterPair.second |= skippedInstrFlags(I);
2084 }
2085 ++NumSkipped;
2086 }
2087 }
2088}
2089
2090bool SimplifyCFGOpt::hoistSuccIdenticalTerminatorToSwitchOrIf(
2091 Instruction *TI, Instruction *I1,
2092 SmallVectorImpl<Instruction *> &OtherSuccTIs,
2093 ArrayRef<BasicBlock *> UniqueSuccessors) {
2094
2095 auto *BI = dyn_cast<CondBrInst>(TI);
2096
2097 bool Changed = false;
2098 BasicBlock *TIParent = TI->getParent();
2099 BasicBlock *BB1 = I1->getParent();
2100
2101 // Use only for an if statement.
2102 auto *I2 = *OtherSuccTIs.begin();
2103 auto *BB2 = I2->getParent();
2104 if (BI) {
2105 assert(OtherSuccTIs.size() == 1);
2106 assert(BI->getSuccessor(0) == I1->getParent());
2107 assert(BI->getSuccessor(1) == I2->getParent());
2108 }
2109
2110 // In the case of an if statement, we try to hoist an invoke.
2111 // FIXME: Can we define a safety predicate for CallBr?
2112 // FIXME: Test case llvm/test/Transforms/SimplifyCFG/2009-06-15-InvokeCrash.ll
2113 // removed in 4c923b3b3fd0ac1edebf0603265ca3ba51724937 commit?
2114 if (isa<InvokeInst>(I1) && (!BI || !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
2115 return false;
2116
2117 // TODO: callbr hoisting currently disabled pending further study.
2118 if (isa<CallBrInst>(I1))
2119 return false;
2120
2121 for (BasicBlock *Succ : successors(BB1)) {
2122 for (PHINode &PN : Succ->phis()) {
2123 Value *BB1V = PN.getIncomingValueForBlock(BB1);
2124 for (Instruction *OtherSuccTI : OtherSuccTIs) {
2125 Value *BB2V = PN.getIncomingValueForBlock(OtherSuccTI->getParent());
2126 if (BB1V == BB2V)
2127 continue;
2128
2129 // In the case of an if statement, check for
2130 // passingValueIsAlwaysUndefined here because we would rather eliminate
2131 // undefined control flow then converting it to a select.
2132 if (!BI || passingValueIsAlwaysUndefined(BB1V, &PN) ||
2134 return false;
2135 }
2136 }
2137 }
2138
2139 // Hoist DbgVariableRecords attached to the terminator to match dbg.*
2140 // intrinsic hoisting behaviour in hoistCommonCodeFromSuccessors.
2141 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherSuccTIs);
2142 // Clone the terminator and hoist it into the pred, without any debug info.
2143 Instruction *NT = I1->clone();
2144 NT->insertInto(TIParent, TI->getIterator());
2145 if (!NT->getType()->isVoidTy()) {
2146 I1->replaceAllUsesWith(NT);
2147 for (Instruction *OtherSuccTI : OtherSuccTIs)
2148 OtherSuccTI->replaceAllUsesWith(NT);
2149 NT->takeName(I1);
2150 }
2151 Changed = true;
2152 NumHoistCommonInstrs += OtherSuccTIs.size() + 1;
2153
2154 // Ensure terminator gets a debug location, even an unknown one, in case
2155 // it involves inlinable calls.
2157 Locs.push_back(I1->getDebugLoc());
2158 for (auto *OtherSuccTI : OtherSuccTIs)
2159 Locs.push_back(OtherSuccTI->getDebugLoc());
2160 NT->setDebugLoc(DebugLoc::getMergedLocations(Locs));
2161
2162 // PHIs created below will adopt NT's merged DebugLoc.
2163 IRBuilder<NoFolder> Builder(NT);
2164
2165 // In the case of an if statement, hoisting one of the terminators from our
2166 // successor is a great thing. Unfortunately, the successors of the if/else
2167 // blocks may have PHI nodes in them. If they do, all PHI entries for BB1/BB2
2168 // must agree for all PHI nodes, so we insert select instruction to compute
2169 // the final result.
2170 if (BI) {
2171 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
2172 for (BasicBlock *Succ : successors(BB1)) {
2173 for (PHINode &PN : Succ->phis()) {
2174 Value *BB1V = PN.getIncomingValueForBlock(BB1);
2175 Value *BB2V = PN.getIncomingValueForBlock(BB2);
2176 if (BB1V == BB2V)
2177 continue;
2178
2179 // These values do not agree. Insert a select instruction before NT
2180 // that determines the right value.
2181 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
2182 if (!SI) {
2183 // Propagate fast-math-flags from phi node to its replacement select.
2185 BI->getCondition(), BB1V, BB2V,
2186 isa<FPMathOperator>(PN) ? &PN : nullptr,
2187 BB1V->getName() + "." + BB2V->getName(), BI));
2188 }
2189
2190 // Make the PHI node use the select for all incoming values for BB1/BB2
2191 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2192 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
2193 PN.setIncomingValue(i, SI);
2194 }
2195 }
2196 }
2197
2199
2200 // Update any PHI nodes in our new successors.
2201 SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
2202 for (BasicBlock *Succ : successors(BB1)) {
2203 addPredecessorToBlock(Succ, TIParent, BB1);
2204
2205 if (DTU && VisitedSuccs.insert(Succ).second)
2206 Updates.push_back({DominatorTree::Insert, TIParent, Succ});
2207 }
2208
2209 if (DTU) {
2210 // TI might be a switch with multi-cases destination, so we need to care for
2211 // the duplication of successors.
2212 for (BasicBlock *Succ : UniqueSuccessors)
2213 Updates.push_back({DominatorTree::Delete, TIParent, Succ});
2214 }
2215
2217 if (DTU)
2218 DTU->applyUpdates(Updates);
2219 return Changed;
2220}
2221
2222// TODO: Refine this. This should avoid cases like turning constant memcpy sizes
2223// into variables.
2225 int OpIdx) {
2226 // Divide/Remainder by constant is typically much cheaper than by variable.
2227 if (I->isIntDivRem())
2228 return OpIdx != 1;
2229 return !isa<IntrinsicInst>(I);
2230}
2231
2232// All instructions in Insts belong to different blocks that all unconditionally
2233// branch to a common successor. Analyze each instruction and return true if it
2234// would be possible to sink them into their successor, creating one common
2235// instruction instead. For every value that would be required to be provided by
2236// PHI node (because an operand varies in each input block), add to PHIOperands.
2239 DenseMap<const Use *, SmallVector<Value *, 4>> &PHIOperands) {
2240 // Prune out obviously bad instructions to move. Each instruction must have
2241 // the same number of uses, and we check later that the uses are consistent.
2242 std::optional<unsigned> NumUses;
2243 for (auto *I : Insts) {
2244 // These instructions may change or break semantics if moved.
2245 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
2246 I->getType()->isTokenTy())
2247 return false;
2248
2249 // Do not try to sink an instruction in an infinite loop - it can cause
2250 // this algorithm to infinite loop.
2251 if (I->getParent()->getSingleSuccessor() == I->getParent())
2252 return false;
2253
2254 // Conservatively return false if I is an inline-asm instruction. Sinking
2255 // and merging inline-asm instructions can potentially create arguments
2256 // that cannot satisfy the inline-asm constraints.
2257 // If the instruction has nomerge or convergent attribute, return false.
2258 if (const auto *C = dyn_cast<CallBase>(I))
2259 if (C->isInlineAsm() || C->cannotMerge() || C->isConvergent())
2260 return false;
2261
2262 if (!NumUses)
2263 NumUses = I->getNumUses();
2264 else if (NumUses != I->getNumUses())
2265 return false;
2266 }
2267
2268 const Instruction *I0 = Insts.front();
2269 const auto I0MMRA = MMRAMetadata(*I0);
2270 for (auto *I : Insts) {
2271 if (!I->isSameOperationAs(I0, Instruction::CompareUsingIntersectedAttrs))
2272 return false;
2273
2274 // Treat MMRAs conservatively. This pass can be quite aggressive and
2275 // could drop a lot of MMRAs otherwise.
2276 if (MMRAMetadata(*I) != I0MMRA)
2277 return false;
2278 }
2279
2280 // Uses must be consistent: If I0 is used in a phi node in the sink target,
2281 // then the other phi operands must match the instructions from Insts. This
2282 // also has to hold true for any phi nodes that would be created as a result
2283 // of sinking. Both of these cases are represented by PhiOperands.
2284 for (const Use &U : I0->uses()) {
2285 auto It = PHIOperands.find(&U);
2286 if (It == PHIOperands.end())
2287 // There may be uses in other blocks when sinking into a loop header.
2288 return false;
2289 if (!equal(Insts, It->second))
2290 return false;
2291 }
2292
2293 // For calls to be sinkable, they must all be indirect, or have same callee.
2294 // I.e. if we have two direct calls to different callees, we don't want to
2295 // turn that into an indirect call. Likewise, if we have an indirect call,
2296 // and a direct call, we don't actually want to have a single indirect call.
2297 if (isa<CallBase>(I0)) {
2298 auto IsIndirectCall = [](const Instruction *I) {
2299 return cast<CallBase>(I)->isIndirectCall();
2300 };
2301 bool HaveIndirectCalls = any_of(Insts, IsIndirectCall);
2302 bool AllCallsAreIndirect = all_of(Insts, IsIndirectCall);
2303 if (HaveIndirectCalls) {
2304 if (!AllCallsAreIndirect)
2305 return false;
2306 } else {
2307 // All callees must be identical.
2308 Value *Callee = nullptr;
2309 for (const Instruction *I : Insts) {
2310 Value *CurrCallee = cast<CallBase>(I)->getCalledOperand();
2311 if (!Callee)
2312 Callee = CurrCallee;
2313 else if (Callee != CurrCallee)
2314 return false;
2315 }
2316 }
2317 }
2318
2319 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
2320 Value *Op = I0->getOperand(OI);
2321 auto SameAsI0 = [&I0, OI](const Instruction *I) {
2322 assert(I->getNumOperands() == I0->getNumOperands());
2323 return I->getOperand(OI) == I0->getOperand(OI);
2324 };
2325 if (!all_of(Insts, SameAsI0)) {
2326 auto CanReplaceOperand = [OI](const Instruction *I) {
2327 return canReplaceOperandWithVariable(I, OI);
2328 };
2330 !all_of(Insts, CanReplaceOperand))
2331 // We can't create a PHI from this operand.
2332 return false;
2333 auto &Ops = PHIOperands[&I0->getOperandUse(OI)];
2334 for (auto *I : Insts)
2335 Ops.push_back(I->getOperand(OI));
2336 }
2337 }
2338 return true;
2339}
2340
2341// Assuming canSinkInstructions(Blocks) has returned true, sink the last
2342// instruction of every block in Blocks to their common successor, commoning
2343// into one instruction.
2345 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
2346
2347 // canSinkInstructions returning true guarantees that every block has at
2348 // least one non-terminator instruction.
2350 for (auto *BB : Blocks) {
2351 Instruction *I = BB->getTerminator();
2352 I = I->getPrevNode();
2353 Insts.push_back(I);
2354 }
2355
2356 // We don't need to do any more checking here; canSinkInstructions should
2357 // have done it all for us.
2358 SmallVector<Value*, 4> NewOperands;
2359 Instruction *I0 = Insts.front();
2360 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
2361 // This check is different to that in canSinkInstructions. There, we
2362 // cared about the global view once simplifycfg (and instcombine) have
2363 // completed - it takes into account PHIs that become trivially
2364 // simplifiable. However here we need a more local view; if an operand
2365 // differs we create a PHI and rely on instcombine to clean up the very
2366 // small mess we may make.
2367 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
2368 return I->getOperand(O) != I0->getOperand(O);
2369 });
2370 if (!NeedPHI) {
2371 NewOperands.push_back(I0->getOperand(O));
2372 continue;
2373 }
2374
2375 // Create a new PHI in the successor block and populate it.
2376 auto *Op = I0->getOperand(O);
2377 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
2378 auto *PN =
2379 PHINode::Create(Op->getType(), Insts.size(), Op->getName() + ".sink");
2380 PN->insertBefore(BBEnd->begin());
2381 for (auto *I : Insts)
2382 PN->addIncoming(I->getOperand(O), I->getParent());
2383 NewOperands.push_back(PN);
2384 }
2385
2386 // Arbitrarily use I0 as the new "common" instruction; remap its operands
2387 // and move it to the start of the successor block.
2388 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
2389 I0->getOperandUse(O).set(NewOperands[O]);
2390
2391 I0->moveBefore(*BBEnd, BBEnd->getFirstInsertionPt());
2392
2393 // Update metadata and IR flags, and merge debug locations.
2394 for (auto *I : Insts)
2395 if (I != I0) {
2396 // The debug location for the "common" instruction is the merged locations
2397 // of all the commoned instructions. We start with the original location
2398 // of the "common" instruction and iteratively merge each location in the
2399 // loop below.
2400 // This is an N-way merge, which will be inefficient if I0 is a CallInst.
2401 // However, as N-way merge for CallInst is rare, so we use simplified API
2402 // instead of using complex API for N-way merge.
2403 I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
2404 combineMetadataForCSE(I0, I, true);
2405 I0->andIRFlags(I);
2406 if (auto *CB = dyn_cast<CallBase>(I0)) {
2407 bool Success = CB->tryIntersectAttributes(cast<CallBase>(I));
2408 assert(Success && "We should not be trying to sink callbases "
2409 "with non-intersectable attributes");
2410 // For NDEBUG Compile.
2411 (void)Success;
2412 }
2413 }
2414
2415 for (User *U : make_early_inc_range(I0->users())) {
2416 // canSinkLastInstruction checked that all instructions are only used by
2417 // phi nodes in a way that allows replacing the phi node with the common
2418 // instruction.
2419 auto *PN = cast<PHINode>(U);
2420 PN->replaceAllUsesWith(I0);
2421 PN->eraseFromParent();
2422 }
2423
2424 // Finally nuke all instructions apart from the common instruction.
2425 for (auto *I : Insts) {
2426 if (I == I0)
2427 continue;
2428 // The remaining uses are debug users, replace those with the common inst.
2429 // In most (all?) cases this just introduces a use-before-def.
2430 assert(I->user_empty() && "Inst unexpectedly still has non-dbg users");
2431 I->replaceAllUsesWith(I0);
2432 I->eraseFromParent();
2433 }
2434}
2435
2436/// Check whether BB's predecessors end with unconditional branches. If it is
2437/// true, sink any common code from the predecessors to BB.
2439 DomTreeUpdater *DTU) {
2440 // We support two situations:
2441 // (1) all incoming arcs are unconditional
2442 // (2) there are non-unconditional incoming arcs
2443 //
2444 // (2) is very common in switch defaults and
2445 // else-if patterns;
2446 //
2447 // if (a) f(1);
2448 // else if (b) f(2);
2449 //
2450 // produces:
2451 //
2452 // [if]
2453 // / \
2454 // [f(1)] [if]
2455 // | | \
2456 // | | |
2457 // | [f(2)]|
2458 // \ | /
2459 // [ end ]
2460 //
2461 // [end] has two unconditional predecessor arcs and one conditional. The
2462 // conditional refers to the implicit empty 'else' arc. This conditional
2463 // arc can also be caused by an empty default block in a switch.
2464 //
2465 // In this case, we attempt to sink code from all *unconditional* arcs.
2466 // If we can sink instructions from these arcs (determined during the scan
2467 // phase below) we insert a common successor for all unconditional arcs and
2468 // connect that to [end], to enable sinking:
2469 //
2470 // [if]
2471 // / \
2472 // [x(1)] [if]
2473 // | | \
2474 // | | \
2475 // | [x(2)] |
2476 // \ / |
2477 // [sink.split] |
2478 // \ /
2479 // [ end ]
2480 //
2481 SmallVector<BasicBlock*,4> UnconditionalPreds;
2482 bool HaveNonUnconditionalPredecessors = false;
2483 for (auto *PredBB : predecessors(BB)) {
2484 auto *PredBr = dyn_cast<UncondBrInst>(PredBB->getTerminator());
2485 if (PredBr)
2486 UnconditionalPreds.push_back(PredBB);
2487 else
2488 HaveNonUnconditionalPredecessors = true;
2489 }
2490 if (UnconditionalPreds.size() < 2)
2491 return false;
2492
2493 // We take a two-step approach to tail sinking. First we scan from the end of
2494 // each block upwards in lockstep. If the n'th instruction from the end of each
2495 // block can be sunk, those instructions are added to ValuesToSink and we
2496 // carry on. If we can sink an instruction but need to PHI-merge some operands
2497 // (because they're not identical in each instruction) we add these to
2498 // PHIOperands.
2499 // We prepopulate PHIOperands with the phis that already exist in BB.
2501 for (PHINode &PN : BB->phis()) {
2503 for (const Use &U : PN.incoming_values())
2504 IncomingVals.insert({PN.getIncomingBlock(U), &U});
2505 auto &Ops = PHIOperands[IncomingVals[UnconditionalPreds[0]]];
2506 for (BasicBlock *Pred : UnconditionalPreds)
2507 Ops.push_back(*IncomingVals[Pred]);
2508 }
2509
2510 int ScanIdx = 0;
2511 SmallPtrSet<Value*,4> InstructionsToSink;
2512 LockstepReverseIterator<true> LRI(UnconditionalPreds);
2513 while (LRI.isValid() &&
2514 canSinkInstructions(*LRI, PHIOperands)) {
2515 LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
2516 << "\n");
2517 InstructionsToSink.insert_range(*LRI);
2518 ++ScanIdx;
2519 --LRI;
2520 }
2521
2522 // If no instructions can be sunk, early-return.
2523 if (ScanIdx == 0)
2524 return false;
2525
2526 bool followedByDeoptOrUnreachable = IsBlockFollowedByDeoptOrUnreachable(BB);
2527
2528 if (!followedByDeoptOrUnreachable) {
2529 // Check whether this is the pointer operand of a load/store.
2530 auto IsMemOperand = [](Use &U) {
2531 auto *I = cast<Instruction>(U.getUser());
2532 if (isa<LoadInst>(I))
2533 return U.getOperandNo() == LoadInst::getPointerOperandIndex();
2534 if (isa<StoreInst>(I))
2535 return U.getOperandNo() == StoreInst::getPointerOperandIndex();
2536 return false;
2537 };
2538
2539 // Okay, we *could* sink last ScanIdx instructions. But how many can we
2540 // actually sink before encountering instruction that is unprofitable to
2541 // sink?
2542 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator<true> &LRI) {
2543 unsigned NumPHIInsts = 0;
2544 for (Use &U : (*LRI)[0]->operands()) {
2545 auto It = PHIOperands.find(&U);
2546 if (It != PHIOperands.end() && !all_of(It->second, [&](Value *V) {
2547 return InstructionsToSink.contains(V);
2548 })) {
2549 ++NumPHIInsts;
2550 // Do not separate a load/store from the gep producing the address.
2551 // The gep can likely be folded into the load/store as an addressing
2552 // mode. Additionally, a load of a gep is easier to analyze than a
2553 // load of a phi.
2554 if (IsMemOperand(U) &&
2555 any_of(It->second, [](Value *V) { return isa<GEPOperator>(V); }))
2556 return false;
2557 // FIXME: this check is overly optimistic. We may end up not sinking
2558 // said instruction, due to the very same profitability check.
2559 // See @creating_too_many_phis in sink-common-code.ll.
2560 }
2561 }
2562 LLVM_DEBUG(dbgs() << "SINK: #phi insts: " << NumPHIInsts << "\n");
2563 return NumPHIInsts <= 1;
2564 };
2565
2566 // We've determined that we are going to sink last ScanIdx instructions,
2567 // and recorded them in InstructionsToSink. Now, some instructions may be
2568 // unprofitable to sink. But that determination depends on the instructions
2569 // that we are going to sink.
2570
2571 // First, forward scan: find the first instruction unprofitable to sink,
2572 // recording all the ones that are profitable to sink.
2573 // FIXME: would it be better, after we detect that not all are profitable.
2574 // to either record the profitable ones, or erase the unprofitable ones?
2575 // Maybe we need to choose (at runtime) the one that will touch least
2576 // instrs?
2577 LRI.reset();
2578 int Idx = 0;
2579 SmallPtrSet<Value *, 4> InstructionsProfitableToSink;
2580 while (Idx < ScanIdx) {
2581 if (!ProfitableToSinkInstruction(LRI)) {
2582 // Too many PHIs would be created.
2583 LLVM_DEBUG(
2584 dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
2585 break;
2586 }
2587 InstructionsProfitableToSink.insert_range(*LRI);
2588 --LRI;
2589 ++Idx;
2590 }
2591
2592 // If no instructions can be sunk, early-return.
2593 if (Idx == 0)
2594 return false;
2595
2596 // Did we determine that (only) some instructions are unprofitable to sink?
2597 if (Idx < ScanIdx) {
2598 // Okay, some instructions are unprofitable.
2599 ScanIdx = Idx;
2600 InstructionsToSink = InstructionsProfitableToSink;
2601
2602 // But, that may make other instructions unprofitable, too.
2603 // So, do a backward scan, do any earlier instructions become
2604 // unprofitable?
2605 assert(
2606 !ProfitableToSinkInstruction(LRI) &&
2607 "We already know that the last instruction is unprofitable to sink");
2608 ++LRI;
2609 --Idx;
2610 while (Idx >= 0) {
2611 // If we detect that an instruction becomes unprofitable to sink,
2612 // all earlier instructions won't be sunk either,
2613 // so preemptively keep InstructionsProfitableToSink in sync.
2614 // FIXME: is this the most performant approach?
2615 for (auto *I : *LRI)
2616 InstructionsProfitableToSink.erase(I);
2617 if (!ProfitableToSinkInstruction(LRI)) {
2618 // Everything starting with this instruction won't be sunk.
2619 ScanIdx = Idx;
2620 InstructionsToSink = InstructionsProfitableToSink;
2621 }
2622 ++LRI;
2623 --Idx;
2624 }
2625 }
2626
2627 // If no instructions can be sunk, early-return.
2628 if (ScanIdx == 0)
2629 return false;
2630 }
2631
2632 bool Changed = false;
2633
2634 if (HaveNonUnconditionalPredecessors) {
2635 if (!followedByDeoptOrUnreachable) {
2636 // It is always legal to sink common instructions from unconditional
2637 // predecessors. However, if not all predecessors are unconditional,
2638 // this transformation might be pessimizing. So as a rule of thumb,
2639 // don't do it unless we'd sink at least one non-speculatable instruction.
2640 // See https://bugs.llvm.org/show_bug.cgi?id=30244
2641 LRI.reset();
2642 int Idx = 0;
2643 bool Profitable = false;
2644 while (Idx < ScanIdx) {
2645 if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
2646 Profitable = true;
2647 break;
2648 }
2649 --LRI;
2650 ++Idx;
2651 }
2652 if (!Profitable)
2653 return false;
2654 }
2655
2656 LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
2657 // We have a conditional edge and we're going to sink some instructions.
2658 // Insert a new block postdominating all blocks we're going to sink from.
2659 if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split", DTU))
2660 // Edges couldn't be split.
2661 return false;
2662 Changed = true;
2663 }
2664
2665 // Now that we've analyzed all potential sinking candidates, perform the
2666 // actual sink. We iteratively sink the last non-terminator of the source
2667 // blocks into their common successor unless doing so would require too
2668 // many PHI instructions to be generated (currently only one PHI is allowed
2669 // per sunk instruction).
2670 //
2671 // We can use InstructionsToSink to discount values needing PHI-merging that will
2672 // actually be sunk in a later iteration. This allows us to be more
2673 // aggressive in what we sink. This does allow a false positive where we
2674 // sink presuming a later value will also be sunk, but stop half way through
2675 // and never actually sink it which means we produce more PHIs than intended.
2676 // This is unlikely in practice though.
2677 int SinkIdx = 0;
2678 for (; SinkIdx != ScanIdx; ++SinkIdx) {
2679 LLVM_DEBUG(dbgs() << "SINK: Sink: "
2680 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
2681 << "\n");
2682
2683 // Because we've sunk every instruction in turn, the current instruction to
2684 // sink is always at index 0.
2685 LRI.reset();
2686
2687 sinkLastInstruction(UnconditionalPreds);
2688 NumSinkCommonInstrs++;
2689 Changed = true;
2690 }
2691 if (SinkIdx != 0)
2692 ++NumSinkCommonCode;
2693 return Changed;
2694}
2695
2696namespace {
2697
2698struct CompatibleSets {
2699 using SetTy = SmallVector<InvokeInst *, 2>;
2700
2702
2703 static bool shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes);
2704
2705 SetTy &getCompatibleSet(InvokeInst *II);
2706
2707 void insert(InvokeInst *II);
2708};
2709
2710CompatibleSets::SetTy &CompatibleSets::getCompatibleSet(InvokeInst *II) {
2711 // Perform a linear scan over all the existing sets, see if the new `invoke`
2712 // is compatible with any particular set. Since we know that all the `invokes`
2713 // within a set are compatible, only check the first `invoke` in each set.
2714 // WARNING: at worst, this has quadratic complexity.
2715 for (CompatibleSets::SetTy &Set : Sets) {
2716 if (CompatibleSets::shouldBelongToSameSet({Set.front(), II}))
2717 return Set;
2718 }
2719
2720 // Otherwise, we either had no sets yet, or this invoke forms a new set.
2721 return Sets.emplace_back();
2722}
2723
2724void CompatibleSets::insert(InvokeInst *II) {
2725 getCompatibleSet(II).emplace_back(II);
2726}
2727
2728bool CompatibleSets::shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes) {
2729 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2730
2731 // Can we theoretically merge these `invoke`s?
2732 auto IsIllegalToMerge = [](InvokeInst *II) {
2733 return II->cannotMerge() || II->isInlineAsm();
2734 };
2735 if (any_of(Invokes, IsIllegalToMerge))
2736 return false;
2737
2738 // Either both `invoke`s must be direct,
2739 // or both `invoke`s must be indirect.
2740 auto IsIndirectCall = [](InvokeInst *II) { return II->isIndirectCall(); };
2741 bool HaveIndirectCalls = any_of(Invokes, IsIndirectCall);
2742 bool AllCallsAreIndirect = all_of(Invokes, IsIndirectCall);
2743 if (HaveIndirectCalls) {
2744 if (!AllCallsAreIndirect)
2745 return false;
2746 } else {
2747 // All callees must be identical.
2748 Value *Callee = nullptr;
2749 for (InvokeInst *II : Invokes) {
2750 Value *CurrCallee = II->getCalledOperand();
2751 assert(CurrCallee && "There is always a called operand.");
2752 if (!Callee)
2753 Callee = CurrCallee;
2754 else if (Callee != CurrCallee)
2755 return false;
2756 }
2757 }
2758
2759 // Either both `invoke`s must not have a normal destination,
2760 // or both `invoke`s must have a normal destination,
2761 auto HasNormalDest = [](InvokeInst *II) {
2762 return !isa<UnreachableInst>(II->getNormalDest()->getFirstNonPHIIt());
2763 };
2764 if (any_of(Invokes, HasNormalDest)) {
2765 // Do not merge `invoke` that does not have a normal destination with one
2766 // that does have a normal destination, even though doing so would be legal.
2767 if (!all_of(Invokes, HasNormalDest))
2768 return false;
2769
2770 // All normal destinations must be identical.
2771 BasicBlock *NormalBB = nullptr;
2772 for (InvokeInst *II : Invokes) {
2773 BasicBlock *CurrNormalBB = II->getNormalDest();
2774 assert(CurrNormalBB && "There is always a 'continue to' basic block.");
2775 if (!NormalBB)
2776 NormalBB = CurrNormalBB;
2777 else if (NormalBB != CurrNormalBB)
2778 return false;
2779 }
2780
2781 // In the normal destination, the incoming values for these two `invoke`s
2782 // must be compatible.
2783 SmallPtrSet<Value *, 16> EquivalenceSet(llvm::from_range, Invokes);
2785 NormalBB, {Invokes[0]->getParent(), Invokes[1]->getParent()},
2786 &EquivalenceSet))
2787 return false;
2788 }
2789
2790#ifndef NDEBUG
2791 // All unwind destinations must be identical.
2792 // We know that because we have started from said unwind destination.
2793 BasicBlock *UnwindBB = nullptr;
2794 for (InvokeInst *II : Invokes) {
2795 BasicBlock *CurrUnwindBB = II->getUnwindDest();
2796 assert(CurrUnwindBB && "There is always an 'unwind to' basic block.");
2797 if (!UnwindBB)
2798 UnwindBB = CurrUnwindBB;
2799 else
2800 assert(UnwindBB == CurrUnwindBB && "Unexpected unwind destination.");
2801 }
2802#endif
2803
2804 // In the unwind destination, the incoming values for these two `invoke`s
2805 // must be compatible.
2807 Invokes.front()->getUnwindDest(),
2808 {Invokes[0]->getParent(), Invokes[1]->getParent()}))
2809 return false;
2810
2811 // Ignoring arguments, these `invoke`s must be identical,
2812 // including operand bundles.
2813 const InvokeInst *II0 = Invokes.front();
2814 for (auto *II : Invokes.drop_front())
2815 if (!II->isSameOperationAs(II0, Instruction::CompareUsingIntersectedAttrs))
2816 return false;
2817
2818 // Can we theoretically form the data operands for the merged `invoke`?
2819 auto IsIllegalToMergeArguments = [](auto Ops) {
2820 Use &U0 = std::get<0>(Ops);
2821 Use &U1 = std::get<1>(Ops);
2822 if (U0 == U1)
2823 return false;
2825 U0.getOperandNo());
2826 };
2827 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2828 if (any_of(zip(Invokes[0]->data_ops(), Invokes[1]->data_ops()),
2829 IsIllegalToMergeArguments))
2830 return false;
2831
2832 return true;
2833}
2834
2835} // namespace
2836
2837// Merge all invokes in the provided set, all of which are compatible
2838// as per the `CompatibleSets::shouldBelongToSameSet()`.
2840 DomTreeUpdater *DTU) {
2841 assert(Invokes.size() >= 2 && "Must have at least two invokes to merge.");
2842
2844 if (DTU)
2845 Updates.reserve(2 + 3 * Invokes.size());
2846
2847 bool HasNormalDest =
2848 !isa<UnreachableInst>(Invokes[0]->getNormalDest()->getFirstNonPHIIt());
2849
2850 // Clone one of the invokes into a new basic block.
2851 // Since they are all compatible, it doesn't matter which invoke is cloned.
2852 InvokeInst *MergedInvoke = [&Invokes, HasNormalDest]() {
2853 InvokeInst *II0 = Invokes.front();
2854 BasicBlock *II0BB = II0->getParent();
2855 BasicBlock *InsertBeforeBlock =
2856 II0->getParent()->getIterator()->getNextNode();
2857 Function *Func = II0BB->getParent();
2858 LLVMContext &Ctx = II0->getContext();
2859
2860 BasicBlock *MergedInvokeBB = BasicBlock::Create(
2861 Ctx, II0BB->getName() + ".invoke", Func, InsertBeforeBlock);
2862
2863 auto *MergedInvoke = cast<InvokeInst>(II0->clone());
2864 // NOTE: all invokes have the same attributes, so no handling needed.
2865 MergedInvoke->insertInto(MergedInvokeBB, MergedInvokeBB->end());
2866
2867 if (!HasNormalDest) {
2868 // This set does not have a normal destination,
2869 // so just form a new block with unreachable terminator.
2870 BasicBlock *MergedNormalDest = BasicBlock::Create(
2871 Ctx, II0BB->getName() + ".cont", Func, InsertBeforeBlock);
2872 auto *UI = new UnreachableInst(Ctx, MergedNormalDest);
2873 UI->setDebugLoc(DebugLoc::getTemporary());
2874 MergedInvoke->setNormalDest(MergedNormalDest);
2875 }
2876
2877 // The unwind destination, however, remainds identical for all invokes here.
2878
2879 return MergedInvoke;
2880 }();
2881
2882 if (DTU) {
2883 // Predecessor blocks that contained these invokes will now branch to
2884 // the new block that contains the merged invoke, ...
2885 for (InvokeInst *II : Invokes)
2886 Updates.push_back(
2887 {DominatorTree::Insert, II->getParent(), MergedInvoke->getParent()});
2888
2889 // ... which has the new `unreachable` block as normal destination,
2890 // or unwinds to the (same for all `invoke`s in this set) `landingpad`,
2891 for (BasicBlock *SuccBBOfMergedInvoke : successors(MergedInvoke))
2892 Updates.push_back({DominatorTree::Insert, MergedInvoke->getParent(),
2893 SuccBBOfMergedInvoke});
2894
2895 // Since predecessor blocks now unconditionally branch to a new block,
2896 // they no longer branch to their original successors.
2897 for (InvokeInst *II : Invokes)
2898 for (BasicBlock *SuccOfPredBB : successors(II->getParent()))
2899 Updates.push_back(
2900 {DominatorTree::Delete, II->getParent(), SuccOfPredBB});
2901 }
2902
2903 bool IsIndirectCall = Invokes[0]->isIndirectCall();
2904
2905 // Form the merged operands for the merged invoke.
2906 for (Use &U : MergedInvoke->operands()) {
2907 // Only PHI together the indirect callees and data operands.
2908 if (MergedInvoke->isCallee(&U)) {
2909 if (!IsIndirectCall)
2910 continue;
2911 } else if (!MergedInvoke->isDataOperand(&U))
2912 continue;
2913
2914 // Don't create trivial PHI's with all-identical incoming values.
2915 bool NeedPHI = any_of(Invokes, [&U](InvokeInst *II) {
2916 return II->getOperand(U.getOperandNo()) != U.get();
2917 });
2918 if (!NeedPHI)
2919 continue;
2920
2921 // Form a PHI out of all the data ops under this index.
2923 U->getType(), /*NumReservedValues=*/Invokes.size(), "", MergedInvoke->getIterator());
2924 for (InvokeInst *II : Invokes)
2925 PN->addIncoming(II->getOperand(U.getOperandNo()), II->getParent());
2926
2927 U.set(PN);
2928 }
2929
2930 // We've ensured that each PHI node has compatible (identical) incoming values
2931 // when coming from each of the `invoke`s in the current merge set,
2932 // so update the PHI nodes accordingly.
2933 for (BasicBlock *Succ : successors(MergedInvoke))
2934 addPredecessorToBlock(Succ, /*NewPred=*/MergedInvoke->getParent(),
2935 /*ExistPred=*/Invokes.front()->getParent());
2936
2937 // And finally, replace the original `invoke`s with an unconditional branch
2938 // to the block with the merged `invoke`. Also, give that merged `invoke`
2939 // the merged debugloc of all the original `invoke`s.
2940 DILocation *MergedDebugLoc = nullptr;
2941 for (InvokeInst *II : Invokes) {
2942 // Compute the debug location common to all the original `invoke`s.
2943 if (!MergedDebugLoc)
2944 MergedDebugLoc = II->getDebugLoc();
2945 else
2946 MergedDebugLoc =
2947 DebugLoc::getMergedLocation(MergedDebugLoc, II->getDebugLoc());
2948
2949 // And replace the old `invoke` with an unconditionally branch
2950 // to the block with the merged `invoke`.
2951 for (BasicBlock *OrigSuccBB : successors(II->getParent()))
2952 OrigSuccBB->removePredecessor(II->getParent());
2953 auto *BI = UncondBrInst::Create(MergedInvoke->getParent(), II->getParent());
2954 // The unconditional branch is part of the replacement for the original
2955 // invoke, so should use its DebugLoc.
2956 BI->setDebugLoc(II->getDebugLoc());
2957 bool Success = MergedInvoke->tryIntersectAttributes(II);
2958 assert(Success && "Merged invokes with incompatible attributes");
2959 // For NDEBUG Compile
2960 (void)Success;
2961 II->replaceAllUsesWith(MergedInvoke);
2962 II->eraseFromParent();
2963 ++NumInvokesMerged;
2964 }
2965 MergedInvoke->setDebugLoc(MergedDebugLoc);
2966 ++NumInvokeSetsFormed;
2967
2968 if (DTU)
2969 DTU->applyUpdates(Updates);
2970}
2971
2972/// If this block is a `landingpad` exception handling block, categorize all
2973/// the predecessor `invoke`s into sets, with all `invoke`s in each set
2974/// being "mergeable" together, and then merge invokes in each set together.
2975///
2976/// This is a weird mix of hoisting and sinking. Visually, it goes from:
2977/// [...] [...]
2978/// | |
2979/// [invoke0] [invoke1]
2980/// / \ / \
2981/// [cont0] [landingpad] [cont1]
2982/// to:
2983/// [...] [...]
2984/// \ /
2985/// [invoke]
2986/// / \
2987/// [cont] [landingpad]
2988///
2989/// But of course we can only do that if the invokes share the `landingpad`,
2990/// edges invoke0->cont0 and invoke1->cont1 are "compatible",
2991/// and the invoked functions are "compatible".
2994 return false;
2995
2996 bool Changed = false;
2997
2998 // FIXME: generalize to all exception handling blocks?
2999 if (!BB->isLandingPad())
3000 return Changed;
3001
3002 CompatibleSets Grouper;
3003
3004 // Record all the predecessors of this `landingpad`. As per verifier,
3005 // the only allowed predecessor is the unwind edge of an `invoke`.
3006 // We want to group "compatible" `invokes` into the same set to be merged.
3007 for (BasicBlock *PredBB : predecessors(BB))
3008 Grouper.insert(cast<InvokeInst>(PredBB->getTerminator()));
3009
3010 // And now, merge `invoke`s that were grouped togeter.
3011 for (ArrayRef<InvokeInst *> Invokes : Grouper.Sets) {
3012 if (Invokes.size() < 2)
3013 continue;
3014 Changed = true;
3015 mergeCompatibleInvokesImpl(Invokes, DTU);
3016 }
3017
3018 return Changed;
3019}
3020
3021namespace {
3022/// Track ephemeral values, which should be ignored for cost-modelling
3023/// purposes. Requires walking instructions in reverse order.
3024class EphemeralValueTracker {
3025 SmallPtrSet<const Instruction *, 32> EphValues;
3026
3027 bool isEphemeral(const Instruction *I) {
3028 if (isa<AssumeInst>(I))
3029 return true;
3030 return !I->mayHaveSideEffects() && !I->isTerminator() &&
3031 all_of(I->users(), [&](const User *U) {
3032 return EphValues.count(cast<Instruction>(U));
3033 });
3034 }
3035
3036public:
3037 bool track(const Instruction *I) {
3038 if (isEphemeral(I)) {
3039 EphValues.insert(I);
3040 return true;
3041 }
3042 return false;
3043 }
3044
3045 bool contains(const Instruction *I) const { return EphValues.contains(I); }
3046};
3047} // namespace
3048
3049/// Determine if we can hoist sink a sole store instruction out of a
3050/// conditional block.
3051///
3052/// We are looking for code like the following:
3053/// BrBB:
3054/// store i32 %add, i32* %arrayidx2
3055/// ... // No other stores or function calls (we could be calling a memory
3056/// ... // function).
3057/// %cmp = icmp ult %x, %y
3058/// br i1 %cmp, label %EndBB, label %ThenBB
3059/// ThenBB:
3060/// store i32 %add5, i32* %arrayidx2
3061/// br label EndBB
3062/// EndBB:
3063/// ...
3064/// We are going to transform this into:
3065/// BrBB:
3066/// store i32 %add, i32* %arrayidx2
3067/// ... //
3068/// %cmp = icmp ult %x, %y
3069/// %add.add5 = select i1 %cmp, i32 %add, %add5
3070/// store i32 %add.add5, i32* %arrayidx2
3071/// ...
3072///
3073/// \return The value from the previous access if the store can be hoisted into
3074/// the predecessor block. PreviousAccess is set to that access. Return
3075/// null otherwise.
3077 BasicBlock *StoreBB, BasicBlock *EndBB,
3078 Instruction *&PreviousAccess) {
3079 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
3080 if (!StoreToHoist)
3081 return nullptr;
3082
3083 // Volatile or atomic.
3084 if (!StoreToHoist->isSimple())
3085 return nullptr;
3086
3087 Value *StorePtr = StoreToHoist->getPointerOperand();
3088 Type *StoreTy = StoreToHoist->getValueOperand()->getType();
3089
3090 // Look for a store to the same pointer in BrBB.
3091 unsigned MaxNumInstToLookAt = 9;
3092 // Skip pseudo probe intrinsic calls which are not really killing any memory
3093 // accesses.
3094 for (Instruction &CurI : reverse(*BrBB)) {
3095 if (!MaxNumInstToLookAt)
3096 break;
3097 --MaxNumInstToLookAt;
3098
3099 if (isa<PseudoProbeInst>(CurI))
3100 continue;
3101
3102 // Could be calling an instruction that affects memory like free().
3103 if (CurI.mayWriteToMemory() && !isa<StoreInst>(CurI))
3104 return nullptr;
3105
3106 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
3107 // Found the previous store to same location and type. Make sure it is
3108 // simple, to avoid introducing a spurious non-atomic write after an
3109 // atomic write.
3110 if (SI->getPointerOperand() == StorePtr &&
3111 SI->getValueOperand()->getType() == StoreTy && SI->isSimple() &&
3112 SI->getAlign() >= StoreToHoist->getAlign()) {
3113 // Found the previous store, return its value operand.
3114 PreviousAccess = SI;
3115 return SI->getValueOperand();
3116 }
3117 return nullptr; // Unknown store.
3118 }
3119
3120 if (auto *LI = dyn_cast<LoadInst>(&CurI)) {
3121 if (LI->getPointerOperand() == StorePtr && LI->getType() == StoreTy &&
3122 LI->isSimple() && LI->getAlign() >= StoreToHoist->getAlign()) {
3123 Value *Obj = getUnderlyingObject(StorePtr);
3124 bool ExplicitlyDereferenceableOnly;
3125 // The dereferenceability query here is only required to satisfy the
3126 // writable contract, actual dereferenceability is proven by the
3127 // presence of an access. As such, we can ignore frees.
3128 if (isWritableObject(Obj, ExplicitlyDereferenceableOnly) &&
3131 .WithoutRet) &&
3132 (!ExplicitlyDereferenceableOnly ||
3133 isDereferenceablePointer(StorePtr, StoreTy, LI->getDataLayout(),
3134 /*IgnoreFree=*/true))) {
3135 // Found a previous load, return it.
3136 PreviousAccess = LI;
3137 return LI;
3138 }
3139 }
3140 // The load didn't work out, but we may still find a store.
3141 }
3142 }
3143
3144 return nullptr;
3145}
3146
3147/// Estimate the cost of the insertion(s) and check that the PHI nodes can be
3148/// converted to selects.
3150 BasicBlock *EndBB,
3151 unsigned &SpeculatedInstructions,
3152 InstructionCost &Cost,
3153 const TargetTransformInfo &TTI) {
3155 BB->getParent()->hasMinSize()
3158
3159 bool HaveRewritablePHIs = false;
3160 for (PHINode &PN : EndBB->phis()) {
3161 Value *OrigV = PN.getIncomingValueForBlock(BB);
3162 Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
3163
3164 // FIXME: Try to remove some of the duplication with
3165 // hoistCommonCodeFromSuccessors. Skip PHIs which are trivial.
3166 if (ThenV == OrigV)
3167 continue;
3168
3169 Cost += TTI.getCmpSelInstrCost(Instruction::Select, PN.getType(),
3170 Type::getInt1Ty(PN.getContext()),
3172
3173 // Don't convert to selects if we could remove undefined behavior instead.
3174 if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
3176 return false;
3177
3178 HaveRewritablePHIs = true;
3179 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
3180 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
3181 if (!OrigCE && !ThenCE)
3182 continue; // Known cheap (FIXME: Maybe not true for aggregates).
3183
3184 InstructionCost OrigCost = OrigCE ? computeSpeculationCost(OrigCE, TTI) : 0;
3185 InstructionCost ThenCost = ThenCE ? computeSpeculationCost(ThenCE, TTI) : 0;
3186 InstructionCost MaxCost =
3188 if (OrigCost + ThenCost > MaxCost)
3189 return false;
3190
3191 // Account for the cost of an unfolded ConstantExpr which could end up
3192 // getting expanded into Instructions.
3193 // FIXME: This doesn't account for how many operations are combined in the
3194 // constant expression.
3195 ++SpeculatedInstructions;
3196 if (SpeculatedInstructions > 1)
3197 return false;
3198 }
3199
3200 return HaveRewritablePHIs;
3201}
3202
3204 std::optional<bool> Invert,
3205 const TargetTransformInfo &TTI) {
3206 // If the branch is non-unpredictable, and is predicted to *not* branch to
3207 // the `then` block, then avoid speculating it.
3208 if (BI->getMetadata(LLVMContext::MD_unpredictable))
3209 return true;
3210
3211 uint64_t TWeight, FWeight;
3212 if (!extractBranchWeights(*BI, TWeight, FWeight) || (TWeight + FWeight) == 0)
3213 return true;
3214
3215 if (!Invert.has_value())
3216 return false;
3217
3218 uint64_t EndWeight = *Invert ? TWeight : FWeight;
3219 BranchProbability BIEndProb =
3220 BranchProbability::getBranchProbability(EndWeight, TWeight + FWeight);
3221 BranchProbability Likely = TTI.getPredictableBranchThreshold();
3222 return BIEndProb < Likely;
3223}
3224
3225/// Speculate a conditional basic block flattening the CFG.
3226///
3227/// Note that this is a very risky transform currently. Speculating
3228/// instructions like this is most often not desirable. Instead, there is an MI
3229/// pass which can do it with full awareness of the resource constraints.
3230/// However, some cases are "obvious" and we should do directly. An example of
3231/// this is speculating a single, reasonably cheap instruction.
3232///
3233/// There is only one distinct advantage to flattening the CFG at the IR level:
3234/// it makes very common but simplistic optimizations such as are common in
3235/// instcombine and the DAG combiner more powerful by removing CFG edges and
3236/// modeling their effects with easier to reason about SSA value graphs.
3237///
3238///
3239/// An illustration of this transform is turning this IR:
3240/// \code
3241/// BB:
3242/// %cmp = icmp ult %x, %y
3243/// br i1 %cmp, label %EndBB, label %ThenBB
3244/// ThenBB:
3245/// %sub = sub %x, %y
3246/// br label BB2
3247/// EndBB:
3248/// %phi = phi [ %sub, %ThenBB ], [ 0, %BB ]
3249/// ...
3250/// \endcode
3251///
3252/// Into this IR:
3253/// \code
3254/// BB:
3255/// %cmp = icmp ult %x, %y
3256/// %sub = sub %x, %y
3257/// %cond = select i1 %cmp, 0, %sub
3258/// ...
3259/// \endcode
3260///
3261/// \returns true if the conditional block is removed.
3262bool SimplifyCFGOpt::speculativelyExecuteBB(CondBrInst *BI,
3263 BasicBlock *ThenBB) {
3264 if (!Options.SpeculateBlocks)
3265 return false;
3266
3267 BasicBlock *BB = BI->getParent();
3268 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
3269 InstructionCost Budget =
3271
3272 // If ThenBB is actually on the false edge of the conditional branch, remember
3273 // to swap the select operands later.
3274 bool Invert = false;
3275 if (ThenBB != BI->getSuccessor(0)) {
3276 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
3277 Invert = true;
3278 }
3279 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
3280
3281 if (!isProfitableToSpeculate(BI, Invert, TTI))
3282 return false;
3283
3284 // Keep a count of how many times instructions are used within ThenBB when
3285 // they are candidates for sinking into ThenBB. Specifically:
3286 // - They are defined in BB, and
3287 // - They have no side effects, and
3288 // - All of their uses are in ThenBB.
3289 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
3290
3291 SmallVector<Instruction *, 4> SpeculatedPseudoProbes;
3292
3293 unsigned SpeculatedInstructions = 0;
3294 bool HoistLoadsStores = Options.HoistLoadsStoresWithCondFaulting;
3295 SmallVector<Instruction *, 2> SpeculatedConditionalLoadsStores;
3296 Value *SpeculatedStoreValue = nullptr;
3297 StoreInst *SpeculatedStore = nullptr;
3298 Instruction *PreviousStoreAccess = nullptr;
3299 EphemeralValueTracker EphTracker;
3300 for (Instruction &I : reverse(drop_end(*ThenBB))) {
3301 // Skip pseudo probes. The consequence is we lose track of the branch
3302 // probability for ThenBB, which is fine since the optimization here takes
3303 // place regardless of the branch probability.
3304 if (isa<PseudoProbeInst>(I)) {
3305 // The probe should be deleted so that it will not be over-counted when
3306 // the samples collected on the non-conditional path are counted towards
3307 // the conditional path. We leave it for the counts inference algorithm to
3308 // figure out a proper count for an unknown probe.
3309 SpeculatedPseudoProbes.push_back(&I);
3310 continue;
3311 }
3312
3313 // Ignore ephemeral values, they will be dropped by the transform.
3314 if (EphTracker.track(&I))
3315 continue;
3316
3317 // Only speculatively execute a single instruction (not counting the
3318 // terminator) for now.
3319 bool IsSafeCheapLoadStore = HoistLoadsStores &&
3321 SpeculatedConditionalLoadsStores.size() <
3323 // Not count load/store into cost if target supports conditional faulting
3324 // b/c it's cheap to speculate it.
3325 if (IsSafeCheapLoadStore)
3326 SpeculatedConditionalLoadsStores.push_back(&I);
3327 else
3328 ++SpeculatedInstructions;
3329
3330 if (SpeculatedInstructions > 1)
3331 return false;
3332
3333 // Don't hoist the instruction if it's unsafe or expensive.
3334 if (!IsSafeCheapLoadStore &&
3336 !(HoistCondStores && !SpeculatedStoreValue &&
3337 (SpeculatedStoreValue = isSafeToSpeculateStore(&I, BB, ThenBB, EndBB,
3338 PreviousStoreAccess))))
3339 return false;
3340 if (!IsSafeCheapLoadStore && !SpeculatedStoreValue &&
3343 return false;
3344
3345 // Store the store speculation candidate.
3346 if (!SpeculatedStore && SpeculatedStoreValue)
3347 SpeculatedStore = cast<StoreInst>(&I);
3348
3349 // Do not hoist the instruction if any of its operands are defined but not
3350 // used in BB. The transformation will prevent the operand from
3351 // being sunk into the use block.
3352 for (Use &Op : I.operands()) {
3354 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
3355 continue; // Not a candidate for sinking.
3356
3357 ++SinkCandidateUseCounts[OpI];
3358 }
3359 }
3360
3361 // Consider any sink candidates which are only used in ThenBB as costs for
3362 // speculation. Note, while we iterate over a DenseMap here, we are summing
3363 // and so iteration order isn't significant.
3364 for (const auto &[Inst, Count] : SinkCandidateUseCounts)
3365 if (Inst->hasNUses(Count)) {
3366 ++SpeculatedInstructions;
3367 if (SpeculatedInstructions > 1)
3368 return false;
3369 }
3370
3371 // Check that we can insert the selects and that it's not too expensive to do
3372 // so.
3373 bool Convert =
3374 SpeculatedStore != nullptr || !SpeculatedConditionalLoadsStores.empty();
3376 Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB,
3377 SpeculatedInstructions, Cost, TTI);
3378 if (!Convert || Cost > Budget)
3379 return false;
3380
3381 // If we get here, we can hoist the instruction and if-convert.
3382 LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
3383
3384 Instruction *Sel = nullptr;
3385 Value *BrCond = BI->getCondition();
3386 // Insert a select of the value of the speculated store.
3387 if (SpeculatedStoreValue) {
3388 IRBuilder<NoFolder> Builder(BI);
3389 Value *OrigV = SpeculatedStore->getValueOperand();
3390 Value *TrueV = SpeculatedStore->getValueOperand();
3391 Value *FalseV = SpeculatedStoreValue;
3392 if (Invert)
3393 std::swap(TrueV, FalseV);
3394 Value *S = Builder.CreateSelect(
3395 BrCond, TrueV, FalseV, "spec.store.select", BI);
3396 Sel = cast<Instruction>(S);
3397 SpeculatedStore->setOperand(0, S);
3398 SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
3399 SpeculatedStore->getDebugLoc());
3400 // The value stored is still conditional, but the store itself is now
3401 // unconditionally executed, so we must be sure that any linked dbg.assign
3402 // intrinsics are tracking the new stored value (the result of the
3403 // select). If we don't, and the store were to be removed by another pass
3404 // (e.g. DSE), then we'd eventually end up emitting a location describing
3405 // the conditional value, unconditionally.
3406 //
3407 // === Before this transformation ===
3408 // pred:
3409 // store %one, %x.dest, !DIAssignID !1
3410 // dbg.assign %one, "x", ..., !1, ...
3411 // br %cond if.then
3412 //
3413 // if.then:
3414 // store %two, %x.dest, !DIAssignID !2
3415 // dbg.assign %two, "x", ..., !2, ...
3416 //
3417 // === After this transformation ===
3418 // pred:
3419 // store %one, %x.dest, !DIAssignID !1
3420 // dbg.assign %one, "x", ..., !1
3421 /// ...
3422 // %merge = select %cond, %two, %one
3423 // store %merge, %x.dest, !DIAssignID !2
3424 // dbg.assign %merge, "x", ..., !2
3425 for (DbgVariableRecord *DbgAssign :
3426 at::getDVRAssignmentMarkers(SpeculatedStore))
3427 if (llvm::is_contained(DbgAssign->location_ops(), OrigV))
3428 DbgAssign->replaceVariableLocationOp(OrigV, S);
3429 }
3430
3431 // Metadata can be dependent on the condition we are hoisting above.
3432 // Strip all UB-implying metadata on the instruction. Drop the debug loc
3433 // to avoid making it appear as if the condition is a constant, which would
3434 // be misleading while debugging.
3435 // Similarly strip attributes that maybe dependent on condition we are
3436 // hoisting above.
3437 for (auto &I : make_early_inc_range(*ThenBB)) {
3438 if (!SpeculatedStoreValue || &I != SpeculatedStore) {
3439 I.dropLocation();
3440 I.dropUBImplyingAttrsAndMetadata();
3441 } else {
3442 assert(PreviousStoreAccess && "Missing previous store access");
3443 AAMDNodes MergedAA = SpeculatedStore->getAAMetadata().merge(
3444 PreviousStoreAccess->getAAMetadata());
3445 I.dropUBImplyingAttrsAndMetadata();
3446 I.setAAMetadata(MergedAA);
3447 }
3448
3449 // Drop ephemeral values.
3450 if (EphTracker.contains(&I)) {
3451 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
3452 I.eraseFromParent();
3453 }
3454 }
3455
3456 // Hoist the instructions.
3457 // Drop DbgVariableRecords attached to these instructions.
3458 for (auto &It : *ThenBB)
3459 for (DbgRecord &DR : make_early_inc_range(It.getDbgRecordRange()))
3460 // Drop all records except assign-kind DbgVariableRecords (dbg.assign
3461 // equivalent).
3462 if (DbgVariableRecord *DVR = dyn_cast<DbgVariableRecord>(&DR);
3463 !DVR || !DVR->isDbgAssign())
3464 It.dropOneDbgRecord(&DR);
3465 BB->splice(BI->getIterator(), ThenBB, ThenBB->begin(),
3466 std::prev(ThenBB->end()));
3467
3468 if (!SpeculatedConditionalLoadsStores.empty())
3469 hoistConditionalLoadsStores(BI, SpeculatedConditionalLoadsStores, Invert,
3470 Sel);
3471
3472 // Insert selects and rewrite the PHI operands.
3473 IRBuilder<NoFolder> Builder(BI);
3474 for (PHINode &PN : EndBB->phis()) {
3475 unsigned OrigI = PN.getBasicBlockIndex(BB);
3476 unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
3477 Value *OrigV = PN.getIncomingValue(OrigI);
3478 Value *ThenV = PN.getIncomingValue(ThenI);
3479
3480 // Skip PHIs which are trivial.
3481 if (OrigV == ThenV)
3482 continue;
3483
3484 // Create a select whose true value is the speculatively executed value and
3485 // false value is the pre-existing value. Swap them if the branch
3486 // destinations were inverted.
3487 Value *TrueV = ThenV, *FalseV = OrigV;
3488 if (Invert)
3489 std::swap(TrueV, FalseV);
3490 // Propagate fast-math flags from the phi node to the replacement select.
3491 Value *V = Builder.CreateSelectFMF(
3492 BrCond, TrueV, FalseV, PN.getFastMathFlagsOrNone(), "spec.select", BI);
3493 PN.setIncomingValue(OrigI, V);
3494 PN.setIncomingValue(ThenI, V);
3495 }
3496
3497 // Remove speculated pseudo probes.
3498 for (Instruction *I : SpeculatedPseudoProbes)
3499 I->eraseFromParent();
3500
3501 ++NumSpeculations;
3502 return true;
3503}
3504
3506
3507// Return false if number of blocks searched is too much.
3508static bool findReaching(BasicBlock *BB, BasicBlock *DefBB,
3509 BlocksSet &ReachesNonLocalUses) {
3510 if (BB == DefBB)
3511 return true;
3512 if (!ReachesNonLocalUses.insert(BB).second)
3513 return true;
3514
3515 if (ReachesNonLocalUses.size() > MaxJumpThreadingLiveBlocks)
3516 return false;
3517 for (BasicBlock *Pred : predecessors(BB))
3518 if (!findReaching(Pred, DefBB, ReachesNonLocalUses))
3519 return false;
3520 return true;
3521}
3522
3523/// Return true if we can thread a branch across this block.
3525 BlocksSet &NonLocalUseBlocks) {
3526 int Size = 0;
3527 EphemeralValueTracker EphTracker;
3528
3529 // Walk the loop in reverse so that we can identify ephemeral values properly
3530 // (values only feeding assumes).
3531 for (Instruction &I : reverse(*BB)) {
3532 // Can't fold blocks that contain noduplicate or convergent calls.
3533 if (CallInst *CI = dyn_cast<CallInst>(&I))
3534 if (CI->cannotDuplicate() || CI->isConvergent())
3535 return false;
3536
3537 // Ignore ephemeral values which are deleted during codegen.
3538 // We will delete Phis while threading, so Phis should not be accounted in
3539 // block's size.
3540 if (!EphTracker.track(&I) && !isa<PHINode>(I)) {
3541 if (Size++ > MaxSmallBlockSize)
3542 return false; // Don't clone large BB's.
3543 }
3544
3545 // Record blocks with non-local uses of values defined in the current basic
3546 // block.
3547 for (User *U : I.users()) {
3549 BasicBlock *UsedInBB = UI->getParent();
3550 if (UsedInBB == BB) {
3551 if (isa<PHINode>(UI))
3552 return false;
3553 } else
3554 NonLocalUseBlocks.insert(UsedInBB);
3555 }
3556
3557 // Looks ok, continue checking.
3558 }
3559
3560 return true;
3561}
3562
3564 BasicBlock *To) {
3565 // Don't look past the block defining the value, we might get the value from
3566 // a previous loop iteration.
3567 auto *I = dyn_cast<Instruction>(V);
3568 if (I && I->getParent() == To)
3569 return nullptr;
3570
3571 // We know the value if the From block branches on it.
3572 auto *BI = dyn_cast<CondBrInst>(From->getTerminator());
3573 if (BI && BI->getCondition() == V &&
3574 BI->getSuccessor(0) != BI->getSuccessor(1))
3575 return BI->getSuccessor(0) == To ? ConstantInt::getTrue(BI->getContext())
3577
3578 return nullptr;
3579}
3580
3582 return CB->isConvergent() && !isa<ConvergenceControlInst>(CB) &&
3584}
3585
3587 BasicBlock *StopBB) {
3588 static constexpr unsigned MaxInstructionsToScan = 512;
3589
3590 // Walk predecessors of StopBB to find blocks that can reach it. Only
3591 // convergent calls on a cycle with StopBB matter - a convergent call on a
3592 // path to function exit cannot have its dynamic instance changed by
3593 // threading.
3594 SmallPtrSet<BasicBlock *, 8> CanReachStop;
3595 SmallPtrSet<BasicBlock *, 8> BlocksWithUncontrolledConvergentCalls;
3597 for (BasicBlock *Pred : predecessors(StopBB))
3598 Worklist.push_back(Pred);
3599
3600 // Cache blocks with relevant calls while building CanReachStop. This keeps
3601 // the instruction scan bounded without a separate block limit.
3602 unsigned NumScannedInstructions = 0;
3603 while (!Worklist.empty()) {
3604 BasicBlock *BB = Worklist.pop_back_val();
3605 if (BB == StopBB)
3606 continue;
3607 if (!CanReachStop.insert(BB).second)
3608 continue;
3609
3610 for (Instruction &I : *BB) {
3611 if (++NumScannedInstructions > MaxInstructionsToScan)
3612 return true;
3613 auto *CB = dyn_cast<CallBase>(&I);
3614 if (CB && isUncontrolledConvergentCall(CB)) {
3615 BlocksWithUncontrolledConvergentCalls.insert(BB);
3616 break;
3617 }
3618 }
3619
3620 append_range(Worklist, predecessors(BB));
3621 }
3622
3623 if (!CanReachStop.contains(From))
3624 return false;
3625
3627 Worklist.push_back(From);
3628
3629 while (!Worklist.empty()) {
3630 BasicBlock *BB = Worklist.pop_back_val();
3631 if (BB == StopBB || !CanReachStop.contains(BB))
3632 continue;
3633
3634 if (!Visited.insert(BB).second)
3635 continue;
3636
3637 if (BlocksWithUncontrolledConvergentCalls.contains(BB))
3638 return true;
3639
3640 append_range(Worklist, successors(BB));
3641 }
3642
3643 return false;
3644}
3645
3646/// If we have a conditional branch on something for which we know the constant
3647/// value in predecessors (e.g. a phi node in the current block), thread edges
3648/// from the predecessor to their ultimate destination.
3651 AssumptionCache *AC, const DataLayout &DL) {
3653 BasicBlock *BB = BI->getParent();
3654 Value *Cond = BI->getCondition();
3656 if (PN && PN->getParent() == BB) {
3657 // Degenerate case of a single entry PHI.
3658 if (PN->getNumIncomingValues() == 1) {
3660 return true;
3661 }
3662
3663 for (Use &U : PN->incoming_values())
3664 if (auto *CB = dyn_cast<ConstantInt>(U))
3665 KnownValues[CB].insert(PN->getIncomingBlock(U));
3666 } else {
3667 for (BasicBlock *Pred : predecessors(BB)) {
3668 if (ConstantInt *CB = getKnownValueOnEdge(Cond, Pred, BB))
3669 KnownValues[CB].insert(Pred);
3670 }
3671 }
3672
3673 if (KnownValues.empty())
3674 return false;
3675
3676 // Now we know that this block has multiple preds and two succs.
3677 // Check that the block is small enough and record which non-local blocks use
3678 // values defined in the block.
3679
3680 BlocksSet NonLocalUseBlocks;
3681 BlocksSet ReachesNonLocalUseBlocks;
3682 if (!blockIsSimpleEnoughToThreadThrough(BB, NonLocalUseBlocks))
3683 return false;
3684
3685 // Jump-threading can only be done to destinations where no values defined
3686 // in BB are live.
3687
3688 // Quickly check if both destinations have uses. If so, jump-threading cannot
3689 // be done.
3690 if (NonLocalUseBlocks.contains(BI->getSuccessor(0)) &&
3691 NonLocalUseBlocks.contains(BI->getSuccessor(1)))
3692 return false;
3693
3694 // Search backward from NonLocalUseBlocks to find which blocks
3695 // reach non-local uses.
3696 for (BasicBlock *UseBB : NonLocalUseBlocks)
3697 // Give up if too many blocks are searched.
3698 if (!findReaching(UseBB, BB, ReachesNonLocalUseBlocks))
3699 return false;
3700
3701 for (const auto &Pair : KnownValues) {
3702 ConstantInt *CB = Pair.first;
3703 ArrayRef<BasicBlock *> PredBBs = Pair.second.getArrayRef();
3704 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
3705
3706 // Okay, we now know that all edges from PredBB should be revectored to
3707 // branch to RealDest.
3708 if (RealDest == BB)
3709 continue; // Skip self loops.
3710
3711 // Skip if the predecessor's terminator is an indirect branch.
3712 if (any_of(PredBBs, [](BasicBlock *PredBB) {
3713 return isa<IndirectBrInst>(PredBB->getTerminator());
3714 }))
3715 continue;
3716
3717 // Only revector to RealDest if no values defined in BB are live.
3718 if (ReachesNonLocalUseBlocks.contains(RealDest))
3719 continue;
3720
3721 // Threading through a branch can bypass a reconvergence point. If the
3722 // destination can execute an uncontrolled convergent operation before
3723 // returning to this block, this may change the dynamic instance of that
3724 // operation.
3725 if (TTI.hasBranchDivergence(BB->getParent()) &&
3727 continue;
3728
3729 LLVM_DEBUG({
3730 dbgs() << "Condition " << *Cond << " in " << BB->getName()
3731 << " has value " << *Pair.first << " in predecessors:\n";
3732 for (const BasicBlock *PredBB : Pair.second)
3733 dbgs() << " " << PredBB->getName() << "\n";
3734 dbgs() << "Threading to destination " << RealDest->getName() << ".\n";
3735 });
3736
3737 // Split the predecessors we are threading into a new edge block. We'll
3738 // clone the instructions into this block, and then redirect it to RealDest.
3739 BasicBlock *EdgeBB = SplitBlockPredecessors(BB, PredBBs, ".critedge", DTU);
3740 if (!EdgeBB)
3741 continue;
3742
3743 // TODO: These just exist to reduce test diff, we can drop them if we like.
3744 EdgeBB->setName(RealDest->getName() + ".critedge");
3745 EdgeBB->moveBefore(RealDest);
3746
3747 // Update PHI nodes.
3748 addPredecessorToBlock(RealDest, EdgeBB, BB);
3749
3750 // BB may have instructions that are being threaded over. Clone these
3751 // instructions into EdgeBB. We know that there will be no uses of the
3752 // cloned instructions outside of EdgeBB.
3753 BasicBlock::iterator InsertPt = EdgeBB->getFirstInsertionPt();
3754 ValueToValueMapTy TranslateMap; // Track translated values.
3755 TranslateMap[Cond] = CB;
3756
3757 // RemoveDIs: track instructions that we optimise away while folding, so
3758 // that we can copy DbgVariableRecords from them later.
3759 BasicBlock::iterator SrcDbgCursor = BB->begin();
3760 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
3761 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
3762 TranslateMap[PN] = PN->getIncomingValueForBlock(EdgeBB);
3763 continue;
3764 }
3765 // Clone the instruction.
3766 Instruction *N = BBI->clone();
3767 // Insert the new instruction into its new home.
3768 N->insertInto(EdgeBB, InsertPt);
3769
3770 if (BBI->hasName())
3771 N->setName(BBI->getName() + ".c");
3772
3773 // Update operands due to translation.
3774 // Key Instructions: Remap all the atom groups.
3775 if (const DebugLoc &DL = BBI->getDebugLoc())
3776 mapAtomInstance(DL, TranslateMap);
3777 RemapInstruction(N, TranslateMap,
3779
3780 // Check for trivial simplification.
3781 if (Value *V = simplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
3782 if (!BBI->use_empty())
3783 TranslateMap[&*BBI] = V;
3784 if (!N->mayHaveSideEffects()) {
3785 N->eraseFromParent(); // Instruction folded away, don't need actual
3786 // inst
3787 N = nullptr;
3788 }
3789 } else {
3790 if (!BBI->use_empty())
3791 TranslateMap[&*BBI] = N;
3792 }
3793 if (N) {
3794 // Copy all debug-info attached to instructions from the last we
3795 // successfully clone, up to this instruction (they might have been
3796 // folded away).
3797 for (; SrcDbgCursor != BBI; ++SrcDbgCursor)
3798 N->cloneDebugInfoFrom(&*SrcDbgCursor);
3799 SrcDbgCursor = std::next(BBI);
3800 // Clone debug-info on this instruction too.
3801 N->cloneDebugInfoFrom(&*BBI);
3802
3803 // Register the new instruction with the assumption cache if necessary.
3804 if (auto *Assume = dyn_cast<AssumeInst>(N))
3805 if (AC)
3806 AC->registerAssumption(Assume);
3807 }
3808 }
3809
3810 for (; &*SrcDbgCursor != BI; ++SrcDbgCursor)
3811 InsertPt->cloneDebugInfoFrom(&*SrcDbgCursor);
3812 InsertPt->cloneDebugInfoFrom(BI);
3813
3814 BB->removePredecessor(EdgeBB);
3815 UncondBrInst *EdgeBI = cast<UncondBrInst>(EdgeBB->getTerminator());
3816 EdgeBI->setSuccessor(0, RealDest);
3817 EdgeBI->setDebugLoc(BI->getDebugLoc());
3818
3819 if (DTU) {
3821 Updates.push_back({DominatorTree::Delete, EdgeBB, BB});
3822 Updates.push_back({DominatorTree::Insert, EdgeBB, RealDest});
3823 DTU->applyUpdates(Updates);
3824 }
3825
3826 // For simplicity, we created a separate basic block for the edge. Merge
3827 // it back into the predecessor if possible. This not only avoids
3828 // unnecessary SimplifyCFG iterations, but also makes sure that we don't
3829 // bypass the check for trivial cycles above.
3830 MergeBlockIntoPredecessor(EdgeBB, DTU);
3831
3832 // Signal repeat, simplifying any other constants.
3833 return std::nullopt;
3834 }
3835
3836 return false;
3837}
3838
3839bool SimplifyCFGOpt::foldCondBranchOnValueKnownInPredecessor(CondBrInst *BI) {
3840 // Note: If BB is a loop header then there is a risk that threading introduces
3841 // a non-canonical loop by moving a back edge. So we avoid this optimization
3842 // for loop headers if NeedCanonicalLoop is set.
3843 if (Options.NeedCanonicalLoop && is_contained(LoopHeaders, BI->getParent()))
3844 return false;
3845
3846 std::optional<bool> Result;
3847 bool EverChanged = false;
3848 do {
3849 // Note that None means "we changed things, but recurse further."
3851 Options.AC, DL);
3852 EverChanged |= Result == std::nullopt || *Result;
3853 } while (Result == std::nullopt);
3854 return EverChanged;
3855}
3856
3857/// Given a BB that starts with the specified two-entry PHI node,
3858/// see if we can eliminate it.
3861 const DataLayout &DL,
3862 bool SpeculateUnpredictables) {
3863 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
3864 // statement", which has a very simple dominance structure. Basically, we
3865 // are trying to find the condition that is being branched on, which
3866 // subsequently causes this merge to happen. We really want control
3867 // dependence information for this check, but simplifycfg can't keep it up
3868 // to date, and this catches most of the cases we care about anyway.
3869 BasicBlock *BB = PN->getParent();
3870
3871 BasicBlock *IfTrue, *IfFalse;
3872 CondBrInst *DomBI = GetIfCondition(BB, IfTrue, IfFalse);
3873 if (!DomBI)
3874 return false;
3875 Value *IfCond = DomBI->getCondition();
3876 // Don't bother if the branch will be constant folded trivially.
3877 if (isa<ConstantInt>(IfCond))
3878 return false;
3879
3880 BasicBlock *DomBlock = DomBI->getParent();
3882 llvm::copy_if(PN->blocks(), std::back_inserter(IfBlocks),
3883 [](BasicBlock *IfBlock) {
3884 return isa<UncondBrInst>(IfBlock->getTerminator());
3885 });
3886 assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) &&
3887 "Will have either one or two blocks to speculate.");
3888
3889 // If the branch is non-unpredictable, see if we either predictably jump to
3890 // the merge bb (if we have only a single 'then' block), or if we predictably
3891 // jump to one specific 'then' block (if we have two of them).
3892 // It isn't beneficial to speculatively execute the code
3893 // from the block that we know is predictably not entered.
3894 bool IsUnpredictable = DomBI->getMetadata(LLVMContext::MD_unpredictable);
3895 if (!IsUnpredictable) {
3896 uint64_t TWeight, FWeight;
3897 if (extractBranchWeights(*DomBI, TWeight, FWeight) &&
3898 (TWeight + FWeight) != 0) {
3899 BranchProbability BITrueProb =
3900 BranchProbability::getBranchProbability(TWeight, TWeight + FWeight);
3901 BranchProbability Likely = TTI.getPredictableBranchThreshold();
3902 BranchProbability BIFalseProb = BITrueProb.getCompl();
3903 if (IfBlocks.size() == 1) {
3904 BranchProbability BIBBProb =
3905 DomBI->getSuccessor(0) == BB ? BITrueProb : BIFalseProb;
3906 if (BIBBProb >= Likely)
3907 return false;
3908 } else {
3909 if (BITrueProb >= Likely || BIFalseProb >= Likely)
3910 return false;
3911 }
3912 }
3913 }
3914
3915 // Don't try to fold an unreachable block. For example, the phi node itself
3916 // can't be the candidate if-condition for a select that we want to form.
3917 if (auto *IfCondPhiInst = dyn_cast<PHINode>(IfCond))
3918 if (IfCondPhiInst->getParent() == BB)
3919 return false;
3920
3921 // Okay, we found that we can merge this two-entry phi node into a select.
3922 // Doing so would require us to fold *all* two entry phi nodes in this block.
3923 // At some point this becomes non-profitable (particularly if the target
3924 // doesn't support cmov's). Only do this transformation if there are two or
3925 // fewer PHI nodes in this block.
3926 unsigned NumPhis = 0;
3927 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
3928 if (NumPhis > 2)
3929 return false;
3930
3931 // Loop over the PHI's seeing if we can promote them all to select
3932 // instructions. While we are at it, keep track of the instructions
3933 // that need to be moved to the dominating block.
3934 SmallPtrSet<Instruction *, 4> AggressiveInsts;
3935 SmallPtrSet<Instruction *, 2> ZeroCostInstructions;
3936 InstructionCost Cost = 0;
3937 InstructionCost Budget =
3939 if (SpeculateUnpredictables && IsUnpredictable)
3940 Budget += TTI.getBranchMispredictPenalty();
3941
3942 bool Changed = false;
3943 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
3944 PHINode *PN = cast<PHINode>(II++);
3945 if (Value *V = simplifyInstruction(PN, {DL, PN})) {
3946 PN->replaceAllUsesWith(V);
3947 PN->eraseFromParent();
3948 Changed = true;
3949 continue;
3950 }
3951
3952 if (!dominatesMergePoint(PN->getIncomingValue(0), BB, DomBI,
3953 AggressiveInsts, Cost, Budget, TTI, AC,
3954 ZeroCostInstructions) ||
3955 !dominatesMergePoint(PN->getIncomingValue(1), BB, DomBI,
3956 AggressiveInsts, Cost, Budget, TTI, AC,
3957 ZeroCostInstructions))
3958 return Changed;
3959 }
3960
3961 // If we folded the first phi, PN dangles at this point. Refresh it. If
3962 // we ran out of PHIs then we simplified them all.
3963 PN = dyn_cast<PHINode>(BB->begin());
3964 if (!PN)
3965 return true;
3966
3967 // Don't fold i1 branches on PHIs which contain binary operators or
3968 // (possibly inverted) select form of or/ands if their parameters are
3969 // an equality test.
3970 auto IsBinOpOrAndEq = [](Value *V) {
3971 CmpPredicate Pred;
3972 if (match(V, m_CombineOr(
3974 m_BinOp(m_Cmp(Pred, m_Value(), m_Value()), m_Value()),
3975 m_BinOp(m_Value(), m_Cmp(Pred, m_Value(), m_Value()))),
3977 m_Cmp(Pred, m_Value(), m_Value()))))) {
3978 return CmpInst::isEquality(Pred);
3979 }
3980 return false;
3981 };
3982 if (PN->getType()->isIntegerTy(1) &&
3983 (IsBinOpOrAndEq(PN->getIncomingValue(0)) ||
3984 IsBinOpOrAndEq(PN->getIncomingValue(1)) || IsBinOpOrAndEq(IfCond)))
3985 return Changed;
3986
3987 // If all PHI nodes are promotable, check to make sure that all instructions
3988 // in the predecessor blocks can be promoted as well. If not, we won't be able
3989 // to get rid of the control flow, so it's not worth promoting to select
3990 // instructions.
3991 for (BasicBlock *IfBlock : IfBlocks)
3992 for (BasicBlock::iterator I = IfBlock->begin(); !I->isTerminator(); ++I)
3993 if (!AggressiveInsts.count(&*I) && !isa<PseudoProbeInst>(I)) {
3994 // This is not an aggressive instruction that we can promote.
3995 // Because of this, we won't be able to get rid of the control flow, so
3996 // the xform is not worth it.
3997 return Changed;
3998 }
3999
4000 // If either of the blocks has it's address taken, we can't do this fold.
4001 if (any_of(IfBlocks,
4002 [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); }))
4003 return Changed;
4004
4005 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond;
4006 if (IsUnpredictable) dbgs() << " (unpredictable)";
4007 dbgs() << " T: " << IfTrue->getName()
4008 << " F: " << IfFalse->getName() << "\n");
4009
4010 // If we can still promote the PHI nodes after this gauntlet of tests,
4011 // do all of the PHI's now.
4012
4013 // Move all 'aggressive' instructions, which are defined in the
4014 // conditional parts of the if's up to the dominating block.
4015 for (BasicBlock *IfBlock : IfBlocks)
4016 hoistAllInstructionsInto(DomBlock, DomBI, IfBlock);
4017
4018 IRBuilder<NoFolder> Builder(DomBI);
4019 // Propagate fast-math-flags from phi nodes to replacement selects.
4020 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
4021 // Change the PHI node into a select instruction.
4022 Value *TrueVal = PN->getIncomingValueForBlock(IfTrue);
4023 Value *FalseVal = PN->getIncomingValueForBlock(IfFalse);
4024
4025 Value *Sel = Builder.CreateSelectFMF(IfCond, TrueVal, FalseVal,
4026 isa<FPMathOperator>(PN) ? PN : nullptr,
4027 "", DomBI);
4028 PN->replaceAllUsesWith(Sel);
4029 Sel->takeName(PN);
4030 PN->eraseFromParent();
4031 }
4032
4033 // At this point, all IfBlocks are empty, so our if statement
4034 // has been flattened. Change DomBlock to jump directly to our new block to
4035 // avoid other simplifycfg's kicking in on the diamond.
4036 Builder.CreateBr(BB);
4037
4039 if (DTU) {
4040 Updates.push_back({DominatorTree::Insert, DomBlock, BB});
4041 for (auto *Successor : successors(DomBlock))
4042 Updates.push_back({DominatorTree::Delete, DomBlock, Successor});
4043 }
4044
4045 DomBI->eraseFromParent();
4046 if (DTU)
4047 DTU->applyUpdates(Updates);
4048
4049 return true;
4050}
4051
4054 Value *RHS, const Twine &Name = "") {
4055 // Try to relax logical op to binary op.
4056 if (impliesPoison(RHS, LHS))
4057 return Builder.CreateBinOp(Opc, LHS, RHS, Name);
4058 if (Opc == Instruction::And)
4059 return Builder.CreateLogicalAnd(LHS, RHS, Name);
4060 if (Opc == Instruction::Or)
4061 return Builder.CreateLogicalOr(LHS, RHS, Name);
4062 llvm_unreachable("Invalid logical opcode");
4063}
4064
4065/// Return true if either PBI or BI has branch weight available, and store
4066/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
4067/// not have branch weight, use 1:1 as its weight.
4069 uint64_t &PredTrueWeight,
4070 uint64_t &PredFalseWeight,
4071 uint64_t &SuccTrueWeight,
4072 uint64_t &SuccFalseWeight) {
4073 bool PredHasWeights =
4074 extractBranchWeights(*PBI, PredTrueWeight, PredFalseWeight);
4075 bool SuccHasWeights =
4076 extractBranchWeights(*BI, SuccTrueWeight, SuccFalseWeight);
4077 if (PredHasWeights || SuccHasWeights) {
4078 if (!PredHasWeights)
4079 PredTrueWeight = PredFalseWeight = 1;
4080 if (!SuccHasWeights)
4081 SuccTrueWeight = SuccFalseWeight = 1;
4082 return true;
4083 } else {
4084 return false;
4085 }
4086}
4087
4088/// Determine if the two branches share a common destination and deduce a glue
4089/// that joins the branches' conditions to arrive at the common destination if
4090/// that would be profitable.
4091static std::optional<std::tuple<BasicBlock *, Instruction::BinaryOps, bool>>
4093 const TargetTransformInfo *TTI) {
4094 assert(BI && PBI && "Both blocks must end with a conditional branches.");
4096 "PredBB must be a predecessor of BB.");
4097
4098 // We have the potential to fold the conditions together, but if the
4099 // predecessor branch is predictable, we may not want to merge them.
4100 uint64_t PTWeight, PFWeight;
4101 BranchProbability PBITrueProb, Likely;
4102 if (TTI && !PBI->getMetadata(LLVMContext::MD_unpredictable) &&
4103 extractBranchWeights(*PBI, PTWeight, PFWeight) &&
4104 (PTWeight + PFWeight) != 0) {
4105 PBITrueProb =
4106 BranchProbability::getBranchProbability(PTWeight, PTWeight + PFWeight);
4107 Likely = TTI->getPredictableBranchThreshold();
4108 }
4109
4110 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4111 // Speculate the 2nd condition unless the 1st is probably true.
4112 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
4113 return {{BI->getSuccessor(0), Instruction::Or, false}};
4114 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4115 // Speculate the 2nd condition unless the 1st is probably false.
4116 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
4117 return {{BI->getSuccessor(1), Instruction::And, false}};
4118 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4119 // Speculate the 2nd condition unless the 1st is probably true.
4120 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
4121 return {{BI->getSuccessor(1), Instruction::And, true}};
4122 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4123 // Speculate the 2nd condition unless the 1st is probably false.
4124 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
4125 return {{BI->getSuccessor(0), Instruction::Or, true}};
4126 }
4127 return std::nullopt;
4128}
4129
4131 DomTreeUpdater *DTU,
4132 MemorySSAUpdater *MSSAU,
4133 const TargetTransformInfo *TTI) {
4134 BasicBlock *BB = BI->getParent();
4135 BasicBlock *PredBlock = PBI->getParent();
4136
4137 // Determine if the two branches share a common destination.
4138 BasicBlock *CommonSucc;
4140 bool InvertPredCond;
4141 std::tie(CommonSucc, Opc, InvertPredCond) =
4143
4144 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
4145
4147 *BB->getModule(), ConstantFolder{},
4149 // The builder is used to create instructions to eliminate the branch in
4150 // BB. If BB's terminator has !annotation metadata, add it to the new
4151 // instructions.
4152 I->copyMetadata(*BB->getTerminator(), LLVMContext::MD_annotation);
4153 }));
4154 Builder.SetInsertPoint(PBI);
4155
4156 // If we need to invert the condition in the pred block to match, do so now.
4157 if (InvertPredCond) {
4158 InvertBranch(PBI, Builder);
4159 }
4160
4161 BasicBlock *UniqueSucc =
4162 PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1);
4163
4164 // Before cloning instructions, notify the successor basic block that it
4165 // is about to have a new predecessor. This will update PHI nodes,
4166 // which will allow us to update live-out uses of bonus instructions.
4167 addPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU);
4168
4169 // Try to update branch weights.
4170 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4171 SmallVector<uint64_t, 2> MDWeights;
4172 if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4173 SuccTrueWeight, SuccFalseWeight)) {
4174
4175 if (PBI->getSuccessor(0) == BB) {
4176 // PBI: br i1 %x, BB, FalseDest
4177 // BI: br i1 %y, UniqueSucc, FalseDest
4178 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
4179 MDWeights.push_back(PredTrueWeight * SuccTrueWeight);
4180 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
4181 // TrueWeight for PBI * FalseWeight for BI.
4182 // We assume that total weights of a CondBrInst can fit into 32 bits.
4183 // Therefore, we will not have overflow using 64-bit arithmetic.
4184 MDWeights.push_back(PredFalseWeight * (SuccFalseWeight + SuccTrueWeight) +
4185 PredTrueWeight * SuccFalseWeight);
4186 } else {
4187 // PBI: br i1 %x, TrueDest, BB
4188 // BI: br i1 %y, TrueDest, UniqueSucc
4189 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
4190 // FalseWeight for PBI * TrueWeight for BI.
4191 MDWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) +
4192 PredFalseWeight * SuccTrueWeight);
4193 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
4194 MDWeights.push_back(PredFalseWeight * SuccFalseWeight);
4195 }
4196
4197 setFittedBranchWeights(*PBI, MDWeights, /*IsExpected=*/false,
4198 /*ElideAllZero=*/true);
4199
4200 // TODO: If BB is reachable from all paths through PredBlock, then we
4201 // could replace PBI's branch probabilities with BI's.
4202 } else {
4203 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
4205 }
4206
4207 // Now, update the CFG.
4208 PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc);
4209
4210 if (DTU)
4211 DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc},
4212 {DominatorTree::Delete, PredBlock, BB}});
4213
4214 // If BI was a loop latch, it may have had associated loop metadata.
4215 // We need to copy it to the new latch, that is, PBI.
4216 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
4217 PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
4218
4219 ValueToValueMapTy VMap; // maps original values to cloned values
4221
4222 Module *M = BB->getModule();
4223
4224 PredBlock->getTerminator()->cloneDebugInfoFrom(BB->getTerminator());
4225 for (DbgVariableRecord &DVR :
4227 RemapDbgRecord(M, &DVR, VMap,
4229 }
4230
4231 // Now that the Cond was cloned into the predecessor basic block,
4232 // or/and the two conditions together.
4233 Value *BICond = VMap[BI->getCondition()];
4234 PBI->setCondition(
4235 createLogicalOp(Builder, Opc, PBI->getCondition(), BICond, "or.cond"));
4236 if (auto *SI = dyn_cast<SelectInst>(PBI->getCondition())) {
4237 if (!MDWeights.empty()) {
4238 assert(isSelectInRoleOfConjunctionOrDisjunction(SI));
4239 setFittedBranchWeights(*SI, {MDWeights[0], MDWeights[1]},
4240 /*IsExpected=*/false, /*ElideAllZero=*/true);
4241 } else {
4243 }
4244 }
4245
4246 ++NumFoldBranchToCommonDest;
4247 return true;
4248}
4249
4250/// Return if an instruction's type or any of its operands' types are a vector
4251/// type.
4252static bool isVectorOp(Instruction &I) {
4253 return I.getType()->isVectorTy() || any_of(I.operands(), [](Use &U) {
4254 return U->getType()->isVectorTy();
4255 });
4256}
4257
4258/// If this basic block is simple enough, and if a predecessor branches to us
4259/// and one of our successors, fold the block into the predecessor and use
4260/// logical operations to pick the right destination.
4262 MemorySSAUpdater *MSSAU,
4263 const TargetTransformInfo *TTI,
4264 AssumptionCache *AC,
4265 unsigned BonusInstThreshold) {
4266 BasicBlock *BB = BI->getParent();
4270
4272
4274 Cond->getParent() != BB || !Cond->hasOneUse())
4275 return false;
4276
4277 // Finally, don't infinitely unroll conditional loops.
4278 if (is_contained(successors(BB), BB))
4279 return false;
4280
4281 // With which predecessors will we want to deal with?
4283 for (BasicBlock *PredBlock : predecessors(BB)) {
4284 CondBrInst *PBI = dyn_cast<CondBrInst>(PredBlock->getTerminator());
4285
4286 // Check that we have two conditional branches. If there is a PHI node in
4287 // the common successor, verify that the same value flows in from both
4288 // blocks.
4289 if (!PBI || !safeToMergeTerminators(BI, PBI))
4290 continue;
4291
4292 // Determine if the two branches share a common destination.
4293 BasicBlock *CommonSucc;
4295 bool InvertPredCond;
4296 if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI))
4297 std::tie(CommonSucc, Opc, InvertPredCond) = *Recipe;
4298 else
4299 continue;
4300
4301 // Check the cost of inserting the necessary logic before performing the
4302 // transformation.
4303 if (TTI) {
4304 Type *Ty = BI->getCondition()->getType();
4305 InstructionCost Cost = TTI->getArithmeticInstrCost(Opc, Ty, CostKind);
4306 if (InvertPredCond && (!PBI->getCondition()->hasOneUse() ||
4307 !isa<CmpInst>(PBI->getCondition())))
4308 Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind);
4309
4311 continue;
4312 }
4313
4314 // Ok, we do want to deal with this predecessor. Record it.
4315 Preds.emplace_back(PredBlock);
4316 }
4317
4318 // If there aren't any predecessors into which we can fold,
4319 // don't bother checking the cost.
4320 if (Preds.empty())
4321 return false;
4322
4323 // Only allow this transformation if computing the condition doesn't involve
4324 // too many instructions and these involved instructions can be executed
4325 // unconditionally. We denote all involved instructions except the condition
4326 // as "bonus instructions", and only allow this transformation when the
4327 // number of the bonus instructions we'll need to create when cloning into
4328 // each predecessor does not exceed a certain threshold.
4329 unsigned NumBonusInsts = 0;
4330 bool SawVectorOp = false;
4331 const unsigned PredCount = Preds.size();
4332 // Speculated instructions will be inserted before the terminator of the
4333 // predecessor. Only handle the simple case of one predecessor.
4334 const Instruction *CtxI =
4335 PredCount == 1 ? Preds[0]->getTerminator() : nullptr;
4336 for (Instruction &I : *BB) {
4337 // Don't check the branch condition comparison itself.
4338 if (&I == Cond)
4339 continue;
4340 // Ignore the terminator.
4342 continue;
4343 // Pseudo probes aren't speculatable but can be dropped on fold.
4345 continue;
4346 // I must be safe to execute unconditionally.
4347 if (!isSafeToSpeculativelyExecute(&I, CtxI, AC))
4348 return false;
4349 SawVectorOp |= isVectorOp(I);
4350
4351 // Account for the cost of duplicating this instruction into each
4352 // predecessor. Ignore free instructions.
4353 if (!TTI || TTI->getInstructionCost(&I, CostKind) !=
4355 NumBonusInsts += PredCount;
4356
4357 // Early exits once we reach the limit.
4358 if (NumBonusInsts >
4359 BonusInstThreshold * BranchFoldToCommonDestVectorMultiplier)
4360 return false;
4361 }
4362
4363 auto IsBCSSAUse = [BB, &I](Use &U) {
4364 auto *UI = cast<Instruction>(U.getUser());
4365 if (auto *PN = dyn_cast<PHINode>(UI))
4366 return PN->getIncomingBlock(U) == BB;
4367 return UI->getParent() == BB && I.comesBefore(UI);
4368 };
4369
4370 // Does this instruction require rewriting of uses?
4371 if (!all_of(I.uses(), IsBCSSAUse))
4372 return false;
4373 }
4374 if (NumBonusInsts >
4375 BonusInstThreshold *
4376 (SawVectorOp ? BranchFoldToCommonDestVectorMultiplier : 1))
4377 return false;
4378
4379 // Ok, we have the budget. Perform the transformation.
4380 for (BasicBlock *PredBlock : Preds) {
4381 auto *PBI = cast<CondBrInst>(PredBlock->getTerminator());
4382 return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI);
4383 }
4384 return false;
4385}
4386
4387// If there is only one store in BB1 and BB2, return it, otherwise return
4388// nullptr.
4390 StoreInst *S = nullptr;
4391 for (auto *BB : {BB1, BB2}) {
4392 if (!BB)
4393 continue;
4394 for (auto &I : *BB)
4395 if (auto *SI = dyn_cast<StoreInst>(&I)) {
4396 if (S)
4397 // Multiple stores seen.
4398 return nullptr;
4399 else
4400 S = SI;
4401 }
4402 }
4403 return S;
4404}
4405
4407 Value *AlternativeV = nullptr) {
4408 // PHI is going to be a PHI node that allows the value V that is defined in
4409 // BB to be referenced in BB's only successor.
4410 //
4411 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
4412 // doesn't matter to us what the other operand is (it'll never get used). We
4413 // could just create a new PHI with an undef incoming value, but that could
4414 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
4415 // other PHI. So here we directly look for some PHI in BB's successor with V
4416 // as an incoming operand. If we find one, we use it, else we create a new
4417 // one.
4418 //
4419 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
4420 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
4421 // where OtherBB is the single other predecessor of BB's only successor.
4422 PHINode *PHI = nullptr;
4423 BasicBlock *Succ = BB->getSingleSuccessor();
4424
4425 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
4426 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
4427 PHI = cast<PHINode>(I);
4428 if (!AlternativeV)
4429 break;
4430
4431 assert(Succ->hasNPredecessors(2));
4432 auto PredI = pred_begin(Succ);
4433 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
4434 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
4435 break;
4436 PHI = nullptr;
4437 }
4438 if (PHI)
4439 return PHI;
4440
4441 // If V is not an instruction defined in BB, just return it.
4442 if (!AlternativeV &&
4443 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
4444 return V;
4445
4446 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge");
4447 PHI->insertBefore(Succ->begin());
4448 PHI->addIncoming(V, BB);
4449 for (BasicBlock *PredBB : predecessors(Succ))
4450 if (PredBB != BB)
4451 PHI->addIncoming(
4452 AlternativeV ? AlternativeV : PoisonValue::get(V->getType()), PredBB);
4453 return PHI;
4454}
4455
4457 BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB,
4458 BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond,
4459 DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) {
4460 // For every pointer, there must be exactly two stores, one coming from
4461 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
4462 // store (to any address) in PTB,PFB or QTB,QFB.
4463 // FIXME: We could relax this restriction with a bit more work and performance
4464 // testing.
4465 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
4466 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
4467 if (!PStore || !QStore)
4468 return false;
4469
4470 // Now check the stores are compatible.
4471 if (!QStore->isUnordered() || !PStore->isUnordered() ||
4472 PStore->getOrdering() != QStore->getOrdering() ||
4473 PStore->getSyncScopeID() != QStore->getSyncScopeID() ||
4474 PStore->getValueOperand()->getType() !=
4475 QStore->getValueOperand()->getType())
4476 return false;
4477
4478 // Check that sinking the store won't cause program behavior changes. Sinking
4479 // the store out of the Q blocks won't change any behavior as we're sinking
4480 // from a block to its unconditional successor. But we're moving a store from
4481 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
4482 // So we need to check that there are no aliasing loads or stores in
4483 // QBI, QTB and QFB. We also need to check there are no conflicting memory
4484 // operations between PStore and the end of its parent block.
4485 //
4486 // The ideal way to do this is to query AliasAnalysis, but we don't
4487 // preserve AA currently so that is dangerous. Be super safe and just
4488 // check there are no other memory operations at all.
4489 for (auto &I : *QFB->getSinglePredecessor())
4490 if (I.mayReadOrWriteMemory())
4491 return false;
4492 for (auto &I : *QFB)
4493 if (&I != QStore && I.mayReadOrWriteMemory())
4494 return false;
4495 if (QTB)
4496 for (auto &I : *QTB)
4497 if (&I != QStore && I.mayReadOrWriteMemory())
4498 return false;
4499 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
4500 I != E; ++I)
4501 if (&*I != PStore && I->mayReadOrWriteMemory())
4502 return false;
4503
4504 // If we're not in aggressive mode, we only optimize if we have some
4505 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
4506 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
4507 if (!BB)
4508 return true;
4509 // Heuristic: if the block can be if-converted/phi-folded and the
4510 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
4511 // thread this store.
4512 InstructionCost Cost = 0;
4513 InstructionCost Budget =
4515 for (auto &I : *BB) {
4516 // Consider terminator instruction to be free.
4517 if (I.isTerminator())
4518 continue;
4519 // If this is one the stores that we want to speculate out of this BB,
4520 // then don't count it's cost, consider it to be free.
4521 if (auto *S = dyn_cast<StoreInst>(&I))
4522 if (llvm::find(FreeStores, S))
4523 continue;
4524 // Else, we have a white-list of instructions that we are ak speculating.
4526 return false; // Not in white-list - not worthwhile folding.
4527 // And finally, if this is a non-free instruction that we are okay
4528 // speculating, ensure that we consider the speculation budget.
4529 Cost +=
4530 TTI.getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
4531 if (Cost > Budget)
4532 return false; // Eagerly refuse to fold as soon as we're out of budget.
4533 }
4534 assert(Cost <= Budget &&
4535 "When we run out of budget we will eagerly return from within the "
4536 "per-instruction loop.");
4537 return true;
4538 };
4539
4540 const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
4542 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
4543 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
4544 return false;
4545
4546 // If PostBB has more than two predecessors, we need to split it so we can
4547 // sink the store.
4548 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
4549 // We know that QFB's only successor is PostBB. And QFB has a single
4550 // predecessor. If QTB exists, then its only successor is also PostBB.
4551 // If QTB does not exist, then QFB's only predecessor has a conditional
4552 // branch to QFB and PostBB.
4553 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
4554 BasicBlock *NewBB =
4555 SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU);
4556 if (!NewBB)
4557 return false;
4558 PostBB = NewBB;
4559 }
4560
4561 // OK, we're going to sink the stores to PostBB. The store has to be
4562 // conditional though, so first create the predicate.
4563 CondBrInst *PBranch =
4565 CondBrInst *QBranch =
4567 Value *PCond = PBranch->getCondition();
4568 Value *QCond = QBranch->getCondition();
4569
4571 PStore->getParent());
4573 QStore->getParent(), PPHI);
4574
4575 IRBuilder<> QB(PostBB->getFirstInsertionPt());
4576
4577 InvertPCond ^= (PStore->getParent() != PTB);
4578 InvertQCond ^= (QStore->getParent() != QTB);
4579 Value *PPred = InvertPCond ? QB.CreateNot(PCond) : PCond;
4580 Value *QPred = InvertQCond ? QB.CreateNot(QCond) : QCond;
4581
4582 Value *CombinedPred = QB.CreateOr(PPred, QPred);
4583
4584 BasicBlock::iterator InsertPt = QB.GetInsertPoint();
4585 auto *T = SplitBlockAndInsertIfThen(CombinedPred, InsertPt,
4586 /*Unreachable=*/false,
4587 /*BranchWeights=*/nullptr, DTU);
4588 if (hasBranchWeightMD(*PBranch) && hasBranchWeightMD(*QBranch)) {
4589 SmallVector<uint32_t, 2> PWeights, QWeights;
4590 extractBranchWeights(*PBranch, PWeights);
4591 extractBranchWeights(*QBranch, QWeights);
4592 if (InvertPCond)
4593 std::swap(PWeights[0], PWeights[1]);
4594 if (InvertQCond)
4595 std::swap(QWeights[0], QWeights[1]);
4596 auto CombinedWeights = getDisjunctionWeights(PWeights, QWeights);
4598 {CombinedWeights[0], CombinedWeights[1]},
4599 /*IsExpected=*/false, /*ElideAllZero=*/true);
4600 }
4601
4602 QB.SetInsertPoint(T);
4603 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
4604 combineMetadataForCSE(QStore, PStore, true);
4605 SI->copyMetadata(*QStore);
4606 // Update any dbg.assign intrinsics to track the merged value (QPHI) instead
4607 // of the original constant values, likely making these identical.
4608 for (auto *DbgAssign : at::getDVRAssignmentMarkers(SI)) {
4609 if (llvm::is_contained(DbgAssign->location_ops(),
4610 PStore->getValueOperand()))
4611 DbgAssign->replaceVariableLocationOp(PStore->getValueOperand(), QPHI);
4612 if (llvm::is_contained(DbgAssign->location_ops(),
4613 QStore->getValueOperand()))
4614 DbgAssign->replaceVariableLocationOp(QStore->getValueOperand(), QPHI);
4615 }
4616
4617 // Choose the minimum alignment. If we could prove both stores execute, we
4618 // could use biggest one. In this case, though, we only know that one of the
4619 // stores executes. And we don't know it's safe to take the alignment from a
4620 // store that doesn't execute.
4621 SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign()));
4622
4623 if (QStore->isAtomic())
4624 SI->setAtomic(QStore->getOrdering(), QStore->getSyncScopeID());
4625
4626 QStore->eraseFromParent();
4627 PStore->eraseFromParent();
4628
4629 return true;
4630}
4631
4633 DomTreeUpdater *DTU, const DataLayout &DL,
4634 const TargetTransformInfo &TTI) {
4635 // The intention here is to find diamonds or triangles (see below) where each
4636 // conditional block contains a store to the same address. Both of these
4637 // stores are conditional, so they can't be unconditionally sunk. But it may
4638 // be profitable to speculatively sink the stores into one merged store at the
4639 // end, and predicate the merged store on the union of the two conditions of
4640 // PBI and QBI.
4641 //
4642 // This can reduce the number of stores executed if both of the conditions are
4643 // true, and can allow the blocks to become small enough to be if-converted.
4644 // This optimization will also chain, so that ladders of test-and-set
4645 // sequences can be if-converted away.
4646 //
4647 // We only deal with simple diamonds or triangles:
4648 //
4649 // PBI or PBI or a combination of the two
4650 // / \ | \
4651 // PTB PFB | PFB
4652 // \ / | /
4653 // QBI QBI
4654 // / \ | \
4655 // QTB QFB | QFB
4656 // \ / | /
4657 // PostBB PostBB
4658 //
4659 // We model triangles as a type of diamond with a nullptr "true" block.
4660 // Triangles are canonicalized so that the fallthrough edge is represented by
4661 // a true condition, as in the diagram above.
4662 BasicBlock *PTB = PBI->getSuccessor(0);
4663 BasicBlock *PFB = PBI->getSuccessor(1);
4664 BasicBlock *QTB = QBI->getSuccessor(0);
4665 BasicBlock *QFB = QBI->getSuccessor(1);
4666 BasicBlock *PostBB = QFB->getSingleSuccessor();
4667
4668 // Make sure we have a good guess for PostBB. If QTB's only successor is
4669 // QFB, then QFB is a better PostBB.
4670 if (QTB->getSingleSuccessor() == QFB)
4671 PostBB = QFB;
4672
4673 // If we couldn't find a good PostBB, stop.
4674 if (!PostBB)
4675 return false;
4676
4677 bool InvertPCond = false, InvertQCond = false;
4678 // Canonicalize fallthroughs to the true branches.
4679 if (PFB == QBI->getParent()) {
4680 std::swap(PFB, PTB);
4681 InvertPCond = true;
4682 }
4683 if (QFB == PostBB) {
4684 std::swap(QFB, QTB);
4685 InvertQCond = true;
4686 }
4687
4688 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
4689 // and QFB may not. Model fallthroughs as a nullptr block.
4690 if (PTB == QBI->getParent())
4691 PTB = nullptr;
4692 if (QTB == PostBB)
4693 QTB = nullptr;
4694
4695 // Legality bailouts. We must have at least the non-fallthrough blocks and
4696 // the post-dominating block, and the non-fallthroughs must only have one
4697 // predecessor.
4698 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
4699 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
4700 };
4701 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
4702 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
4703 return false;
4704 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
4705 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
4706 return false;
4707 if (!QBI->getParent()->hasNUses(2))
4708 return false;
4709
4710 // OK, this is a sequence of two diamonds or triangles.
4711 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
4712 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
4713 for (auto *BB : {PTB, PFB}) {
4714 if (!BB)
4715 continue;
4716 for (auto &I : *BB)
4718 PStoreAddresses.insert(SI->getPointerOperand());
4719 }
4720 for (auto *BB : {QTB, QFB}) {
4721 if (!BB)
4722 continue;
4723 for (auto &I : *BB)
4725 QStoreAddresses.insert(SI->getPointerOperand());
4726 }
4727
4728 set_intersect(PStoreAddresses, QStoreAddresses);
4729 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
4730 // clear what it contains.
4731 auto &CommonAddresses = PStoreAddresses;
4732
4733 bool Changed = false;
4734 for (auto *Address : CommonAddresses)
4735 Changed |=
4736 mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address,
4737 InvertPCond, InvertQCond, DTU, DL, TTI);
4738 return Changed;
4739}
4740
4741/// If the previous block ended with a widenable branch, determine if reusing
4742/// the target block is profitable and legal. This will have the effect of
4743/// "widening" PBI, but doesn't require us to reason about hosting safety.
4745 DomTreeUpdater *DTU) {
4746 // TODO: This can be generalized in two important ways:
4747 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
4748 // values from the PBI edge.
4749 // 2) We can sink side effecting instructions into BI's fallthrough
4750 // successor provided they doesn't contribute to computation of
4751 // BI's condition.
4752 BasicBlock *IfTrueBB = PBI->getSuccessor(0);
4753 BasicBlock *IfFalseBB = PBI->getSuccessor(1);
4754 if (!isWidenableBranch(PBI) || IfTrueBB != BI->getParent() ||
4755 !BI->getParent()->getSinglePredecessor())
4756 return false;
4757 if (!IfFalseBB->phis().empty())
4758 return false; // TODO
4759 // This helps avoid infinite loop with SimplifyCondBranchToCondBranch which
4760 // may undo the transform done here.
4761 // TODO: There might be a more fine-grained solution to this.
4762 if (!llvm::succ_empty(IfFalseBB))
4763 return false;
4764 // Use lambda to lazily compute expensive condition after cheap ones.
4765 auto NoSideEffects = [](BasicBlock &BB) {
4766 return llvm::none_of(BB, [](const Instruction &I) {
4767 return I.mayWriteToMemory() || I.mayHaveSideEffects();
4768 });
4769 };
4770 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
4771 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
4772 NoSideEffects(*BI->getParent())) {
4773 auto *OldSuccessor = BI->getSuccessor(1);
4774 OldSuccessor->removePredecessor(BI->getParent());
4775 BI->setSuccessor(1, IfFalseBB);
4776 if (DTU)
4777 DTU->applyUpdates(
4778 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4779 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4780 return true;
4781 }
4782 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
4783 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
4784 NoSideEffects(*BI->getParent())) {
4785 auto *OldSuccessor = BI->getSuccessor(0);
4786 OldSuccessor->removePredecessor(BI->getParent());
4787 BI->setSuccessor(0, IfFalseBB);
4788 if (DTU)
4789 DTU->applyUpdates(
4790 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4791 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4792 return true;
4793 }
4794 return false;
4795}
4796
4797/// If we have a conditional branch as a predecessor of another block,
4798/// this function tries to simplify it. We know
4799/// that PBI and BI are both conditional branches, and BI is in one of the
4800/// successor blocks of PBI - PBI branches to BI.
4802 DomTreeUpdater *DTU,
4803 const DataLayout &DL,
4804 const TargetTransformInfo &TTI) {
4805 BasicBlock *BB = BI->getParent();
4806
4807 // If this block ends with a branch instruction, and if there is a
4808 // predecessor that ends on a branch of the same condition, make
4809 // this conditional branch redundant.
4810 if (PBI->getCondition() == BI->getCondition() &&
4811 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
4812 // Okay, the outcome of this conditional branch is statically
4813 // knowable. If this block had a single pred, handle specially, otherwise
4814 // foldCondBranchOnValueKnownInPredecessor() will handle it.
4815 if (BB->getSinglePredecessor()) {
4816 // Turn this into a branch on constant.
4817 bool CondIsTrue = PBI->getSuccessor(0) == BB;
4818 BI->setCondition(
4819 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
4820 return true; // Nuke the branch on constant.
4821 }
4822 }
4823
4824 // If the previous block ended with a widenable branch, determine if reusing
4825 // the target block is profitable and legal. This will have the effect of
4826 // "widening" PBI, but doesn't require us to reason about hosting safety.
4827 if (tryWidenCondBranchToCondBranch(PBI, BI, DTU))
4828 return true;
4829
4830 // If both branches are conditional and both contain stores to the same
4831 // address, remove the stores from the conditionals and create a conditional
4832 // merged store at the end.
4833 if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI))
4834 return true;
4835
4836 // If this is a conditional branch in an empty block, and if any
4837 // predecessors are a conditional branch to one of our destinations,
4838 // fold the conditions into logical ops and one cond br.
4839
4840 // Ignore dbg intrinsics.
4841 if (&*BB->begin() != BI)
4842 return false;
4843
4844 int PBIOp, BIOp;
4845 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4846 PBIOp = 0;
4847 BIOp = 0;
4848 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4849 PBIOp = 0;
4850 BIOp = 1;
4851 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4852 PBIOp = 1;
4853 BIOp = 0;
4854 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4855 PBIOp = 1;
4856 BIOp = 1;
4857 } else {
4858 return false;
4859 }
4860
4861 // Check to make sure that the other destination of this branch
4862 // isn't BB itself. If so, this is an infinite loop that will
4863 // keep getting unwound.
4864 if (PBI->getSuccessor(PBIOp) == BB)
4865 return false;
4866
4867 // If predecessor's branch probability to BB is too low don't merge branches.
4868 SmallVector<uint32_t, 2> PredWeights;
4869 if (!PBI->getMetadata(LLVMContext::MD_unpredictable) &&
4870 extractBranchWeights(*PBI, PredWeights) &&
4871 (static_cast<uint64_t>(PredWeights[0]) + PredWeights[1]) != 0) {
4872
4874 PredWeights[PBIOp],
4875 static_cast<uint64_t>(PredWeights[0]) + PredWeights[1]);
4876
4877 BranchProbability Likely = TTI.getPredictableBranchThreshold();
4878 if (CommonDestProb >= Likely)
4879 return false;
4880 }
4881
4882 // Do not perform this transformation if it would require
4883 // insertion of a large number of select instructions. For targets
4884 // without predication/cmovs, this is a big pessimization.
4885
4886 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
4887 BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1);
4888 unsigned NumPhis = 0;
4889 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
4890 ++II, ++NumPhis) {
4891 if (NumPhis > 2) // Disable this xform.
4892 return false;
4893 }
4894
4895 // Finally, if everything is ok, fold the branches to logical ops.
4896 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
4897
4898 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
4899 << "AND: " << *BI->getParent());
4900
4902
4903 // If OtherDest *is* BB, then BB is a basic block with a single conditional
4904 // branch in it, where one edge (OtherDest) goes back to itself but the other
4905 // exits. We don't *know* that the program avoids the infinite loop
4906 // (even though that seems likely). If we do this xform naively, we'll end up
4907 // recursively unpeeling the loop. Since we know that (after the xform is
4908 // done) that the block *is* infinite if reached, we just make it an obviously
4909 // infinite loop with no cond branch.
4910 if (OtherDest == BB) {
4911 // Insert it at the end of the function, because it's either code,
4912 // or it won't matter if it's hot. :)
4913 BasicBlock *InfLoopBlock =
4914 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
4915 UncondBrInst::Create(InfLoopBlock, InfLoopBlock);
4916 if (DTU)
4917 Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
4918 OtherDest = InfLoopBlock;
4919 }
4920
4921 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4922
4923 // BI may have other predecessors. Because of this, we leave
4924 // it alone, but modify PBI.
4925
4926 // Make sure we get to CommonDest on True&True directions.
4927 Value *PBICond = PBI->getCondition();
4928 IRBuilder<NoFolder> Builder(PBI);
4929 if (PBIOp)
4930 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
4931
4932 Value *BICond = BI->getCondition();
4933 if (BIOp)
4934 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
4935
4936 // Merge the conditions.
4937 Value *Cond =
4938 createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge");
4939
4940 // Modify PBI to branch on the new condition to the new dests.
4941 PBI->setCondition(Cond);
4942 PBI->setSuccessor(0, CommonDest);
4943 PBI->setSuccessor(1, OtherDest);
4944
4945 if (DTU) {
4946 Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest});
4947 Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest});
4948
4949 DTU->applyUpdates(Updates);
4950 }
4951
4952 // Update branch weight for PBI.
4953 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4954 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
4955 bool HasWeights =
4956 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4957 SuccTrueWeight, SuccFalseWeight);
4958 if (HasWeights) {
4959 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4960 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4961 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4962 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4963 // The weight to CommonDest should be PredCommon * SuccTotal +
4964 // PredOther * SuccCommon.
4965 // The weight to OtherDest should be PredOther * SuccOther.
4966 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
4967 PredOther * SuccCommon,
4968 PredOther * SuccOther};
4969
4970 setFittedBranchWeights(*PBI, NewWeights, /*IsExpected=*/false,
4971 /*ElideAllZero=*/true);
4972 // Cond may be a select instruction with the first operand set to "true", or
4973 // the second to "false" (see how createLogicalOp works for `and` and `or`)
4974 if (auto *SI = dyn_cast<SelectInst>(Cond)) {
4975 assert(isSelectInRoleOfConjunctionOrDisjunction(SI));
4976 // The select is predicated on PBICond
4977 assert(SI->getCondition() == PBICond);
4978 // The corresponding probabilities are what was referred to above as
4979 // PredCommon and PredOther.
4980 setFittedBranchWeights(*SI, {PredCommon, PredOther},
4981 /*IsExpected=*/false, /*ElideAllZero=*/true);
4982 }
4983 }
4984
4985 // OtherDest may have phi nodes. If so, add an entry from PBI's
4986 // block that are identical to the entries for BI's block.
4987 addPredecessorToBlock(OtherDest, PBI->getParent(), BB);
4988
4989 // We know that the CommonDest already had an edge from PBI to
4990 // it. If it has PHIs though, the PHIs may have different
4991 // entries for BB and PBI's BB. If so, insert a select to make
4992 // them agree.
4993 for (PHINode &PN : CommonDest->phis()) {
4994 Value *BIV = PN.getIncomingValueForBlock(BB);
4995 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
4996 Value *PBIV = PN.getIncomingValue(PBBIdx);
4997 if (BIV != PBIV) {
4998 // Insert a select in PBI to pick the right value.
5000 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
5001 PN.setIncomingValue(PBBIdx, NV);
5002 // The select has the same condition as PBI, in the same BB. The
5003 // probabilities don't change.
5004 if (HasWeights) {
5005 uint64_t TrueWeight = PBIOp ? PredFalseWeight : PredTrueWeight;
5006 uint64_t FalseWeight = PBIOp ? PredTrueWeight : PredFalseWeight;
5007 setFittedBranchWeights(*NV, {TrueWeight, FalseWeight},
5008 /*IsExpected=*/false, /*ElideAllZero=*/true);
5009 }
5010 }
5011 }
5012
5013 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
5014 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
5015
5016 // This basic block is probably dead. We know it has at least
5017 // one fewer predecessor.
5018 return true;
5019}
5020
5021// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
5022// true or to FalseBB if Cond is false.
5023// Takes care of updating the successors and removing the old terminator.
5024// Also makes sure not to introduce new successors by assuming that edges to
5025// non-successor TrueBBs and FalseBBs aren't reachable.
5026bool SimplifyCFGOpt::simplifyTerminatorOnSelect(Instruction *OldTerm,
5027 Value *Cond, BasicBlock *TrueBB,
5028 BasicBlock *FalseBB,
5029 uint32_t TrueWeight,
5030 uint32_t FalseWeight) {
5031 auto *BB = OldTerm->getParent();
5032 // Remove any superfluous successor edges from the CFG.
5033 // First, figure out which successors to preserve.
5034 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
5035 // successor.
5036 BasicBlock *KeepEdge1 = TrueBB;
5037 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
5038
5039 SmallSetVector<BasicBlock *, 2> RemovedSuccessors;
5040
5041 // Then remove the rest.
5042 for (BasicBlock *Succ : successors(OldTerm)) {
5043 // Make sure only to keep exactly one copy of each edge.
5044 if (Succ == KeepEdge1)
5045 KeepEdge1 = nullptr;
5046 else if (Succ == KeepEdge2)
5047 KeepEdge2 = nullptr;
5048 else {
5049 Succ->removePredecessor(BB,
5050 /*KeepOneInputPHIs=*/true);
5051
5052 if (Succ != TrueBB && Succ != FalseBB)
5053 RemovedSuccessors.insert(Succ);
5054 }
5055 }
5056
5057 IRBuilder<> Builder(OldTerm);
5058 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
5059
5060 // Insert an appropriate new terminator.
5061 if (!KeepEdge1 && !KeepEdge2) {
5062 if (TrueBB == FalseBB) {
5063 // We were only looking for one successor, and it was present.
5064 // Create an unconditional branch to it.
5065 Builder.CreateBr(TrueBB);
5066 } else {
5067 // We found both of the successors we were looking for.
5068 // Create a conditional branch sharing the condition of the select.
5069 CondBrInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
5070 setBranchWeights(*NewBI, {TrueWeight, FalseWeight},
5071 /*IsExpected=*/false, /*ElideAllZero=*/true);
5072 }
5073 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
5074 // Neither of the selected blocks were successors, so this
5075 // terminator must be unreachable.
5076 new UnreachableInst(OldTerm->getContext(), OldTerm->getIterator());
5077 } else {
5078 // One of the selected values was a successor, but the other wasn't.
5079 // Insert an unconditional branch to the one that was found;
5080 // the edge to the one that wasn't must be unreachable.
5081 if (!KeepEdge1) {
5082 // Only TrueBB was found.
5083 Builder.CreateBr(TrueBB);
5084 } else {
5085 // Only FalseBB was found.
5086 Builder.CreateBr(FalseBB);
5087 }
5088 }
5089
5091
5092 if (DTU) {
5093 SmallVector<DominatorTree::UpdateType, 2> Updates;
5094 Updates.reserve(RemovedSuccessors.size());
5095 for (auto *RemovedSuccessor : RemovedSuccessors)
5096 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
5097 DTU->applyUpdates(Updates);
5098 }
5099
5100 return true;
5101}
5102
5103// Folds switch(select(icmp eq X, C, K, X)) into switch(X), retargeting
5104// (or adding) the case for C to wherever K currently dispatches to:
5105// %cmp = icmp eq T %x, C
5106// %key = select i1 %cmp, T K, T %x
5107// switch T %key, label %default [ T K, label %case_k ... ]
5108// becomes
5109// switch T %x, label %default [ T C, label %case_k
5110// T K, label %case_k ... ]
5111bool SimplifyCFGOpt::simplifySwitchOnSelectRemap(SwitchInst *SI,
5112 SelectInst *Select, Value *X,
5113 ConstantInt *C, bool Negate) {
5114 Value *TrueVal = Select->getTrueValue();
5115 Value *FalseVal = Select->getFalseValue();
5116 if (Negate)
5117 std::swap(TrueVal, FalseVal);
5118 if (FalseVal != X)
5119 return false;
5120 auto *K = dyn_cast<ConstantInt>(TrueVal);
5121 if (!K)
5122 return false;
5123
5124 BasicBlock *DestFork = SI->findCaseValue(K)->getCaseSuccessor();
5125 auto CaseC = SI->findCaseValue(C);
5126 bool IsDefault = CaseC == SI->case_default();
5127 // Save before setSuccessor()/addCase() change it.
5128 BasicBlock *OldDest = CaseC->getCaseSuccessor();
5129 BasicBlock *BB = SI->getParent();
5130
5131 // Switch on X first: removePredecessor() below may fold X away if it is a
5132 // PHI in OldDest, and the RAUW must update the switch condition too.
5133 SI->setCondition(X);
5134
5135 if (OldDest != DestFork) {
5136 if (!IsDefault)
5137 OldDest->removePredecessor(BB);
5138 if (IsDefault)
5139 SI->addCase(C, DestFork);
5140 else
5141 CaseC->setSuccessor(DestFork);
5142 // Not a new edge (BB->DestFork exists via K), just adding the PHI
5143 // entry.
5144 addPredecessorToBlock(DestFork, BB, BB);
5145
5146 if (!IsDefault) {
5147 // Edge to OldDest is gone only if nothing else still uses it.
5148 bool OldDestStillTargeted = any_of(
5149 successors(SI), [&](BasicBlock *Succ) { return Succ == OldDest; });
5150 if (DTU && !OldDestStillTargeted)
5151 DTU->applyUpdates({{DominatorTree::Delete, BB, OldDest}});
5152 }
5153
5154 // Update the profile information on the switch if we had a profile
5155 // for both it and the select instruction.
5156 SmallVector<uint32_t> SwitchWeights;
5157 bool SwitchHasBranchWeights = extractBranchWeights(*SI, SwitchWeights);
5158 // If we add a case, ensure the length of the branch weights list matches
5159 // to make iterating over them easier later.
5160 if (IsDefault)
5161 SwitchWeights.push_back(0);
5164 bool SelectHasBranchWeights =
5166 uint64_t SelectTotalWeight = SelectTrueWeight + SelectFalseWeight;
5167 if (Negate)
5169 if (SwitchHasBranchWeights && SelectHasBranchWeights &&
5171 // We update the branch weights by subtracting P(x=C) from the probability
5172 // of case K in the switch (what C redirect to before the transformation),
5173 // plugging the probability for case C into the switch (which we derive
5174 // from the select), and ensuring everything is scaled to have a common
5175 // denominator.
5176 uint64_t SwitchTotalWeight = sum_of(SwitchWeights, uint64_t{0});
5177 SmallVector<uint64_t> NewSwitchWeights;
5178 NewSwitchWeights.reserve(SwitchWeights.size());
5179 NewSwitchWeights.push_back(SwitchWeights[0] * SelectTotalWeight);
5180 for (const auto &[SwitchCase, SwitchWeight] :
5181 zip(SI->cases(), drop_begin(SwitchWeights))) {
5182 if (SwitchCase.getCaseValue() == C) {
5183 NewSwitchWeights.push_back(SwitchTotalWeight * SelectTrueWeight);
5184 } else if (SwitchCase.getCaseValue() == K) {
5185 // In reality, P(key=K) > P(x=C) should always hold, but explicitly
5186 // guard against bad profiles here to prevent underflow by saturating
5187 // to zero.
5188 uint64_t ProbabilityKeyEqualsK = SwitchWeight * SelectTotalWeight;
5189 uint64_t ProbabilityXEqualsC = SelectTrueWeight * SwitchTotalWeight;
5190 uint64_t ProbabilityXEqualsK =
5191 ProbabilityKeyEqualsK > ProbabilityXEqualsC
5192 ? ProbabilityKeyEqualsK - ProbabilityXEqualsC
5193 : 0;
5194 NewSwitchWeights.push_back(ProbabilityXEqualsK);
5195 } else {
5196 NewSwitchWeights.push_back(SwitchWeight * SelectTotalWeight);
5197 }
5198 }
5199 setFittedBranchWeights(*SI, NewSwitchWeights, /*IsExpected=*/false);
5200 } else if (SwitchHasBranchWeights) {
5201 // If we only have branch weights on the switch, we cannot reconstruct
5202 // branch weights correctly, so mark them as unknown if the function has
5203 // a profile count. Reset the branch weights first to ensure we remove
5204 // the now invalid branch weights if the function is not otherwise
5205 // profiled.
5206 SI->setMetadata(LLVMContext::MD_prof, nullptr);
5208 }
5209 }
5210
5211 // The compare/select are now dead.
5213 return true;
5214}
5215
5216// Replaces
5217// (switch (select cond, X, Y)) on constant X, Y
5218// with a branch - conditional if X and Y lead to distinct BBs,
5219// unconditional otherwise.
5220bool SimplifyCFGOpt::simplifySwitchOnSelect(SwitchInst *SI,
5221 SelectInst *Select) {
5222 CmpPredicate Pred;
5223 Value *X;
5224 ConstantInt *C;
5225 if (Select->hasOneUse() &&
5226 match(Select->getCondition(),
5227 m_ICmp(Pred, m_Value(X), m_ConstantInt(C))) &&
5228 ICmpInst::isEquality(Pred) &&
5229 simplifySwitchOnSelectRemap(SI, Select, X, C, Pred == ICmpInst::ICMP_NE))
5230 return true;
5231
5232 // Check for constant integer values in the select.
5233 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
5234 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
5235 if (!TrueVal || !FalseVal)
5236 return false;
5237
5238 // Find the relevant condition and destinations.
5239 Value *Condition = Select->getCondition();
5240 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
5241 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
5242
5243 // Get weight for TrueBB and FalseBB.
5244 uint32_t TrueWeight = 0, FalseWeight = 0;
5245 SmallVector<uint64_t, 8> Weights;
5246 bool HasWeights = hasBranchWeightMD(*SI);
5247 if (HasWeights) {
5248 getBranchWeights(SI, Weights);
5249 if (Weights.size() == 1 + SI->getNumCases()) {
5250 TrueWeight =
5251 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
5252 FalseWeight =
5253 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
5254 }
5255 }
5256
5257 // Perform the actual simplification.
5258 return simplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
5259 FalseWeight);
5260}
5261
5262// Replaces
5263// (indirectbr (select cond, blockaddress(@fn, BlockA),
5264// blockaddress(@fn, BlockB)))
5265// with
5266// (br cond, BlockA, BlockB).
5267bool SimplifyCFGOpt::simplifyIndirectBrOnSelect(IndirectBrInst *IBI,
5268 SelectInst *SI) {
5269 // Check that both operands of the select are block addresses.
5270 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
5271 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
5272 if (!TBA || !FBA)
5273 return false;
5274
5275 // Extract the actual blocks.
5276 BasicBlock *TrueBB = TBA->getBasicBlock();
5277 BasicBlock *FalseBB = FBA->getBasicBlock();
5278
5279 // The select's profile becomes the profile of the conditional branch that
5280 // replaces the indirect branch.
5281 SmallVector<uint32_t> SelectBranchWeights(2);
5282 extractBranchWeights(*SI, SelectBranchWeights);
5283 // Perform the actual simplification.
5284 return simplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
5285 SelectBranchWeights[0],
5286 SelectBranchWeights[1]);
5287}
5288
5289/// This is called when we find an icmp instruction
5290/// (a seteq/setne with a constant) as the only instruction in a
5291/// block that ends with an uncond branch. We are looking for a very specific
5292/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
5293/// this case, we merge the first two "or's of icmp" into a switch, but then the
5294/// default value goes to an uncond block with a seteq in it, we get something
5295/// like:
5296///
5297/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
5298/// DEFAULT:
5299/// %tmp = icmp eq i8 %A, 92
5300/// br label %end
5301/// end:
5302/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
5303///
5304/// We prefer to split the edge to 'end' so that there is a true/false entry to
5305/// the PHI, merging the third icmp into the switch.
5306bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
5307 ICmpInst *ICI, IRBuilder<> &Builder) {
5308 // Select == nullptr means we assume that there is a hidden no-op select
5309 // instruction of `_ = select %icmp, true, false` after `%icmp = icmp ...`
5310 return tryToSimplifyUncondBranchWithICmpSelectInIt(ICI, nullptr, Builder);
5311}
5312
5313/// Similar to tryToSimplifyUncondBranchWithICmpInIt, but handle a more generic
5314/// case. This is called when we find an icmp instruction (a seteq/setne with a
5315/// constant) and its following select instruction as the only TWO instructions
5316/// in a block that ends with an uncond branch. We are looking for a very
5317/// specific pattern that occurs when "
5318/// if (A == 1) return C1;
5319/// if (A == 2) return C2;
5320/// if (A < 3) return C3;
5321/// return C4;
5322/// " gets simplified. In this case, we merge the first two "branches of icmp"
5323/// into a switch, but then the default value goes to an uncond block with a lt
5324/// icmp and select in it, as InstCombine can not simplify "A < 3" as "A == 2".
5325/// After SimplifyCFG and other subsequent optimizations (e.g., SCCP), we might
5326/// get something like:
5327///
5328/// case1:
5329/// switch i8 %A, label %DEFAULT [ i8 0, label %end i8 1, label %case2 ]
5330/// case2:
5331/// br label %end
5332/// DEFAULT:
5333/// %tmp = icmp eq i8 %A, 2
5334/// %val = select i1 %tmp, i8 C3, i8 C4
5335/// br label %end
5336/// end:
5337/// _ = phi i8 [ C1, %case1 ], [ C2, %case2 ], [ %val, %DEFAULT ]
5338///
5339/// We prefer to split the edge to 'end' so that there are TWO entries of V3/V4
5340/// to the PHI, merging the icmp & select into the switch, as follows:
5341///
5342/// case1:
5343/// switch i8 %A, label %DEFAULT [
5344/// i8 0, label %end
5345/// i8 1, label %case2
5346/// i8 2, label %case3
5347/// ]
5348/// case2:
5349/// br label %end
5350/// case3:
5351/// br label %end
5352/// DEFAULT:
5353/// br label %end
5354/// end:
5355/// _ = phi i8 [ C1, %case1 ], [ C2, %case2 ], [ C3, %case2 ], [ C4, %DEFAULT]
5356bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpSelectInIt(
5357 ICmpInst *ICI, SelectInst *Select, IRBuilder<> &Builder) {
5358 BasicBlock *BB = ICI->getParent();
5359
5360 // If the block has any PHIs in it or the icmp/select has multiple uses, it is
5361 // too complex.
5362 /// TODO: support multi-phis in succ BB of select's BB.
5363 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse() ||
5364 (Select && !Select->hasOneUse()))
5365 return false;
5366
5367 // The pattern we're looking for is where our only predecessor is a switch on
5368 // 'V' and this block is the default case for the switch. In this case we can
5369 // fold the compared value into the switch to simplify things.
5370 BasicBlock *Pred = BB->getSinglePredecessor();
5371 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
5372 return false;
5373
5374 Value *IcmpCond;
5375 ConstantInt *NewCaseVal;
5376 CmpPredicate Predicate;
5377
5378 // Match icmp X, C
5379 if (!match(ICI,
5380 m_ICmp(Predicate, m_Value(IcmpCond), m_ConstantInt(NewCaseVal))))
5381 return false;
5382
5383 Value *SelectCond, *SelectTrueVal, *SelectFalseVal;
5385 if (!Select) {
5386 // If Select == nullptr, we can assume that there is a hidden no-op select
5387 // just after icmp
5388 SelectCond = ICI;
5389 SelectTrueVal = Builder.getTrue();
5390 SelectFalseVal = Builder.getFalse();
5391 User = ICI->user_back();
5392 } else {
5393 SelectCond = Select->getCondition();
5394 // Check if the select condition is the same as the icmp condition.
5395 if (SelectCond != ICI)
5396 return false;
5397 SelectTrueVal = Select->getTrueValue();
5398 SelectFalseVal = Select->getFalseValue();
5399 User = Select->user_back();
5400 }
5401
5402 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
5403 if (SI->getCondition() != IcmpCond)
5404 return false;
5405
5406 // If BB is reachable on a non-default case, then we simply know the value of
5407 // V in this block. Substitute it and constant fold the icmp instruction
5408 // away.
5409 if (SI->getDefaultDest() != BB) {
5410 ConstantInt *VVal = SI->findCaseDest(BB);
5411 assert(VVal && "Should have a unique destination value");
5412 ICI->setOperand(0, VVal);
5413
5414 if (Value *V = simplifyInstruction(ICI, {DL, ICI})) {
5415 ICI->replaceAllUsesWith(V);
5416 ICI->eraseFromParent();
5417 }
5418 // BB is now empty, so it is likely to simplify away.
5419 return requestResimplify();
5420 }
5421
5422 // Ok, the block is reachable from the default dest. If the constant we're
5423 // comparing exists in one of the other edges, then we can constant fold ICI
5424 // and zap it.
5425 if (SI->findCaseValue(NewCaseVal) != SI->case_default()) {
5426 Value *V;
5427 if (Predicate == ICmpInst::ICMP_EQ)
5429 else
5431
5432 ICI->replaceAllUsesWith(V);
5433 ICI->eraseFromParent();
5434 // BB is now empty, so it is likely to simplify away.
5435 return requestResimplify();
5436 }
5437
5438 // The use of the select has to be in the 'end' block, by the only PHI node in
5439 // the block.
5440 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
5441 PHINode *PHIUse = dyn_cast<PHINode>(User);
5442 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
5444 return false;
5445
5446 // If the icmp is a SETEQ, then the default dest gets SelectFalseVal, the new
5447 // edge gets SelectTrueVal in the PHI.
5448 Value *DefaultCst = SelectFalseVal;
5449 Value *NewCst = SelectTrueVal;
5450
5451 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
5452 std::swap(DefaultCst, NewCst);
5453
5454 // Replace Select (which is used by the PHI for the default value) with
5455 // SelectFalseVal or SelectTrueVal depending on if ICI is EQ or NE.
5456 if (Select) {
5457 Select->replaceAllUsesWith(DefaultCst);
5458 Select->eraseFromParent();
5459 } else {
5460 ICI->replaceAllUsesWith(DefaultCst);
5461 }
5462 ICI->eraseFromParent();
5463
5464 SmallVector<DominatorTree::UpdateType, 2> Updates;
5465
5466 // Okay, the switch goes to this block on a default value. Add an edge from
5467 // the switch to the merge point on the compared value.
5468 BasicBlock *NewBB =
5469 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
5470 {
5471 SwitchInstProfUpdateWrapper SIW(*SI);
5472 auto W0 = SIW.getSuccessorWeight(0);
5474 if (W0) {
5475 NewW = ((uint64_t(*W0) + 1) >> 1);
5476 SIW.setSuccessorWeight(0, *NewW);
5477 }
5478 SIW.addCase(NewCaseVal, NewBB, NewW);
5479 if (DTU)
5480 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
5481 }
5482
5483 // NewBB branches to the phi block, add the uncond branch and the phi entry.
5484 Builder.SetInsertPoint(NewBB);
5485 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
5486 Builder.CreateBr(SuccBlock);
5487 PHIUse->addIncoming(NewCst, NewBB);
5488 if (DTU) {
5489 Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock});
5490 DTU->applyUpdates(Updates);
5491 }
5492 return true;
5493}
5494
5495/// Check to see if it is branching on an or/and chain of icmp instructions, and
5496/// fold it into a switch instruction if so.
5497bool SimplifyCFGOpt::simplifyBranchOnICmpChain(CondBrInst *BI,
5498 IRBuilder<> &Builder,
5499 const DataLayout &DL) {
5501 if (!Cond)
5502 return false;
5503
5504 // Change br (X == 0 | X == 1), T, F into a switch instruction.
5505 // If this is a bunch of seteq's or'd together, or if it's a bunch of
5506 // 'setne's and'ed together, collect them.
5507
5508 // Try to gather values from a chain of and/or to be turned into a switch
5509 ConstantComparesGatherer ConstantCompare(Cond, DL);
5510 // Unpack the result
5511 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
5512 Value *CompVal = ConstantCompare.CompValue;
5513 unsigned UsedICmps = ConstantCompare.UsedICmps;
5514 Value *ExtraCase = ConstantCompare.Extra;
5515 bool TrueWhenEqual = ConstantCompare.IsEq;
5516
5517 // If we didn't have a multiply compared value, fail.
5518 if (!CompVal)
5519 return false;
5520
5521 // Avoid turning single icmps into a switch.
5522 if (UsedICmps <= 1)
5523 return false;
5524
5525 // There might be duplicate constants in the list, which the switch
5526 // instruction can't handle, remove them now.
5528 Values.erase(llvm::unique(Values), Values.end());
5529
5530 // If Extra was used, we require at least two switch values to do the
5531 // transformation. A switch with one value is just a conditional branch.
5532 if (ExtraCase && Values.size() < 2)
5533 return false;
5534
5535 SmallVector<uint32_t> BranchWeights;
5536 const bool HasProfile = extractBranchWeights(*BI, BranchWeights);
5537
5538 // Figure out which block is which destination.
5539 BasicBlock *DefaultBB = BI->getSuccessor(1);
5540 BasicBlock *EdgeBB = BI->getSuccessor(0);
5541 if (!TrueWhenEqual) {
5542 std::swap(DefaultBB, EdgeBB);
5543 if (HasProfile)
5544 std::swap(BranchWeights[0], BranchWeights[1]);
5545 }
5546
5547 BasicBlock *BB = BI->getParent();
5548
5549 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
5550 << " cases into SWITCH. BB is:\n"
5551 << *BB);
5552
5553 SmallVector<DominatorTree::UpdateType, 2> Updates;
5554
5555 // If there are any extra values that couldn't be folded into the switch
5556 // then we evaluate them with an explicit branch first. Split the block
5557 // right before the condbr to handle it.
5558 if (ExtraCase) {
5559 BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr,
5560 /*MSSAU=*/nullptr, "switch.early.test");
5561
5562 // Remove the uncond branch added to the old block.
5563 Instruction *OldTI = BB->getTerminator();
5564 Builder.SetInsertPoint(OldTI);
5565
5566 // There can be an unintended UB if extra values are Poison. Before the
5567 // transformation, extra values may not be evaluated according to the
5568 // condition, and it will not raise UB. But after transformation, we are
5569 // evaluating extra values before checking the condition, and it will raise
5570 // UB. It can be solved by adding freeze instruction to extra values.
5571 AssumptionCache *AC = Options.AC;
5572
5573 if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr))
5574 ExtraCase = Builder.CreateFreeze(ExtraCase);
5575
5576 // We don't have any info about this condition.
5577 auto *Br = TrueWhenEqual ? Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB)
5578 : Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
5580
5581 OldTI->eraseFromParent();
5582
5583 if (DTU)
5584 Updates.push_back({DominatorTree::Insert, BB, EdgeBB});
5585
5586 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
5587 // for the edge we just added.
5588 addPredecessorToBlock(EdgeBB, BB, NewBB);
5589
5590 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
5591 << "\nEXTRABB = " << *BB);
5592 BB = NewBB;
5593 }
5594
5595 Builder.SetInsertPoint(BI);
5596 // Convert pointer to int before we switch.
5597 if (CompVal->getType()->isPointerTy()) {
5598 assert(!DL.hasUnstableRepresentation(CompVal->getType()) &&
5599 "Should not end up here with unstable pointers");
5600 CompVal = Builder.CreatePtrToInt(
5601 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
5602 }
5603
5604 // Check if we can represent the values as a contiguous range. If so, we use a
5605 // range check + conditional branch instead of a switch.
5606 if (Values.front()->getValue() - Values.back()->getValue() ==
5607 Values.size() - 1) {
5608 ConstantRange RangeToCheck = ConstantRange::getNonEmpty(
5609 Values.back()->getValue(), Values.front()->getValue() + 1);
5610 APInt Offset, RHS;
5611 ICmpInst::Predicate Pred;
5612 RangeToCheck.getEquivalentICmp(Pred, RHS, Offset);
5613 Value *X = CompVal;
5614 if (!Offset.isZero())
5615 X = Builder.CreateAdd(X, ConstantInt::get(CompVal->getType(), Offset));
5616 Value *Cond =
5617 Builder.CreateICmp(Pred, X, ConstantInt::get(CompVal->getType(), RHS));
5618 CondBrInst *NewBI = Builder.CreateCondBr(Cond, EdgeBB, DefaultBB);
5619 if (HasProfile)
5620 setBranchWeights(*NewBI, BranchWeights, /*IsExpected=*/false);
5621 else
5623 if (MDNode *Unpredictable = BI->getMetadata(LLVMContext::MD_unpredictable))
5624 NewBI->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
5625 // We don't need to update PHI nodes since we don't add any new edges.
5626 } else {
5627 // Create the new switch instruction now.
5628 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
5629 if (MDNode *Unpredictable = BI->getMetadata(LLVMContext::MD_unpredictable))
5630 New->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
5631 if (HasProfile) {
5632 // We know the weight of the default case. We don't know the weight of the
5633 // other cases, but rather than completely lose profiling info, we split
5634 // the remaining probability equally over them.
5635 SmallVector<uint32_t> NewWeights(Values.size() + 1);
5636 NewWeights[0] = BranchWeights[1]; // this is the default, and we swapped
5637 // if TrueWhenEqual.
5638 for (auto &V : drop_begin(NewWeights))
5639 V = BranchWeights[0] / Values.size();
5640 setBranchWeights(*New, NewWeights, /*IsExpected=*/false);
5641 } else {
5643 }
5644
5645 // Add all of the 'cases' to the switch instruction.
5646 for (ConstantInt *Val : Values)
5647 New->addCase(Val, EdgeBB);
5648
5649 // We added edges from PI to the EdgeBB. As such, if there were any
5650 // PHI nodes in EdgeBB, they need entries to be added corresponding to
5651 // the number of edges added.
5652 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
5653 PHINode *PN = cast<PHINode>(BBI);
5654 Value *InVal = PN->getIncomingValueForBlock(BB);
5655 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
5656 PN->addIncoming(InVal, BB);
5657 }
5658 }
5659
5660 // Erase the old branch instruction.
5662 if (DTU)
5663 DTU->applyUpdates(Updates);
5664
5665 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
5666 return true;
5667}
5668
5669bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
5670 if (isa<PHINode>(RI->getValue()))
5671 return simplifyCommonResume(RI);
5672 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHIIt()) &&
5673 RI->getValue() == &*RI->getParent()->getFirstNonPHIIt())
5674 // The resume must unwind the exception that caused control to branch here.
5675 return simplifySingleResume(RI);
5676
5677 return false;
5678}
5679
5680// Check if cleanup block is empty
5682 for (Instruction &I : R) {
5683 auto *II = dyn_cast<IntrinsicInst>(&I);
5684 if (!II || II->getIntrinsicID() != Intrinsic::lifetime_end)
5685 return false;
5686 }
5687 return true;
5688}
5689
5690// Simplify resume that is shared by several landing pads (phi of landing pad).
5691bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
5692 BasicBlock *BB = RI->getParent();
5693
5694 // Check that there are no other instructions except for debug and lifetime
5695 // intrinsics between the phi's and resume instruction.
5696 if (!isCleanupBlockEmpty(make_range(RI->getParent()->getFirstNonPHIIt(),
5697 BB->getTerminator()->getIterator())))
5698 return false;
5699
5700 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
5701 auto *PhiLPInst = cast<PHINode>(RI->getValue());
5702
5703 // Check incoming blocks to see if any of them are trivial.
5704 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
5705 Idx++) {
5706 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
5707 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
5708
5709 // If the block has other successors, we can not delete it because
5710 // it has other dependents.
5711 if (IncomingBB->getUniqueSuccessor() != BB)
5712 continue;
5713
5714 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHIIt());
5715 // Not the landing pad that caused the control to branch here.
5716 if (IncomingValue != LandingPad)
5717 continue;
5718
5720 make_range(LandingPad->getNextNode(), IncomingBB->getTerminator())))
5721 TrivialUnwindBlocks.insert(IncomingBB);
5722 }
5723
5724 // If no trivial unwind blocks, don't do any simplifications.
5725 if (TrivialUnwindBlocks.empty())
5726 return false;
5727
5728 // Turn all invokes that unwind here into calls.
5729 for (auto *TrivialBB : TrivialUnwindBlocks) {
5730 // Blocks that will be simplified should be removed from the phi node.
5731 // Note there could be multiple edges to the resume block, and we need
5732 // to remove them all.
5733 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
5734 BB->removePredecessor(TrivialBB, true);
5735
5736 for (BasicBlock *Pred :
5738 removeUnwindEdge(Pred, DTU);
5739 ++NumInvokes;
5740 }
5741
5742 // In each SimplifyCFG run, only the current processed block can be erased.
5743 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
5744 // of erasing TrivialBB, we only remove the branch to the common resume
5745 // block so that we can later erase the resume block since it has no
5746 // predecessors.
5747 TrivialBB->getTerminator()->eraseFromParent();
5748 new UnreachableInst(RI->getContext(), TrivialBB);
5749 if (DTU)
5750 DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}});
5751 }
5752
5753 // Delete the resume block if all its predecessors have been removed.
5754 if (pred_empty(BB))
5755 DeleteDeadBlock(BB, DTU);
5756
5757 return !TrivialUnwindBlocks.empty();
5758}
5759
5760// Simplify resume that is only used by a single (non-phi) landing pad.
5761bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
5762 BasicBlock *BB = RI->getParent();
5763 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHIIt());
5764 assert(RI->getValue() == LPInst &&
5765 "Resume must unwind the exception that caused control to here");
5766
5767 // Check that there are no other instructions except for debug intrinsics.
5769 make_range<Instruction *>(LPInst->getNextNode(), RI)))
5770 return false;
5771
5772 // Turn all invokes that unwind here into calls and delete the basic block.
5773 for (BasicBlock *Pred : llvm::make_early_inc_range(predecessors(BB))) {
5774 removeUnwindEdge(Pred, DTU);
5775 ++NumInvokes;
5776 }
5777
5778 // The landingpad is now unreachable. Zap it.
5779 DeleteDeadBlock(BB, DTU);
5780 return true;
5781}
5782
5784 // If this is a trivial cleanup pad that executes no instructions, it can be
5785 // eliminated. If the cleanup pad continues to the caller, any predecessor
5786 // that is an EH pad will be updated to continue to the caller and any
5787 // predecessor that terminates with an invoke instruction will have its invoke
5788 // instruction converted to a call instruction. If the cleanup pad being
5789 // simplified does not continue to the caller, each predecessor will be
5790 // updated to continue to the unwind destination of the cleanup pad being
5791 // simplified.
5792 BasicBlock *BB = RI->getParent();
5793 CleanupPadInst *CPInst = RI->getCleanupPad();
5794 if (CPInst->getParent() != BB)
5795 // This isn't an empty cleanup.
5796 return false;
5797
5798 // We cannot kill the pad if it has multiple uses. This typically arises
5799 // from unreachable basic blocks.
5800 if (!CPInst->hasOneUse())
5801 return false;
5802
5803 // Check that there are no other instructions except for benign intrinsics.
5805 make_range<Instruction *>(CPInst->getNextNode(), RI)))
5806 return false;
5807
5808 // If the cleanup return we are simplifying unwinds to the caller, this will
5809 // set UnwindDest to nullptr.
5810 BasicBlock *UnwindDest = RI->getUnwindDest();
5811
5812 // We're about to remove BB from the control flow. Before we do, sink any
5813 // PHINodes into the unwind destination. Doing this before changing the
5814 // control flow avoids some potentially slow checks, since we can currently
5815 // be certain that UnwindDest and BB have no common predecessors (since they
5816 // are both EH pads).
5817 if (UnwindDest) {
5818 // First, go through the PHI nodes in UnwindDest and update any nodes that
5819 // reference the block we are removing
5820 for (PHINode &DestPN : UnwindDest->phis()) {
5821 int Idx = DestPN.getBasicBlockIndex(BB);
5822 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
5823 assert(Idx != -1);
5824 // This PHI node has an incoming value that corresponds to a control
5825 // path through the cleanup pad we are removing. If the incoming
5826 // value is in the cleanup pad, it must be a PHINode (because we
5827 // verified above that the block is otherwise empty). Otherwise, the
5828 // value is either a constant or a value that dominates the cleanup
5829 // pad being removed.
5830 //
5831 // Because BB and UnwindDest are both EH pads, all of their
5832 // predecessors must unwind to these blocks, and since no instruction
5833 // can have multiple unwind destinations, there will be no overlap in
5834 // incoming blocks between SrcPN and DestPN.
5835 Value *SrcVal = DestPN.getIncomingValue(Idx);
5836 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
5837
5838 bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB;
5839 for (auto *Pred : predecessors(BB)) {
5840 Value *Incoming =
5841 NeedPHITranslation ? SrcPN->getIncomingValueForBlock(Pred) : SrcVal;
5842 DestPN.addIncoming(Incoming, Pred);
5843 }
5844 }
5845
5846 // Sink any remaining PHI nodes directly into UnwindDest.
5847 BasicBlock::iterator InsertPt = UnwindDest->getFirstNonPHIIt();
5848 for (PHINode &PN : make_early_inc_range(BB->phis())) {
5849 if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB))
5850 // If the PHI node has no uses or all of its uses are in this basic
5851 // block (meaning they are debug or lifetime intrinsics), just leave
5852 // it. It will be erased when we erase BB below.
5853 continue;
5854
5855 // Otherwise, sink this PHI node into UnwindDest.
5856 // Any predecessors to UnwindDest which are not already represented
5857 // must be back edges which inherit the value from the path through
5858 // BB. In this case, the PHI value must reference itself.
5859 for (auto *pred : predecessors(UnwindDest))
5860 if (pred != BB)
5861 PN.addIncoming(&PN, pred);
5862 PN.moveBefore(InsertPt);
5863 // Also, add a dummy incoming value for the original BB itself,
5864 // so that the PHI is well-formed until we drop said predecessor.
5865 PN.addIncoming(PoisonValue::get(PN.getType()), BB);
5866 }
5867 }
5868
5869 std::vector<DominatorTree::UpdateType> Updates;
5870
5871 // We use make_early_inc_range here because we will remove all predecessors.
5873 if (UnwindDest == nullptr) {
5874 if (DTU) {
5875 DTU->applyUpdates(Updates);
5876 Updates.clear();
5877 }
5878 removeUnwindEdge(PredBB, DTU);
5879 ++NumInvokes;
5880 } else {
5881 BB->removePredecessor(PredBB);
5882 Instruction *TI = PredBB->getTerminator();
5883 TI->replaceUsesOfWith(BB, UnwindDest);
5884 if (DTU) {
5885 Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest});
5886 Updates.push_back({DominatorTree::Delete, PredBB, BB});
5887 }
5888 }
5889 }
5890
5891 if (DTU)
5892 DTU->applyUpdates(Updates);
5893
5894 DeleteDeadBlock(BB, DTU);
5895
5896 return true;
5897}
5898
5899// Try to merge two cleanuppads together.
5901 // Skip any cleanuprets which unwind to caller, there is nothing to merge
5902 // with.
5903 BasicBlock *UnwindDest = RI->getUnwindDest();
5904 if (!UnwindDest)
5905 return false;
5906
5907 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
5908 // be safe to merge without code duplication.
5909 if (UnwindDest->getSinglePredecessor() != RI->getParent())
5910 return false;
5911
5912 // Verify that our cleanuppad's unwind destination is another cleanuppad.
5913 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
5914 if (!SuccessorCleanupPad)
5915 return false;
5916
5917 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
5918 // Replace any uses of the successor cleanupad with the predecessor pad
5919 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
5920 // funclet bundle operands.
5921 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
5922 // Remove the old cleanuppad.
5923 SuccessorCleanupPad->eraseFromParent();
5924 // Now, we simply replace the cleanupret with a branch to the unwind
5925 // destination.
5926 UncondBrInst::Create(UnwindDest, RI->getParent());
5927 RI->eraseFromParent();
5928
5929 return true;
5930}
5931
5932bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
5933 // It is possible to transiantly have an undef cleanuppad operand because we
5934 // have deleted some, but not all, dead blocks.
5935 // Eventually, this block will be deleted.
5936 if (isa<UndefValue>(RI->getOperand(0)))
5937 return false;
5938
5939 if (mergeCleanupPad(RI))
5940 return true;
5941
5942 if (removeEmptyCleanup(RI, DTU))
5943 return true;
5944
5945 return false;
5946}
5947
5948// WARNING: keep in sync with InstCombinerImpl::visitUnreachableInst()!
5949bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
5950 BasicBlock *BB = UI->getParent();
5951
5952 bool Changed = false;
5953
5954 // Ensure that any debug-info records that used to occur after the Unreachable
5955 // are moved to in front of it -- otherwise they'll "dangle" at the end of
5956 // the block.
5958
5959 // Debug-info records on the unreachable inst itself should be deleted, as
5960 // below we delete everything past the final executable instruction.
5961 UI->dropDbgRecords();
5962
5963 // If there are any instructions immediately before the unreachable that can
5964 // be removed, do so.
5965 while (UI->getIterator() != BB->begin()) {
5967 --BBI;
5968
5970 break; // Can not drop any more instructions. We're done here.
5971 // Otherwise, this instruction can be freely erased,
5972 // even if it is not side-effect free.
5973
5974 // Note that deleting EH's here is in fact okay, although it involves a bit
5975 // of subtle reasoning. If this inst is an EH, all the predecessors of this
5976 // block will be the unwind edges of Invoke/CatchSwitch/CleanupReturn,
5977 // and we can therefore guarantee this block will be erased.
5978
5979 // If we're deleting this, we're deleting any subsequent debug info, so
5980 // delete DbgRecords.
5981 BBI->dropDbgRecords();
5982
5983 // Delete this instruction (any uses are guaranteed to be dead)
5984 BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
5985 BBI->eraseFromParent();
5986 Changed = true;
5987 }
5988
5989 // If the unreachable instruction is the first in the block, take a gander
5990 // at all of the predecessors of this instruction, and simplify them.
5991 if (&BB->front() != UI)
5992 return Changed;
5993
5994 std::vector<DominatorTree::UpdateType> Updates;
5995
5996 SmallSetVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
5997 for (BasicBlock *Predecessor : Preds) {
5998 Instruction *TI = Predecessor->getTerminator();
5999 IRBuilder<> Builder(TI);
6000 if (isa<UncondBrInst>(TI)) {
6001 new UnreachableInst(TI->getContext(), TI->getIterator());
6002 TI->eraseFromParent();
6003 Changed = true;
6004 if (DTU)
6005 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6006 } else if (auto *BI = dyn_cast<CondBrInst>(TI)) {
6007 // We could either have a proper unconditional branch,
6008 // or a degenerate conditional branch with matching destinations.
6009 if (BI->getSuccessor(0) == BI->getSuccessor(1)) {
6010 new UnreachableInst(TI->getContext(), TI->getIterator());
6011 TI->eraseFromParent();
6012 Changed = true;
6013 } else {
6014 Value* Cond = BI->getCondition();
6015 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
6016 "The destinations are guaranteed to be different here.");
6017 CallInst *Assumption;
6018 if (BI->getSuccessor(0) == BB) {
6019 Assumption = Builder.CreateAssumption(Builder.CreateNot(Cond));
6020 Builder.CreateBr(BI->getSuccessor(1));
6021 } else {
6022 assert(BI->getSuccessor(1) == BB && "Incorrect CFG");
6023 Assumption = Builder.CreateAssumption(Cond);
6024 Builder.CreateBr(BI->getSuccessor(0));
6025 }
6026 if (Options.AC)
6027 Options.AC->registerAssumption(cast<AssumeInst>(Assumption));
6028
6030 Changed = true;
6031 }
6032 if (DTU)
6033 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6034 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
6035 SwitchInstProfUpdateWrapper SU(*SI);
6036 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
6037 if (i->getCaseSuccessor() != BB) {
6038 ++i;
6039 continue;
6040 }
6041 BB->removePredecessor(SU->getParent());
6042 i = SU.removeCase(i);
6043 e = SU->case_end();
6044 Changed = true;
6045 }
6046 // Note that the default destination can't be removed!
6047 if (DTU && SI->getDefaultDest() != BB)
6048 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6049 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
6050 if (II->getUnwindDest() == BB) {
6051 if (DTU) {
6052 DTU->applyUpdates(Updates);
6053 Updates.clear();
6054 }
6055 auto *CI = cast<CallInst>(removeUnwindEdge(TI->getParent(), DTU));
6056 if (!CI->doesNotThrow())
6057 CI->setDoesNotThrow();
6058 Changed = true;
6059 }
6060 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
6061 if (CSI->getUnwindDest() == BB) {
6062 if (DTU) {
6063 DTU->applyUpdates(Updates);
6064 Updates.clear();
6065 }
6066 removeUnwindEdge(TI->getParent(), DTU);
6067 Changed = true;
6068 continue;
6069 }
6070
6071 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
6072 E = CSI->handler_end();
6073 I != E; ++I) {
6074 if (*I == BB) {
6075 CSI->removeHandler(I);
6076 --I;
6077 --E;
6078 Changed = true;
6079 }
6080 }
6081 if (DTU)
6082 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6083 if (CSI->getNumHandlers() == 0) {
6084 if (CSI->hasUnwindDest()) {
6085 // Redirect all predecessors of the block containing CatchSwitchInst
6086 // to instead branch to the CatchSwitchInst's unwind destination.
6087 if (DTU) {
6088 for (auto *PredecessorOfPredecessor : predecessors(Predecessor)) {
6089 Updates.push_back({DominatorTree::Insert,
6090 PredecessorOfPredecessor,
6091 CSI->getUnwindDest()});
6092 Updates.push_back({DominatorTree::Delete,
6093 PredecessorOfPredecessor, Predecessor});
6094 }
6095 }
6096 Predecessor->replaceAllUsesWith(CSI->getUnwindDest());
6097 } else {
6098 // Rewrite all preds to unwind to caller (or from invoke to call).
6099 if (DTU) {
6100 DTU->applyUpdates(Updates);
6101 Updates.clear();
6102 }
6103 SmallVector<BasicBlock *, 8> EHPreds(predecessors(Predecessor));
6104 for (BasicBlock *EHPred : EHPreds)
6105 removeUnwindEdge(EHPred, DTU);
6106 }
6107 // The catchswitch is no longer reachable.
6108 new UnreachableInst(CSI->getContext(), CSI->getIterator());
6109 CSI->eraseFromParent();
6110 Changed = true;
6111 }
6112 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
6113 (void)CRI;
6114 assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB &&
6115 "Expected to always have an unwind to BB.");
6116 if (DTU)
6117 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6118 new UnreachableInst(TI->getContext(), TI->getIterator());
6119 TI->eraseFromParent();
6120 Changed = true;
6121 }
6122 }
6123
6124 if (DTU)
6125 DTU->applyUpdates(Updates);
6126
6127 // If this block is now dead, remove it.
6128 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
6129 DeleteDeadBlock(BB, DTU);
6130 return true;
6131 }
6132
6133 return Changed;
6134}
6135
6144
6145static std::optional<ContiguousCasesResult>
6148 BasicBlock *Dest, BasicBlock *OtherDest) {
6149 assert(Cases.size() >= 1);
6150
6152 const APInt &Min = Cases.back()->getValue();
6153 const APInt &Max = Cases.front()->getValue();
6154 APInt Offset = Max - Min;
6155 size_t ContiguousOffset = Cases.size() - 1;
6156 if (Offset == ContiguousOffset) {
6157 return ContiguousCasesResult{
6158 /*Min=*/Cases.back(),
6159 /*Max=*/Cases.front(),
6160 /*Dest=*/Dest,
6161 /*OtherDest=*/OtherDest,
6162 /*Cases=*/&Cases,
6163 /*OtherCases=*/&OtherCases,
6164 };
6165 }
6166 ConstantRange CR = computeConstantRange(Condition, /*ForSigned=*/false,
6167 SimplifyQuery(Dest->getDataLayout()));
6168 // If this is a wrapping contiguous range, that is, [Min, OtherMin] +
6169 // [OtherMax, Max] (also [OtherMax, OtherMin]), [OtherMin+1, OtherMax-1] is a
6170 // contiguous range for the other destination. N.B. If CR is not a full range,
6171 // Max+1 is not equal to Min. It's not continuous in arithmetic.
6172 if (Max == CR.getUnsignedMax() && Min == CR.getUnsignedMin()) {
6173 assert(Cases.size() >= 2);
6174 auto *It =
6175 std::adjacent_find(Cases.begin(), Cases.end(), [](auto L, auto R) {
6176 return L->getValue() != R->getValue() + 1;
6177 });
6178 if (It == Cases.end())
6179 return std::nullopt;
6180 auto [OtherMax, OtherMin] = std::make_pair(*It, *std::next(It));
6181 if ((Max - OtherMax->getValue()) + (OtherMin->getValue() - Min) ==
6182 Cases.size() - 2) {
6183 return ContiguousCasesResult{
6184 /*Min=*/cast<ConstantInt>(
6185 ConstantInt::get(OtherMin->getType(), OtherMin->getValue() + 1)),
6186 /*Max=*/
6188 ConstantInt::get(OtherMax->getType(), OtherMax->getValue() - 1)),
6189 /*Dest=*/OtherDest,
6190 /*OtherDest=*/Dest,
6191 /*Cases=*/&OtherCases,
6192 /*OtherCases=*/&Cases,
6193 };
6194 }
6195 }
6196 return std::nullopt;
6197}
6198
6200 DomTreeUpdater *DTU,
6201 bool RemoveOrigDefaultBlock = true) {
6202 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
6203 auto *BB = Switch->getParent();
6204 auto *OrigDefaultBlock = Switch->getDefaultDest();
6205 if (RemoveOrigDefaultBlock)
6206 OrigDefaultBlock->removePredecessor(BB);
6207 BasicBlock *NewDefaultBlock = BasicBlock::Create(
6208 BB->getContext(), BB->getName() + ".unreachabledefault", BB->getParent(),
6209 OrigDefaultBlock);
6210 auto *UI = new UnreachableInst(Switch->getContext(), NewDefaultBlock);
6212 Switch->setDefaultDest(&*NewDefaultBlock);
6213 if (DTU) {
6215 Updates.push_back({DominatorTree::Insert, BB, &*NewDefaultBlock});
6216 if (RemoveOrigDefaultBlock &&
6217 !is_contained(successors(BB), OrigDefaultBlock))
6218 Updates.push_back({DominatorTree::Delete, BB, &*OrigDefaultBlock});
6219 DTU->applyUpdates(Updates);
6220 }
6221}
6222
6223/// Turn a switch into an integer range comparison and branch.
6224/// Switches with more than 2 destinations are ignored.
6225/// Switches with 1 destination are also ignored.
6226bool SimplifyCFGOpt::turnSwitchRangeIntoICmp(SwitchInst *SI,
6227 IRBuilder<> &Builder) {
6228 assert(SI->getNumCases() > 1 && "Degenerate switch?");
6229
6230 bool HasDefault = !SI->defaultDestUnreachable();
6231
6232 auto *BB = SI->getParent();
6233 // Partition the cases into two sets with different destinations.
6234 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
6235 BasicBlock *DestB = nullptr;
6238
6239 for (auto Case : SI->cases()) {
6240 BasicBlock *Dest = Case.getCaseSuccessor();
6241 if (!DestA)
6242 DestA = Dest;
6243 if (Dest == DestA) {
6244 CasesA.push_back(Case.getCaseValue());
6245 continue;
6246 }
6247 if (!DestB)
6248 DestB = Dest;
6249 if (Dest == DestB) {
6250 CasesB.push_back(Case.getCaseValue());
6251 continue;
6252 }
6253 return false; // More than two destinations.
6254 }
6255 if (!DestB)
6256 return false; // All destinations are the same and the default is unreachable
6257
6258 assert(DestA && DestB &&
6259 "Single-destination switch should have been folded.");
6260 assert(DestA != DestB);
6261 assert(DestB != SI->getDefaultDest());
6262 assert(!CasesB.empty() && "There must be non-default cases.");
6263 assert(!CasesA.empty() || HasDefault);
6264
6265 // Figure out if one of the sets of cases form a contiguous range.
6266 std::optional<ContiguousCasesResult> ContiguousCases;
6267
6268 // Only one icmp is needed when there is only one case.
6269 if (!HasDefault && CasesA.size() == 1)
6270 ContiguousCases = ContiguousCasesResult{
6271 /*Min=*/CasesA[0],
6272 /*Max=*/CasesA[0],
6273 /*Dest=*/DestA,
6274 /*OtherDest=*/DestB,
6275 /*Cases=*/&CasesA,
6276 /*OtherCases=*/&CasesB,
6277 };
6278 else if (CasesB.size() == 1)
6279 ContiguousCases = ContiguousCasesResult{
6280 /*Min=*/CasesB[0],
6281 /*Max=*/CasesB[0],
6282 /*Dest=*/DestB,
6283 /*OtherDest=*/DestA,
6284 /*Cases=*/&CasesB,
6285 /*OtherCases=*/&CasesA,
6286 };
6287 // Correctness: Cases to the default destination cannot be contiguous cases.
6288 else if (!HasDefault)
6289 ContiguousCases =
6290 findContiguousCases(SI->getCondition(), CasesA, CasesB, DestA, DestB);
6291
6292 if (!ContiguousCases)
6293 ContiguousCases =
6294 findContiguousCases(SI->getCondition(), CasesB, CasesA, DestB, DestA);
6295
6296 if (!ContiguousCases)
6297 return false;
6298
6299 auto [Min, Max, Dest, OtherDest, Cases, OtherCases] = *ContiguousCases;
6300
6301 // Start building the compare and branch.
6302
6304 Constant *NumCases = ConstantInt::get(Offset->getType(),
6305 Max->getValue() - Min->getValue() + 1);
6306 Instruction *NewBI;
6307 if (NumCases->isOneValue()) {
6308 assert(Max->getValue() == Min->getValue());
6309 Value *Cmp = Builder.CreateICmpEQ(SI->getCondition(), Min);
6310 NewBI = Builder.CreateCondBr(Cmp, Dest, OtherDest);
6311 }
6312 // If NumCases overflowed, then all possible values jump to the successor.
6313 else if (NumCases->isNullValue() && !Cases->empty()) {
6314 NewBI = Builder.CreateBr(Dest);
6315 } else {
6316 Value *Sub = SI->getCondition();
6317 if (!Offset->isNullValue())
6318 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
6319 Value *Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
6320 NewBI = Builder.CreateCondBr(Cmp, Dest, OtherDest);
6321 }
6322
6323 // Update weight for the newly-created conditional branch.
6324 if (hasBranchWeightMD(*SI) && isa<CondBrInst>(NewBI)) {
6325 SmallVector<uint64_t, 8> Weights;
6326 getBranchWeights(SI, Weights);
6327 if (Weights.size() == 1 + SI->getNumCases()) {
6328 uint64_t TrueWeight = 0;
6329 uint64_t FalseWeight = 0;
6330 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
6331 if (SI->getSuccessor(I) == Dest)
6332 TrueWeight += Weights[I];
6333 else
6334 FalseWeight += Weights[I];
6335 }
6336 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
6337 TrueWeight /= 2;
6338 FalseWeight /= 2;
6339 }
6340 setFittedBranchWeights(*NewBI, {TrueWeight, FalseWeight},
6341 /*IsExpected=*/false, /*ElideAllZero=*/true);
6342 }
6343 }
6344
6345 // Prune obsolete incoming values off the successors' PHI nodes.
6346 for (auto &PHI : make_early_inc_range(Dest->phis())) {
6347 unsigned PreviousEdges = Cases->size();
6348 if (Dest == SI->getDefaultDest())
6349 ++PreviousEdges;
6350 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
6351 PHI.removeIncomingValue(SI->getParent());
6352 }
6353 for (auto &PHI : make_early_inc_range(OtherDest->phis())) {
6354 unsigned PreviousEdges = OtherCases->size();
6355 if (OtherDest == SI->getDefaultDest())
6356 ++PreviousEdges;
6357 unsigned E = PreviousEdges - 1;
6358 // Remove all incoming values from OtherDest if OtherDest is unreachable.
6359 if (isa<UncondBrInst>(NewBI))
6360 ++E;
6361 for (unsigned I = 0; I != E; ++I)
6362 PHI.removeIncomingValue(SI->getParent());
6363 }
6364
6365 // Clean up the default block.
6366 SmallVector<DominatorTree::UpdateType, 2> Updates;
6367 if (!HasDefault) {
6368 BasicBlock *OrigDefaultBlock = SI->getDefaultDest();
6369 OrigDefaultBlock->removePredecessor(BB);
6370 Updates.push_back({DominatorTree::Delete, BB, OrigDefaultBlock});
6371 }
6372
6373 // Drop the switch.
6374 SI->eraseFromParent();
6375
6376 if (isa<UncondBrInst>(NewBI))
6377 Updates.push_back({DominatorTree::Delete, BB, OtherDest});
6378
6379 if (DTU)
6380 DTU->applyUpdates(Updates);
6381 return true;
6382}
6383
6384/// Compute masked bits for the condition of a switch
6385/// and use it to remove dead cases.
6387 AssumptionCache *AC,
6388 const DataLayout &DL) {
6389 Value *Cond = SI->getCondition();
6392 bool IsKnownValuesValid = collectPossibleValues(Cond, KnownValues, 4);
6393
6394 // We can also eliminate cases by determining that their values are outside of
6395 // the limited range of the condition based on how many significant (non-sign)
6396 // bits are in the condition value.
6397 unsigned MaxSignificantBitsInCond =
6399
6400 // Gather dead cases.
6402 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
6403 SmallVector<BasicBlock *, 8> UniqueSuccessors;
6404 for (const auto &Case : SI->cases()) {
6405 auto *Successor = Case.getCaseSuccessor();
6406 if (DTU) {
6407 auto [It, Inserted] = NumPerSuccessorCases.try_emplace(Successor);
6408 if (Inserted)
6409 UniqueSuccessors.push_back(Successor);
6410 ++It->second;
6411 }
6412 ConstantInt *CaseC = Case.getCaseValue();
6413 const APInt &CaseVal = CaseC->getValue();
6414 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
6415 (CaseVal.getSignificantBits() > MaxSignificantBitsInCond) ||
6416 (IsKnownValuesValid && !KnownValues.contains(CaseC))) {
6417 DeadCases.push_back(CaseC);
6418 if (DTU)
6419 --NumPerSuccessorCases[Successor];
6420 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
6421 << " is dead.\n");
6422 } else if (IsKnownValuesValid)
6423 KnownValues.erase(CaseC);
6424 }
6425
6426 // If we can prove that the cases must cover all possible values, the
6427 // default destination becomes dead and we can remove it. If we know some
6428 // of the bits in the value, we can use that to more precisely compute the
6429 // number of possible unique case values.
6430 bool HasDefault = !SI->defaultDestUnreachable();
6431 const unsigned NumUnknownBits =
6432 Known.getBitWidth() - (Known.Zero | Known.One).popcount();
6433 assert(NumUnknownBits <= Known.getBitWidth());
6434 if (HasDefault && DeadCases.empty()) {
6435 if (IsKnownValuesValid && all_of(KnownValues, IsaPred<UndefValue>)) {
6437 return true;
6438 }
6439
6440 if (NumUnknownBits < 64 /* avoid overflow */) {
6441 uint64_t AllNumCases = 1ULL << NumUnknownBits;
6442 if (SI->getNumCases() == AllNumCases) {
6444 return true;
6445 }
6446 // When only one case value is missing, replace default with that case.
6447 // Eliminating the default branch will provide more opportunities for
6448 // optimization, such as lookup tables.
6449 if (SI->getNumCases() == AllNumCases - 1) {
6450 assert(NumUnknownBits > 1 && "Should be canonicalized to a branch");
6451 IntegerType *CondTy = cast<IntegerType>(Cond->getType());
6452 if (CondTy->getIntegerBitWidth() > 64 ||
6453 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
6454 return false;
6455
6456 uint64_t MissingCaseVal = 0;
6457 for (const auto &Case : SI->cases())
6458 MissingCaseVal ^= Case.getCaseValue()->getValue().getLimitedValue();
6459 auto *MissingCase = cast<ConstantInt>(
6460 ConstantInt::get(Cond->getType(), MissingCaseVal));
6462 SIW.addCase(MissingCase, SI->getDefaultDest(),
6463 SIW.getSuccessorWeight(0));
6465 /*RemoveOrigDefaultBlock*/ false);
6466 SIW.setSuccessorWeight(0, 0);
6467 return true;
6468 }
6469 }
6470 }
6471
6472 if (DeadCases.empty())
6473 return false;
6474
6476 for (ConstantInt *DeadCase : DeadCases) {
6477 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
6478 assert(CaseI != SI->case_default() &&
6479 "Case was not found. Probably mistake in DeadCases forming.");
6480 // Prune unused values from PHI nodes.
6481 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
6482 SIW.removeCase(CaseI);
6483 }
6484
6485 if (DTU) {
6486 std::vector<DominatorTree::UpdateType> Updates;
6487 for (auto *Successor : UniqueSuccessors)
6488 if (NumPerSuccessorCases[Successor] == 0)
6489 Updates.push_back({DominatorTree::Delete, SI->getParent(), Successor});
6490 DTU->applyUpdates(Updates);
6491 }
6492
6493 return true;
6494}
6495
6496/// If BB would be eligible for simplification by
6497/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
6498/// by an unconditional branch), look at the phi node for BB in the successor
6499/// block and see if the incoming value is equal to CaseValue. If so, return
6500/// the phi node, and set PhiIndex to BB's index in the phi node.
6502 BasicBlock *BB, int *PhiIndex) {
6503 if (&*BB->getFirstNonPHIIt() != BB->getTerminator())
6504 return nullptr; // BB must be empty to be a candidate for simplification.
6505 if (!BB->getSinglePredecessor())
6506 return nullptr; // BB must be dominated by the switch.
6507
6509 if (!Branch)
6510 return nullptr; // Terminator must be unconditional branch.
6511
6512 BasicBlock *Succ = Branch->getSuccessor();
6513
6514 for (PHINode &PHI : Succ->phis()) {
6515 int Idx = PHI.getBasicBlockIndex(BB);
6516 assert(Idx >= 0 && "PHI has no entry for predecessor?");
6517
6518 Value *InValue = PHI.getIncomingValue(Idx);
6519 if (InValue != CaseValue)
6520 continue;
6521
6522 *PhiIndex = Idx;
6523 return &PHI;
6524 }
6525
6526 return nullptr;
6527}
6528
6529/// Try to forward the condition of a switch instruction to a phi node
6530/// dominated by the switch, if that would mean that some of the destination
6531/// blocks of the switch can be folded away. Return true if a change is made.
6533 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
6534
6535 ForwardingNodesMap ForwardingNodes;
6536 BasicBlock *SwitchBlock = SI->getParent();
6537 bool Changed = false;
6538 for (const auto &Case : SI->cases()) {
6539 ConstantInt *CaseValue = Case.getCaseValue();
6540 BasicBlock *CaseDest = Case.getCaseSuccessor();
6541
6542 // Replace phi operands in successor blocks that are using the constant case
6543 // value rather than the switch condition variable:
6544 // switchbb:
6545 // switch i32 %x, label %default [
6546 // i32 17, label %succ
6547 // ...
6548 // succ:
6549 // %r = phi i32 ... [ 17, %switchbb ] ...
6550 // -->
6551 // %r = phi i32 ... [ %x, %switchbb ] ...
6552
6553 for (PHINode &Phi : CaseDest->phis()) {
6554 // This only works if there is exactly 1 incoming edge from the switch to
6555 // a phi. If there is >1, that means multiple cases of the switch map to 1
6556 // value in the phi, and that phi value is not the switch condition. Thus,
6557 // this transform would not make sense (the phi would be invalid because
6558 // a phi can't have different incoming values from the same block).
6559 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
6560 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
6561 count(Phi.blocks(), SwitchBlock) == 1) {
6562 Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
6563 Changed = true;
6564 }
6565 }
6566
6567 // Collect phi nodes that are indirectly using this switch's case constants.
6568 int PhiIdx;
6569 if (auto *Phi = findPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
6570 ForwardingNodes[Phi].push_back(PhiIdx);
6571 }
6572
6573 for (auto &ForwardingNode : ForwardingNodes) {
6574 PHINode *Phi = ForwardingNode.first;
6575 SmallVectorImpl<int> &Indexes = ForwardingNode.second;
6576 // Check if it helps to fold PHI.
6577 if (Indexes.size() < 2 && !llvm::is_contained(Phi->incoming_values(), SI->getCondition()))
6578 continue;
6579
6580 for (int Index : Indexes)
6581 Phi->setIncomingValue(Index, SI->getCondition());
6582 Changed = true;
6583 }
6584
6585 return Changed;
6586}
6587
6588/// Return true if the backend will be able to handle
6589/// initializing an array of constants like C.
6591 if (C->isThreadDependent())
6592 return false;
6593 if (C->isDLLImportDependent())
6594 return false;
6595
6598 return false;
6599
6600 // Globals cannot contain scalable types.
6601 if (C->getType()->isScalableTy())
6602 return false;
6603
6605 // Pointer casts and in-bounds GEPs will not prohibit the backend from
6606 // materializing the array of constants.
6607 Constant *StrippedC = cast<Constant>(CE->stripInBoundsConstantOffsets());
6608 if (StrippedC == C || !validLookupTableConstant(StrippedC, TTI))
6609 return false;
6610 }
6611
6612 if (!TTI.shouldBuildLookupTablesForConstant(C))
6613 return false;
6614
6615 return true;
6616}
6617
6618/// If V is a Constant, return it. Otherwise, try to look up
6619/// its constant value in ConstantPool, returning 0 if it's not there.
6620static Constant *
6623 if (Constant *C = dyn_cast<Constant>(V))
6624 return C;
6625 return ConstantPool.lookup(V);
6626}
6627
6628/// Try to fold instruction I into a constant. This works for
6629/// simple instructions such as binary operations where both operands are
6630/// constant or can be replaced by constants from the ConstantPool. Returns the
6631/// resulting constant on success, 0 otherwise.
6632static Constant *
6636 Constant *A = lookupConstant(Select->getCondition(), ConstantPool);
6637 if (!A)
6638 return nullptr;
6639 if (A->isAllOnesValue())
6640 return lookupConstant(Select->getTrueValue(), ConstantPool);
6641 if (A->isNullValue())
6642 return lookupConstant(Select->getFalseValue(), ConstantPool);
6643 return nullptr;
6644 }
6645
6647 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
6648 if (Constant *A = lookupConstant(I->getOperand(N), ConstantPool))
6649 COps.push_back(A);
6650 else
6651 return nullptr;
6652 }
6653
6654 return ConstantFoldInstOperands(I, COps, DL);
6655}
6656
6657/// Try to determine the resulting constant values in phi nodes
6658/// at the common destination basic block, *CommonDest, for one of the case
6659/// destinations CaseDest corresponding to value CaseVal (nullptr for the
6660/// default case), of a switch instruction SI.
6661static bool
6663 BasicBlock **CommonDest,
6664 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
6665 const DataLayout &DL) {
6666 // The block from which we enter the common destination.
6667 BasicBlock *Pred = SI->getParent();
6668
6669 // If CaseDest is empty except for some side-effect free instructions through
6670 // which we can constant-propagate the CaseVal, continue to its successor.
6672 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
6673 for (Instruction &I : *CaseDest) {
6674 if (I.isTerminator()) {
6675 // If the terminator is a simple branch, continue to the next block.
6676 if (I.getNumSuccessors() != 1 || I.isSpecialTerminator())
6677 return false;
6678 Pred = CaseDest;
6679 CaseDest = I.getSuccessor(0);
6680 } else if (Constant *C = constantFold(&I, DL, ConstantPool)) {
6681 // Instruction is side-effect free and constant.
6682
6683 // If the instruction has uses outside this block or a phi node slot for
6684 // the block, it is not safe to bypass the instruction since it would then
6685 // no longer dominate all its uses.
6686 for (auto &Use : I.uses()) {
6687 User *User = Use.getUser();
6689 if (I->getParent() == CaseDest)
6690 continue;
6691 if (PHINode *Phi = dyn_cast<PHINode>(User))
6692 if (Phi->getIncomingBlock(Use) == CaseDest)
6693 continue;
6694 return false;
6695 }
6696
6697 ConstantPool.insert(std::make_pair(&I, C));
6698 } else {
6699 break;
6700 }
6701 }
6702
6703 // If we did not have a CommonDest before, use the current one.
6704 if (!*CommonDest)
6705 *CommonDest = CaseDest;
6706 // If the destination isn't the common one, abort.
6707 if (CaseDest != *CommonDest)
6708 return false;
6709
6710 // Get the values for this case from phi nodes in the destination block.
6711 for (PHINode &PHI : (*CommonDest)->phis()) {
6712 int Idx = PHI.getBasicBlockIndex(Pred);
6713 if (Idx == -1)
6714 continue;
6715
6716 Constant *ConstVal =
6717 lookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
6718 if (!ConstVal)
6719 return false;
6720
6721 Res.push_back(std::make_pair(&PHI, ConstVal));
6722 }
6723
6724 return Res.size() > 0;
6725}
6726
6727// Helper function used to add CaseVal to the list of cases that generate
6728// Result. Returns the updated number of cases that generate this result.
6729static size_t mapCaseToResult(ConstantInt *CaseVal,
6730 SwitchCaseResultVectorTy &UniqueResults,
6731 Constant *Result) {
6732 for (auto &I : UniqueResults) {
6733 if (I.first == Result) {
6734 I.second.push_back(CaseVal);
6735 return I.second.size();
6736 }
6737 }
6738 UniqueResults.push_back(
6739 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
6740 return 1;
6741}
6742
6743// Helper function that initializes a map containing
6744// results for the PHI node of the common destination block for a switch
6745// instruction. Returns false if multiple PHI nodes have been found or if
6746// there is not a common destination block for the switch.
6748 BasicBlock *&CommonDest,
6749 SwitchCaseResultVectorTy &UniqueResults,
6750 Constant *&DefaultResult,
6751 const DataLayout &DL,
6752 uintptr_t MaxUniqueResults) {
6753 for (const auto &I : SI->cases()) {
6754 ConstantInt *CaseVal = I.getCaseValue();
6755
6756 // Resulting value at phi nodes for this case value.
6757 SwitchCaseResultsTy Results;
6758 if (!getCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
6759 DL))
6760 return false;
6761
6762 // Only one value per case is permitted.
6763 if (Results.size() > 1)
6764 return false;
6765
6766 // Add the case->result mapping to UniqueResults.
6767 const size_t NumCasesForResult =
6768 mapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
6769
6770 // Early out if there are too many cases for this result.
6771 if (NumCasesForResult > MaxSwitchCasesPerResult)
6772 return false;
6773
6774 // Early out if there are too many unique results.
6775 if (UniqueResults.size() > MaxUniqueResults)
6776 return false;
6777
6778 // Check the PHI consistency.
6779 if (!PHI)
6780 PHI = Results[0].first;
6781 else if (PHI != Results[0].first)
6782 return false;
6783 }
6784 // Find the default result value.
6786 getCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
6787 DL);
6788 // If the default value is not found abort unless the default destination
6789 // is unreachable.
6790 DefaultResult =
6791 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
6792
6793 return DefaultResult || SI->defaultDestUnreachable();
6794}
6795
6796// Helper function that checks if it is possible to transform a switch with only
6797// two cases (or two cases + default) that produces a result into a select.
6798// TODO: Handle switches with more than 2 cases that map to the same result.
6799// The branch weights correspond to the provided Condition (i.e. if Condition is
6800// modified from the original SwitchInst, the caller must adjust the weights)
6801static Value *foldSwitchToSelect(const SwitchCaseResultVectorTy &ResultVector,
6802 Constant *DefaultResult, Value *Condition,
6803 IRBuilder<> &Builder, const DataLayout &DL,
6804 ArrayRef<uint32_t> BranchWeights) {
6805 // If we are selecting between only two cases transform into a simple
6806 // select or a two-way select if default is possible.
6807 // Example:
6808 // switch (a) { %0 = icmp eq i32 %a, 10
6809 // case 10: return 42; %1 = select i1 %0, i32 42, i32 4
6810 // case 20: return 2; ----> %2 = icmp eq i32 %a, 20
6811 // default: return 4; %3 = select i1 %2, i32 2, i32 %1
6812 // }
6813
6814 const bool HasBranchWeights = !BranchWeights.empty();
6815
6816 if (ResultVector.size() == 2 && ResultVector[0].second.size() == 1 &&
6817 ResultVector[1].second.size() == 1) {
6818 ConstantInt *FirstCase = ResultVector[0].second[0];
6819 ConstantInt *SecondCase = ResultVector[1].second[0];
6820 Value *SelectValue = ResultVector[1].first;
6821 if (DefaultResult) {
6822 Value *ValueCompare =
6823 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
6824 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
6825 DefaultResult, "switch.select");
6826 if (auto *SI = dyn_cast<SelectInst>(SelectValue);
6827 SI && HasBranchWeights) {
6828 // We start with 3 probabilities, where the numerator is the
6829 // corresponding BranchWeights[i], and the denominator is the sum over
6830 // BranchWeights. We want the probability and negative probability of
6831 // Condition == SecondCase.
6832 assert(BranchWeights.size() == 3);
6834 *SI, {BranchWeights[2], BranchWeights[0] + BranchWeights[1]},
6835 /*IsExpected=*/false, /*ElideAllZero=*/true);
6836 }
6837 }
6838 Value *ValueCompare =
6839 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
6840 Value *Ret = Builder.CreateSelect(ValueCompare, ResultVector[0].first,
6841 SelectValue, "switch.select");
6842 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6843 // We may have had a DefaultResult. Base the position of the first and
6844 // second's branch weights accordingly. Also the proability that Condition
6845 // != FirstCase needs to take that into account.
6846 assert(BranchWeights.size() >= 2);
6847 size_t FirstCasePos = (Condition != nullptr);
6848 size_t SecondCasePos = FirstCasePos + 1;
6849 uint32_t DefaultCase = (Condition != nullptr) ? BranchWeights[0] : 0;
6851 {BranchWeights[FirstCasePos],
6852 DefaultCase + BranchWeights[SecondCasePos]},
6853 /*IsExpected=*/false, /*ElideAllZero=*/true);
6854 }
6855 return Ret;
6856 }
6857
6858 // Handle the degenerate case where two cases have the same result value.
6859 if (ResultVector.size() == 1 && DefaultResult) {
6860 ArrayRef<ConstantInt *> CaseValues = ResultVector[0].second;
6861 unsigned CaseCount = CaseValues.size();
6862 // n bits group cases map to the same result:
6863 // case 0,4 -> Cond & 0b1..1011 == 0 ? result : default
6864 // case 0,2,4,6 -> Cond & 0b1..1001 == 0 ? result : default
6865 // case 0,2,8,10 -> Cond & 0b1..0101 == 0 ? result : default
6866 if (isPowerOf2_32(CaseCount)) {
6867 ConstantInt *MinCaseVal = CaseValues[0];
6868 // If there are bits that are set exclusively by CaseValues, we
6869 // can transform the switch into a select if the conjunction of
6870 // all the values uniquely identify CaseValues.
6871 APInt AndMask = APInt::getAllOnes(MinCaseVal->getBitWidth());
6872
6873 // Find the minimum value and compute the and of all the case values.
6874 for (auto *Case : CaseValues) {
6875 if (Case->getValue().slt(MinCaseVal->getValue()))
6876 MinCaseVal = Case;
6877 AndMask &= Case->getValue();
6878 }
6879 KnownBits Known = computeKnownBits(Condition, DL);
6880
6881 if (!AndMask.isZero() && Known.getMaxValue().uge(AndMask)) {
6882 // Compute the number of bits that are free to vary.
6883 unsigned FreeBits = Known.countMaxActiveBits() - AndMask.popcount();
6884
6885 // Check if the number of values covered by the mask is equal
6886 // to the number of cases.
6887 if (FreeBits == Log2_32(CaseCount)) {
6888 Value *And = Builder.CreateAnd(Condition, AndMask);
6889 Value *Cmp = Builder.CreateICmpEQ(
6890 And, Constant::getIntegerValue(And->getType(), AndMask));
6891 Value *Ret =
6892 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6893 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6894 // We know there's a Default case. We base the resulting branch
6895 // weights off its probability.
6896 assert(BranchWeights.size() >= 2);
6898 *SI,
6899 {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6900 /*IsExpected=*/false, /*ElideAllZero=*/true);
6901 }
6902 return Ret;
6903 }
6904 }
6905
6906 // Mark the bits case number touched.
6907 APInt BitMask = APInt::getZero(MinCaseVal->getBitWidth());
6908 for (auto *Case : CaseValues)
6909 BitMask |= (Case->getValue() - MinCaseVal->getValue());
6910
6911 // Check if cases with the same result can cover all number
6912 // in touched bits.
6913 if (BitMask.popcount() == Log2_32(CaseCount)) {
6914 if (!MinCaseVal->isNullValue())
6915 Condition = Builder.CreateSub(Condition, MinCaseVal);
6916 Value *And = Builder.CreateAnd(Condition, ~BitMask, "switch.and");
6917 Value *Cmp = Builder.CreateICmpEQ(
6918 And, Constant::getNullValue(And->getType()), "switch.selectcmp");
6919 Value *Ret =
6920 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6921 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6922 assert(BranchWeights.size() >= 2);
6924 *SI,
6925 {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6926 /*IsExpected=*/false, /*ElideAllZero=*/true);
6927 }
6928 return Ret;
6929 }
6930 }
6931
6932 // Handle the degenerate case where two cases have the same value.
6933 if (CaseValues.size() == 2) {
6934 Value *Cmp1 = Builder.CreateICmpEQ(Condition, CaseValues[0],
6935 "switch.selectcmp.case1");
6936 Value *Cmp2 = Builder.CreateICmpEQ(Condition, CaseValues[1],
6937 "switch.selectcmp.case2");
6938 Value *Cmp = Builder.CreateOr(Cmp1, Cmp2, "switch.selectcmp");
6939 Value *Ret =
6940 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6941 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6942 assert(BranchWeights.size() >= 2);
6944 *SI, {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6945 /*IsExpected=*/false, /*ElideAllZero=*/true);
6946 }
6947 return Ret;
6948 }
6949 }
6950
6951 return nullptr;
6952}
6953
6954// Helper function to cleanup a switch instruction that has been converted into
6955// a select, fixing up PHI nodes and basic blocks.
6957 Value *SelectValue,
6958 IRBuilder<> &Builder,
6959 DomTreeUpdater *DTU) {
6960 std::vector<DominatorTree::UpdateType> Updates;
6961
6962 BasicBlock *SelectBB = SI->getParent();
6963 BasicBlock *DestBB = PHI->getParent();
6964
6965 if (DTU && !is_contained(predecessors(DestBB), SelectBB))
6966 Updates.push_back({DominatorTree::Insert, SelectBB, DestBB});
6967 Builder.CreateBr(DestBB);
6968
6969 // Remove the switch.
6970
6971 PHI->removeIncomingValueIf(
6972 [&](unsigned Idx) { return PHI->getIncomingBlock(Idx) == SelectBB; });
6973 PHI->addIncoming(SelectValue, SelectBB);
6974
6975 SmallPtrSet<BasicBlock *, 4> RemovedSuccessors;
6976 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
6977 BasicBlock *Succ = SI->getSuccessor(i);
6978
6979 if (Succ == DestBB)
6980 continue;
6981 Succ->removePredecessor(SelectBB);
6982 if (DTU && RemovedSuccessors.insert(Succ).second)
6983 Updates.push_back({DominatorTree::Delete, SelectBB, Succ});
6984 }
6985 SI->eraseFromParent();
6986 if (DTU)
6987 DTU->applyUpdates(Updates);
6988}
6989
6990/// If a switch is only used to initialize one or more phi nodes in a common
6991/// successor block with only two different constant values, try to replace the
6992/// switch with a select. Returns true if the fold was made.
6994 DomTreeUpdater *DTU, const DataLayout &DL) {
6995 Value *const Cond = SI->getCondition();
6996 PHINode *PHI = nullptr;
6997 BasicBlock *CommonDest = nullptr;
6998 Constant *DefaultResult;
6999 SwitchCaseResultVectorTy UniqueResults;
7000 // Collect all the cases that will deliver the same value from the switch.
7001 if (!initializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
7002 DL, /*MaxUniqueResults*/ 2))
7003 return false;
7004
7005 assert(PHI != nullptr && "PHI for value select not found");
7006 Builder.SetInsertPoint(SI);
7007 SmallVector<uint32_t, 4> BranchWeights;
7008 [[maybe_unused]] auto HasWeights =
7010 assert(!HasWeights == (BranchWeights.empty()));
7011 assert(BranchWeights.empty() ||
7012 (BranchWeights.size() >=
7013 UniqueResults.size() + (DefaultResult != nullptr)));
7014
7015 Value *SelectValue = foldSwitchToSelect(UniqueResults, DefaultResult, Cond,
7016 Builder, DL, BranchWeights);
7017 if (!SelectValue)
7018 return false;
7019
7020 removeSwitchAfterSelectFold(SI, PHI, SelectValue, Builder, DTU);
7021 return true;
7022}
7023
7024namespace {
7025
7026/// This class finds alternatives for switches to ultimately
7027/// replace the switch.
7028class SwitchReplacement {
7029public:
7030 /// Create a helper for optimizations to use as a switch replacement.
7031 /// Find a better representation for the content of Values,
7032 /// using DefaultValue to fill any holes in the table.
7033 /// If no representation is possible, isValid() returns false.
7034 SwitchReplacement(
7035 Module &M, uint64_t TableSize, ConstantInt *Offset,
7036 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
7037 Constant *DefaultValue, const DataLayout &DL,
7038 const TargetTransformInfo &TTI, const StringRef &FuncName);
7039
7040 /// Build instructions with Builder to retrieve values using Index
7041 /// and replace the switch.
7042 Value *replaceSwitch(Value *Index, IRBuilder<> &Builder, const DataLayout &DL,
7043 Function *Func);
7044
7045 /// Return true if a table with TableSize elements of
7046 /// type ElementType would fit in a target-legal register.
7047 static bool wouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
7048 Type *ElementType);
7049
7050 /// Return the default value of the switch.
7051 Constant *getDefaultValue();
7052
7053 /// Return true if the replacement is a lookup table.
7054 bool isLookupTable();
7055
7056 /// Return true if the replacement is a bit map.
7057 bool isBitMap();
7058
7059 /// Return true if a suitable switch replacement was found.
7060 bool isValid() const { return Kind != InvalidKind; }
7061
7062private:
7063 // Depending on the switch, there are different alternatives.
7064 enum {
7065 // No suitable replacement was found.
7066 InvalidKind,
7067
7068 // For switches where each case contains the same value, we just have to
7069 // store that single value and return it for each lookup.
7070 SingleValueKind,
7071
7072 // For switches where there is a linear relationship between table index
7073 // and values. We calculate the result with a simple multiplication
7074 // and addition instead of a table lookup.
7075 LinearMapKind,
7076
7077 // For small tables with integer elements, we can pack them into a bitmap
7078 // that fits into a target-legal register. Values are retrieved by
7079 // shift and mask operations.
7080 BitMapKind,
7081
7082 // The table is stored as an array of values. Values are retrieved by load
7083 // instructions from the table.
7084 LookupTableKind
7085 } Kind;
7086
7087 // The default value of the switch.
7088 Constant *DefaultValue;
7089
7090 // The type of the output values.
7091 Type *ValueType;
7092
7093 // For SingleValueKind, this is the single value.
7094 Constant *SingleValue = nullptr;
7095
7096 // For BitMapKind, this is the bitmap.
7097 ConstantInt *BitMap = nullptr;
7098 IntegerType *BitMapElementTy = nullptr;
7099
7100 // For LinearMapKind, these are the constants used to derive the value.
7101 ConstantInt *LinearOffset = nullptr;
7102 ConstantInt *LinearMultiplier = nullptr;
7103 bool LinearMapValWrapped = false;
7104
7105 // For LookupTableKind, this is the table.
7106 Constant *Initializer = nullptr;
7107};
7108
7109} // end anonymous namespace
7110
7111SwitchReplacement::SwitchReplacement(
7112 Module &M, uint64_t TableSize, ConstantInt *Offset,
7113 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
7114 Constant *DefaultValue, const DataLayout &DL,
7115 const TargetTransformInfo &TTI, const StringRef &FuncName)
7116 : DefaultValue(DefaultValue) {
7117 assert(Values.size() && "Can't build lookup table without values!");
7118 assert(TableSize >= Values.size() && "Can't fit values in table!");
7119
7120 // If all values in the table are equal, this is that value.
7121 SingleValue = Values.begin()->second;
7122
7123 ValueType = Values.begin()->second->getType();
7124
7125 // Build up the table contents.
7126 SmallVector<Constant *, 64> TableContents(TableSize);
7127 for (const auto &[CaseVal, CaseRes] : Values) {
7128 assert(CaseRes->getType() == ValueType);
7129
7130 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
7131 TableContents[Idx] = CaseRes;
7132
7133 if (SingleValue && !isa<PoisonValue>(CaseRes) && CaseRes != SingleValue)
7134 SingleValue = isa<PoisonValue>(SingleValue) ? CaseRes : nullptr;
7135 }
7136
7137 // Fill in any holes in the table with the default result.
7138 if (Values.size() < TableSize) {
7139 assert(DefaultValue &&
7140 "Need a default value to fill the lookup table holes.");
7141 assert(DefaultValue->getType() == ValueType);
7142 for (uint64_t I = 0; I < TableSize; ++I) {
7143 if (!TableContents[I])
7144 TableContents[I] = DefaultValue;
7145 }
7146
7147 // If the default value is poison, all the holes are poison.
7148 bool DefaultValueIsPoison = isa<PoisonValue>(DefaultValue);
7149
7150 if (DefaultValue != SingleValue && !DefaultValueIsPoison)
7151 SingleValue = nullptr;
7152 }
7153
7154 // If each element in the table contains the same value, we only need to store
7155 // that single value.
7156 if (SingleValue) {
7157 Kind = SingleValueKind;
7158 return;
7159 }
7160
7161 // Check if we can derive the value with a linear transformation from the
7162 // table index.
7164 bool LinearMappingPossible = true;
7165 APInt PrevVal;
7166 APInt DistToPrev;
7167 // When linear map is monotonic and signed overflow doesn't happen on
7168 // maximum index, we can attach nsw on Add and Mul.
7169 bool NonMonotonic = false;
7170 assert(TableSize >= 2 && "Should be a SingleValue table.");
7171 // Check if there is the same distance between two consecutive values.
7172 for (uint64_t I = 0; I < TableSize; ++I) {
7173 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
7174
7175 if (!ConstVal && isa<PoisonValue>(TableContents[I])) {
7176 // This is an poison, so it's (probably) a lookup table hole.
7177 // To prevent any regressions from before we switched to using poison as
7178 // the default value, holes will fall back to using the first value.
7179 // This can be removed once we add proper handling for poisons in lookup
7180 // tables.
7181 ConstVal = dyn_cast<ConstantInt>(Values[0].second);
7182 }
7183
7184 if (!ConstVal) {
7185 // We only handle literal integers when checking for a linear mapping.
7186 LinearMappingPossible = false;
7187 break;
7188 }
7189 const APInt &Val = ConstVal->getValue();
7190 if (I != 0) {
7191 APInt Dist = Val - PrevVal;
7192 if (I == 1) {
7193 DistToPrev = Dist;
7194 } else if (Dist != DistToPrev) {
7195 LinearMappingPossible = false;
7196 break;
7197 }
7198 NonMonotonic |=
7199 Dist.isStrictlyPositive() ? Val.sle(PrevVal) : Val.sgt(PrevVal);
7200 }
7201 PrevVal = Val;
7202 }
7203 if (LinearMappingPossible) {
7204 LinearOffset = cast<ConstantInt>(TableContents[0]);
7205 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
7206 APInt M = LinearMultiplier->getValue();
7207 bool MayWrap = true;
7208 if (isIntN(M.getBitWidth(), TableSize - 1))
7209 (void)M.smul_ov(APInt(M.getBitWidth(), TableSize - 1), MayWrap);
7210 LinearMapValWrapped = NonMonotonic || MayWrap;
7211 Kind = LinearMapKind;
7212 return;
7213 }
7214 }
7215
7216 // If the values are integer constants and the table fits in a register,
7217 // build a bitmap.
7218 if (wouldFitInRegister(DL, TableSize, ValueType) &&
7219 all_of(TableContents, IsaPred<ConstantInt, UndefValue>)) {
7221 APInt TableInt(TableSize * IT->getBitWidth(), 0);
7222 for (uint64_t I = TableSize; I > 0; --I) {
7223 TableInt <<= IT->getBitWidth();
7224 // Insert values into the bitmap. Undef values are set to zero.
7225 if (!isa<UndefValue>(TableContents[I - 1])) {
7226 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
7227 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
7228 }
7229 }
7230 BitMap = ConstantInt::get(M.getContext(), TableInt);
7231 BitMapElementTy = IT;
7232 Kind = BitMapKind;
7233 return;
7234 }
7235
7236 // The remaining representation needs a global initializer.
7237 if (!all_of(TableContents,
7238 [&](Constant *C) { return validLookupTableConstant(C, TTI); })) {
7239 Kind = InvalidKind;
7240 return;
7241 }
7242
7243 if (auto *IT = dyn_cast<IntegerType>(ValueType)) {
7244 ConstantRange Range(IT->getBitWidth(), false);
7245 for (Constant *Value : TableContents)
7246 if (!isa<UndefValue>(Value))
7247 Range = Range.unionWith(cast<ConstantInt>(Value)->getValue());
7248 // TODO: handle sign extension as well?
7249 unsigned NeededBitWidth =
7250 std::max(TTI.getMinimumLookupTableEntryBitWidth(),
7251 unsigned(PowerOf2Ceil(Range.getActiveBits())));
7252 if (NeededBitWidth < IT->getBitWidth()) {
7253 IntegerType *DstTy = IntegerType::get(IT->getContext(), NeededBitWidth);
7254 for (Constant *&Value : TableContents)
7255 Value = ConstantFoldCastInstruction(Instruction::Trunc, Value, DstTy);
7256 }
7257 }
7258
7259 // Store the table in an array.
7260 auto *TableTy = ArrayType::get(TableContents[0]->getType(), TableSize);
7261 Initializer = ConstantArray::get(TableTy, TableContents);
7262
7263 Kind = LookupTableKind;
7264}
7265
7266Value *SwitchReplacement::replaceSwitch(Value *Index, IRBuilder<> &Builder,
7267 const DataLayout &DL, Function *Func) {
7268 switch (Kind) {
7269 case InvalidKind:
7270 llvm_unreachable("Cannot use an invalid switch replacement");
7271 case SingleValueKind:
7272 return SingleValue;
7273 case LinearMapKind: {
7274 ++NumLinearMaps;
7275 // Derive the result value from the input value.
7276 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
7277 false, "switch.idx.cast");
7278 if (!LinearMultiplier->isOne())
7279 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult",
7280 /*HasNUW = */ false,
7281 /*HasNSW = */ !LinearMapValWrapped);
7282
7283 if (!LinearOffset->isZero())
7284 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset",
7285 /*HasNUW = */ false,
7286 /*HasNSW = */ !LinearMapValWrapped);
7287 return Result;
7288 }
7289 case BitMapKind: {
7290 ++NumBitMaps;
7291 // Type of the bitmap (e.g. i59).
7292 IntegerType *MapTy = BitMap->getIntegerType();
7293
7294 // Cast Index to the same type as the bitmap.
7295 // Note: The Index is <= the number of elements in the table, so
7296 // truncating it to the width of the bitmask is safe.
7297 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
7298
7299 // Multiply the shift amount by the element width. NUW/NSW can always be
7300 // set, because wouldFitInRegister guarantees Index * ShiftAmt is in
7301 // BitMap's bit width.
7302 ShiftAmt = Builder.CreateMul(
7303 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
7304 "switch.shiftamt",/*HasNUW =*/true,/*HasNSW =*/true);
7305
7306 // Shift down.
7307 Value *DownShifted =
7308 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
7309 // Mask off.
7310 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
7311 }
7312 case LookupTableKind: {
7313 ++NumLookupTables;
7314 auto *Table =
7315 new GlobalVariable(*Func->getParent(), Initializer->getType(),
7316 /*isConstant=*/true, GlobalVariable::PrivateLinkage,
7317 Initializer, "switch.table." + Func->getName());
7318 Table->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
7319 // Set the alignment to that of an array items. We will be only loading one
7320 // value out of it.
7321 Table->setAlignment(DL.getPrefTypeAlign(ValueType));
7322 Type *IndexTy = DL.getIndexType(Table->getType());
7323 auto *ArrayTy = cast<ArrayType>(Table->getValueType());
7324
7325 if (Index->getType() != IndexTy) {
7326 unsigned OldBitWidth = Index->getType()->getIntegerBitWidth();
7327 Index = Builder.CreateZExtOrTrunc(Index, IndexTy);
7328 if (auto *Zext = dyn_cast<ZExtInst>(Index))
7329 Zext->setNonNeg(
7330 isUIntN(OldBitWidth - 1, ArrayTy->getNumElements() - 1));
7331 }
7332
7333 Value *GEPIndices[] = {ConstantInt::get(IndexTy, 0), Index};
7334 Value *GEP =
7335 Builder.CreateInBoundsGEP(ArrayTy, Table, GEPIndices, "switch.gep");
7336 Value *Load =
7337 Builder.CreateLoad(ArrayTy->getElementType(), GEP, "switch.load");
7338 if (Load->getType() == ValueType)
7339 return Load;
7340 return Builder.CreateZExt(Load, ValueType, "switch.ext");
7341 }
7342 }
7343 llvm_unreachable("Unknown helper kind!");
7344}
7345
7346bool SwitchReplacement::wouldFitInRegister(const DataLayout &DL,
7347 uint64_t TableSize,
7348 Type *ElementType) {
7349 auto *IT = dyn_cast<IntegerType>(ElementType);
7350 if (!IT)
7351 return false;
7352 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
7353 // are <= 15, we could try to narrow the type.
7354
7355 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
7356 if (TableSize >= UINT_MAX / IT->getBitWidth())
7357 return false;
7358 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
7359}
7360
7362 const DataLayout &DL) {
7363 // Allow any legal type.
7364 if (TTI.isTypeLegal(Ty))
7365 return true;
7366
7367 auto *IT = dyn_cast<IntegerType>(Ty);
7368 if (!IT)
7369 return false;
7370
7371 // Also allow power of 2 integer types that have at least 8 bits and fit in
7372 // a register. These types are common in frontend languages and targets
7373 // usually support loads of these types.
7374 // TODO: We could relax this to any integer that fits in a register and rely
7375 // on ABI alignment and padding in the table to allow the load to be widened.
7376 // Or we could widen the constants and truncate the load.
7377 unsigned BitWidth = IT->getBitWidth();
7378 return BitWidth >= 8 && isPowerOf2_32(BitWidth) &&
7379 DL.fitsInLegalInteger(IT->getBitWidth());
7380}
7381
7382Constant *SwitchReplacement::getDefaultValue() { return DefaultValue; }
7383
7384bool SwitchReplacement::isLookupTable() { return Kind == LookupTableKind; }
7385
7386bool SwitchReplacement::isBitMap() { return Kind == BitMapKind; }
7387
7388static bool isSwitchDense(uint64_t NumCases, uint64_t CaseRange, bool OptSize) {
7389 // 40% is the default density for building a jump table in optsize/minsize
7390 // mode, 10% is the default density for jump tables. See also
7391 // TargetLoweringBase::isSuitableForJumpTable(), which this function was based
7392 // on.
7393 const uint64_t MinDensity = OptSize ? 40 : 10;
7394
7395 if (CaseRange >= UINT64_MAX / 100)
7396 return false; // Avoid multiplication overflows below.
7397
7398 return NumCases * 100 >= CaseRange * MinDensity;
7399}
7400
7401static bool isSwitchDense(ArrayRef<int64_t> Values, bool OptSize) {
7402 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
7403 uint64_t Range = Diff + 1;
7404 if (Range < Diff)
7405 return false; // Overflow.
7406
7407 return isSwitchDense(Values.size(), Range, OptSize);
7408}
7409
7410static std::optional<unsigned>
7412 bool OptSize) {
7413 assert(Values.size() > 1 && "expected multiple switch cases");
7414 if (!llvm::all_of(Values, [Base](int64_t V) { return V >= Base; }))
7415 return std::nullopt;
7416
7417 // First, transform the values by subtracting Base.
7418 SmallVector<int64_t, 4> ReducedValues(Values);
7419 uint64_t ReducedValuesOr = 0;
7420 for (auto &V : ReducedValues) {
7421 uint64_t Reduced = (uint64_t)V - (uint64_t)Base;
7422 ReducedValuesOr |= Reduced;
7423 V = (int64_t)Reduced;
7424 }
7425
7426 // Conceptually, the reduced values are non-negative distances from Base.
7427 // Since the rest of the transform is bitwise only, treat them as unsigned
7428 // bit patterns from here.
7429
7430 // countr_zero(0) returns 64. As Values is guaranteed to have more than
7431 // one element and LLVM disallows duplicate cases, ReducedValuesOr will
7432 // have at least one bit set, so Shift will be less than 64.
7433 unsigned Shift = llvm::countr_zero(ReducedValuesOr);
7434 assert(Shift < 64);
7435 if (Shift > 0)
7436 for (auto &V : ReducedValues)
7437 V = (int64_t)((uint64_t)V >> Shift);
7438
7439 if (!isSwitchDense(ReducedValues, OptSize))
7440 return std::nullopt;
7441
7442 return Shift;
7443}
7444
7445/// Determine whether a lookup table should be built for this switch, based on
7446/// the number of cases, size of the table, and the types of the results.
7447// TODO: We could support larger than legal types by limiting based on the
7448// number of loads required and/or table size. If the constants are small we
7449// could use smaller table entries and extend after the load.
7451 const TargetTransformInfo &TTI,
7452 const DataLayout &DL,
7453 const SmallVector<Type *> &ResultTypes) {
7454 if (SI->getNumCases() > TableSize)
7455 return false; // TableSize overflowed.
7456
7457 bool AllTablesFitInRegister = true;
7458 bool HasIllegalType = false;
7459 for (const auto &Ty : ResultTypes) {
7460 // Saturate this flag to true.
7461 HasIllegalType = HasIllegalType || !isTypeLegalForLookupTable(Ty, TTI, DL);
7462
7463 // Saturate this flag to false.
7464 AllTablesFitInRegister =
7465 AllTablesFitInRegister &&
7466 SwitchReplacement::wouldFitInRegister(DL, TableSize, Ty);
7467
7468 // If both flags saturate, we're done. NOTE: This *only* works with
7469 // saturating flags, and all flags have to saturate first due to the
7470 // non-deterministic behavior of iterating over a dense map.
7471 if (HasIllegalType && !AllTablesFitInRegister)
7472 break;
7473 }
7474
7475 // If each table would fit in a register, we should build it anyway.
7476 if (AllTablesFitInRegister)
7477 return true;
7478
7479 // Don't build a table that doesn't fit in-register if it has illegal types.
7480 if (HasIllegalType)
7481 return false;
7482
7483 return isSwitchDense(SI->getNumCases(), TableSize,
7484 SI->getFunction()->hasOptSize());
7485}
7486
7488 ConstantInt &MinCaseVal, const ConstantInt &MaxCaseVal,
7489 bool HasDefaultResults, const SmallVector<Type *> &ResultTypes,
7490 const DataLayout &DL, const TargetTransformInfo &TTI) {
7491 if (MinCaseVal.isNullValue())
7492 return true;
7493 if (MinCaseVal.isNegative() ||
7494 MaxCaseVal.getLimitedValue() == std::numeric_limits<uint64_t>::max() ||
7495 !HasDefaultResults)
7496 return false;
7497 return all_of(ResultTypes, [&](const auto &ResultType) {
7498 return SwitchReplacement::wouldFitInRegister(
7499 DL, MaxCaseVal.getLimitedValue() + 1 /* TableSize */, ResultType);
7500 });
7501}
7502
7503/// Try to reuse the switch table index compare. Following pattern:
7504/// \code
7505/// if (idx < tablesize)
7506/// r = table[idx]; // table does not contain default_value
7507/// else
7508/// r = default_value;
7509/// if (r != default_value)
7510/// ...
7511/// \endcode
7512/// Is optimized to:
7513/// \code
7514/// cond = idx < tablesize;
7515/// if (cond)
7516/// r = table[idx];
7517/// else
7518/// r = default_value;
7519/// if (cond)
7520/// ...
7521/// \endcode
7522/// Jump threading will then eliminate the second if(cond).
7524 User *PhiUser, BasicBlock *PhiBlock, CondBrInst *RangeCheckBranch,
7525 Constant *DefaultValue,
7526 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
7528 if (!CmpInst)
7529 return;
7530
7531 // We require that the compare is in the same block as the phi so that jump
7532 // threading can do its work afterwards.
7533 if (CmpInst->getParent() != PhiBlock)
7534 return;
7535
7537 if (!CmpOp1)
7538 return;
7539
7540 Value *RangeCmp = RangeCheckBranch->getCondition();
7541 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
7542 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
7543
7544 // Check if the compare with the default value is constant true or false.
7545 const DataLayout &DL = PhiBlock->getDataLayout();
7547 CmpInst->getPredicate(), DefaultValue, CmpOp1, DL);
7548 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
7549 return;
7550
7551 // Check if the compare with the case values is distinct from the default
7552 // compare result.
7553 for (auto ValuePair : Values) {
7555 CmpInst->getPredicate(), ValuePair.second, CmpOp1, DL);
7556 if (!CaseConst || CaseConst == DefaultConst ||
7557 (CaseConst != TrueConst && CaseConst != FalseConst))
7558 return;
7559 }
7560
7561 // Check if the branch instruction dominates the phi node. It's a simple
7562 // dominance check, but sufficient for our needs.
7563 // Although this check is invariant in the calling loops, it's better to do it
7564 // at this late stage. Practically we do it at most once for a switch.
7565 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
7566 for (BasicBlock *Pred : predecessors(PhiBlock)) {
7567 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
7568 return;
7569 }
7570
7571 if (DefaultConst == FalseConst) {
7572 // The compare yields the same result. We can replace it.
7573 CmpInst->replaceAllUsesWith(RangeCmp);
7574 ++NumTableCmpReuses;
7575 } else {
7576 // The compare yields the same result, just inverted. We can replace it.
7577 Value *InvertedTableCmp = BinaryOperator::CreateXor(
7578 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
7579 RangeCheckBranch->getIterator());
7580 CmpInst->replaceAllUsesWith(InvertedTableCmp);
7581 ++NumTableCmpReuses;
7582 }
7583}
7584
7585/// If the switch is only used to initialize one or more phi nodes in a common
7586/// successor block with different constant values, replace the switch with
7587/// lookup tables.
7589 DomTreeUpdater *DTU, const DataLayout &DL,
7590 const TargetTransformInfo &TTI,
7591 bool ConvertSwitchToLookupTable) {
7592 assert(SI->getNumCases() > 1 && "Degenerate switch?");
7593
7594 BasicBlock *BB = SI->getParent();
7595 Function *Fn = BB->getParent();
7596
7597 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
7598 // split off a dense part and build a lookup table for that.
7599
7600 // FIXME: This creates arrays of GEPs to constant strings, which means each
7601 // GEP needs a runtime relocation in PIC code. We should just build one big
7602 // string and lookup indices into that.
7603
7604 // Ignore switches with less than three cases. Lookup tables will not make
7605 // them faster, so we don't analyze them.
7606 if (SI->getNumCases() < 3)
7607 return false;
7608
7609 // Figure out the corresponding result for each case value and phi node in the
7610 // common destination, as well as the min and max case values.
7611 assert(!SI->cases().empty());
7612 SwitchInst::CaseIt CI = SI->case_begin();
7613 ConstantInt *MinCaseVal = CI->getCaseValue();
7614 ConstantInt *MaxCaseVal = CI->getCaseValue();
7615
7616 BasicBlock *CommonDest = nullptr;
7617
7618 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
7620
7622 SmallVector<Type *> ResultTypes;
7624
7625 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
7626 ConstantInt *CaseVal = CI->getCaseValue();
7627 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
7628 MinCaseVal = CaseVal;
7629 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
7630 MaxCaseVal = CaseVal;
7631
7632 // Resulting value at phi nodes for this case value.
7634 ResultsTy Results;
7635 if (!getCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
7636 Results, DL))
7637 return false;
7638
7639 // Append the result and result types from this case to the list for each
7640 // phi.
7641 for (const auto &I : Results) {
7642 PHINode *PHI = I.first;
7643 Constant *Value = I.second;
7644 auto [It, Inserted] = ResultLists.try_emplace(PHI);
7645 if (Inserted)
7646 PHIs.push_back(PHI);
7647 It->second.push_back(std::make_pair(CaseVal, Value));
7648 ResultTypes.push_back(PHI->getType());
7649 }
7650 }
7651
7652 // If the table has holes, we need a constant result for the default case
7653 // or a bitmask that fits in a register.
7654 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
7655 bool HasDefaultResults = getCaseResults(SI, nullptr, SI->getDefaultDest(),
7656 &CommonDest, DefaultResultsList, DL);
7657 for (const auto &I : DefaultResultsList) {
7658 PHINode *PHI = I.first;
7659 Constant *Result = I.second;
7660 DefaultResults[PHI] = Result;
7661 }
7662
7663 bool UseSwitchConditionAsTableIndex = shouldUseSwitchConditionAsTableIndex(
7664 *MinCaseVal, *MaxCaseVal, HasDefaultResults, ResultTypes, DL, TTI);
7665 uint64_t TableSize;
7666 ConstantInt *TableIndexOffset;
7667 if (UseSwitchConditionAsTableIndex) {
7668 TableSize = MaxCaseVal->getLimitedValue() + 1;
7669 TableIndexOffset = ConstantInt::get(MaxCaseVal->getIntegerType(), 0);
7670 } else {
7671 TableSize =
7672 (MaxCaseVal->getValue() - MinCaseVal->getValue()).getLimitedValue() + 1;
7673
7674 TableIndexOffset = MinCaseVal;
7675 }
7676
7677 // If the default destination is unreachable, or if the lookup table covers
7678 // all values of the conditional variable, branch directly to the lookup table
7679 // BB. Otherwise, check that the condition is within the case range.
7680 uint64_t NumResults = ResultLists[PHIs[0]].size();
7681 bool DefaultIsReachable = !SI->defaultDestUnreachable();
7682
7683 bool TableHasHoles = (NumResults < TableSize);
7684
7685 // If the table has holes but the default destination doesn't produce any
7686 // constant results, the lookup table entries corresponding to the holes will
7687 // contain poison.
7688 bool AllHolesArePoison = TableHasHoles && !HasDefaultResults;
7689
7690 // If the default destination doesn't produce a constant result but is still
7691 // reachable, and the lookup table has holes, we need to use a mask to
7692 // determine if the current index should load from the lookup table or jump
7693 // to the default case.
7694 // The mask is unnecessary if the table has holes but the default destination
7695 // is unreachable, as in that case the holes must also be unreachable.
7696 bool NeedMask = AllHolesArePoison && DefaultIsReachable;
7697 if (NeedMask) {
7698 // As an extra penalty for the validity test we require more cases.
7699 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
7700 return false;
7701 if (!DL.fitsInLegalInteger(TableSize))
7702 return false;
7703 }
7704
7705 if (!shouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
7706 return false;
7707
7708 // Compute the table index value.
7709 Value *TableIndex;
7710 if (UseSwitchConditionAsTableIndex) {
7711 TableIndex = SI->getCondition();
7712 if (HasDefaultResults) {
7713 // Grow the table to cover all possible index values to avoid the range
7714 // check. It will use the default result to fill in the table hole later,
7715 // so make sure it exist.
7716 ConstantRange CR = computeConstantRange(TableIndex, /*ForSigned=*/false,
7717 SimplifyQuery(DL));
7718 // Grow the table shouldn't have any size impact by checking
7719 // wouldFitInRegister.
7720 // TODO: Consider growing the table also when it doesn't fit in a register
7721 // if no optsize is specified.
7722 const uint64_t UpperBound = CR.getUpper().getLimitedValue();
7723 if (!CR.isUpperWrapped() &&
7724 all_of(ResultTypes, [&](const auto &ResultType) {
7725 return SwitchReplacement::wouldFitInRegister(DL, UpperBound,
7726 ResultType);
7727 })) {
7728 // There may be some case index larger than the UpperBound (unreachable
7729 // case), so make sure the table size does not get smaller.
7730 TableSize = std::max(UpperBound, TableSize);
7731 // The default branch is unreachable after we enlarge the lookup table.
7732 // Adjust DefaultIsReachable to reuse code path.
7733 DefaultIsReachable = false;
7734 }
7735 }
7736 }
7737
7738 // Keep track of the switch replacement for each phi
7740 for (PHINode *PHI : PHIs) {
7741 const auto &ResultList = ResultLists[PHI];
7742
7743 Type *ResultType = ResultList.begin()->second->getType();
7744 // Use any value to fill the lookup table holes.
7745 Constant *DefaultVal =
7746 AllHolesArePoison ? PoisonValue::get(ResultType) : DefaultResults[PHI];
7747 StringRef FuncName = Fn->getName();
7748 SwitchReplacement Replacement(*Fn->getParent(), TableSize, TableIndexOffset,
7749 ResultList, DefaultVal, DL, TTI, FuncName);
7750 if (!Replacement.isValid())
7751 return false;
7752 PhiToReplacementMap.insert({PHI, Replacement});
7753 }
7754
7755 bool AnyLookupTables = any_of(
7756 PhiToReplacementMap, [](auto &KV) { return KV.second.isLookupTable(); });
7757 bool AnyBitMaps = any_of(PhiToReplacementMap,
7758 [](auto &KV) { return KV.second.isBitMap(); });
7759
7760 // A few conditions prevent the generation of lookup tables:
7761 // 1. The target does not support lookup tables.
7762 // 2. The "no-jump-tables" function attribute is set.
7763 // However, these objections do not apply to other switch replacements, like
7764 // the bitmap, so we only stop here if any of these conditions are met and we
7765 // want to create a LUT. Otherwise, continue with the switch replacement.
7766 if (AnyLookupTables &&
7767 (!TTI.shouldBuildLookupTables() ||
7768 Fn->getFnAttribute("no-jump-tables").getValueAsBool()))
7769 return false;
7770
7771 // In the early optimization pipeline, disable formation of lookup tables,
7772 // bit maps and mask checks, as they may inhibit further optimization.
7773 if (!ConvertSwitchToLookupTable &&
7774 (AnyLookupTables || AnyBitMaps || NeedMask))
7775 return false;
7776
7777 Builder.SetInsertPoint(SI);
7778 // TableIndex is the switch condition - TableIndexOffset if we don't
7779 // use the condition directly
7780 if (!UseSwitchConditionAsTableIndex) {
7781 // If the default is unreachable, all case values are s>= MinCaseVal. Then
7782 // we can try to attach nsw.
7783 bool MayWrap = true;
7784 if (!DefaultIsReachable) {
7785 APInt Res =
7786 MaxCaseVal->getValue().ssub_ov(MinCaseVal->getValue(), MayWrap);
7787 (void)Res;
7788 }
7789 TableIndex = Builder.CreateSub(SI->getCondition(), TableIndexOffset,
7790 "switch.tableidx", /*HasNUW =*/false,
7791 /*HasNSW =*/!MayWrap);
7792 }
7793
7794 std::vector<DominatorTree::UpdateType> Updates;
7795
7796 // Compute the maximum table size representable by the integer type we are
7797 // switching upon.
7798 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
7799 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
7800 assert(MaxTableSize >= TableSize &&
7801 "It is impossible for a switch to have more entries than the max "
7802 "representable value of its input integer type's size.");
7803
7804 // Create the BB that does the lookups.
7805 Module &Mod = *CommonDest->getParent()->getParent();
7806 BasicBlock *LookupBB = BasicBlock::Create(
7807 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
7808
7809 CondBrInst *RangeCheckBranch = nullptr;
7810 CondBrInst *CondBranch = nullptr;
7811
7812 Builder.SetInsertPoint(SI);
7813 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
7814 const bool IsFullyCoveredLookupTable =
7815 !DefaultIsReachable || GeneratingCoveredLookupTable;
7816 if (IsFullyCoveredLookupTable) {
7817 Builder.CreateBr(LookupBB);
7818 if (DTU)
7819 Updates.push_back({DominatorTree::Insert, BB, LookupBB});
7820 // Note: We call removeProdecessor later since we need to be able to get the
7821 // PHI value for the default case in case we're using a bit mask.
7822 } else {
7823 Value *Cmp = Builder.CreateICmpULT(
7824 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
7825 RangeCheckBranch =
7826 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
7827 CondBranch = RangeCheckBranch;
7828 if (DTU)
7829 Updates.push_back({DominatorTree::Insert, BB, LookupBB});
7830 }
7831
7832 // Populate the BB that does the lookups.
7833 Builder.SetInsertPoint(LookupBB);
7834
7835 if (NeedMask) {
7836 // Before doing the lookup, we do the hole check. The LookupBB is therefore
7837 // re-purposed to do the hole check, and we create a new LookupBB.
7838 BasicBlock *MaskBB = LookupBB;
7839 MaskBB->setName("switch.hole_check");
7840 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
7841 CommonDest->getParent(), CommonDest);
7842
7843 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
7844 // unnecessary illegal types.
7845 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
7846 APInt MaskInt(TableSizePowOf2, 0);
7847 APInt One(TableSizePowOf2, 1);
7848 // Build bitmask; fill in a 1 bit for every case.
7849 const ResultListTy &ResultList = ResultLists[PHIs[0]];
7850 for (const auto &Result : ResultList) {
7851 uint64_t Idx = (Result.first->getValue() - TableIndexOffset->getValue())
7852 .getLimitedValue();
7853 MaskInt |= One << Idx;
7854 }
7855 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
7856
7857 // Get the TableIndex'th bit of the bitmask.
7858 // If this bit is 0 (meaning hole) jump to the default destination,
7859 // else continue with table lookup.
7860 IntegerType *MapTy = TableMask->getIntegerType();
7861 Value *MaskIndex =
7862 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
7863 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
7864 Value *LoBit = Builder.CreateTrunc(
7865 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
7866 if (!IsFullyCoveredLookupTable)
7868 CondBranch = Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
7869 if (DTU) {
7870 Updates.push_back({DominatorTree::Insert, MaskBB, LookupBB});
7871 Updates.push_back({DominatorTree::Insert, MaskBB, SI->getDefaultDest()});
7872 }
7873 Builder.SetInsertPoint(LookupBB);
7874 addPredecessorToBlock(SI->getDefaultDest(), MaskBB, BB);
7875 }
7876
7877 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
7878 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
7879 // do not delete PHINodes here.
7880 SI->getDefaultDest()->removePredecessor(BB,
7881 /*KeepOneInputPHIs=*/true);
7882 if (DTU)
7883 Updates.push_back({DominatorTree::Delete, BB, SI->getDefaultDest()});
7884 }
7885
7886 for (PHINode *PHI : PHIs) {
7887 const ResultListTy &ResultList = ResultLists[PHI];
7888 auto Replacement = PhiToReplacementMap.at(PHI);
7889 auto *Result = Replacement.replaceSwitch(TableIndex, Builder, DL, Fn);
7890 // Do a small peephole optimization: re-use the switch table compare if
7891 // possible.
7892 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
7893 BasicBlock *PhiBlock = PHI->getParent();
7894 // Search for compare instructions which use the phi.
7895 for (auto *User : PHI->users()) {
7896 reuseTableCompare(User, PhiBlock, RangeCheckBranch,
7897 Replacement.getDefaultValue(), ResultList);
7898 }
7899 }
7900
7901 PHI->addIncoming(Result, LookupBB);
7902 }
7903
7904 Builder.CreateBr(CommonDest);
7905 if (DTU)
7906 Updates.push_back({DominatorTree::Insert, LookupBB, CommonDest});
7907
7908 SmallVector<uint32_t> BranchWeights;
7909 const bool HasBranchWeights =
7910 CondBranch && extractBranchWeights(*SI, BranchWeights);
7911 uint64_t ToLookupWeight = 0;
7912 uint64_t ToDefaultWeight = 0;
7913
7914 // Remove the switch.
7915 SmallPtrSet<BasicBlock *, 8> RemovedSuccessors;
7916 for (unsigned I = 0, E = SI->getNumSuccessors(); I < E; ++I) {
7917 BasicBlock *Succ = SI->getSuccessor(I);
7918
7919 if (Succ == SI->getDefaultDest()) {
7920 if (HasBranchWeights)
7921 ToDefaultWeight += BranchWeights[I];
7922 continue;
7923 }
7924 Succ->removePredecessor(BB);
7925 if (DTU && RemovedSuccessors.insert(Succ).second)
7926 Updates.push_back({DominatorTree::Delete, BB, Succ});
7927 if (HasBranchWeights)
7928 ToLookupWeight += BranchWeights[I];
7929 }
7930 SI->eraseFromParent();
7931 // In the case where we do not have a fully covered lookup table (i.e., we
7932 // need a range check), and we need a mask check, we split the default case
7933 // into two different cases for which we cannot infer branch weights.
7934 // Otherwise we have a single branch for which we can infer branch weights.
7935 if ((NeedMask && !IsFullyCoveredLookupTable) &&
7938 else if (HasBranchWeights)
7939 setFittedBranchWeights(*CondBranch, {ToLookupWeight, ToDefaultWeight},
7940 /*IsExpected=*/false);
7941 if (DTU)
7942 DTU->applyUpdates(Updates);
7943
7944 if (NeedMask)
7945 ++NumLookupTablesHoles;
7946 return true;
7947}
7948
7949/// Try to transform a switch that has "holes" in it to a contiguous sequence
7950/// of cases.
7951///
7952/// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
7953/// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
7954///
7955/// This converts a sparse switch into a dense switch which allows better
7956/// lowering and could also allow transforming into a lookup table.
7958 const DataLayout &DL,
7959 const TargetTransformInfo &TTI) {
7960 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
7961 if (CondTy->getIntegerBitWidth() > 64 ||
7962 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
7963 return false;
7964 // Only bother with this optimization if there are more than 3 switch cases;
7965 // SDAG will only bother creating jump tables for 4 or more cases.
7966 if (SI->getNumCases() < 4)
7967 return false;
7968
7969 // This transform is agnostic to the signedness of the input or case values. We
7970 // can treat the case values as signed or unsigned. We can optimize more common
7971 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
7972 // as signed.
7974 for (const auto &C : SI->cases())
7975 Values.push_back(C.getCaseValue()->getValue().getSExtValue());
7977
7978 // If the switch is already dense, there's nothing useful to do here.
7979 bool OptSize = SI->getFunction()->hasOptSize();
7980 if (isSwitchDense(Values, OptSize))
7981 return false;
7982
7983 // Find a Base and corresponding Shift that results in a dense switch range.
7984 // Values[0] is the local minimum.
7985 int64_t Base = Values[0];
7986 std::optional<unsigned> Shift;
7987 // Prefer Base=0 when shifting out common low zero bits still produces a dense
7988 // range, as this avoids an unnecessary `(condition - local_min)` expression.
7989 // However, avoiding the subtract can leave a wider reduced range than using
7990 // the local minimum, so require Base=0 to satisfy the stricter optsize
7991 // density threshold before falling back to the normal density policy for
7992 // local-min.
7993 if ((Shift = getDenseSwitchRangeReductionShift(Values, /*Base=*/0,
7994 /*OptSize=*/true)))
7995 Base = 0;
7996 else if (Base != 0)
7998
7999 if (!Shift)
8000 return false;
8001
8002 // The obvious transform is to shift the switch condition right and emit a
8003 // check that the condition actually cleanly divided by GCD, i.e.
8004 // C & (1 << Shift - 1) == 0
8005 // inserting a new CFG edge to handle the case where it didn't divide cleanly.
8006 //
8007 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
8008 // shift and puts the shifted-off bits in the uppermost bits. If any of these
8009 // are nonzero then the switch condition will be very large and will hit the
8010 // default case.
8011 //
8012 // This transform can be done speculatively because it is so cheap - it
8013 // results in a single rotate operation being inserted.
8014
8015 auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
8016 Builder.SetInsertPoint(SI);
8017 Value *Sub = SI->getCondition();
8018 if (Base != 0)
8019 Sub = Builder.CreateSub(Sub, ConstantInt::getSigned(Ty, Base));
8020 Value *Rot = Builder.CreateIntrinsic(
8021 Ty, Intrinsic::fshl,
8022 {Sub, Sub, ConstantInt::get(Ty, Ty->getBitWidth() - *Shift)});
8023 SI->replaceUsesOfWith(SI->getCondition(), Rot);
8024
8025 for (auto Case : SI->cases()) {
8026 auto *Orig = Case.getCaseValue();
8027 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base, true);
8028 Case.setValue(cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(*Shift))));
8029 }
8030 return true;
8031}
8032
8033/// Tries to transform the switch when the condition is umin with a constant.
8034/// In that case, the default branch can be replaced by the constant's branch.
8035/// This method also removes dead cases when the simplification cannot replace
8036/// the default branch.
8037///
8038/// For example:
8039/// switch(umin(a, 3)) {
8040/// case 0:
8041/// case 1:
8042/// case 2:
8043/// case 3:
8044/// case 4:
8045/// // ...
8046/// default:
8047/// unreachable
8048/// }
8049///
8050/// Transforms into:
8051///
8052/// switch(a) {
8053/// case 0:
8054/// case 1:
8055/// case 2:
8056/// default:
8057/// // This is case 3
8058/// }
8060 Value *A;
8062
8063 if (!match(SI->getCondition(), m_UMin(m_Value(A), m_ConstantInt(Constant))))
8064 return false;
8065
8068 BasicBlock *BB = SIW->getParent();
8069
8070 // Dead cases are removed even when the simplification fails.
8071 // A case is dead when its value is higher than the Constant.
8072 for (auto I = SI->case_begin(), E = SI->case_end(); I != E;) {
8073 if (!I->getCaseValue()->getValue().ugt(Constant->getValue())) {
8074 ++I;
8075 continue;
8076 }
8077 BasicBlock *DeadCaseBB = I->getCaseSuccessor();
8078 DeadCaseBB->removePredecessor(BB);
8079 I = SIW.removeCase(I);
8080 E = SIW->case_end();
8081 if (!is_contained(successors(BB), DeadCaseBB))
8082 Updates.push_back({DominatorTree::Delete, BB, DeadCaseBB});
8083 }
8084
8085 auto Case = SI->findCaseValue(Constant);
8086 // If the case value is not found, `findCaseValue` returns the default case.
8087 // In this scenario, since there is no explicit `case 3:`, the simplification
8088 // fails. The simplification also fails when the switch’s default destination
8089 // is reachable.
8090 if (!SI->defaultDestUnreachable() || Case == SI->case_default()) {
8091 if (DTU)
8092 DTU->applyUpdates(Updates);
8093 return !Updates.empty();
8094 }
8095
8096 BasicBlock *Unreachable = SI->getDefaultDest();
8097 SIW.replaceDefaultDest(Case);
8098 SIW.removeCase(Case);
8099 SIW->setCondition(A);
8100
8101 Updates.push_back({DominatorTree::Delete, BB, Unreachable});
8102
8103 if (DTU)
8104 DTU->applyUpdates(Updates);
8105
8106 return true;
8107}
8108
8110 const DataLayout &DL,
8111 AssumptionCache *AC) {
8112 assert(SI);
8113 if (SI->defaultDestUnreachable())
8114 return false;
8115
8116 // If it can be proved that the switch condition takes some concrete value
8117 // in the default block, we can make some nice simplifications to the
8118 // switch.
8119 BasicBlock *Default = SI->getDefaultDest();
8120 const Instruction *CtxI = &*Default->getFirstNonPHIIt();
8122 SI->getCondition(),
8123 SimplifyQuery(DL, /*DT=*/nullptr, AC, CtxI).allowEphemerals(true));
8124 if (!Known.isConstant())
8125 return false;
8126
8127 // At this point, we know that only one value can be mapped to the
8128 // default block. So, if a case doesn't exist for it already, we
8129 // can create one pointing to the default block.
8130 ConstantInt *CaseVal =
8131 ConstantInt::get(SI->getContext(), Known.getConstant());
8132 const llvm::SwitchInst::CaseIt CaseIt = SI->findCaseValue(CaseVal);
8133 if (CaseIt == SI->case_default()) {
8135 SIW.addCase(CaseVal, Default, SIW.getSuccessorWeight(0));
8136 SIW.setSuccessorWeight(0, 0);
8137 }
8138 // If there is a pre-existing case for the constant, the default branch
8139 // will be removed rather than being moved. Thus, we are removing an edge
8140 // in the CFG, and need to update any PHIs in the default block.
8141 createUnreachableSwitchDefault(SI, DTU, /*RemoveOrigDefaultBlock=*/CaseIt !=
8142 SI->case_default());
8143
8144 assert(SI->getNumCases() > 0 && "Switch should have at least one case");
8145 assert(SI->findCaseValue(CaseVal) != SI->case_default() &&
8146 "Proven value should have a dedicated case");
8147 assert(SI->defaultDestUnreachable());
8148 return true;
8149}
8150
8151/// Tries to transform switch of powers of two to reduce switch range.
8152/// For example, switch like:
8153/// switch (C) { case 1: case 2: case 64: case 128: }
8154/// will be transformed to:
8155/// switch (count_trailing_zeros(C)) { case 0: case 1: case 6: case 7: }
8156///
8157/// This transformation allows better lowering and may transform the switch
8158/// instruction into a sequence of bit manipulation and a smaller
8159/// log2(C)-indexed value table (instead of traditionally emitting a load of the
8160/// address of the jump target, and indirectly jump to it).
8162 DomTreeUpdater *DTU,
8163 const DataLayout &DL,
8164 const TargetTransformInfo &TTI) {
8165 Value *Condition = SI->getCondition();
8166 LLVMContext &Context = SI->getContext();
8167 auto *CondTy = cast<IntegerType>(Condition->getType());
8168
8169 if (CondTy->getIntegerBitWidth() > 64 ||
8170 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
8171 return false;
8172
8173 // Ensure trailing zeroes count intrinsic emission is not too expensive.
8174 IntrinsicCostAttributes Attrs(Intrinsic::cttz, CondTy,
8175 {Condition, ConstantInt::getTrue(Context)});
8176 if (TTI.getIntrinsicInstrCost(Attrs, TTI::TCK_SizeAndLatency) >
8177 TTI::TCC_Basic * 2)
8178 return false;
8179
8180 // Only bother with this optimization if there are more than 3 switch cases.
8181 // SDAG will start emitting jump tables for 4 or more cases.
8182 if (SI->getNumCases() < 4)
8183 return false;
8184
8185 // Check that switch cases are powers of two.
8187 for (const auto &Case : SI->cases()) {
8188 uint64_t CaseValue = Case.getCaseValue()->getValue().getZExtValue();
8189 if (llvm::has_single_bit(CaseValue))
8190 Values.push_back(CaseValue);
8191 else
8192 return false;
8193 }
8194
8195 // isSwichDense requires case values to be sorted.
8197 if (!isSwitchDense(Values.size(),
8198 llvm::countr_zero(Values.back()) -
8199 llvm::countr_zero(Values.front()) + 1,
8200 SI->getFunction()->hasOptSize()))
8201 // Transform is unable to generate dense switch.
8202 return false;
8203
8204 Builder.SetInsertPoint(SI);
8205
8206 if (!SI->defaultDestUnreachable()) {
8207 // Let non-power-of-two inputs jump to the default case, when the latter is
8208 // reachable.
8209 auto *PopC = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Condition);
8210 auto *IsPow2 = Builder.CreateICmpEQ(PopC, ConstantInt::get(CondTy, 1));
8211
8212 auto *OrigBB = SI->getParent();
8213 auto *DefaultCaseBB = SI->getDefaultDest();
8214 BasicBlock *SplitBB = SplitBlock(OrigBB, SI, DTU);
8215 auto It = OrigBB->getTerminator()->getIterator();
8216 SmallVector<uint32_t> Weights;
8217 auto HasWeights = extractBranchWeights(*SI, Weights);
8218 auto *BI = CondBrInst::Create(IsPow2, SplitBB, DefaultCaseBB, It);
8219 if (HasWeights && any_of(Weights, not_equal_to(0))) {
8220 // IsPow2 covers a subset of the cases in which we'd go to the default
8221 // label. The other is those powers of 2 that don't appear in the case
8222 // statement. We don't know the distribution of the values coming in, so
8223 // the safest is to split 50-50 the original probability to `default`.
8224 uint64_t OrigDenominator =
8226 SmallVector<uint64_t> NewWeights(2);
8227 NewWeights[1] = Weights[0] / 2;
8228 NewWeights[0] = OrigDenominator - NewWeights[1];
8229 setFittedBranchWeights(*BI, NewWeights, /*IsExpected=*/false);
8230 // The probability of executing the default block stays constant. It was
8231 // p_d = Weights[0] / OrigDenominator
8232 // we rewrite as W/D
8233 // We want to find the probability of the default branch of the switch
8234 // statement. Let's call it X. We have W/D = W/2D + X * (1-W/2D)
8235 // i.e. the original probability is the probability we go to the default
8236 // branch from the BI branch, or we take the default branch on the SI.
8237 // Meaning X = W / (2D - W), or (W/2) / (D - W/2)
8238 // This matches using W/2 for the default branch probability numerator and
8239 // D-W/2 as the denominator.
8240 Weights[0] = NewWeights[1];
8241 uint64_t CasesDenominator = OrigDenominator - Weights[0];
8242 for (auto &W : drop_begin(Weights))
8243 W = NewWeights[0] * static_cast<double>(W) / CasesDenominator;
8244
8245 setBranchWeights(*SI, Weights, /*IsExpected=*/false);
8246 }
8247 // BI is handling the default case for SI, and so should share its DebugLoc.
8248 BI->setDebugLoc(SI->getDebugLoc());
8249 It->eraseFromParent();
8250
8251 addPredecessorToBlock(DefaultCaseBB, OrigBB, SplitBB);
8252 if (DTU)
8253 DTU->applyUpdates({{DominatorTree::Insert, OrigBB, DefaultCaseBB}});
8254 }
8255
8256 // Replace each case with its trailing zeros number.
8257 for (auto &Case : SI->cases()) {
8258 auto *OrigValue = Case.getCaseValue();
8259 Case.setValue(ConstantInt::get(OrigValue->getIntegerType(),
8260 OrigValue->getValue().countr_zero()));
8261 }
8262
8263 // Replace condition with its trailing zeros number.
8264 auto *ConditionTrailingZeros = Builder.CreateIntrinsic(
8265 Intrinsic::cttz, {CondTy}, {Condition, ConstantInt::getTrue(Context)});
8266
8267 SI->setCondition(ConditionTrailingZeros);
8268
8269 return true;
8270}
8271
8272/// Fold switch over ucmp/scmp intrinsic to br if two of the switch arms have
8273/// the same destination.
8275 DomTreeUpdater *DTU) {
8276 auto *Cmp = dyn_cast<CmpIntrinsic>(SI->getCondition());
8277 if (!Cmp || !Cmp->hasOneUse())
8278 return false;
8279
8281 bool HasWeights = extractBranchWeights(getBranchWeightMDNode(*SI), Weights);
8282 if (!HasWeights)
8283 Weights.resize(4); // Avoid checking HasWeights everywhere.
8284
8285 // Normalize to [us]cmp == Res ? Succ : OtherSucc.
8286 int64_t Res;
8287 BasicBlock *Succ, *OtherSucc;
8288 uint32_t SuccWeight = 0, OtherSuccWeight = 0;
8289 BasicBlock *Unreachable = nullptr;
8290
8291 if (SI->getNumCases() == 2) {
8292 // Find which of 1, 0 or -1 is missing (handled by default dest).
8293 SmallSet<int64_t, 3> Missing;
8294 Missing.insert(1);
8295 Missing.insert(0);
8296 Missing.insert(-1);
8297
8298 Succ = SI->getDefaultDest();
8299 SuccWeight = Weights[0];
8300 OtherSucc = nullptr;
8301 for (auto &Case : SI->cases()) {
8302 std::optional<int64_t> Val =
8303 Case.getCaseValue()->getValue().trySExtValue();
8304 if (!Val)
8305 return false;
8306 if (!Missing.erase(*Val))
8307 return false;
8308 if (OtherSucc && OtherSucc != Case.getCaseSuccessor())
8309 return false;
8310 OtherSucc = Case.getCaseSuccessor();
8311 OtherSuccWeight += Weights[Case.getSuccessorIndex()];
8312 }
8313
8314 assert(Missing.size() == 1 && "Should have one case left");
8315 Res = *Missing.begin();
8316 } else if (SI->getNumCases() == 3 && SI->defaultDestUnreachable()) {
8317 // Normalize so that Succ is taken once and OtherSucc twice.
8318 Unreachable = SI->getDefaultDest();
8319 Succ = OtherSucc = nullptr;
8320 for (auto &Case : SI->cases()) {
8321 BasicBlock *NewSucc = Case.getCaseSuccessor();
8322 uint32_t Weight = Weights[Case.getSuccessorIndex()];
8323 if (!OtherSucc || OtherSucc == NewSucc) {
8324 OtherSucc = NewSucc;
8325 OtherSuccWeight += Weight;
8326 } else if (!Succ) {
8327 Succ = NewSucc;
8328 SuccWeight = Weight;
8329 } else if (Succ == NewSucc) {
8330 std::swap(Succ, OtherSucc);
8331 std::swap(SuccWeight, OtherSuccWeight);
8332 } else
8333 return false;
8334 }
8335 for (auto &Case : SI->cases()) {
8336 std::optional<int64_t> Val =
8337 Case.getCaseValue()->getValue().trySExtValue();
8338 if (!Val || (Val != 1 && Val != 0 && Val != -1))
8339 return false;
8340 if (Case.getCaseSuccessor() == Succ) {
8341 Res = *Val;
8342 break;
8343 }
8344 }
8345 } else {
8346 return false;
8347 }
8348
8349 // Determine predicate for the missing case.
8351 switch (Res) {
8352 case 1:
8353 Pred = ICmpInst::ICMP_UGT;
8354 break;
8355 case 0:
8356 Pred = ICmpInst::ICMP_EQ;
8357 break;
8358 case -1:
8359 Pred = ICmpInst::ICMP_ULT;
8360 break;
8361 }
8362 if (Cmp->isSigned())
8363 Pred = ICmpInst::getSignedPredicate(Pred);
8364
8365 MDNode *NewWeights = nullptr;
8366 if (HasWeights)
8367 NewWeights = MDBuilder(SI->getContext())
8368 .createBranchWeights(SuccWeight, OtherSuccWeight);
8369
8370 BasicBlock *BB = SI->getParent();
8371 Builder.SetInsertPoint(SI->getIterator());
8372 Value *ICmp = Builder.CreateICmp(Pred, Cmp->getLHS(), Cmp->getRHS());
8373 Builder.CreateCondBr(ICmp, Succ, OtherSucc, NewWeights,
8374 SI->getMetadata(LLVMContext::MD_unpredictable));
8375 OtherSucc->removePredecessor(BB);
8376 if (Unreachable)
8377 Unreachable->removePredecessor(BB);
8378 SI->eraseFromParent();
8379 Cmp->eraseFromParent();
8380 if (DTU && Unreachable)
8381 DTU->applyUpdates({{DominatorTree::Delete, BB, Unreachable}});
8382 return true;
8383}
8384
8385/// Checking whether two BBs are equal depends on the contents of the
8386/// BasicBlock and the incoming values of their successor PHINodes.
8387/// PHINode::getIncomingValueForBlock is O(|Preds|), so we'd like to avoid
8388/// calling this function on each BasicBlock every time isEqual is called,
8389/// especially since the same BasicBlock may be passed as an argument multiple
8390/// times. To do this, we can precompute a map of PHINode -> Pred BasicBlock ->
8391/// IncomingValue and add it in the Wrapper so isEqual can do O(1) checking
8392/// of the incoming values.
8395
8396 // One Phi usually has < 8 incoming values.
8400
8401 // We only merge the identical non-entry BBs with
8402 // - terminator unconditional br to Succ (pending relaxation),
8403 // - does not have address taken / weird control.
8404 static bool canBeMerged(const BasicBlock *BB) {
8405 assert(BB && "Expected non-null BB");
8406 // Entry block cannot be eliminated or have predecessors.
8407 if (BB->isEntryBlock())
8408 return false;
8409
8410 // Single successor and must be Succ.
8411 // FIXME: Relax that the terminator is a BranchInst by checking for equality
8412 // on other kinds of terminators. We decide to only support unconditional
8413 // branches for now for compile time reasons.
8414 auto *BI = dyn_cast<UncondBrInst>(BB->getTerminator());
8415 if (!BI)
8416 return false;
8417
8418 // Avoid blocks that are "address-taken" (blockaddress) or have unusual
8419 // uses.
8420 if (BB->hasAddressTaken() || BB->isEHPad())
8421 return false;
8422
8423 // TODO: relax this condition to merge equal blocks with >1 instructions?
8424 // Here, we use a O(1) form of the O(n) comparison of `size() != 1`.
8425 if (&BB->front() != &BB->back())
8426 return false;
8427
8428 // The BB must have at least one predecessor.
8429 if (pred_empty(BB))
8430 return false;
8431
8432 return true;
8433 }
8434};
8435
8437 static unsigned getHashValue(const EqualBBWrapper *EBW) {
8438 BasicBlock *BB = EBW->BB;
8440 assert(BB->size() == 1 && "Expected just a single branch in the BB");
8441
8442 // Since we assume the BB is just a single UncondBrInst with a single
8443 // successor, we hash as the BB and the incoming Values of its successor
8444 // PHIs. Initially, we tried to just use the successor BB as the hash, but
8445 // including the incoming PHI values leads to better performance.
8446 // We also tried to build a map from BB -> Succs.IncomingValues ahead of
8447 // time and passing it in EqualBBWrapper, but this slowed down the average
8448 // compile time without having any impact on the worst case compile time.
8449 BasicBlock *Succ = BI->getSuccessor();
8450 auto PhiValsForBB = map_range(Succ->phis(), [&](PHINode &Phi) {
8451 return (*EBW->PhiPredIVs)[&Phi][BB];
8452 });
8453 return hash_combine(Succ, hash_combine_range(PhiValsForBB));
8454 }
8455 static bool isEqual(const EqualBBWrapper *LHS, const EqualBBWrapper *RHS) {
8456 BasicBlock *A = LHS->BB;
8457 BasicBlock *B = RHS->BB;
8458
8459 // FIXME: we checked that the size of A and B are both 1 in
8460 // mergeIdenticalUncondBBs to make the Case list smaller to
8461 // improve performance. If we decide to support BasicBlocks with more
8462 // than just a single instruction, we need to check that A.size() ==
8463 // B.size() here, and we need to check more than just the BranchInsts
8464 // for equality.
8465
8466 UncondBrInst *ABI = cast<UncondBrInst>(A->getTerminator());
8467 UncondBrInst *BBI = cast<UncondBrInst>(B->getTerminator());
8468 if (ABI->getSuccessor() != BBI->getSuccessor())
8469 return false;
8470
8471 // Need to check that PHIs in successor have matching values.
8472 BasicBlock *Succ = ABI->getSuccessor();
8473 auto IfPhiIVMatch = [&](PHINode &Phi) {
8474 // Replace O(|Pred|) Phi.getIncomingValueForBlock with this O(1) hashmap
8475 // query.
8476 auto &PredIVs = (*LHS->PhiPredIVs)[&Phi];
8477 return PredIVs[A] == PredIVs[B];
8478 };
8479 return all_of(Succ->phis(), IfPhiIVMatch);
8480 }
8481};
8482
8483// Merge identical BBs into one of them.
8485 DomTreeUpdater *DTU) {
8486 if (Candidates.size() < 2)
8487 return false;
8488
8489 // Build Cases. Skip BBs that are not candidates for simplification. Mark
8490 // PHINodes which need to be processed into PhiPredIVs. We decide to process
8491 // an entire PHI at once after the loop, opposed to calling
8492 // getIncomingValueForBlock inside this loop, since each call to
8493 // getIncomingValueForBlock is O(|Preds|).
8494 EqualBBWrapper::Phi2IVsMap PhiPredIVs;
8496 BBs2Merge.reserve(Candidates.size());
8498
8499 for (BasicBlock *BB : Candidates) {
8500 BasicBlock *Succ = BB->getSingleSuccessor();
8501 assert(Succ && "Expected unconditional BB");
8502 BBs2Merge.emplace_back(EqualBBWrapper{BB, &PhiPredIVs});
8503 Phis.insert_range(make_pointer_range(Succ->phis()));
8504 }
8505
8506 // Precompute a data structure to improve performance of isEqual for
8507 // EqualBBWrapper.
8508 PhiPredIVs.reserve(Phis.size());
8509 for (PHINode *Phi : Phis) {
8510 auto &IVs =
8511 PhiPredIVs.try_emplace(Phi, Phi->getNumIncomingValues()).first->second;
8512 // Pre-fill all incoming for O(1) lookup as Phi.getIncomingValueForBlock is
8513 // O(|Pred|).
8514 for (auto &IV : Phi->incoming_values())
8515 IVs.insert({Phi->getIncomingBlock(IV), IV.get()});
8516 }
8517
8518 // Group duplicates using DenseSet with custom equality/hashing.
8519 // Build a set such that if the EqualBBWrapper exists in the set and another
8520 // EqualBBWrapper isEqual, then the equivalent EqualBBWrapper which is not in
8521 // the set should be replaced with the one in the set. If the EqualBBWrapper
8522 // is not in the set, then it should be added to the set so other
8523 // EqualBBWrapper can check against it in the same manner. We use
8524 // EqualBBWrapper instead of just BasicBlock because we'd like to pass around
8525 // information to isEquality, getHashValue, and when doing the replacement
8526 // with better performance.
8528 Keep.reserve(BBs2Merge.size());
8529
8531 Updates.reserve(BBs2Merge.size() * 2);
8532
8533 bool MadeChange = false;
8534
8535 // Helper: redirect all edges X -> DeadPred to X -> LivePred.
8536 auto RedirectIncomingEdges = [&](BasicBlock *Dead, BasicBlock *Live) {
8539 if (DTU) {
8540 // All predecessors of DeadPred (except the common predecessor) will be
8541 // moved to LivePred.
8542 Updates.reserve(Updates.size() + DeadPreds.size() * 2);
8544 predecessors(Live));
8545 for (BasicBlock *PredOfDead : DeadPreds) {
8546 // Do not modify those common predecessors of DeadPred and LivePred.
8547 if (!LivePreds.contains(PredOfDead))
8548 Updates.push_back({DominatorTree::Insert, PredOfDead, Live});
8549 Updates.push_back({DominatorTree::Delete, PredOfDead, Dead});
8550 }
8551 }
8552 LLVM_DEBUG(dbgs() << "Replacing duplicate pred BB ";
8553 Dead->printAsOperand(dbgs()); dbgs() << " with pred ";
8554 Live->printAsOperand(dbgs()); dbgs() << " for ";
8555 Live->getSingleSuccessor()->printAsOperand(dbgs());
8556 dbgs() << "\n");
8557 // Replace successors in all predecessors of DeadPred.
8558 for (BasicBlock *PredOfDead : DeadPreds) {
8559 Instruction *T = PredOfDead->getTerminator();
8560 T->replaceSuccessorWith(Dead, Live);
8561 }
8562 };
8563
8564 // Try to eliminate duplicate predecessors.
8565 for (const auto &EBW : BBs2Merge) {
8566 // EBW is a candidate for simplification. If we find a duplicate BB,
8567 // replace it.
8568 const auto &[It, Inserted] = Keep.insert(&EBW);
8569 if (Inserted)
8570 continue;
8571
8572 // Found duplicate: merge P into canonical predecessor It->Pred.
8573 BasicBlock *KeepBB = (*It)->BB;
8574 BasicBlock *DeadBB = EBW.BB;
8575
8576 // Avoid merging a BB with itself.
8577 if (KeepBB == DeadBB)
8578 continue;
8579
8580 // Redirect all edges into DeadPred to KeepPred.
8581 RedirectIncomingEdges(DeadBB, KeepBB);
8582
8583 // Now DeadBB should become unreachable; leave DCE to later,
8584 // but we can try to simplify it if it only branches to Succ.
8585 // (We won't erase here to keep the routine simple and DT-safe.)
8586 assert(pred_empty(DeadBB) && "DeadBB should be unreachable.");
8587 MadeChange = true;
8588 }
8589
8590 if (DTU && !Updates.empty())
8591 DTU->applyUpdates(Updates);
8592
8593 return MadeChange;
8594}
8595
8596bool SimplifyCFGOpt::simplifyDuplicateSwitchArms(SwitchInst *SI,
8597 DomTreeUpdater *DTU) {
8598 // Collect candidate switch-arms top-down.
8599 SmallSetVector<BasicBlock *, 16> FilteredArms(
8602 return mergeIdenticalBBs(FilteredArms.getArrayRef(), DTU);
8603}
8604
8605bool SimplifyCFGOpt::simplifyDuplicatePredecessors(BasicBlock *BB,
8606 DomTreeUpdater *DTU) {
8607 // Need at least 2 predecessors to do anything.
8608 if (!BB || !BB->hasNPredecessorsOrMore(2))
8609 return false;
8610
8611 // Compilation time consideration: retain the canonical loop, otherwise, we
8612 // require more time in the later loop canonicalization.
8613 if (Options.NeedCanonicalLoop && is_contained(LoopHeaders, BB))
8614 return false;
8615
8616 // Collect candidate predecessors bottom-up.
8617 SmallSetVector<BasicBlock *, 8> FilteredPreds(
8620 return mergeIdenticalBBs(FilteredPreds.getArrayRef(), DTU);
8621}
8622
8623bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
8624 BasicBlock *BB = SI->getParent();
8625
8626 if (isValueEqualityComparison(SI)) {
8627 // If we only have one predecessor, and if it is a branch on this value,
8628 // see if that predecessor totally determines the outcome of this switch.
8629 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
8630 if (simplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
8631 return requestResimplify();
8632
8633 Value *Cond = SI->getCondition();
8634 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
8635 if (simplifySwitchOnSelect(SI, Select))
8636 return requestResimplify();
8637
8638 // If the block only contains the switch, see if we can fold the block
8639 // away into any preds.
8640 if (SI == &*BB->begin())
8641 if (foldValueComparisonIntoPredecessors(SI, Builder))
8642 return requestResimplify();
8643 }
8644
8645 // Try to transform the switch into an icmp and a branch.
8646 // The conversion from switch to comparison may lose information on
8647 // impossible switch values, so disable it early in the pipeline.
8648 if (Options.ConvertSwitchRangeToICmp && turnSwitchRangeIntoICmp(SI, Builder))
8649 return requestResimplify();
8650
8651 // Remove unreachable cases.
8652 if (eliminateDeadSwitchCases(SI, DTU, Options.AC, DL))
8653 return requestResimplify();
8654
8655 if (simplifySwitchOfCmpIntrinsic(SI, Builder, DTU))
8656 return requestResimplify();
8657
8658 if (trySwitchToSelect(SI, Builder, DTU, DL))
8659 return requestResimplify();
8660
8661 if (Options.ForwardSwitchCondToPhi && forwardSwitchConditionToPHI(SI))
8662 return requestResimplify();
8663
8664 // The conversion of switches to arithmetic or lookup table is disabled in
8665 // the early optimization pipeline, as it may lose information or make the
8666 // resulting code harder to analyze.
8667 if (Options.ConvertSwitchToArithmetic || Options.ConvertSwitchToLookupTable)
8668 if (simplifySwitchLookup(SI, Builder, DTU, DL, TTI,
8669 Options.ConvertSwitchToLookupTable))
8670 return requestResimplify();
8671
8672 if (simplifySwitchOfPowersOfTwo(SI, Builder, DTU, DL, TTI))
8673 return requestResimplify();
8674
8675 if (reduceSwitchRange(SI, Builder, DL, TTI))
8676 return requestResimplify();
8677
8678 if (HoistCommon &&
8679 hoistCommonCodeFromSuccessors(SI, !Options.HoistCommonInsts))
8680 return requestResimplify();
8681
8682 // We can merge identical switch arms early to enhance more aggressive
8683 // optimization on switch.
8684 if (simplifyDuplicateSwitchArms(SI, DTU))
8685 return requestResimplify();
8686
8687 if (simplifySwitchWhenUMin(SI, DTU))
8688 return requestResimplify();
8689
8690 if (simplifySwitchDefaultBranch(SI, DTU, DL, Options.AC))
8691 return requestResimplify();
8692
8693 return false;
8694}
8695
8696bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) {
8697 BasicBlock *BB = IBI->getParent();
8698 bool Changed = false;
8699 SmallVector<uint32_t> BranchWeights;
8700 const bool HasBranchWeights = extractBranchWeights(*IBI, BranchWeights);
8701
8702 DenseMap<const BasicBlock *, uint64_t> TargetWeight;
8703 if (HasBranchWeights)
8704 for (size_t I = 0, E = IBI->getNumDestinations(); I < E; ++I)
8705 TargetWeight[IBI->getDestination(I)] += BranchWeights[I];
8706
8707 // Eliminate redundant destinations.
8708 SmallPtrSet<Value *, 8> Succs;
8709 SmallSetVector<BasicBlock *, 8> RemovedSuccs;
8710 for (unsigned I = 0, E = IBI->getNumDestinations(); I != E; ++I) {
8711 BasicBlock *Dest = IBI->getDestination(I);
8712 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
8713 if (!Dest->hasAddressTaken())
8714 RemovedSuccs.insert(Dest);
8715 Dest->removePredecessor(BB);
8716 IBI->removeDestination(I);
8717 --I;
8718 --E;
8719 Changed = true;
8720 }
8721 }
8722
8723 if (DTU) {
8724 std::vector<DominatorTree::UpdateType> Updates;
8725 Updates.reserve(RemovedSuccs.size());
8726 for (auto *RemovedSucc : RemovedSuccs)
8727 Updates.push_back({DominatorTree::Delete, BB, RemovedSucc});
8728 DTU->applyUpdates(Updates);
8729 }
8730
8731 if (IBI->getNumDestinations() == 0) {
8732 // If the indirectbr has no successors, change it to unreachable.
8733 new UnreachableInst(IBI->getContext(), IBI->getIterator());
8735 return true;
8736 }
8737
8738 if (IBI->getNumDestinations() == 1) {
8739 // If the indirectbr has one successor, change it to a direct branch.
8742 return true;
8743 }
8744 if (HasBranchWeights) {
8745 SmallVector<uint64_t> NewBranchWeights(IBI->getNumDestinations());
8746 for (size_t I = 0, E = IBI->getNumDestinations(); I < E; ++I)
8747 NewBranchWeights[I] += TargetWeight.find(IBI->getDestination(I))->second;
8748 setFittedBranchWeights(*IBI, NewBranchWeights, /*IsExpected=*/false);
8749 }
8750 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
8751 if (simplifyIndirectBrOnSelect(IBI, SI))
8752 return requestResimplify();
8753 }
8754 return Changed;
8755}
8756
8757/// Given an block with only a single landing pad and a unconditional branch
8758/// try to find another basic block which this one can be merged with. This
8759/// handles cases where we have multiple invokes with unique landing pads, but
8760/// a shared handler.
8761///
8762/// We specifically choose to not worry about merging non-empty blocks
8763/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
8764/// practice, the optimizer produces empty landing pad blocks quite frequently
8765/// when dealing with exception dense code. (see: instcombine, gvn, if-else
8766/// sinking in this file)
8767///
8768/// This is primarily a code size optimization. We need to avoid performing
8769/// any transform which might inhibit optimization (such as our ability to
8770/// specialize a particular handler via tail commoning). We do this by not
8771/// merging any blocks which require us to introduce a phi. Since the same
8772/// values are flowing through both blocks, we don't lose any ability to
8773/// specialize. If anything, we make such specialization more likely.
8774///
8775/// Phis in the successor are allowed if both blocks pass the same value, or
8776/// each passes its own landing pad value and that is its only use: the merged
8777/// block's landing pad then carries the value for both edges.
8779 BasicBlock *BB, DomTreeUpdater *DTU) {
8780 auto Succ = BB->getUniqueSuccessor();
8781 assert(Succ);
8782
8783 for (BasicBlock *OtherPred : predecessors(Succ)) {
8784 if (BB == OtherPred)
8785 continue;
8786 BasicBlock::iterator I = OtherPred->begin();
8788 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
8789 continue;
8790 ++I;
8792 if (!BI2 || !BI2->isIdenticalTo(BI))
8793 continue;
8794
8795 // Merging must not require a new phi in the merged landing pad block.
8796 if (!all_of(Succ->phis(), [&](PHINode &PN) {
8797 Value *V = PN.getIncomingValueForBlock(BB);
8798 Value *V2 = PN.getIncomingValueForBlock(OtherPred);
8799 return V == V2 || (V == LPad && V2 == LPad2);
8800 }))
8801 continue;
8802
8803 // Those phis must be the only uses of the landing pads. Otherwise, with a
8804 // loop through Succ, a use would be clobbered when the merged pad is
8805 // re-entered.
8806 unsigned NumLPadPhis = count_if(Succ->phis(), [&](PHINode &PN) {
8807 return PN.getIncomingValueForBlock(BB) == LPad;
8808 });
8809 if (!LPad->hasNUses(NumLPadPhis) || !LPad2->hasNUses(NumLPadPhis))
8810 continue;
8811
8812 std::vector<DominatorTree::UpdateType> Updates;
8813
8814 // We've found an identical block. Update our predecessors to take that
8815 // path instead and make ourselves dead.
8817 for (BasicBlock *Pred : UniquePreds) {
8818 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
8819 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
8820 "unexpected successor");
8821 II->setUnwindDest(OtherPred);
8822 if (DTU) {
8823 Updates.push_back({DominatorTree::Insert, Pred, OtherPred});
8824 Updates.push_back({DominatorTree::Delete, Pred, BB});
8825 }
8826 }
8827
8829 for (BasicBlock *Succ : UniqueSuccs) {
8830 Succ->removePredecessor(BB);
8831 if (DTU)
8832 Updates.push_back({DominatorTree::Delete, BB, Succ});
8833 }
8834
8835 IRBuilder<> Builder(BI);
8836 Builder.CreateUnreachable();
8837 BI->eraseFromParent();
8838 if (DTU)
8839 DTU->applyUpdates(Updates);
8840 return true;
8841 }
8842 return false;
8843}
8844
8845bool SimplifyCFGOpt::simplifyUncondBranch(UncondBrInst *BI,
8846 IRBuilder<> &Builder) {
8847 BasicBlock *BB = BI->getParent();
8848 BasicBlock *Succ = BI->getSuccessor(0);
8849
8850 // If the Terminator is the only non-phi instruction, simplify the block.
8851 // If LoopHeader is provided, check if the block or its successor is a loop
8852 // header. (This is for early invocations before loop simplify and
8853 // vectorization to keep canonical loop forms for nested loops. These blocks
8854 // can be eliminated when the pass is invoked later in the back-end.)
8855 // Note that if BB has only one predecessor then we do not introduce new
8856 // backedge, so we can eliminate BB.
8857 bool NeedCanonicalLoop =
8858 Options.NeedCanonicalLoop &&
8859 (!LoopHeaders.empty() && BB->hasNPredecessorsOrMore(2) &&
8860 (is_contained(LoopHeaders, BB) || is_contained(LoopHeaders, Succ)));
8862 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
8863 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB, DTU))
8864 return true;
8865
8866 // If the only instruction in the block is a seteq/setne comparison against a
8867 // constant, try to simplify the block.
8868 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
8869 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
8870 ++I;
8871 if (I->isTerminator() &&
8872 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
8873 return true;
8874 if (isa<SelectInst>(I) && I->getNextNode()->isTerminator() &&
8875 tryToSimplifyUncondBranchWithICmpSelectInIt(ICI, cast<SelectInst>(I),
8876 Builder))
8877 return true;
8878 }
8879 }
8880
8881 // See if we can merge an empty landing pad block with another which is
8882 // equivalent.
8883 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
8884 ++I;
8885 if (I->isTerminator() && tryToMergeLandingPad(LPad, BI, BB, DTU))
8886 return true;
8887 }
8888
8889 return false;
8890}
8891
8893 BasicBlock *PredPred = nullptr;
8894 for (auto *P : predecessors(BB)) {
8895 BasicBlock *PPred = P->getSinglePredecessor();
8896 if (!PPred || (PredPred && PredPred != PPred))
8897 return nullptr;
8898 PredPred = PPred;
8899 }
8900 return PredPred;
8901}
8902
8903/// Fold the following pattern:
8904/// bb0:
8905/// br i1 %cond1, label %bb1, label %bb2
8906/// bb1:
8907/// br i1 %cond2, label %bb3, label %bb4
8908/// bb2:
8909/// br i1 %cond2, label %bb4, label %bb3
8910/// bb3:
8911/// ...
8912/// bb4:
8913/// ...
8914/// into
8915/// bb0:
8916/// %cond = xor i1 %cond1, %cond2
8917/// br i1 %cond, label %bb4, label %bb3
8918/// bb3:
8919/// ...
8920/// bb4:
8921/// ...
8922/// NOTE: %cond2 always dominates the terminator of bb0.
8924 BasicBlock *BB = BI->getParent();
8925 BasicBlock *BB1 = BI->getSuccessor(0);
8926 BasicBlock *BB2 = BI->getSuccessor(1);
8927 auto IsSimpleSuccessor = [BB](BasicBlock *Succ, CondBrInst *&SuccBI) {
8928 if (Succ == BB)
8929 return false;
8930 if (&Succ->front() != Succ->getTerminator())
8931 return false;
8932 SuccBI = dyn_cast<CondBrInst>(Succ->getTerminator());
8933 if (!SuccBI)
8934 return false;
8935 BasicBlock *Succ1 = SuccBI->getSuccessor(0);
8936 BasicBlock *Succ2 = SuccBI->getSuccessor(1);
8937 return Succ1 != Succ && Succ2 != Succ && Succ1 != BB && Succ2 != BB &&
8938 !isa<PHINode>(Succ1->front()) && !isa<PHINode>(Succ2->front());
8939 };
8940 CondBrInst *BB1BI, *BB2BI;
8941 if (!IsSimpleSuccessor(BB1, BB1BI) || !IsSimpleSuccessor(BB2, BB2BI))
8942 return false;
8943
8944 if (BB1BI->getCondition() != BB2BI->getCondition() ||
8945 BB1BI->getSuccessor(0) != BB2BI->getSuccessor(1) ||
8946 BB1BI->getSuccessor(1) != BB2BI->getSuccessor(0))
8947 return false;
8948
8949 BasicBlock *BB3 = BB1BI->getSuccessor(0);
8950 BasicBlock *BB4 = BB1BI->getSuccessor(1);
8951 // Bail out on trivial cases to avoid bothering to handle the special case in
8952 // the code below.
8953 if (BB3 == BB4)
8954 return false;
8955 IRBuilder<> Builder(BI);
8956 BI->setCondition(
8957 Builder.CreateXor(BI->getCondition(), BB1BI->getCondition()));
8958 BB1->removePredecessor(BB);
8959 BI->setSuccessor(0, BB4);
8960 BB2->removePredecessor(BB);
8961 BI->setSuccessor(1, BB3);
8962 if (DTU) {
8964 Updates.push_back({DominatorTree::Delete, BB, BB1});
8965 Updates.push_back({DominatorTree::Insert, BB, BB4});
8966 Updates.push_back({DominatorTree::Delete, BB, BB2});
8967 Updates.push_back({DominatorTree::Insert, BB, BB3});
8968
8969 DTU->applyUpdates(Updates);
8970 }
8971 bool HasWeight = false;
8972 uint64_t BBTWeight, BBFWeight;
8973 if (extractBranchWeights(*BI, BBTWeight, BBFWeight))
8974 HasWeight = true;
8975 else
8976 BBTWeight = BBFWeight = 1;
8977 uint64_t BB1TWeight, BB1FWeight;
8978 if (extractBranchWeights(*BB1BI, BB1TWeight, BB1FWeight))
8979 HasWeight = true;
8980 else
8981 BB1TWeight = BB1FWeight = 1;
8982 uint64_t BB2TWeight, BB2FWeight;
8983 if (extractBranchWeights(*BB2BI, BB2TWeight, BB2FWeight))
8984 HasWeight = true;
8985 else
8986 BB2TWeight = BB2FWeight = 1;
8987 if (HasWeight) {
8988 uint64_t Weights[2] = {BBTWeight * BB1FWeight + BBFWeight * BB2TWeight,
8989 BBTWeight * BB1TWeight + BBFWeight * BB2FWeight};
8990 setFittedBranchWeights(*BI, Weights, /*IsExpected=*/false,
8991 /*ElideAllZero=*/true);
8992 }
8993 return true;
8994}
8995
8996bool SimplifyCFGOpt::simplifyCondBranch(CondBrInst *BI, IRBuilder<> &Builder) {
8997 assert(
8999 BI->getSuccessor(0) != BI->getSuccessor(1) &&
9000 "Tautological conditional branch should have been eliminated already.");
9001
9002 BasicBlock *BB = BI->getParent();
9003 if (!Options.SimplifyCondBranch ||
9004 BI->getFunction()->hasFnAttribute(Attribute::OptForFuzzing))
9005 return false;
9006
9007 // Conditional branch
9008 if (isValueEqualityComparison(BI)) {
9009 // If we only have one predecessor, and if it is a branch on this value,
9010 // see if that predecessor totally determines the outcome of this
9011 // switch.
9012 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
9013 if (simplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
9014 return requestResimplify();
9015
9016 // This block must be empty, except for the setcond inst, if it exists.
9017 // Ignore pseudo intrinsics.
9018 for (auto &I : *BB) {
9019 if (isa<PseudoProbeInst>(I) ||
9020 &I == cast<Instruction>(BI->getCondition()))
9021 continue;
9022 if (&I == BI)
9023 if (foldValueComparisonIntoPredecessors(BI, Builder))
9024 return requestResimplify();
9025 break;
9026 }
9027 }
9028
9029 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
9030 if (simplifyBranchOnICmpChain(BI, Builder, DL))
9031 return true;
9032
9033 // If this basic block has dominating predecessor blocks and the dominating
9034 // blocks' conditions imply BI's condition, we know the direction of BI.
9035 std::optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
9036 if (Imp) {
9037 // Turn this into a branch on constant.
9038 auto *OldCond = BI->getCondition();
9039 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
9040 : ConstantInt::getFalse(BB->getContext());
9041 BI->setCondition(TorF);
9043 return requestResimplify();
9044 }
9045
9046 // If this basic block is ONLY a compare and a branch, and if a predecessor
9047 // branches to us and one of our successors, fold the comparison into the
9048 // predecessor and use logical operations to pick the right destination.
9049 if (Options.SpeculateBlocks &&
9050 foldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI, Options.AC,
9051 Options.BonusInstThreshold))
9052 return requestResimplify();
9053
9054 // We have a conditional branch to two blocks that are only reachable
9055 // from BI. We know that the condbr dominates the two blocks, so see if
9056 // there is any identical code in the "then" and "else" blocks. If so, we
9057 // can hoist it up to the branching block.
9058 if (BI->getSuccessor(0)->getSinglePredecessor()) {
9059 if (BI->getSuccessor(1)->getSinglePredecessor()) {
9060 if (HoistCommon &&
9061 hoistCommonCodeFromSuccessors(BI, !Options.HoistCommonInsts))
9062 return requestResimplify();
9063
9064 if (BI && Options.HoistLoadsStoresWithCondFaulting &&
9065 isProfitableToSpeculate(BI, std::nullopt, TTI)) {
9066 SmallVector<Instruction *, 2> SpeculatedConditionalLoadsStores;
9067 auto CanSpeculateConditionalLoadsStores = [&]() {
9068 for (auto *Succ : successors(BB)) {
9069 for (Instruction &I : *Succ) {
9070 if (I.isTerminator()) {
9071 if (I.getNumSuccessors() > 1)
9072 return false;
9073 continue;
9074 } else if (!isSafeCheapLoadStore(&I, TTI) ||
9075 SpeculatedConditionalLoadsStores.size() ==
9077 return false;
9078 }
9079 SpeculatedConditionalLoadsStores.push_back(&I);
9080 }
9081 }
9082 return !SpeculatedConditionalLoadsStores.empty();
9083 };
9084
9085 if (CanSpeculateConditionalLoadsStores()) {
9086 hoistConditionalLoadsStores(BI, SpeculatedConditionalLoadsStores,
9087 std::nullopt, nullptr);
9088 return requestResimplify();
9089 }
9090 }
9091 } else {
9092 // If Successor #1 has multiple preds, we may be able to conditionally
9093 // execute Successor #0 if it branches to Successor #1.
9094 Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
9095 if (Succ0TI->getNumSuccessors() == 1 &&
9096 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
9097 if (speculativelyExecuteBB(BI, BI->getSuccessor(0)))
9098 return requestResimplify();
9099 }
9100 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
9101 // If Successor #0 has multiple preds, we may be able to conditionally
9102 // execute Successor #1 if it branches to Successor #0.
9103 Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
9104 if (Succ1TI->getNumSuccessors() == 1 &&
9105 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
9106 if (speculativelyExecuteBB(BI, BI->getSuccessor(1)))
9107 return requestResimplify();
9108 }
9109
9110 // If this is a branch on something for which we know the constant value in
9111 // predecessors (e.g. a phi node in the current block), thread control
9112 // through this block.
9113 if (foldCondBranchOnValueKnownInPredecessor(BI))
9114 return requestResimplify();
9115
9116 // Scan predecessor blocks for conditional branches.
9117 for (BasicBlock *Pred : predecessors(BB))
9118 if (CondBrInst *PBI = dyn_cast<CondBrInst>(Pred->getTerminator()))
9119 if (PBI != BI)
9120 if (SimplifyCondBranchToCondBranch(PBI, BI, DTU, DL, TTI))
9121 return requestResimplify();
9122
9123 // Look for diamond patterns.
9124 if (MergeCondStores)
9125 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
9126 if (CondBrInst *PBI = dyn_cast<CondBrInst>(PrevBB->getTerminator()))
9127 if (PBI != BI)
9128 if (mergeConditionalStores(PBI, BI, DTU, DL, TTI))
9129 return requestResimplify();
9130
9131 // Look for nested conditional branches.
9132 if (mergeNestedCondBranch(BI, DTU))
9133 return requestResimplify();
9134
9135 return false;
9136}
9137
9138/// Check if passing a value to an instruction will cause undefined behavior.
9139static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified) {
9140 assert(V->getType() == I->getType() && "Mismatched types");
9142 if (!C)
9143 return false;
9144
9145 if (I->use_empty())
9146 return false;
9147
9148 if (C->isNullValue() || isa<UndefValue>(C)) {
9149 // Find the first same-block use with a UB-triggering opcode, skipping
9150 // cross-block or before-I uses.
9151 auto FindUse = llvm::find_if(I->uses(), [I](auto &U) {
9152 auto *Use = cast<Instruction>(U.getUser());
9153 // Only same-block uses after I can witness UB at I's program point.
9154 // Self-uses and before-I uses can occur when I is a PHI node.
9155 if (Use->getParent() != I->getParent() || Use == I || Use->comesBefore(I))
9156 return false;
9157 // Change this list when we want to add new instructions.
9158 switch (Use->getOpcode()) {
9159 default:
9160 return false;
9161 case Instruction::GetElementPtr:
9162 case Instruction::Ret:
9163 case Instruction::BitCast:
9164 case Instruction::Load:
9165 case Instruction::Store:
9166 case Instruction::Call:
9167 case Instruction::CallBr:
9168 case Instruction::Invoke:
9169 case Instruction::UDiv:
9170 case Instruction::URem:
9171 // Note: signed div/rem of INT_MIN / -1 is also immediate UB, not
9172 // implemented to avoid code complexity as it is unclear how useful such
9173 // logic is.
9174 case Instruction::SDiv:
9175 case Instruction::SRem:
9176 return true;
9177 }
9178 });
9179 if (FindUse == I->use_end())
9180 return false;
9181 auto &Use = *FindUse;
9182 auto *User = cast<Instruction>(Use.getUser());
9183
9184 // Now make sure that there are no instructions in between that can alter
9185 // control flow (eg. calls)
9186 auto InstrRange =
9187 make_range(std::next(I->getIterator()), User->getIterator());
9188 if (any_of(InstrRange, [](Instruction &I) {
9190 }))
9191 return false;
9192
9193 // Look through GEPs. A load from a GEP derived from NULL is still undefined
9195 if (GEP->getPointerOperand() == I) {
9196 // The type of GEP may differ from the type of base pointer.
9197 // Bail out on vector GEPs, as they are not handled by other checks.
9198 if (GEP->getType()->isVectorTy())
9199 return false;
9200 // The current base address is null, there are four cases to consider:
9201 // getelementptr (TY, null, 0) -> null
9202 // getelementptr (TY, null, not zero) -> may be modified
9203 // getelementptr inbounds (TY, null, 0) -> null
9204 // getelementptr inbounds (TY, null, not zero) -> poison iff null is
9205 // undefined?
9206 if (!GEP->hasAllZeroIndices() &&
9207 (!GEP->isInBounds() ||
9208 NullPointerIsDefined(GEP->getFunction(),
9209 GEP->getPointerAddressSpace())))
9210 PtrValueMayBeModified = true;
9211 return passingValueIsAlwaysUndefined(V, GEP, PtrValueMayBeModified);
9212 }
9213
9214 // Look through return.
9215 if (ReturnInst *Ret = dyn_cast<ReturnInst>(User)) {
9216 bool HasNoUndefAttr =
9217 Ret->getFunction()->hasRetAttribute(Attribute::NoUndef);
9218 // Return undefined to a noundef return value is undefined.
9219 if (isa<UndefValue>(C) && HasNoUndefAttr)
9220 return true;
9221 // Return null to a nonnull+noundef return value is undefined.
9222 if (C->isNullValue() && HasNoUndefAttr &&
9223 Ret->getFunction()->hasRetAttribute(Attribute::NonNull)) {
9224 return !PtrValueMayBeModified;
9225 }
9226 }
9227
9228 // Load from null is undefined.
9229 if (LoadInst *LI = dyn_cast<LoadInst>(User))
9230 if (!LI->isVolatile())
9231 return !NullPointerIsDefined(LI->getFunction(),
9232 LI->getPointerAddressSpace());
9233
9234 // Store to null is undefined.
9236 if (!SI->isVolatile())
9237 return (!NullPointerIsDefined(SI->getFunction(),
9238 SI->getPointerAddressSpace())) &&
9239 SI->getPointerOperand() == I;
9240
9241 // llvm.assume(false/undef) always triggers immediate UB.
9242 if (auto *Assume = dyn_cast<AssumeInst>(User)) {
9243 // Ignore assume operand bundles.
9244 if (I == Assume->getArgOperand(0))
9245 return true;
9246 }
9247
9248 if (auto *CB = dyn_cast<CallBase>(User)) {
9249 if (C->isNullValue() && NullPointerIsDefined(CB->getFunction()))
9250 return false;
9251 // A call to null is undefined.
9252 if (CB->getCalledOperand() == I)
9253 return true;
9254
9255 if (CB->isArgOperand(&Use)) {
9256 unsigned ArgIdx = CB->getArgOperandNo(&Use);
9257 // Passing null to a nonnnull+noundef argument is undefined.
9258 if (isa<ConstantPointerNull>(C) && C->getType()->isPointerTy() &&
9259 CB->paramHasNonNullAttr(ArgIdx, /*AllowUndefOrPoison=*/false))
9260 return !PtrValueMayBeModified;
9261 // Passing undef to a noundef argument is undefined.
9262 if (isa<UndefValue>(C) && CB->isPassingUndefUB(ArgIdx))
9263 return true;
9264 }
9265 }
9266 // Div/Rem by zero is immediate UB
9267 if (match(User, m_BinOp(m_Value(), m_Specific(I))) && User->isIntDivRem())
9268 return true;
9269 }
9270 return false;
9271}
9272
9273/// If BB has an incoming value that will always trigger undefined behavior
9274/// (eg. null pointer dereference), remove the branch leading here.
9276 DomTreeUpdater *DTU,
9277 AssumptionCache *AC) {
9278 for (PHINode &PHI : BB->phis())
9279 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
9280 if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
9281 BasicBlock *Predecessor = PHI.getIncomingBlock(i);
9282 Instruction *T = Predecessor->getTerminator();
9283 IRBuilder<> Builder(T);
9284 if (isa<UncondBrInst>(T)) {
9285 BB->removePredecessor(Predecessor);
9286 // Turn unconditional branches into unreachables.
9287 Builder.CreateUnreachable();
9288 T->eraseFromParent();
9289 if (DTU)
9290 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
9291 return true;
9292 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(T)) {
9293 BB->removePredecessor(Predecessor);
9294 // Handle degenerate conditional branches.
9295 if (BI->getSuccessor(0) == BI->getSuccessor(1)) {
9296 // The only difference from the UncondBrInst path above is that it
9297 // has two edges in CFG.
9298 BB->removePredecessor(Predecessor);
9299 // Turn unconditional branches into unreachables.
9300 Builder.CreateUnreachable();
9301 } else {
9302 // Preserve guarding condition in assume, because it might not be
9303 // inferrable from any dominating condition.
9304 Value *Cond = BI->getCondition();
9305 CallInst *Assumption;
9306 if (BI->getSuccessor(0) == BB)
9307 Assumption = Builder.CreateAssumption(Builder.CreateNot(Cond));
9308 else
9309 Assumption = Builder.CreateAssumption(Cond);
9310 if (AC)
9311 AC->registerAssumption(cast<AssumeInst>(Assumption));
9312 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
9313 : BI->getSuccessor(0));
9314 }
9315 BI->eraseFromParent();
9316 if (DTU)
9317 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
9318 return true;
9319 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
9320 // Redirect all branches leading to UB into
9321 // a newly created unreachable block.
9322 BasicBlock *Unreachable = BasicBlock::Create(
9323 Predecessor->getContext(), "unreachable", BB->getParent(), BB);
9324 Builder.SetInsertPoint(Unreachable);
9325 // The new block contains only one instruction: Unreachable
9326 Builder.CreateUnreachable();
9327 for (const auto &Case : SI->cases())
9328 if (Case.getCaseSuccessor() == BB) {
9329 BB->removePredecessor(Predecessor);
9330 Case.setSuccessor(Unreachable);
9331 }
9332 if (SI->getDefaultDest() == BB) {
9333 BB->removePredecessor(Predecessor);
9334 SI->setDefaultDest(Unreachable);
9335 }
9336
9337 if (DTU)
9338 DTU->applyUpdates(
9339 { { DominatorTree::Insert, Predecessor, Unreachable },
9340 { DominatorTree::Delete, Predecessor, BB } });
9341 return true;
9342 }
9343 }
9344
9345 return false;
9346}
9347
9348bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
9349 bool Changed = false;
9350
9351 assert(BB && BB->getParent() && "Block not embedded in function!");
9352 assert(BB->hasTerminator() && "Degenerate basic block encountered!");
9353
9354 // Remove basic blocks that have no predecessors (except the entry block)...
9355 // or that just have themself as a predecessor. These are unreachable.
9356 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
9357 BB->getSinglePredecessor() == BB) {
9358 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
9359 DeleteDeadBlock(BB, DTU);
9360 return true;
9361 }
9362
9363 // Check to see if we can constant propagate this terminator instruction
9364 // away...
9365 Changed |= ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true,
9366 /*TLI=*/nullptr, DTU);
9367
9368 // Check for and eliminate duplicate PHI nodes in this block.
9370
9371 // Check for and remove branches that will always cause undefined behavior.
9373 return requestResimplify();
9374
9375 // Merge basic blocks into their predecessor if there is only one distinct
9376 // pred, and if there is only one distinct successor of the predecessor, and
9377 // if there are no PHI nodes.
9378 if (MergeBlockIntoPredecessor(BB, DTU))
9379 return true;
9380
9381 if (SinkCommon && Options.SinkCommonInsts) {
9382 if (sinkCommonCodeFromPredecessors(BB, DTU) ||
9383 mergeCompatibleInvokes(BB, DTU)) {
9384 // sinkCommonCodeFromPredecessors() does not automatically CSE PHI's,
9385 // so we may now how duplicate PHI's.
9386 // Let's rerun EliminateDuplicatePHINodes() first,
9387 // before foldTwoEntryPHINode() potentially converts them into select's,
9388 // after which we'd need a whole EarlyCSE pass run to cleanup them.
9389 return true;
9390 }
9391 // Merge identical predecessors of this block.
9392 if (simplifyDuplicatePredecessors(BB, DTU))
9393 return true;
9394 }
9395
9396 if (Options.SpeculateBlocks &&
9397 !BB->getParent()->hasFnAttribute(Attribute::OptForFuzzing)) {
9398 // If there is a trivial two-entry PHI node in this basic block, and we can
9399 // eliminate it, do so now.
9400 if (auto *PN = dyn_cast<PHINode>(BB->begin()))
9401 if (PN->getNumIncomingValues() == 2)
9402 if (foldTwoEntryPHINode(PN, TTI, DTU, Options.AC, DL,
9403 Options.SpeculateUnpredictables))
9404 return true;
9405 }
9406
9407 IRBuilder<> Builder(BB);
9409 Builder.SetInsertPoint(Terminator);
9410 switch (Terminator->getOpcode()) {
9411 case Instruction::UncondBr:
9412 Changed |= simplifyUncondBranch(cast<UncondBrInst>(Terminator), Builder);
9413 break;
9414 case Instruction::CondBr:
9415 Changed |= simplifyCondBranch(cast<CondBrInst>(Terminator), Builder);
9416 break;
9417 case Instruction::Resume:
9418 Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder);
9419 break;
9420 case Instruction::CleanupRet:
9421 Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator));
9422 break;
9423 case Instruction::Switch:
9424 Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder);
9425 break;
9426 case Instruction::Unreachable:
9427 Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator));
9428 break;
9429 case Instruction::IndirectBr:
9430 Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator));
9431 break;
9432 }
9433
9434 return Changed;
9435}
9436
9437bool SimplifyCFGOpt::run(BasicBlock *BB) {
9438 bool Changed = false;
9439
9440 // Repeated simplify BB as long as resimplification is requested.
9441 do {
9442 Resimplify = false;
9443
9444 // Perform one round of simplifcation. Resimplify flag will be set if
9445 // another iteration is requested.
9446 Changed |= simplifyOnce(BB);
9447 } while (Resimplify);
9448
9449 return Changed;
9450}
9451
9454 ArrayRef<WeakVH> LoopHeaders) {
9455 return SimplifyCFGOpt(TTI, DTU, BB->getDataLayout(), LoopHeaders,
9456 Options)
9457 .run(BB);
9458}
#define Fail
#define Success
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
static MachineBasicBlock * OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
Function Alias Analysis Results
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
This file defines the DenseMap class.
@ Default
#define DEBUG_TYPE
Hexagon Common GEP
static bool IsIndirectCall(const MachineInstr *MI)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
static Constant * getFalse(Type *Ty)
For a boolean type or a vector of boolean type, return false or a vector with every element false.
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
This file contains the declarations for metadata subclasses.
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
This file contains the declarations for profiling metadata utility functions.
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."))
const SmallVectorImpl< MachineOperand > & Cond
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:480
Provides some synthesis utilities to produce sequences of values.
This file defines generic set operations that may be used on set's of different types,...
This file implements a set that has insertion order iteration characteristics.
static std::optional< ContiguousCasesResult > findContiguousCases(Value *Condition, SmallVectorImpl< ConstantInt * > &Cases, SmallVectorImpl< ConstantInt * > &OtherCases, BasicBlock *Dest, BasicBlock *OtherDest)
static void addPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, BasicBlock *ExistPred, MemorySSAUpdater *MSSAU=nullptr)
Update PHI nodes in Succ to indicate that there will now be entries in it from the 'NewPred' block.
static bool validLookupTableConstant(Constant *C, const TargetTransformInfo &TTI)
Return true if the backend will be able to handle initializing an array of constants like C.
static StoreInst * findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2)
static bool isSwitchDense(uint64_t NumCases, uint64_t CaseRange, bool OptSize)
static bool validateAndCostRequiredSelects(BasicBlock *BB, BasicBlock *ThenBB, BasicBlock *EndBB, unsigned &SpeculatedInstructions, InstructionCost &Cost, const TargetTransformInfo &TTI)
Estimate the cost of the insertion(s) and check that the PHI nodes can be converted to selects.
static bool simplifySwitchLookup(SwitchInst *SI, IRBuilder<> &Builder, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI, bool ConvertSwitchToLookupTable)
If the switch is only used to initialize one or more phi nodes in a common successor block with diffe...
static void removeSwitchAfterSelectFold(SwitchInst *SI, PHINode *PHI, Value *SelectValue, IRBuilder<> &Builder, DomTreeUpdater *DTU)
static bool valuesOverlap(std::vector< ValueEqualityComparisonCase > &C1, std::vector< ValueEqualityComparisonCase > &C2)
Return true if there are any keys in C1 that exist in C2 as well.
static bool isProfitableToSpeculate(const CondBrInst *BI, std::optional< bool > Invert, const TargetTransformInfo &TTI)
static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB, BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
static bool mergeCleanupPad(CleanupReturnInst *RI)
static bool isVectorOp(Instruction &I)
Return if an instruction's type or any of its operands' types are a vector type.
static BasicBlock * allPredecessorsComeFromSameSource(BasicBlock *BB)
static void cloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(BasicBlock *BB, BasicBlock *PredBlock, ValueToValueMapTy &VMap)
static int constantIntSortPredicate(ConstantInt *const *P1, ConstantInt *const *P2)
static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified=false)
Check if passing a value to an instruction will cause undefined behavior.
static std::optional< std::tuple< BasicBlock *, Instruction::BinaryOps, bool > > shouldFoldCondBranchesToCommonDestination(CondBrInst *BI, CondBrInst *PBI, const TargetTransformInfo *TTI)
Determine if the two branches share a common destination and deduce a glue that joins the branches' c...
static bool isSafeToHoistInstr(Instruction *I, unsigned Flags)
static std::optional< bool > foldCondBranchOnValueKnownInPredecessorImpl(CondBrInst *BI, const TargetTransformInfo &TTI, DomTreeUpdater *DTU, AssumptionCache *AC, const DataLayout &DL)
If we have a conditional branch on something for which we know the constant value in predecessors (e....
static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, Instruction *I1, Instruction *I2)
static ConstantInt * getConstantInt(Value *V, const DataLayout &DL)
Extract ConstantInt from value, looking through IntToPtr and PointerNullValue.
static bool simplifySwitchOfCmpIntrinsic(SwitchInst *SI, IRBuilderBase &Builder, DomTreeUpdater *DTU)
Fold switch over ucmp/scmp intrinsic to br if two of the switch arms have the same destination.
static bool shouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, const TargetTransformInfo &TTI, const DataLayout &DL, const SmallVector< Type * > &ResultTypes)
Determine whether a lookup table should be built for this switch, based on the number of cases,...
static Constant * constantFold(Instruction *I, const DataLayout &DL, const SmallDenseMap< Value *, Constant * > &ConstantPool)
Try to fold instruction I into a constant.
static bool getCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, BasicBlock **CommonDest, SmallVectorImpl< std::pair< PHINode *, Constant * > > &Res, const DataLayout &DL)
Try to determine the resulting constant values in phi nodes at the common destination basic block,...
static bool areIdenticalUpToCommutativity(const Instruction *I1, const Instruction *I2)
static bool forwardSwitchConditionToPHI(SwitchInst *SI)
Try to forward the condition of a switch instruction to a phi node dominated by the switch,...
static PHINode * findPHIForConditionForwarding(ConstantInt *CaseValue, BasicBlock *BB, int *PhiIndex)
If BB would be eligible for simplification by TryToSimplifyUncondBranchFromEmptyBlock (i....
static bool reachesUncontrolledConvergentCallBeforeBlock(BasicBlock *From, BasicBlock *StopBB)
static bool simplifySwitchOfPowersOfTwo(SwitchInst *SI, IRBuilder<> &Builder, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
Tries to transform switch of powers of two to reduce switch range.
static bool isCleanupBlockEmpty(iterator_range< BasicBlock::iterator > R)
static Value * ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB, Value *AlternativeV=nullptr)
static Value * createLogicalOp(IRBuilderBase &Builder, Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="")
static void hoistConditionalLoadsStores(CondBrInst *BI, SmallVectorImpl< Instruction * > &SpeculatedConditionalLoadsStores, std::optional< bool > Invert, Instruction *Sel)
If the target supports conditional faulting, we look for the following pattern:
static bool shouldHoistCommonInstructions(Instruction *I1, Instruction *I2, const TargetTransformInfo &TTI)
Helper function for hoistCommonCodeFromSuccessors.
static bool reduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder, const DataLayout &DL, const TargetTransformInfo &TTI)
Try to transform a switch that has "holes" in it to a contiguous sequence of cases.
static bool safeToMergeTerminators(Instruction *SI1, Instruction *SI2, SmallSetVector< BasicBlock *, 4 > *FailBlocks=nullptr)
Return true if it is safe to merge these two terminator instructions together.
SkipFlags
@ SkipReadMem
@ SkipSideEffect
@ SkipImplicitControlFlow
static bool simplifySwitchDefaultBranch(SwitchInst *SI, DomTreeUpdater *DTU, const DataLayout &DL, AssumptionCache *AC)
static bool incomingValuesAreCompatible(BasicBlock *BB, ArrayRef< BasicBlock * > IncomingBlocks, SmallPtrSetImpl< Value * > *EquivalenceSet=nullptr)
Return true if all the PHI nodes in the basic block BB receive compatible (identical) incoming values...
static void createUnreachableSwitchDefault(SwitchInst *Switch, DomTreeUpdater *DTU, bool RemoveOrigDefaultBlock=true)
static Value * foldSwitchToSelect(const SwitchCaseResultVectorTy &ResultVector, Constant *DefaultResult, Value *Condition, IRBuilder<> &Builder, const DataLayout &DL, ArrayRef< uint32_t > BranchWeights)
static bool sinkCommonCodeFromPredecessors(BasicBlock *BB, DomTreeUpdater *DTU)
Check whether BB's predecessors end with unconditional branches.
static bool isTypeLegalForLookupTable(Type *Ty, const TargetTransformInfo &TTI, const DataLayout &DL)
static bool eliminateDeadSwitchCases(SwitchInst *SI, DomTreeUpdater *DTU, AssumptionCache *AC, const DataLayout &DL)
Compute masked bits for the condition of a switch and use it to remove dead cases.
static bool blockIsSimpleEnoughToThreadThrough(BasicBlock *BB, BlocksSet &NonLocalUseBlocks)
Return true if we can thread a branch across this block.
static bool foldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI, DomTreeUpdater *DTU, AssumptionCache *AC, const DataLayout &DL, bool SpeculateUnpredictables)
Given a BB that starts with the specified two-entry PHI node, see if we can eliminate it.
static bool findReaching(BasicBlock *BB, BasicBlock *DefBB, BlocksSet &ReachesNonLocalUses)
static bool extractPredSuccWeights(CondBrInst *PBI, CondBrInst *BI, uint64_t &PredTrueWeight, uint64_t &PredFalseWeight, uint64_t &SuccTrueWeight, uint64_t &SuccFalseWeight)
Return true if either PBI or BI has branch weight available, and store the weights in {Pred|Succ}...
static bool shouldUseSwitchConditionAsTableIndex(ConstantInt &MinCaseVal, const ConstantInt &MaxCaseVal, bool HasDefaultResults, const SmallVector< Type * > &ResultTypes, const DataLayout &DL, const TargetTransformInfo &TTI)
static InstructionCost computeSpeculationCost(const User *I, const TargetTransformInfo &TTI)
Compute an abstract "cost" of speculating the given instruction, which is assumed to be safe to specu...
static bool performBranchToCommonDestFolding(CondBrInst *BI, CondBrInst *PBI, DomTreeUpdater *DTU, MemorySSAUpdater *MSSAU, const TargetTransformInfo *TTI)
static std::optional< unsigned > getDenseSwitchRangeReductionShift(ArrayRef< int64_t > Values, int64_t Base, bool OptSize)
SmallPtrSet< BasicBlock *, 8 > BlocksSet
static unsigned skippedInstrFlags(Instruction *I)
static bool mergeCompatibleInvokes(BasicBlock *BB, DomTreeUpdater *DTU)
If this block is a landingpad exception handling block, categorize all the predecessor invokes into s...
static bool replacingOperandWithVariableIsCheap(const Instruction *I, int OpIdx)
static void eraseTerminatorAndDCECond(Instruction *TI, MemorySSAUpdater *MSSAU=nullptr)
static void eliminateBlockCases(BasicBlock *BB, std::vector< ValueEqualityComparisonCase > &Cases)
Given a vector of bb/value pairs, remove any entries in the list that match the specified block.
static bool mergeConditionalStores(CondBrInst *PBI, CondBrInst *QBI, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
static bool mergeNestedCondBranch(CondBrInst *BI, DomTreeUpdater *DTU)
Fold the following pattern: bb0: br i1 cond1, label bb1, label bb2 bb1: br i1 cond2,...
static void sinkLastInstruction(ArrayRef< BasicBlock * > Blocks)
static size_t mapCaseToResult(ConstantInt *CaseVal, SwitchCaseResultVectorTy &UniqueResults, Constant *Result)
static bool tryWidenCondBranchToCondBranch(CondBrInst *PBI, CondBrInst *BI, DomTreeUpdater *DTU)
If the previous block ended with a widenable branch, determine if reusing the target block is profita...
static void mergeCompatibleInvokesImpl(ArrayRef< InvokeInst * > Invokes, DomTreeUpdater *DTU)
static bool mergeIdenticalBBs(ArrayRef< BasicBlock * > Candidates, DomTreeUpdater *DTU)
static void getBranchWeights(Instruction *TI, SmallVectorImpl< uint64_t > &Weights)
Get Weights of a given terminator, the default weight is at the front of the vector.
static bool tryToMergeLandingPad(LandingPadInst *LPad, UncondBrInst *BI, BasicBlock *BB, DomTreeUpdater *DTU)
Given an block with only a single landing pad and a unconditional branch try to find another basic bl...
static bool initializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest, SwitchCaseResultVectorTy &UniqueResults, Constant *&DefaultResult, const DataLayout &DL, uintptr_t MaxUniqueResults)
static Value * isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, BasicBlock *StoreBB, BasicBlock *EndBB, Instruction *&PreviousAccess)
Determine if we can hoist sink a sole store instruction out of a conditional block.
static Constant * lookupConstant(Value *V, const SmallDenseMap< Value *, Constant * > &ConstantPool)
If V is a Constant, return it.
static bool SimplifyCondBranchToCondBranch(CondBrInst *PBI, CondBrInst *BI, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
If we have a conditional branch as a predecessor of another block, this function tries to simplify it...
static bool canSinkInstructions(ArrayRef< Instruction * > Insts, DenseMap< const Use *, SmallVector< Value *, 4 > > &PHIOperands)
static void hoistLockstepIdenticalDbgVariableRecords(Instruction *TI, Instruction *I1, SmallVectorImpl< Instruction * > &OtherInsts)
Hoists DbgVariableRecords from I1 and OtherInstrs that are identical in lock-step to TI.
static bool removeEmptyCleanup(CleanupReturnInst *RI, DomTreeUpdater *DTU)
static bool trySwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder, DomTreeUpdater *DTU, const DataLayout &DL)
If a switch is only used to initialize one or more phi nodes in a common successor block with only tw...
static bool removeUndefIntroducingPredecessor(BasicBlock *BB, DomTreeUpdater *DTU, AssumptionCache *AC)
If BB has an incoming value that will always trigger undefined behavior (eg.
static bool isUncontrolledConvergentCall(CallBase *CB)
static bool simplifySwitchWhenUMin(SwitchInst *SI, DomTreeUpdater *DTU)
Tries to transform the switch when the condition is umin with a constant.
static bool isSafeCheapLoadStore(const Instruction *I, const TargetTransformInfo &TTI)
static ConstantInt * getKnownValueOnEdge(Value *V, BasicBlock *From, BasicBlock *To)
static bool dominatesMergePoint(Value *V, BasicBlock *BB, Instruction *InsertPt, SmallPtrSetImpl< Instruction * > &AggressiveInsts, InstructionCost &Cost, InstructionCost Budget, const TargetTransformInfo &TTI, AssumptionCache *AC, SmallPtrSetImpl< Instruction * > &ZeroCostInstructions, unsigned Depth=0)
If we have a merge point of an "if condition" as accepted above, return true if the specified value d...
static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock, CondBrInst *RangeCheckBranch, Constant *DefaultValue, const SmallVectorImpl< std::pair< ConstantInt *, Constant * > > &Values)
Try to reuse the switch table index compare.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1551
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1998
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
Definition APInt.h:1594
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1979
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM_ABI bool getValueAsBool() const
Return the attribute's value as a boolean.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:509
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasTerminator() const LLVM_READONLY
Returns whether the block has a terminator.
Definition BasicBlock.h:232
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:666
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:463
LLVM_ABI const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI void flushTerminatorDbgRecords()
Eject any debug-info trailing at the end of a block.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrPseudoProbe() const
Returns an iterator to the first instruction in this block that is not a PHINode or a pseudo operatio...
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
size_t size() const
Definition BasicBlock.h:461
LLVM_ABI bool isLandingPad() const
Return true if this basic block is a landing pad.
LLVM_ABI bool hasNPredecessorsOrMore(unsigned N) const
Return true if this block has N predecessors or more.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition BasicBlock.h:638
LLVM_ABI const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
BasicBlock * getBasicBlock() const
Definition Constants.h:1125
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
BranchProbability getCompl() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void addRangeRetAttr(const ConstantRange &CR)
adds the range attribute to the list of attributes.
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
bool isConvergent() const
Determine if the invoke is convergent.
Value * getConvergenceControlToken() const
Return the convergence control token for this call, if it exists.
bool isDataOperand(const Use *U) const
bool tryIntersectAttributes(const CallBase *Other)
Try to intersect the attributes from 'this' CallBase and the 'Other' CallBase.
This class represents a function call, abstracting a target machine's calling convention.
mapped_iterator< op_iterator, DerefFnTy > handler_iterator
CleanupPadInst * getCleanupPad() const
Convenience accessor.
BasicBlock * getUnwindDest() const
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
bool isEquality() const
Determine if this is an equals/not equals predicate.
Definition InstrTypes.h:978
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Conditional Branch instruction.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void setCondition(Value *V)
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1316
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
ConstantFolder - Create constants with minimum, target independent, folding.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
bool isNegative() const
Definition Constants.h:214
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
IntegerType * getIntegerType() const
Variant of the getType() method to always return an IntegerType, which reduces the amount of casting ...
Definition Constants.h:198
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A constant pointer value that points to null.
Definition Constants.h:716
This class represents a range of values.
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
LLVM_ABI ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
const APInt & getLower() const
Return the lower value for this range.
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI bool isSizeLargerThan(uint64_t MaxSize) const
Compare set size of this range with Value.
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI bool isUpperWrapped() const
Return true if the exclusive upper bound wraps around the unsigned domain.
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange inverse() const
Return a new range that is the logical not of the current set.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
LLVM_ABI bool isOneValue() const
Returns true if the value is one.
Definition Constants.cpp:82
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Base class for non-instruction debug metadata records that have positions within IR.
LLVM_ABI void removeFromParent()
simple_ilist< DbgRecord >::iterator self_iterator
Record of a variable value-assignment, aka a non instruction representation of the dbg....
A debug info location.
Definition DebugLoc.h:126
bool isSameSourceLocation(const DebugLoc &Other) const
Return true if the source locations match, ignoring isImplicitCode and source atom info.
Definition DebugLoc.h:250
static DebugLoc getTemporary()
Definition DebugLoc.h:152
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
Definition DebugLoc.cpp:186
static LLVM_ABI DebugLoc getMergedLocations(ArrayRef< DebugLoc > Locs)
Try to combine the vector of locations passed as input in a single one.
Definition DebugLoc.cpp:173
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
ValueT & at(const_arg_type_t< KeyT > Val)
Return the entry for the specified key, or abort if no such entry exists.
Definition DenseMap.h:811
void reserve(size_type NumEntries)
Grow the DenseMap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:721
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
const BasicBlock & getEntryBlock() const
Definition Function.h:794
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2398
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2139
CondBrInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition IRBuilder.h:1212
LLVM_ABI Value * CreateSelectFMF(Value *C, Value *True, Value *False, FMFSource FMFSource, const Twine &Name="", Instruction *MDFrom=nullptr)
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition IRBuilder.h:445
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
BasicBlock::iterator GetInsertPoint() const
Definition IRBuilder.h:176
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition IRBuilder.h:2735
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:228
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1528
LLVM_ABI CallInst * CreateAssumption(Value *Cond)
Create an assume intrinsic call that allows the optimizer to assume that the provided condition will ...
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition IRBuilder.h:2019
UncondBrInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition IRBuilder.h:1206
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1850
SwitchInst * CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases=10, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a switch instruction with the specified value, default dest, and with a hint for the number of...
Definition IRBuilder.h:1235
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2382
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1907
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2121
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1925
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1418
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2233
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:450
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition IRBuilder.h:2107
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition IRBuilder.h:2323
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:196
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2492
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1588
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1452
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
Definition IRBuilder.h:74
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
Indirect Branch Instruction.
BasicBlock * getDestination(unsigned i)
Return the specified destination.
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
LLVM_ABI void removeDestination(unsigned i)
This method removes the specified successor from the indirectbr instruction.
LLVM_ABI void dropUBImplyingAttrsAndMetadata(ArrayRef< unsigned > Keep={})
Drop any attributes or metadata that can cause immediate undefined behavior.
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI iterator_range< simple_ilist< DbgRecord >::iterator > cloneDebugInfoFrom(const Instruction *From, std::optional< simple_ilist< DbgRecord >::iterator > FromHere=std::nullopt, bool InsertAtHead=false)
Clone any debug-info attached to From onto this instruction.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange() const
Return a range over the DbgRecords attached to this instruction.
LLVM_ABI void dropLocation()
Drop the instruction's debug location.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
bool isTerminator() const
iterator_range< user_iterator > users()
LLVM_ABI bool isUsedOutsideOfBlock(const BasicBlock *BB) const LLVM_READONLY
Return true if there are any uses of this instruction in blocks other than the specified block.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
@ CompareUsingIntersectedAttrs
Check for equivalence with intersected callbase attrs.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
LLVM_ABI bool isIdenticalTo(const Instruction *I) const LLVM_READONLY
Return true if the specified instruction is exactly identical to the current one.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI void applyMergedLocation(DebugLoc LocA, DebugLoc LocB)
Merge 2 debug locations and apply it to the Instruction.
LLVM_ABI void dropDbgRecords()
Erase any DbgRecords attached to this instruction.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Invoke instruction.
void setNormalDest(BasicBlock *B)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
The landingpad instruction holds all of the information necessary to generate correct exception handl...
An instruction for reading from memory.
static unsigned getPointerOperandIndex()
Iterates through instructions in a set of blocks in reverse order from the first non-terminator.
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
Metadata node.
Definition Metadata.h:1081
Helper class to manipulate !mmra metadata nodes.
bool empty() const
Definition MapVector.h:79
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
size_type size() const
Definition MapVector.h:58
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Value * getValue() const
Convenience accessor.
Return a value (possibly void), from a function.
This class represents the LLVM 'select' instruction.
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void insert_range(Range &&R)
Definition SetVector.h:182
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this store instruction.
Align getAlign() const
bool isSimple() const
Value * getValueOperand()
bool isUnordered() const
static unsigned getPointerOperandIndex()
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this store instruction.
Value * getPointerOperand()
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
A wrapper class to simplify modification of SwitchInst cases along with their prof branch_weights met...
LLVM_ABI void setSuccessorWeight(unsigned idx, CaseWeightOpt W)
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W)
Delegate the call to the underlying SwitchInst::addCase() and set the specified branch weight for the...
LLVM_ABI CaseWeightOpt getSuccessorWeight(unsigned idx)
LLVM_ABI void replaceDefaultDest(SwitchInst::CaseIt I)
Replace the default destination by given case.
std::optional< uint32_t > CaseWeightOpt
LLVM_ABI SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I)
Delegate the call to the underlying SwitchInst::removeCase() and remove correspondent branch weight.
Multiway switch.
CaseIt case_end()
Returns a read/write iterator that points one past the last in the SwitchInst.
BasicBlock * getSuccessor(unsigned idx) const
void setCondition(Value *V)
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
CaseIteratorImpl< CaseHandle > CaseIt
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
unsigned getNumSuccessors() const
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
TargetCostKind
The kind of cost model.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCC_Free
Expected to fold away in lowering.
@ TCC_Basic
The cost of a typical 'add' instruction.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
Unconditional Branch instruction.
void setSuccessor(BasicBlock *NewSucc)
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i=0) const
'undef' values are things that do not have specified contents.
Definition Constants.h:1657
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
LLVM_ABI void set(Value *Val)
Definition Value.h:876
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
const Use & getOperandUse(unsigned i) const
Definition User.h:220
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
static constexpr uint64_t MaximumAlignment
Definition Value.h:801
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:50
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition Value.cpp:143
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
Represents an op.with.overflow intrinsic.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
A range adaptor for a pair of iterators.
Changed
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
NoWrapTrunc_match< OpTy, TruncInst::NoUnsignedWrap > m_NUWTrunc(const OpTy &Op)
Matches trunc nuw.
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
SmallVector< DbgVariableRecord * > getDVRAssignmentMarkers(const Instruction *Inst)
Return a range of dbg_assign records for which Inst performs the assignment they encode.
Definition DebugInfo.h:209
LLVM_ABI void deleteAssignmentMarkers(const Instruction *Inst)
Delete the llvm.dbg.assign intrinsics linked to Inst.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
constexpr double e
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
constexpr auto not_equal_to(T &&Arg)
Functor variant of std::not_equal_to that can be used as a UnaryPredicate in functional algorithms li...
Definition STLExtras.h:2196
LLVM_ABI bool foldBranchToCommonDest(CondBrInst *BI, llvm::DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, const TargetTransformInfo *TTI=nullptr, AssumptionCache *AC=nullptr, unsigned BonusInstThreshold=1)
If this basic block is ONLY a setcc and a branch, and if a predecessor branches to us and one of our ...
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:61
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:520
bool succ_empty(const Instruction *I)
Definition CFG.h:141
LLVM_ABI bool IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB)
Check if we can prove that all paths starting from this block converge to a block that either has a @...
LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Definition Local.cpp:133
static cl::opt< unsigned > MaxSwitchCasesPerResult("max-switch-cases-per-result", cl::Hidden, cl::init(16), cl::desc("Limit cases to analyze when converting a switch to select"))
InstructionCost Cost
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
static cl::opt< bool > SpeculateOneExpensiveInst("speculate-one-expensive-inst", cl::Hidden, cl::init(true), cl::desc("Allow exactly one expensive instruction to be speculatively " "executed"))
@ Known
Known to have no common set bits.
@ Dead
Unused definition.
auto pred_end(const MachineBasicBlock *BB)
void set_intersect(S1Ty &S1, const S2Ty &S2)
set_intersect(A, B) - Compute A := A ^ B Identical to set_intersection, except that it works on set<>...
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
auto accumulate(R &&Range, E &&Init)
Wrapper for std::accumulate.
Definition STLExtras.h:1718
constexpr from_range_t from_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI MDNode * getBranchWeightMDNode(const Instruction &I)
Get the branch weights metadata node.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
static cl::opt< unsigned > MaxSpeculationDepth("max-speculation-depth", cl::Hidden, cl::init(10), cl::desc("Limit maximum recursion depth when calculating costs of " "speculatively executed instructions"))
OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P)
Provide wrappers to std::copy_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1807
static cl::opt< unsigned > PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2), cl::desc("Control the amount of phi node folding to perform (default = 2)"))
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
static cl::opt< bool > MergeCondStoresAggressively("simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false), cl::desc("When merging conditional stores, do so even if the resultant " "basic blocks are unlikely to be if-converted as a result"))
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
static cl::opt< unsigned > BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden, cl::init(2), cl::desc("Maximum cost of combining conditions when " "folding branches"))
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:380
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
static cl::opt< bool > SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), cl::desc("Sink common instructions down to the end block"))
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2216
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
static cl::opt< bool > HoistStoresWithCondFaulting("simplifycfg-hoist-stores-with-cond-faulting", cl::Hidden, cl::init(true), cl::desc("Hoist stores if the target supports conditional faulting"))
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
constexpr detail::StaticCastFunc< To > StaticCastTo
Function objects corresponding to the Cast types defined above.
Definition Casting.h:882
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI CondBrInst * GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, BasicBlock *&IfFalse)
Check whether BB is the merge point of a if-region.
LLVM_ABI bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes,...
Definition Local.cpp:1145
void RemapDbgRecordRange(Module *M, iterator_range< DbgRecordIterator > Range, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecords Range using the value map VM.
LLVM_ABI void InvertBranch(CondBrInst *PBI, IRBuilderBase &Builder)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
static cl::opt< bool > EnableMergeCompatibleInvokes("simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(true), cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"))
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition ValueMapper.h:98
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition ValueMapper.h:80
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
LLVM_ABI Instruction * removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
Replace 'BB's terminator with one that does not have an unwind successor block.
Definition Local.cpp:2871
auto succ_size(const MachineBasicBlock *BB)
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:552
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
static cl::opt< unsigned > MaxJumpThreadingLiveBlocks("max-jump-threading-live-blocks", cl::Hidden, cl::init(24), cl::desc("Limit number of blocks a define in a threaded block is allowed " "to be live in"))
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition Local.cpp:3124
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:3403
@ 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:3909
DWARFExpression::Operation Op
LLVM_ABI bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, unsigned MaxUsesToExplore=0)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
LLVM_ABI bool FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
void RemapDbgRecord(Module *M, DbgRecord *DR, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecord DR using the value map VM.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
auto sum_of(R &&Range, E Init=E{0})
Returns the sum of all values in Range with Init initial value.
Definition STLExtras.h:1733
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
static cl::opt< bool > HoistCondStores("simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), cl::desc("Hoist conditional stores if an unconditional store precedes"))
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
LLVM_ABI bool simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, DomTreeUpdater *DTU=nullptr, const SimplifyCFGOptions &Options={}, ArrayRef< WeakVH > LoopHeaders={})
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
auto predecessors(const MachineBasicBlock *BB)
static cl::opt< unsigned > HoistLoadsStoresWithCondFaultingThreshold("hoist-loads-stores-with-cond-faulting-threshold", cl::Hidden, cl::init(6), cl::desc("Control the maximal conditional load/store that we are willing " "to speculatively execute to eliminate conditional branch " "(default = 6)"))
static cl::opt< bool > HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true), cl::desc("Hoist common instructions up to the parent block"))
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
static cl::opt< unsigned > TwoEntryPHINodeFoldingThreshold("two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4), cl::desc("Control the maximal total instruction cost that we are willing " "to speculatively execute to fold a 2-entry PHI node into a " "select (default = 4)"))
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
SmallVector< uint64_t, 2 > getDisjunctionWeights(const SmallVector< T1, 2 > &B1, const SmallVector< T2, 2 > &B2)
Get the branch weights of a branch conditioned on b1 || b2, where b1 and b2 are 2 booleans that are t...
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition STLExtras.h:1612
LLVM_ABI bool hasBranchWeightMD(const Instruction &I)
Checks if an instructions has Branch Weight Metadata.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const SimplifyQuery &Q, bool IgnoreFree=false)
Equivalent to isDereferenceableAndAlignedPointer with an alignment of 1.
Definition Loads.cpp:266
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
static cl::opt< bool > HoistLoadsWithCondFaulting("simplifycfg-hoist-loads-with-cond-faulting", cl::Hidden, cl::init(true), cl::desc("Hoist loads if the target supports conditional faulting"))
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
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:1501
@ Keep
No function return thunk.
Definition CodeGen.h:317
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI void RemapSourceAtom(Instruction *I, ValueToValueMapTy &VM)
Remap source location atom.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:287
LLVM_ABI bool isWritableObject(const Value *Object, bool &ExplicitlyDereferenceableOnly)
Return true if the Object is writable, in the sense that any location based on this pointer that can ...
LLVM_ABI void mapAtomInstance(const DebugLoc &DL, ValueToValueMapTy &VMap)
Mark a cloned instruction as a new instance so that its source loc can be updated when remapped.
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:368
LLVM_ABI void extractFromBranchWeightMD64(const MDNode *ProfileData, SmallVectorImpl< uint64_t > &Weights)
Faster version of extractBranchWeights() that skips checks and must only be called with "branch_weigh...
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
SmallVectorImpl< ConstantInt * > * Cases
SmallVectorImpl< ConstantInt * > * OtherCases
Checking whether two BBs are equal depends on the contents of the BasicBlock and the incoming values ...
SmallDenseMap< BasicBlock *, Value *, 8 > BB2ValueMap
Phi2IVsMap * PhiPredIVs
DenseMap< PHINode *, BB2ValueMap > Phi2IVsMap
static bool canBeMerged(const BasicBlock *BB)
BasicBlock * BB
LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
static bool isEqual(const EqualBBWrapper *LHS, const EqualBBWrapper *RHS)
static unsigned getHashValue(const EqualBBWrapper *EBW)
An information struct used to provide DenseMap with the various necessary components for a given valu...
Matching combinators.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342