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