1//===- JumpThreading.cpp - Thread control through conditional blocks ------===//
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// This file implements the Jump Threading pass.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Transforms/Scalar/JumpThreading.h"
14#include "ScalarOptions.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/MapVector.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/ScopeExit.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/Analysis/BlockFrequencyInfo.h"
24#include "llvm/Analysis/BranchProbabilityInfo.h"
25#include "llvm/Analysis/CFG.h"
26#include "llvm/Analysis/ConstantFolding.h"
27#include "llvm/Analysis/GlobalsModRef.h"
28#include "llvm/Analysis/GuardUtils.h"
29#include "llvm/Analysis/InstructionSimplify.h"
30#include "llvm/Analysis/LazyValueInfo.h"
31#include "llvm/Analysis/Loads.h"
32#include "llvm/Analysis/LoopInfo.h"
33#include "llvm/Analysis/MemoryLocation.h"
34#include "llvm/Analysis/PostDominators.h"
35#include "llvm/Analysis/TargetLibraryInfo.h"
36#include "llvm/Analysis/TargetTransformInfo.h"
37#include "llvm/Analysis/ValueTracking.h"
38#include "llvm/IR/BasicBlock.h"
39#include "llvm/IR/CFG.h"
40#include "llvm/IR/Constant.h"
41#include "llvm/IR/ConstantRange.h"
42#include "llvm/IR/Constants.h"
43#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/DebugInfo.h"
45#include "llvm/IR/Dominators.h"
46#include "llvm/IR/Function.h"
47#include "llvm/IR/InstrTypes.h"
48#include "llvm/IR/Instruction.h"
49#include "llvm/IR/Instructions.h"
50#include "llvm/IR/IntrinsicInst.h"
51#include "llvm/IR/Intrinsics.h"
52#include "llvm/IR/LLVMContext.h"
53#include "llvm/IR/MDBuilder.h"
54#include "llvm/IR/Metadata.h"
55#include "llvm/IR/Module.h"
56#include "llvm/IR/PassManager.h"
57#include "llvm/IR/PatternMatch.h"
58#include "llvm/IR/ProfDataUtils.h"
59#include "llvm/IR/Type.h"
60#include "llvm/IR/Use.h"
61#include "llvm/IR/Value.h"
62#include "llvm/Support/BlockFrequency.h"
63#include "llvm/Support/BranchProbability.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/CommandLine.h"
66#include "llvm/Support/Debug.h"
67#include "llvm/Support/raw_ostream.h"
68#include "llvm/Transforms/Utils/BasicBlockUtils.h"
69#include "llvm/Transforms/Utils/Cloning.h"
70#include "llvm/Transforms/Utils/Local.h"
71#include "llvm/Transforms/Utils/SSAUpdater.h"
72#include "llvm/Transforms/Utils/ValueMapper.h"
73#include <cassert>
74#include <cstdint>
75#include <iterator>
76#include <memory>
77#include <utility>
78
79using namespace llvm;
80using namespace jumpthreading;
81
82#define DEBUG_TYPE "jump-threading"
83
84STATISTIC(NumThreads, "Number of jumps threaded");
85STATISTIC(NumFolds, "Number of terminators folded");
86STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi");
87
88namespace llvm {
89extern cl::opt<bool> ProfcheckDisableMetadataFixes;
90}
91
92JumpThreadingPass::JumpThreadingPass(int T) {
93 DefaultBBDupThreshold = (T == -1) ? 6 : unsigned(T);
94}
95
96// Update branch probability information according to conditional
97// branch probability. This is usually made possible for cloned branches
98// in inline instances by the context specific profile in the caller.
99// For instance,
100//
101// [Block PredBB]
102// [Branch PredBr]
103// if (t) {
104// Block A;
105// } else {
106// Block B;
107// }
108//
109// [Block BB]
110// cond = PN([true, %A], [..., %B]); // PHI node
111// [Branch CondBr]
112// if (cond) {
113// ... // P(cond == true) = 1%
114// }
115//
116// Here we know that when block A is taken, cond must be true, which means
117// P(cond == true | A) = 1
118//
119// Given that P(cond == true) = P(cond == true | A) * P(A) +
120// P(cond == true | B) * P(B)
121// we get:
122// P(cond == true ) = P(A) + P(cond == true | B) * P(B)
123//
124// which gives us:
125// P(A) is less than P(cond == true), i.e.
126// P(t == true) <= P(cond == true)
127//
128// In other words, if we know P(cond == true) is unlikely, we know
129// that P(t == true) is also unlikely.
130//
131static void updatePredecessorProfileMetadata(PHINode *PN, BasicBlock *BB) {
132 CondBrInst *CondBr = dyn_cast<CondBrInst>(Val: BB->getTerminator());
133 if (!CondBr)
134 return;
135
136 uint64_t TrueWeight, FalseWeight;
137 if (!extractBranchWeights(I: *CondBr, TrueVal&: TrueWeight, FalseVal&: FalseWeight))
138 return;
139
140 if (TrueWeight + FalseWeight == 0)
141 // Zero branch_weights do not give a hint for getting branch probabilities.
142 // Technically it would result in division by zero denominator, which is
143 // TrueWeight + FalseWeight.
144 return;
145
146 // Returns the outgoing edge of the dominating predecessor block
147 // that leads to the PhiNode's incoming block:
148 auto GetPredOutEdge =
149 [](BasicBlock *IncomingBB,
150 BasicBlock *PhiBB) -> std::pair<BasicBlock *, BasicBlock *> {
151 auto *PredBB = IncomingBB;
152 auto *SuccBB = PhiBB;
153 SmallPtrSet<BasicBlock *, 16> Visited;
154 while (true) {
155 if (isa<CondBrInst>(Val: PredBB->getTerminator()))
156 return {PredBB, SuccBB};
157 Visited.insert(Ptr: PredBB);
158 auto *SinglePredBB = PredBB->getSinglePredecessor();
159 if (!SinglePredBB)
160 return {nullptr, nullptr};
161
162 // Stop searching when SinglePredBB has been visited. It means we see
163 // an unreachable loop.
164 if (Visited.count(Ptr: SinglePredBB))
165 return {nullptr, nullptr};
166
167 SuccBB = PredBB;
168 PredBB = SinglePredBB;
169 }
170 };
171
172 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
173 Value *PhiOpnd = PN->getIncomingValue(i);
174 ConstantInt *CI = dyn_cast<ConstantInt>(Val: PhiOpnd);
175
176 if (!CI || !CI->getType()->isIntegerTy(BitWidth: 1))
177 continue;
178
179 BranchProbability BP =
180 (CI->isOne() ? BranchProbability::getBranchProbability(
181 Numerator: TrueWeight, Denominator: TrueWeight + FalseWeight)
182 : BranchProbability::getBranchProbability(
183 Numerator: FalseWeight, Denominator: TrueWeight + FalseWeight));
184
185 auto PredOutEdge = GetPredOutEdge(PN->getIncomingBlock(i), BB);
186 if (!PredOutEdge.first)
187 return;
188
189 BasicBlock *PredBB = PredOutEdge.first;
190 CondBrInst *PredBr = dyn_cast<CondBrInst>(Val: PredBB->getTerminator());
191 if (!PredBr)
192 return;
193
194 uint64_t PredTrueWeight, PredFalseWeight;
195 // FIXME: We currently only set the profile data when it is missing.
196 // With PGO, this can be used to refine even existing profile data with
197 // context information. This needs to be done after more performance
198 // testing.
199 if (extractBranchWeights(I: *PredBr, TrueVal&: PredTrueWeight, FalseVal&: PredFalseWeight))
200 continue;
201
202 // We can not infer anything useful when BP >= 50%, because BP is the
203 // upper bound probability value.
204 if (BP >= BranchProbability(50, 100))
205 continue;
206
207 uint32_t Weights[2];
208 if (PredBr->getSuccessor(i: 0) == PredOutEdge.second) {
209 Weights[0] = BP.getNumerator();
210 Weights[1] = BP.getCompl().getNumerator();
211 } else {
212 Weights[0] = BP.getCompl().getNumerator();
213 Weights[1] = BP.getNumerator();
214 }
215 setBranchWeights(I&: *PredBr, Weights, IsExpected: hasBranchWeightOrigin(I: *PredBr));
216 }
217}
218
219PreservedAnalyses JumpThreadingPass::run(Function &F,
220 FunctionAnalysisManager &AM) {
221 auto &TTI = AM.getResult<TargetIRAnalysis>(IR&: F);
222 // Jump Threading has no sense for the targets with divergent CF
223 if (TTI.hasBranchDivergence(F: &F))
224 return PreservedAnalyses::all();
225 auto &TLI = AM.getResult<TargetLibraryAnalysis>(IR&: F);
226 auto &LVI = AM.getResult<LazyValueAnalysis>(IR&: F);
227 auto &AA = AM.getResult<AAManager>(IR&: F);
228 auto &DT = AM.getResult<DominatorTreeAnalysis>(IR&: F);
229
230 bool Changed =
231 runImpl(F, FAM: &AM, TLI: &TLI, TTI: &TTI, LVI: &LVI, AA: &AA,
232 DTU: std::make_unique<DomTreeUpdater>(
233 args: &DT, args: nullptr, args: DomTreeUpdater::UpdateStrategy::Lazy),
234 BFI: nullptr, BPI: nullptr);
235
236 if (!Changed)
237 return PreservedAnalyses::all();
238
239
240 getDomTreeUpdater()->flush();
241
242#if defined(EXPENSIVE_CHECKS)
243 assert(getDomTreeUpdater()->getDomTree().verify(
244 DominatorTree::VerificationLevel::Full) &&
245 "DT broken after JumpThreading");
246 assert((!getDomTreeUpdater()->hasPostDomTree() ||
247 getDomTreeUpdater()->getPostDomTree().verify(
248 PostDominatorTree::VerificationLevel::Full)) &&
249 "PDT broken after JumpThreading");
250#else
251 assert(getDomTreeUpdater()->getDomTree().verify(
252 DominatorTree::VerificationLevel::Fast) &&
253 "DT broken after JumpThreading");
254 assert((!getDomTreeUpdater()->hasPostDomTree() ||
255 getDomTreeUpdater()->getPostDomTree().verify(
256 PostDominatorTree::VerificationLevel::Fast)) &&
257 "PDT broken after JumpThreading");
258#endif
259
260 return getPreservedAnalysis();
261}
262
263bool JumpThreadingPass::runImpl(Function &F_, FunctionAnalysisManager *FAM_,
264 TargetLibraryInfo *TLI_,
265 TargetTransformInfo *TTI_, LazyValueInfo *LVI_,
266 AliasAnalysis *AA_,
267 std::unique_ptr<DomTreeUpdater> DTU_,
268 BlockFrequencyInfo *BFI_,
269 BranchProbabilityInfo *BPI_) {
270 LLVM_DEBUG(dbgs() << "Jump threading on function '" << F_.getName() << "'\n");
271 Opts = &ScalarOptions::Global;
272 F = &F_;
273 FAM = FAM_;
274 TLI = TLI_;
275 TTI = TTI_;
276 LVI = LVI_;
277 AA = AA_;
278 DTU = std::move(DTU_);
279 BFI = BFI_;
280 BPI = BPI_;
281 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
282 M: F->getParent(), id: Intrinsic::experimental_guard);
283 HasGuards = GuardDecl && !GuardDecl->use_empty();
284
285 // Reduce the number of instructions duplicated when optimizing strictly for
286 // size.
287 if (Opts->jump_threading_threshold)
288 BBDupThreshold = *Opts->jump_threading_threshold;
289 else if (F->hasMinSize())
290 BBDupThreshold = 3;
291 else
292 BBDupThreshold = DefaultBBDupThreshold;
293
294 assert(DTU && "DTU isn't passed into JumpThreading before using it.");
295 assert(DTU->hasDomTree() && "JumpThreading relies on DomTree to proceed.");
296 DominatorTree &DT = DTU->getDomTree();
297
298 Unreachable.clear();
299 for (auto &BB : *F)
300 if (!DT.isReachableFromEntry(A: &BB))
301 Unreachable.insert(Ptr: &BB);
302
303 if (!Opts->jump_threading_across_loop_headers)
304 findLoopHeaders(F&: *F);
305
306 bool EverChanged = false;
307 bool Changed;
308 do {
309 Changed = false;
310 for (auto &BB : *F) {
311 if (Unreachable.count(Ptr: &BB))
312 continue;
313 while (processBlock(BB: &BB)) // Thread all of the branches we can over BB.
314 Changed = ChangedSinceLastAnalysisUpdate = true;
315
316 // Stop processing BB if it's the entry or is now deleted. The following
317 // routines attempt to eliminate BB and locating a suitable replacement
318 // for the entry is non-trivial.
319 if (&BB == &F->getEntryBlock() || DTU->isBBPendingDeletion(DelBB: &BB))
320 continue;
321
322 if (pred_empty(BB: &BB)) {
323 // When processBlock makes BB unreachable it doesn't bother to fix up
324 // the instructions in it. We must remove BB to prevent invalid IR.
325 LLVM_DEBUG(dbgs() << " JT: Deleting dead block '" << BB.getName()
326 << "' with terminator: " << *BB.getTerminator()
327 << '\n');
328 LoopHeaders.erase(Ptr: &BB);
329 LVI->eraseBlock(BB: &BB);
330 DeleteDeadBlock(BB: &BB, DTU: DTU.get());
331 Changed = ChangedSinceLastAnalysisUpdate = true;
332 continue;
333 }
334
335 // processBlock doesn't thread BBs with unconditional TIs. However, if BB
336 // is "almost empty", we attempt to merge BB with its sole successor.
337 if (auto *BI = dyn_cast<UncondBrInst>(Val: BB.getTerminator())) {
338 BasicBlock *Succ = BI->getSuccessor();
339 if (
340 // The terminator must be the only non-phi instruction in BB.
341 BB.getFirstNonPHIOrDbg(SkipPseudoOp: true)->isTerminator() &&
342 // Don't alter Loop headers and latches to ensure another pass can
343 // detect and transform nested loops later.
344 !LoopHeaders.count(Ptr: &BB) && !LoopHeaders.count(Ptr: Succ) &&
345 TryToSimplifyUncondBranchFromEmptyBlock(BB: &BB, DTU: DTU.get())) {
346 // BB is valid for cleanup here because we passed in DTU. F remains
347 // BB's parent until a DTU->getDomTree() event.
348 LVI->eraseBlock(BB: &BB);
349 Changed = ChangedSinceLastAnalysisUpdate = true;
350 }
351 }
352 }
353 EverChanged |= Changed;
354 } while (Changed);
355
356 // Jump threading may have introduced redundant debug values into F which
357 // should be removed.
358 if (EverChanged)
359 for (auto &BB : *F) {
360 RemoveRedundantDbgInstrs(BB: &BB);
361 }
362
363 LoopHeaders.clear();
364 return EverChanged;
365}
366
367// Replace uses of Cond with ToVal when safe to do so. If all uses are
368// replaced, we can remove Cond. We cannot blindly replace all uses of Cond
369// because we may incorrectly replace uses when guards/assumes are uses of
370// of `Cond` and we used the guards/assume to reason about the `Cond` value
371// at the end of block. RAUW unconditionally replaces all uses
372// including the guards/assumes themselves and the uses before the
373// guard/assume.
374static bool replaceFoldableUses(Instruction *Cond, Value *ToVal,
375 BasicBlock *KnownAtEndOfBB) {
376 bool Changed = false;
377 assert(Cond->getType() == ToVal->getType());
378 // We can unconditionally replace all uses in non-local blocks (i.e. uses
379 // strictly dominated by BB), since LVI information is true from the
380 // terminator of BB.
381 if (Cond->getParent() == KnownAtEndOfBB)
382 Changed |= replaceNonLocalUsesWith(From: Cond, To: ToVal);
383 for (Instruction &I : reverse(C&: *KnownAtEndOfBB)) {
384 // Replace any debug-info record users of Cond with ToVal.
385 for (DbgVariableRecord &DVR : filterDbgVars(R: I.getDbgRecordRange()))
386 DVR.replaceVariableLocationOp(OldValue: Cond, NewValue: ToVal, AllowEmpty: true);
387
388 // Reached the Cond whose uses we are trying to replace, so there are no
389 // more uses.
390 if (&I == Cond)
391 break;
392 // We only replace uses in instructions that are guaranteed to reach the end
393 // of BB, where we know Cond is ToVal.
394 if (!isGuaranteedToTransferExecutionToSuccessor(I: &I))
395 break;
396 Changed |= I.replaceUsesOfWith(From: Cond, To: ToVal);
397 }
398 if (Cond->use_empty() && !Cond->mayHaveSideEffects()) {
399 Cond->eraseFromParent();
400 Changed = true;
401 }
402 return Changed;
403}
404
405/// Return the cost of duplicating a piece of this block from first non-phi
406/// and before StopAt instruction to thread across it. Stop scanning the block
407/// when exceeding the threshold. If duplication is impossible, returns ~0U.
408static unsigned getJumpThreadDuplicationCost(const ScalarOptions &Opts,
409 const TargetTransformInfo *TTI,
410 BasicBlock *BB,
411 Instruction *StopAt,
412 unsigned Threshold) {
413 assert(StopAt->getParent() == BB && "Not an instruction from proper BB?");
414
415 // Do not duplicate the BB if it has a lot of PHI nodes.
416 // If a threadable chain is too long then the number of PHI nodes can add up,
417 // leading to a substantial increase in compile time when rewriting the SSA.
418 unsigned PhiCount = 0;
419 Instruction *FirstNonPHI = nullptr;
420 for (Instruction &I : *BB) {
421 if (!isa<PHINode>(Val: &I)) {
422 FirstNonPHI = &I;
423 break;
424 }
425 if (++PhiCount > Opts.jump_threading_phi_threshold)
426 return ~0U;
427 }
428
429 /// Ignore PHI nodes, these will be flattened when duplication happens.
430 BasicBlock::const_iterator I(FirstNonPHI);
431
432 // FIXME: THREADING will delete values that are just used to compute the
433 // branch, so they shouldn't count against the duplication cost.
434
435 unsigned Bonus = 0;
436 if (BB->getTerminator() == StopAt) {
437 // Threading through a switch statement is particularly profitable. If this
438 // block ends in a switch, decrease its cost to make it more likely to
439 // happen.
440 if (isa<SwitchInst>(Val: StopAt))
441 Bonus = 6;
442
443 // The same holds for indirect branches, but slightly more so.
444 if (isa<IndirectBrInst>(Val: StopAt))
445 Bonus = 8;
446 }
447
448 // Bump the threshold up so the early exit from the loop doesn't skip the
449 // terminator-based Size adjustment at the end.
450 Threshold += Bonus;
451
452 // Sum up the cost of each instruction until we get to the terminator. Don't
453 // include the terminator because the copy won't include it.
454 unsigned Size = 0;
455 for (; &*I != StopAt; ++I) {
456
457 // Stop scanning the block if we've reached the threshold.
458 if (Size > Threshold)
459 return Size;
460
461 // Bail out if this instruction gives back a token type, it is not possible
462 // to duplicate it if it is used outside this BB.
463 if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB))
464 return ~0U;
465
466 // Blocks with NoDuplicate are modelled as having infinite cost, so they
467 // are never duplicated.
468 if (const CallInst *CI = dyn_cast<CallInst>(Val&: I))
469 if (CI->cannotDuplicate() || CI->isConvergent())
470 return ~0U;
471
472 if (TTI->getInstructionCost(U: &*I, CostKind: TargetTransformInfo::TCK_SizeAndLatency) ==
473 TargetTransformInfo::TCC_Free)
474 continue;
475
476 // All other instructions count for at least one unit.
477 ++Size;
478
479 // Calls are more expensive. If they are non-intrinsic calls, we model them
480 // as having cost of 4. If they are a non-vector intrinsic, we model them
481 // as having cost of 2 total, and if they are a vector intrinsic, we model
482 // them as having cost 1.
483 if (const CallInst *CI = dyn_cast<CallInst>(Val&: I)) {
484 if (!isa<IntrinsicInst>(Val: CI))
485 Size += 3;
486 else if (!CI->getType()->isVectorTy())
487 Size += 1;
488 }
489 }
490
491 return Size > Bonus ? Size - Bonus : 0;
492}
493
494/// findLoopHeaders - We do not want jump threading to turn proper loop
495/// structures into irreducible loops. Doing this breaks up the loop nesting
496/// hierarchy and pessimizes later transformations. To prevent this from
497/// happening, we first have to find the loop headers. Here we approximate this
498/// by finding targets of backedges in the CFG.
499///
500/// Note that there definitely are cases when we want to allow threading of
501/// edges across a loop header. For example, threading a jump from outside the
502/// loop (the preheader) to an exit block of the loop is definitely profitable.
503/// It is also almost always profitable to thread backedges from within the loop
504/// to exit blocks, and is often profitable to thread backedges to other blocks
505/// within the loop (forming a nested loop). This simple analysis is not rich
506/// enough to track all of these properties and keep it up-to-date as the CFG
507/// mutates, so we don't allow any of these transformations.
508void JumpThreadingPass::findLoopHeaders(Function &F) {
509 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
510 FindFunctionBackedges(F, Result&: Edges);
511 LoopHeaders.insert_range(R: llvm::make_second_range(c&: Edges));
512}
513
514/// getKnownConstant - Helper method to determine if we can thread over a
515/// terminator with the given value as its condition, and if so what value to
516/// use for that. What kind of value this is depends on whether we want an
517/// integer or a block address, but an undef is always accepted.
518/// Returns null if Val is null or not an appropriate constant.
519static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
520 if (!Val)
521 return nullptr;
522
523 // Undef is "known" enough.
524 if (UndefValue *U = dyn_cast<UndefValue>(Val))
525 return U;
526
527 if (Preference == WantBlockAddress)
528 return dyn_cast<BlockAddress>(Val: Val->stripPointerCasts());
529
530 return dyn_cast<ConstantInt>(Val);
531}
532
533/// computeValueKnownInPredecessors - Given a basic block BB and a value V, see
534/// if we can infer that the value is a known ConstantInt/BlockAddress or undef
535/// in any of our predecessors. If so, return the known list of value and pred
536/// BB in the result vector.
537///
538/// This returns true if there were any known values.
539bool JumpThreadingPass::computeValueKnownInPredecessorsImpl(
540 Value *V, BasicBlock *BB, PredValueInfo &Result,
541 ConstantPreference Preference, SmallPtrSet<Value *, 4> &RecursionSet,
542 Instruction *CtxI) {
543 const DataLayout &DL = BB->getDataLayout();
544
545 // This method walks up use-def chains recursively. Because of this, we could
546 // get into an infinite loop going around loops in the use-def chain. To
547 // prevent this, keep track of what (value, block) pairs we've already visited
548 // and terminate the search if we loop back to them
549 if (!RecursionSet.insert(Ptr: V).second)
550 return false;
551
552 // If V is a constant, then it is known in all predecessors.
553 if (Constant *KC = getKnownConstant(Val: V, Preference)) {
554 for (BasicBlock *Pred : predecessors(BB))
555 Result.emplace_back(Args&: KC, Args&: Pred);
556
557 return !Result.empty();
558 }
559
560 // If V is a non-instruction value, or an instruction in a different block,
561 // then it can't be derived from a PHI.
562 Instruction *I = dyn_cast<Instruction>(Val: V);
563 if (!I || I->getParent() != BB) {
564
565 // Okay, if this is a live-in value, see if it has a known value at the any
566 // edge from our predecessors.
567 for (BasicBlock *P : predecessors(BB)) {
568 using namespace PatternMatch;
569 // If the value is known by LazyValueInfo to be a constant in a
570 // predecessor, use that information to try to thread this block.
571 Constant *PredCst = LVI->getConstantOnEdge(V, FromBB: P, ToBB: BB, CtxI);
572 // If I is a non-local compare-with-constant instruction, use more-rich
573 // 'getPredicateOnEdge' method. This would be able to handle value
574 // inequalities better, for example if the compare is "X < 4" and "X < 3"
575 // is known true but "X < 4" itself is not available.
576 CmpPredicate Pred;
577 Value *Val;
578 Constant *Cst;
579 if (!PredCst && match(V, P: m_Cmp(Pred, L: m_Value(V&: Val), R: m_Constant(C&: Cst))))
580 PredCst = LVI->getPredicateOnEdge(Pred, V: Val, C: Cst, FromBB: P, ToBB: BB, CtxI);
581 if (Constant *KC = getKnownConstant(Val: PredCst, Preference))
582 Result.emplace_back(Args&: KC, Args&: P);
583 }
584
585 return !Result.empty();
586 }
587
588 /// If I is a PHI node, then we know the incoming values for any constants.
589 if (PHINode *PN = dyn_cast<PHINode>(Val: I)) {
590 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
591 Value *InVal = PN->getIncomingValue(i);
592 if (Constant *KC = getKnownConstant(Val: InVal, Preference)) {
593 Result.emplace_back(Args&: KC, Args: PN->getIncomingBlock(i));
594 } else {
595 Constant *CI = LVI->getConstantOnEdge(V: InVal,
596 FromBB: PN->getIncomingBlock(i),
597 ToBB: BB, CtxI);
598 if (Constant *KC = getKnownConstant(Val: CI, Preference))
599 Result.emplace_back(Args&: KC, Args: PN->getIncomingBlock(i));
600 }
601 }
602
603 return !Result.empty();
604 }
605
606 // Handle Cast instructions.
607 if (CastInst *CI = dyn_cast<CastInst>(Val: I)) {
608 Value *Source = CI->getOperand(i_nocapture: 0);
609 PredValueInfoTy Vals;
610 computeValueKnownInPredecessorsImpl(V: Source, BB, Result&: Vals, Preference,
611 RecursionSet, CtxI);
612 if (Vals.empty())
613 return false;
614
615 // Convert the known values.
616 for (auto &Val : Vals)
617 if (Constant *Folded = ConstantFoldCastOperand(Opcode: CI->getOpcode(), C: Val.first,
618 DestTy: CI->getType(), DL))
619 Result.emplace_back(Args&: Folded, Args&: Val.second);
620
621 return !Result.empty();
622 }
623
624 if (FreezeInst *FI = dyn_cast<FreezeInst>(Val: I)) {
625 Value *Source = FI->getOperand(i_nocapture: 0);
626 computeValueKnownInPredecessorsImpl(V: Source, BB, Result, Preference,
627 RecursionSet, CtxI);
628
629 erase_if(C&: Result, P: [](auto &Pair) {
630 return !isGuaranteedNotToBeUndefOrPoison(Pair.first);
631 });
632
633 return !Result.empty();
634 }
635
636 // Handle some boolean conditions.
637 if (I->getType()->getPrimitiveSizeInBits() == 1) {
638 using namespace PatternMatch;
639 if (Preference != WantInteger)
640 return false;
641 // X | true -> true
642 // X & false -> false
643 Value *Op0, *Op1;
644 if (match(V: I, P: m_LogicalOr(L: m_Value(V&: Op0), R: m_Value(V&: Op1))) ||
645 match(V: I, P: m_LogicalAnd(L: m_Value(V&: Op0), R: m_Value(V&: Op1)))) {
646 PredValueInfoTy LHSVals, RHSVals;
647
648 computeValueKnownInPredecessorsImpl(V: Op0, BB, Result&: LHSVals, Preference: WantInteger,
649 RecursionSet, CtxI);
650 computeValueKnownInPredecessorsImpl(V: Op1, BB, Result&: RHSVals, Preference: WantInteger,
651 RecursionSet, CtxI);
652
653 if (LHSVals.empty() && RHSVals.empty())
654 return false;
655
656 ConstantInt *InterestingVal;
657 if (match(V: I, P: m_LogicalOr()))
658 InterestingVal = ConstantInt::getTrue(Context&: I->getContext());
659 else
660 InterestingVal = ConstantInt::getFalse(Context&: I->getContext());
661
662 SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
663
664 // Scan for the sentinel. If we find an undef, force it to the
665 // interesting value: x|undef -> true and x&undef -> false.
666 for (const auto &LHSVal : LHSVals)
667 if (LHSVal.first == InterestingVal || isa<UndefValue>(Val: LHSVal.first)) {
668 Result.emplace_back(Args&: InterestingVal, Args: LHSVal.second);
669 LHSKnownBBs.insert(Ptr: LHSVal.second);
670 }
671 for (const auto &RHSVal : RHSVals)
672 if (RHSVal.first == InterestingVal || isa<UndefValue>(Val: RHSVal.first)) {
673 // If we already inferred a value for this block on the LHS, don't
674 // re-add it.
675 if (!LHSKnownBBs.count(Ptr: RHSVal.second))
676 Result.emplace_back(Args&: InterestingVal, Args: RHSVal.second);
677 }
678
679 return !Result.empty();
680 }
681
682 // Handle the NOT form of XOR.
683 if (I->getOpcode() == Instruction::Xor &&
684 isa<ConstantInt>(Val: I->getOperand(i: 1)) &&
685 cast<ConstantInt>(Val: I->getOperand(i: 1))->isOne()) {
686 computeValueKnownInPredecessorsImpl(V: I->getOperand(i: 0), BB, Result,
687 Preference: WantInteger, RecursionSet, CtxI);
688 if (Result.empty())
689 return false;
690
691 // Invert the known values.
692 for (auto &R : Result)
693 R.first = ConstantExpr::getNot(C: R.first);
694
695 return true;
696 }
697
698 // Try to simplify some other binary operator values.
699 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: I)) {
700 if (Preference != WantInteger)
701 return false;
702 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: BO->getOperand(i_nocapture: 1))) {
703 PredValueInfoTy LHSVals;
704 computeValueKnownInPredecessorsImpl(V: BO->getOperand(i_nocapture: 0), BB, Result&: LHSVals,
705 Preference: WantInteger, RecursionSet, CtxI);
706
707 // Try to use constant folding to simplify the binary operator.
708 for (const auto &LHSVal : LHSVals) {
709 Constant *V = LHSVal.first;
710 Constant *Folded =
711 ConstantFoldBinaryOpOperands(Opcode: BO->getOpcode(), LHS: V, RHS: CI, DL);
712
713 if (Constant *KC = getKnownConstant(Val: Folded, Preference: WantInteger))
714 Result.emplace_back(Args&: KC, Args: LHSVal.second);
715 }
716 }
717
718 return !Result.empty();
719 }
720
721 // Handle compare with phi operand, where the PHI is defined in this block.
722 if (CmpInst *Cmp = dyn_cast<CmpInst>(Val: I)) {
723 if (Preference != WantInteger)
724 return false;
725 Type *CmpType = Cmp->getType();
726 Value *CmpLHS = Cmp->getOperand(i_nocapture: 0);
727 Value *CmpRHS = Cmp->getOperand(i_nocapture: 1);
728 CmpInst::Predicate Pred = Cmp->getPredicate();
729
730 PHINode *PN = dyn_cast<PHINode>(Val: CmpLHS);
731 if (!PN)
732 PN = dyn_cast<PHINode>(Val: CmpRHS);
733 // Do not perform phi translation across a loop header phi, because this
734 // may result in comparison of values from two different loop iterations.
735 // FIXME: This check is broken if LoopHeaders is not populated.
736 if (PN && PN->getParent() == BB && !LoopHeaders.contains(Ptr: BB)) {
737 const DataLayout &DL = PN->getDataLayout();
738 // We can do this simplification if any comparisons fold to true or false.
739 // See if any do.
740 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
741 BasicBlock *PredBB = PN->getIncomingBlock(i);
742 Value *LHS, *RHS;
743 if (PN == CmpLHS) {
744 LHS = PN->getIncomingValue(i);
745 RHS = CmpRHS->DoPHITranslation(CurBB: BB, PredBB);
746 } else {
747 LHS = CmpLHS->DoPHITranslation(CurBB: BB, PredBB);
748 RHS = PN->getIncomingValue(i);
749 }
750 Value *Res = simplifyCmpInst(Predicate: Pred, LHS, RHS, Q: {DL});
751 if (!Res) {
752 if (!isa<Constant>(Val: RHS))
753 continue;
754
755 // getPredicateOnEdge call will make no sense if LHS is defined in BB.
756 auto LHSInst = dyn_cast<Instruction>(Val: LHS);
757 if (LHSInst && LHSInst->getParent() == BB)
758 continue;
759
760 Res = LVI->getPredicateOnEdge(Pred, V: LHS, C: cast<Constant>(Val: RHS), FromBB: PredBB,
761 ToBB: BB, CtxI: CtxI ? CtxI : Cmp);
762 }
763
764 if (Constant *KC = getKnownConstant(Val: Res, Preference: WantInteger))
765 Result.emplace_back(Args&: KC, Args&: PredBB);
766 }
767
768 return !Result.empty();
769 }
770
771 // If comparing a live-in value against a constant, see if we know the
772 // live-in value on any predecessors.
773 if (isa<Constant>(Val: CmpRHS) && !CmpType->isVectorTy()) {
774 Constant *CmpConst = cast<Constant>(Val: CmpRHS);
775
776 if (!isa<Instruction>(Val: CmpLHS) ||
777 cast<Instruction>(Val: CmpLHS)->getParent() != BB) {
778 for (BasicBlock *P : predecessors(BB)) {
779 // If the value is known by LazyValueInfo to be a constant in a
780 // predecessor, use that information to try to thread this block.
781 Constant *Res = LVI->getPredicateOnEdge(Pred, V: CmpLHS, C: CmpConst, FromBB: P, ToBB: BB,
782 CtxI: CtxI ? CtxI : Cmp);
783 if (Constant *KC = getKnownConstant(Val: Res, Preference: WantInteger))
784 Result.emplace_back(Args&: KC, Args&: P);
785 }
786
787 return !Result.empty();
788 }
789
790 // InstCombine can fold some forms of constant range checks into
791 // (icmp (add (x, C1)), C2). See if we have we have such a thing with
792 // x as a live-in.
793 {
794 using namespace PatternMatch;
795
796 Value *AddLHS;
797 ConstantInt *AddConst;
798 if (isa<ConstantInt>(Val: CmpConst) &&
799 match(V: CmpLHS, P: m_Add(L: m_Value(V&: AddLHS), R: m_ConstantInt(CI&: AddConst)))) {
800 if (!isa<Instruction>(Val: AddLHS) ||
801 cast<Instruction>(Val: AddLHS)->getParent() != BB) {
802 for (BasicBlock *P : predecessors(BB)) {
803 // If the value is known by LazyValueInfo to be a ConstantRange in
804 // a predecessor, use that information to try to thread this
805 // block.
806 ConstantRange CR = LVI->getConstantRangeOnEdge(
807 V: AddLHS, FromBB: P, ToBB: BB, CtxI: CtxI ? CtxI : cast<Instruction>(Val: CmpLHS));
808 // Propagate the range through the addition.
809 CR = CR.add(Other: AddConst->getValue());
810
811 // Get the range where the compare returns true.
812 ConstantRange CmpRange = ConstantRange::makeExactICmpRegion(
813 Pred, Other: cast<ConstantInt>(Val: CmpConst)->getValue());
814
815 Constant *ResC;
816 if (CmpRange.contains(CR))
817 ResC = ConstantInt::getTrue(Ty: CmpType);
818 else if (CmpRange.inverse().contains(CR))
819 ResC = ConstantInt::getFalse(Ty: CmpType);
820 else
821 continue;
822
823 Result.emplace_back(Args&: ResC, Args&: P);
824 }
825
826 return !Result.empty();
827 }
828 }
829 }
830
831 // Try to find a constant value for the LHS of a comparison,
832 // and evaluate it statically if we can.
833 PredValueInfoTy LHSVals;
834 computeValueKnownInPredecessorsImpl(V: I->getOperand(i: 0), BB, Result&: LHSVals,
835 Preference: WantInteger, RecursionSet, CtxI);
836
837 for (const auto &LHSVal : LHSVals) {
838 Constant *V = LHSVal.first;
839 Constant *Folded =
840 ConstantFoldCompareInstOperands(Predicate: Pred, LHS: V, RHS: CmpConst, DL);
841 if (Constant *KC = getKnownConstant(Val: Folded, Preference: WantInteger))
842 Result.emplace_back(Args&: KC, Args: LHSVal.second);
843 }
844
845 return !Result.empty();
846 }
847 }
848
849 if (SelectInst *SI = dyn_cast<SelectInst>(Val: I)) {
850 // Handle select instructions where at least one operand is a known constant
851 // and we can figure out the condition value for any predecessor block.
852 Constant *TrueVal = getKnownConstant(Val: SI->getTrueValue(), Preference);
853 Constant *FalseVal = getKnownConstant(Val: SI->getFalseValue(), Preference);
854 PredValueInfoTy Conds;
855 if ((TrueVal || FalseVal) &&
856 computeValueKnownInPredecessorsImpl(V: SI->getCondition(), BB, Result&: Conds,
857 Preference: WantInteger, RecursionSet, CtxI)) {
858 for (auto &C : Conds) {
859 Constant *Cond = C.first;
860
861 // Figure out what value to use for the condition.
862 bool KnownCond;
863 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: Cond)) {
864 // A known boolean.
865 KnownCond = CI->isOne();
866 } else {
867 assert(isa<UndefValue>(Cond) && "Unexpected condition value");
868 // Either operand will do, so be sure to pick the one that's a known
869 // constant.
870 // FIXME: Do this more cleverly if both values are known constants?
871 KnownCond = (TrueVal != nullptr);
872 }
873
874 // See if the select has a known constant value for this predecessor.
875 if (Constant *Val = KnownCond ? TrueVal : FalseVal)
876 Result.emplace_back(Args&: Val, Args&: C.second);
877 }
878
879 return !Result.empty();
880 }
881 }
882
883 // If all else fails, see if LVI can figure out a constant value for us.
884 assert(CtxI->getParent() == BB && "CtxI should be in BB");
885 Constant *CI = LVI->getConstant(V, CtxI);
886 if (Constant *KC = getKnownConstant(Val: CI, Preference)) {
887 for (BasicBlock *Pred : predecessors(BB))
888 Result.emplace_back(Args&: KC, Args&: Pred);
889 }
890
891 return !Result.empty();
892}
893
894/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
895/// in an undefined jump, decide which block is best to revector to.
896///
897/// Since we can pick an arbitrary destination, we pick the successor with the
898/// fewest predecessors. This should reduce the in-degree of the others.
899static unsigned getBestDestForJumpOnUndef(BasicBlock *BB) {
900 Instruction *BBTerm = BB->getTerminator();
901 unsigned MinSucc = 0;
902 BasicBlock *TestBB = BBTerm->getSuccessor(Idx: MinSucc);
903 // Compute the successor with the minimum number of predecessors.
904 unsigned MinNumPreds = pred_size(BB: TestBB);
905 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
906 TestBB = BBTerm->getSuccessor(Idx: i);
907 unsigned NumPreds = pred_size(BB: TestBB);
908 if (NumPreds < MinNumPreds) {
909 MinSucc = i;
910 MinNumPreds = NumPreds;
911 }
912 }
913
914 return MinSucc;
915}
916
917static bool hasAddressTakenAndUsed(BasicBlock *BB) {
918 if (!BB->hasAddressTaken()) return false;
919
920 // If the block has its address taken, it may be a tree of dead constants
921 // hanging off of it. These shouldn't keep the block alive.
922 BlockAddress *BA = BlockAddress::get(BB);
923 BA->removeDeadConstantUsers();
924 return !BA->use_empty();
925}
926
927/// processBlock - If there are any predecessors whose control can be threaded
928/// through to a successor, transform them now.
929bool JumpThreadingPass::processBlock(BasicBlock *BB) {
930 // If the block is trivially dead, just return and let the caller nuke it.
931 // This simplifies other transformations.
932 if (DTU->isBBPendingDeletion(DelBB: BB) ||
933 (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()))
934 return false;
935
936 // If this block has a single predecessor, and if that pred has a single
937 // successor, merge the blocks. This encourages recursive jump threading
938 // because now the condition in this block can be threaded through
939 // predecessors of our predecessor block.
940 if (maybeMergeBasicBlockIntoOnlyPred(BB))
941 return true;
942
943 if (tryToUnfoldSelectInCurrBB(BB))
944 return true;
945
946 // Look if we can propagate guards to predecessors.
947 if (HasGuards && processGuards(BB))
948 return true;
949
950 // What kind of constant we're looking for.
951 ConstantPreference Preference = WantInteger;
952
953 // Look to see if the terminator is a conditional branch, switch or indirect
954 // branch, if not we can't thread it.
955 Value *Condition;
956 Instruction *Terminator = BB->getTerminator();
957 if (CondBrInst *BI = dyn_cast<CondBrInst>(Val: Terminator)) {
958 Condition = BI->getCondition();
959 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Val: Terminator)) {
960 Condition = SI->getCondition();
961 } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Val: Terminator)) {
962 // Can't thread indirect branch with no successors.
963 if (IB->getNumSuccessors() == 0) return false;
964 Condition = IB->getAddress()->stripPointerCasts();
965 Preference = WantBlockAddress;
966 } else {
967 return false; // Must be an invoke or callbr.
968 }
969
970 // Keep track if we constant folded the condition in this invocation.
971 bool ConstantFolded = false;
972
973 // Run constant folding to see if we can reduce the condition to a simple
974 // constant.
975 if (Instruction *I = dyn_cast<Instruction>(Val: Condition)) {
976 Value *SimpleVal =
977 ConstantFoldInstruction(I, DL: BB->getDataLayout(), TLI);
978 if (SimpleVal) {
979 I->replaceAllUsesWith(V: SimpleVal);
980 if (isInstructionTriviallyDead(I, TLI))
981 I->eraseFromParent();
982 Condition = SimpleVal;
983 ConstantFolded = true;
984 }
985 }
986
987 // If the terminator is branching on an undef or freeze undef, we can pick any
988 // of the successors to branch to. Let getBestDestForJumpOnUndef decide.
989 auto *FI = dyn_cast<FreezeInst>(Val: Condition);
990 if (isa<UndefValue>(Val: Condition) ||
991 (FI && isa<UndefValue>(Val: FI->getOperand(i_nocapture: 0)) && FI->hasOneUse())) {
992 unsigned BestSucc = getBestDestForJumpOnUndef(BB);
993 std::vector<DominatorTree::UpdateType> Updates;
994
995 // Fold the branch/switch.
996 Instruction *BBTerm = BB->getTerminator();
997 Updates.reserve(n: BBTerm->getNumSuccessors());
998 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
999 if (i == BestSucc) continue;
1000 BasicBlock *Succ = BBTerm->getSuccessor(Idx: i);
1001 Succ->removePredecessor(Pred: BB, KeepOneInputPHIs: true);
1002 Updates.push_back(x: {DominatorTree::Delete, BB, Succ});
1003 }
1004
1005 LLVM_DEBUG(dbgs() << " In block '" << BB->getName()
1006 << "' folding undef terminator: " << *BBTerm << '\n');
1007 Instruction *NewBI = UncondBrInst::Create(Target: BBTerm->getSuccessor(Idx: BestSucc),
1008 InsertBefore: BBTerm->getIterator());
1009 NewBI->setDebugLoc(BBTerm->getDebugLoc());
1010 ++NumFolds;
1011 BBTerm->eraseFromParent();
1012 DTU->applyUpdatesPermissive(Updates);
1013 if (FI)
1014 FI->eraseFromParent();
1015 return true;
1016 }
1017
1018 // If the terminator of this block is branching on a constant, simplify the
1019 // terminator to an unconditional branch. This can occur due to threading in
1020 // other blocks.
1021 if (getKnownConstant(Val: Condition, Preference)) {
1022 LLVM_DEBUG(dbgs() << " In block '" << BB->getName()
1023 << "' folding terminator: " << *BB->getTerminator()
1024 << '\n');
1025 ++NumFolds;
1026 ConstantFoldTerminator(BB, DeleteDeadConditions: true, TLI: nullptr, DTU: DTU.get());
1027 if (auto *BPI = getBPI())
1028 BPI->eraseBlock(BB);
1029 return true;
1030 }
1031
1032 Instruction *CondInst = dyn_cast<Instruction>(Val: Condition);
1033
1034 // All the rest of our checks depend on the condition being an instruction.
1035 if (!CondInst) {
1036 // FIXME: Unify this with code below.
1037 if (processThreadableEdges(Cond: Condition, BB, Preference, CtxI: Terminator))
1038 return true;
1039 return ConstantFolded;
1040 }
1041
1042 // Some of the following optimization can safely work on the unfrozen cond.
1043 Value *CondWithoutFreeze = CondInst;
1044 if (auto *FI = dyn_cast<FreezeInst>(Val: CondInst))
1045 CondWithoutFreeze = FI->getOperand(i_nocapture: 0);
1046
1047 if (CmpInst *CondCmp = dyn_cast<CmpInst>(Val: CondWithoutFreeze)) {
1048 // If we're branching on a conditional, LVI might be able to determine
1049 // it's value at the branch instruction. We only handle comparisons
1050 // against a constant at this time.
1051 if (Constant *CondConst = dyn_cast<Constant>(Val: CondCmp->getOperand(i_nocapture: 1))) {
1052 Constant *Res =
1053 LVI->getPredicateAt(Pred: CondCmp->getPredicate(), V: CondCmp->getOperand(i_nocapture: 0),
1054 C: CondConst, CtxI: BB->getTerminator(),
1055 /*UseBlockValue=*/false);
1056 if (Res) {
1057 // We can safely replace *some* uses of the CondInst if it has
1058 // exactly one value as returned by LVI. RAUW is incorrect in the
1059 // presence of guards and assumes, that have the `Cond` as the use. This
1060 // is because we use the guards/assume to reason about the `Cond` value
1061 // at the end of block, but RAUW unconditionally replaces all uses
1062 // including the guards/assumes themselves and the uses before the
1063 // guard/assume.
1064 if (replaceFoldableUses(Cond: CondCmp, ToVal: Res, KnownAtEndOfBB: BB))
1065 return true;
1066 }
1067
1068 // We did not manage to simplify this branch, try to see whether
1069 // CondCmp depends on a known phi-select pattern.
1070 if (tryToUnfoldSelect(CondCmp, BB))
1071 return true;
1072 }
1073 }
1074
1075 if (SwitchInst *SI = dyn_cast<SwitchInst>(Val: BB->getTerminator()))
1076 if (tryToUnfoldSelect(SI, BB))
1077 return true;
1078
1079 // Check for some cases that are worth simplifying. Right now we want to look
1080 // for loads that are used by a switch or by the condition for the branch. If
1081 // we see one, check to see if it's partially redundant. If so, insert a PHI
1082 // which can then be used to thread the values.
1083 Value *SimplifyValue = CondWithoutFreeze;
1084
1085 if (CmpInst *CondCmp = dyn_cast<CmpInst>(Val: SimplifyValue))
1086 if (isa<Constant>(Val: CondCmp->getOperand(i_nocapture: 1)))
1087 SimplifyValue = CondCmp->getOperand(i_nocapture: 0);
1088
1089 // TODO: There are other places where load PRE would be profitable, such as
1090 // more complex comparisons.
1091 if (LoadInst *LoadI = dyn_cast<LoadInst>(Val: SimplifyValue))
1092 if (simplifyPartiallyRedundantLoad(LI: LoadI))
1093 return true;
1094
1095 // Before threading, try to propagate profile data backwards:
1096 if (PHINode *PN = dyn_cast<PHINode>(Val: CondInst))
1097 if (PN->getParent() == BB && isa<CondBrInst>(Val: BB->getTerminator()))
1098 updatePredecessorProfileMetadata(PN, BB);
1099
1100 // Handle a variety of cases where we are branching on something derived from
1101 // a PHI node in the current block. If we can prove that any predecessors
1102 // compute a predictable value based on a PHI node, thread those predecessors.
1103 if (processThreadableEdges(Cond: CondInst, BB, Preference, CtxI: Terminator))
1104 return true;
1105
1106 // If this is an otherwise-unfoldable branch on a phi node or freeze(phi) in
1107 // the current block, see if we can simplify.
1108 PHINode *PN = dyn_cast<PHINode>(Val: CondWithoutFreeze);
1109 if (PN && PN->getParent() == BB && isa<CondBrInst>(Val: BB->getTerminator()))
1110 return processBranchOnPHI(PN);
1111
1112 // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
1113 if (CondInst->getOpcode() == Instruction::Xor &&
1114 CondInst->getParent() == BB && isa<CondBrInst>(Val: BB->getTerminator()))
1115 return processBranchOnXOR(BO: cast<BinaryOperator>(Val: CondInst));
1116
1117 // Search for a stronger dominating condition that can be used to simplify a
1118 // conditional branch leaving BB.
1119 if (processImpliedCondition(BB))
1120 return true;
1121
1122 return false;
1123}
1124
1125bool JumpThreadingPass::processImpliedCondition(BasicBlock *BB) {
1126 auto *BI = dyn_cast<CondBrInst>(Val: BB->getTerminator());
1127 if (!BI)
1128 return false;
1129
1130 Value *Cond = BI->getCondition();
1131 // Assuming that predecessor's branch was taken, if pred's branch condition
1132 // (V) implies Cond, Cond can be either true, undef, or poison. In this case,
1133 // freeze(Cond) is either true or a nondeterministic value.
1134 // If freeze(Cond) has only one use, we can freely fold freeze(Cond) to true
1135 // without affecting other instructions.
1136 auto *FICond = dyn_cast<FreezeInst>(Val: Cond);
1137 if (FICond && FICond->hasOneUse())
1138 Cond = FICond->getOperand(i_nocapture: 0);
1139 else
1140 FICond = nullptr;
1141
1142 BasicBlock *CurrentBB = BB;
1143 BasicBlock *CurrentPred = BB->getSinglePredecessor();
1144 unsigned Iter = 0;
1145
1146 auto &DL = BB->getDataLayout();
1147
1148 while (CurrentPred &&
1149 Iter++ < Opts->jump_threading_implication_search_threshold) {
1150 auto *PBI = dyn_cast<CondBrInst>(Val: CurrentPred->getTerminator());
1151 if (!PBI)
1152 return false;
1153 if (PBI->getSuccessor(i: 0) != CurrentBB && PBI->getSuccessor(i: 1) != CurrentBB)
1154 return false;
1155
1156 bool CondIsTrue = PBI->getSuccessor(i: 0) == CurrentBB;
1157 std::optional<bool> Implication =
1158 isImpliedCondition(LHS: PBI->getCondition(), RHS: Cond, DL, LHSIsTrue: CondIsTrue);
1159
1160 // If the branch condition of BB (which is Cond) and CurrentPred are
1161 // exactly the same freeze instruction, Cond can be folded into CondIsTrue.
1162 if (!Implication && FICond && isa<FreezeInst>(Val: PBI->getCondition())) {
1163 if (cast<FreezeInst>(Val: PBI->getCondition())->getOperand(i_nocapture: 0) ==
1164 FICond->getOperand(i_nocapture: 0))
1165 Implication = CondIsTrue;
1166 }
1167
1168 if (Implication) {
1169 BasicBlock *KeepSucc = BI->getSuccessor(i: *Implication ? 0 : 1);
1170 BasicBlock *RemoveSucc = BI->getSuccessor(i: *Implication ? 1 : 0);
1171 RemoveSucc->removePredecessor(Pred: BB);
1172 UncondBrInst *UncondBI =
1173 UncondBrInst::Create(Target: KeepSucc, InsertBefore: BI->getIterator());
1174 UncondBI->setDebugLoc(BI->getDebugLoc());
1175 ++NumFolds;
1176 BI->eraseFromParent();
1177 if (FICond)
1178 FICond->eraseFromParent();
1179
1180 DTU->applyUpdatesPermissive(Updates: {{DominatorTree::Delete, BB, RemoveSucc}});
1181 if (auto *BPI = getBPI())
1182 BPI->eraseBlock(BB);
1183 return true;
1184 }
1185 CurrentBB = CurrentPred;
1186 CurrentPred = CurrentBB->getSinglePredecessor();
1187 }
1188
1189 return false;
1190}
1191
1192/// Return true if Op is an instruction defined in the given block.
1193static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB) {
1194 if (Instruction *OpInst = dyn_cast<Instruction>(Val: Op))
1195 if (OpInst->getParent() == BB)
1196 return true;
1197 return false;
1198}
1199
1200/// simplifyPartiallyRedundantLoad - If LoadI is an obviously partially
1201/// redundant load instruction, eliminate it by replacing it with a PHI node.
1202/// This is an important optimization that encourages jump threading, and needs
1203/// to be run interlaced with other jump threading tasks.
1204bool JumpThreadingPass::simplifyPartiallyRedundantLoad(LoadInst *LoadI) {
1205 // Don't hack volatile and ordered loads.
1206 if (!LoadI->isUnordered()) return false;
1207
1208 // If the load is defined in a block with exactly one predecessor, it can't be
1209 // partially redundant.
1210 BasicBlock *LoadBB = LoadI->getParent();
1211 if (LoadBB->getSinglePredecessor())
1212 return false;
1213
1214 // If the load is defined in an EH pad, it can't be partially redundant,
1215 // because the edges between the invoke and the EH pad cannot have other
1216 // instructions between them.
1217 if (LoadBB->isEHPad())
1218 return false;
1219
1220 Value *LoadedPtr = LoadI->getOperand(i_nocapture: 0);
1221
1222 // If the loaded operand is defined in the LoadBB and its not a phi,
1223 // it can't be available in predecessors.
1224 if (isOpDefinedInBlock(Op: LoadedPtr, BB: LoadBB) && !isa<PHINode>(Val: LoadedPtr))
1225 return false;
1226
1227 // Scan a few instructions up from the load, to see if it is obviously live at
1228 // the entry to its block.
1229 BasicBlock::iterator BBIt(LoadI);
1230 bool IsLoadCSE;
1231 BatchAAResults BatchAA(*AA);
1232 // The dominator tree is updated lazily and may not be valid at this point.
1233 BatchAA.disableDominatorTree();
1234 if (Value *AvailableVal = FindAvailableLoadedValue(
1235 Load: LoadI, ScanBB: LoadBB, ScanFrom&: BBIt, MaxInstsToScan: DefMaxInstsToScan, AA: &BatchAA, IsLoadCSE: &IsLoadCSE)) {
1236 // If the value of the load is locally available within the block, just use
1237 // it. This frequently occurs for reg2mem'd allocas.
1238
1239 if (IsLoadCSE) {
1240 LoadInst *NLoadI = cast<LoadInst>(Val: AvailableVal);
1241 combineMetadataForCSE(K: NLoadI, J: LoadI, DoesKMove: false);
1242 LVI->forgetValue(V: NLoadI);
1243 };
1244
1245 // If the returned value is the load itself, replace with poison. This can
1246 // only happen in dead loops.
1247 if (AvailableVal == LoadI)
1248 AvailableVal = PoisonValue::get(T: LoadI->getType());
1249 if (AvailableVal->getType() != LoadI->getType()) {
1250 AvailableVal = CastInst::CreateBitOrPointerCast(
1251 S: AvailableVal, Ty: LoadI->getType(), Name: "", InsertBefore: LoadI->getIterator());
1252 cast<Instruction>(Val: AvailableVal)->setDebugLoc(LoadI->getDebugLoc());
1253 }
1254 LoadI->replaceAllUsesWith(V: AvailableVal);
1255 LoadI->eraseFromParent();
1256 return true;
1257 }
1258
1259 // Otherwise, if we scanned the whole block and got to the top of the block,
1260 // we know the block is locally transparent to the load. If not, something
1261 // might clobber its value.
1262 if (BBIt != LoadBB->begin())
1263 return false;
1264
1265 // If all of the loads and stores that feed the value have the same AA tags,
1266 // then we can propagate them onto any newly inserted loads.
1267 AAMDNodes AATags = LoadI->getAAMetadata();
1268
1269 SmallPtrSet<BasicBlock*, 8> PredsScanned;
1270
1271 using AvailablePredsTy = SmallVector<std::pair<BasicBlock *, Value *>, 8>;
1272
1273 AvailablePredsTy AvailablePreds;
1274 BasicBlock *OneUnavailablePred = nullptr;
1275 SmallVector<LoadInst*, 8> CSELoads;
1276
1277 // If we got here, the loaded value is transparent through to the start of the
1278 // block. Check to see if it is available in any of the predecessor blocks.
1279 for (BasicBlock *PredBB : predecessors(BB: LoadBB)) {
1280 // If we already scanned this predecessor, skip it.
1281 if (!PredsScanned.insert(Ptr: PredBB).second)
1282 continue;
1283
1284 BBIt = PredBB->end();
1285 unsigned NumScanedInst = 0;
1286 Value *PredAvailable = nullptr;
1287 // NOTE: We don't CSE load that is volatile or anything stronger than
1288 // unordered, that should have been checked when we entered the function.
1289 assert(LoadI->isUnordered() &&
1290 "Attempting to CSE volatile or atomic loads");
1291 // If this is a load on a phi pointer, phi-translate it and search
1292 // for available load/store to the pointer in predecessors.
1293 Type *AccessTy = LoadI->getType();
1294 const auto &DL = LoadI->getDataLayout();
1295 MemoryLocation Loc(LoadedPtr->DoPHITranslation(CurBB: LoadBB, PredBB),
1296 LocationSize::precise(Value: DL.getTypeStoreSize(Ty: AccessTy)),
1297 AATags);
1298 PredAvailable = findAvailablePtrLoadStore(
1299 Loc, AccessTy, AccessProps: LoadI->getProperties(), ScanBB: PredBB, ScanFrom&: BBIt, MaxInstsToScan: DefMaxInstsToScan,
1300 AA: &BatchAA, IsLoadCSE: &IsLoadCSE, NumScanedInst: &NumScanedInst);
1301
1302 // If PredBB has a single predecessor, continue scanning through the
1303 // single predecessor.
1304 BasicBlock *SinglePredBB = PredBB;
1305 while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() &&
1306 NumScanedInst < DefMaxInstsToScan) {
1307 SinglePredBB = SinglePredBB->getSinglePredecessor();
1308 if (SinglePredBB) {
1309 BBIt = SinglePredBB->end();
1310 PredAvailable = findAvailablePtrLoadStore(
1311 Loc, AccessTy, AccessProps: LoadI->getProperties(), ScanBB: SinglePredBB, ScanFrom&: BBIt,
1312 MaxInstsToScan: (DefMaxInstsToScan - NumScanedInst), AA: &BatchAA, IsLoadCSE: &IsLoadCSE,
1313 NumScanedInst: &NumScanedInst);
1314 }
1315 }
1316
1317 if (!PredAvailable) {
1318 OneUnavailablePred = PredBB;
1319 continue;
1320 }
1321
1322 if (IsLoadCSE)
1323 CSELoads.push_back(Elt: cast<LoadInst>(Val: PredAvailable));
1324
1325 // If so, this load is partially redundant. Remember this info so that we
1326 // can create a PHI node.
1327 AvailablePreds.emplace_back(Args&: PredBB, Args&: PredAvailable);
1328 }
1329
1330 // If the loaded value isn't available in any predecessor, it isn't partially
1331 // redundant.
1332 if (AvailablePreds.empty()) return false;
1333
1334 // Okay, the loaded value is available in at least one (and maybe all!)
1335 // predecessors. If the value is unavailable in more than one unique
1336 // predecessor, we want to insert a merge block for those common predecessors.
1337 // This ensures that we only have to insert one reload, thus not increasing
1338 // code size.
1339 BasicBlock *UnavailablePred = nullptr;
1340
1341 // If the value is unavailable in one of predecessors, we will end up
1342 // inserting a new instruction into them. It is only valid if all the
1343 // instructions before LoadI are guaranteed to pass execution to its
1344 // successor, or if LoadI is safe to speculate.
1345 // TODO: If this logic becomes more complex, and we will perform PRE insertion
1346 // farther than to a predecessor, we need to reuse the code from GVN's PRE.
1347 // It requires domination tree analysis, so for this simple case it is an
1348 // overkill.
1349 std::optional<bool> GuaranteedToTransfer;
1350 auto CanSpeculateInto = [&](const BasicBlock *Pred) {
1351 if (isSafeToSpeculativelyExecute(I: LoadI, CtxI: Pred->getTerminator()))
1352 return true;
1353
1354 if (!GuaranteedToTransfer)
1355 GuaranteedToTransfer = isGuaranteedToTransferExecutionToSuccessor(
1356 Begin: LoadBB->begin(), End: LoadI->getIterator());
1357 return *GuaranteedToTransfer;
1358 };
1359
1360 // If there is exactly one predecessor where the value is unavailable, the
1361 // already computed 'OneUnavailablePred' block is it. If it ends in an
1362 // unconditional branch, we know that it isn't a critical edge.
1363 if (PredsScanned.size() == AvailablePreds.size()+1 &&
1364 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
1365 UnavailablePred = OneUnavailablePred;
1366 if (!CanSpeculateInto(UnavailablePred))
1367 return false;
1368 } else if (PredsScanned.size() != AvailablePreds.size()) {
1369 // Otherwise, we had multiple unavailable predecessors or we had a critical
1370 // edge from the one.
1371 SmallVector<BasicBlock*, 8> PredsToSplit;
1372 SmallPtrSet<BasicBlock *, 8> AvailablePredSet(
1373 llvm::from_range, llvm::make_first_range(c&: AvailablePreds));
1374
1375 // Add all the unavailable predecessors to the PredsToSplit list.
1376 for (BasicBlock *P : predecessors(BB: LoadBB)) {
1377 // If the predecessor is an indirect goto, we can't split the edge.
1378 if (isa<IndirectBrInst>(Val: P->getTerminator()))
1379 return false;
1380
1381 if (!AvailablePredSet.count(Ptr: P)) {
1382 if (!CanSpeculateInto(P))
1383 return false;
1384 PredsToSplit.push_back(Elt: P);
1385 }
1386 }
1387
1388 // Split them out to their own block.
1389 UnavailablePred = splitBlockPreds(BB: LoadBB, Preds: PredsToSplit, Suffix: "thread-pre-split");
1390 }
1391
1392 // If the value isn't available in all predecessors, then there will be
1393 // exactly one where it isn't available. Insert a load on that edge and add
1394 // it to the AvailablePreds list.
1395 if (UnavailablePred) {
1396 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
1397 "Can't handle critical edge here!");
1398 LoadInst *NewVal = new LoadInst(
1399 LoadI->getType(), LoadedPtr->DoPHITranslation(CurBB: LoadBB, PredBB: UnavailablePred),
1400 LoadI->getName() + ".pr", false, LoadI->getAlign(),
1401 LoadI->getOrdering(), LoadI->getSyncScopeID(),
1402 UnavailablePred->getTerminator()->getIterator());
1403 NewVal->setDebugLoc(LoadI->getDebugLoc());
1404 if (AATags)
1405 NewVal->setAAMetadata(AATags);
1406
1407 AvailablePreds.emplace_back(Args&: UnavailablePred, Args&: NewVal);
1408 }
1409
1410 // Now we know that each predecessor of this block has a value in
1411 // AvailablePreds, sort them for efficient access as we're walking the preds.
1412 array_pod_sort(Start: AvailablePreds.begin(), End: AvailablePreds.end());
1413
1414 // Create a PHI node at the start of the block for the PRE'd load value.
1415 PHINode *PN = PHINode::Create(Ty: LoadI->getType(), NumReservedValues: pred_size(BB: LoadBB), NameStr: "");
1416 PN->insertBefore(InsertPos: LoadBB->begin());
1417 PN->takeName(V: LoadI);
1418 PN->setDebugLoc(LoadI->getDebugLoc());
1419
1420 // Insert new entries into the PHI for each predecessor. A single block may
1421 // have multiple entries here.
1422 for (BasicBlock *P : predecessors(BB: LoadBB)) {
1423 AvailablePredsTy::iterator I =
1424 llvm::lower_bound(Range&: AvailablePreds, Value: std::make_pair(x&: P, y: (Value *)nullptr));
1425
1426 assert(I != AvailablePreds.end() && I->first == P &&
1427 "Didn't find entry for predecessor!");
1428
1429 // If we have an available predecessor but it requires casting, insert the
1430 // cast in the predecessor and use the cast. Note that we have to update the
1431 // AvailablePreds vector as we go so that all of the PHI entries for this
1432 // predecessor use the same bitcast.
1433 Value *&PredV = I->second;
1434 if (PredV->getType() != LoadI->getType()) {
1435 PredV = CastInst::CreateBitOrPointerCast(
1436 S: PredV, Ty: LoadI->getType(), Name: "", InsertBefore: P->getTerminator()->getIterator());
1437 // The new cast is producing the value used to replace the load
1438 // instruction, so uses the load's debug location. If P does not always
1439 // branch to the load BB however then the debug location must be dropped,
1440 // as it is hoisted past a conditional branch.
1441 DebugLoc DL = P->getTerminator()->getNumSuccessors() == 1
1442 ? LoadI->getDebugLoc()
1443 : DebugLoc::getDropped();
1444 cast<CastInst>(Val: PredV)->setDebugLoc(DL);
1445 }
1446
1447 PN->addIncoming(V: PredV, BB: I->first);
1448 }
1449
1450 for (LoadInst *PredLoadI : CSELoads) {
1451 combineMetadataForCSE(K: PredLoadI, J: LoadI, DoesKMove: true);
1452 LVI->forgetValue(V: PredLoadI);
1453 }
1454
1455 LoadI->replaceAllUsesWith(V: PN);
1456 LoadI->eraseFromParent();
1457
1458 return true;
1459}
1460
1461/// findMostPopularDest - The specified list contains multiple possible
1462/// threadable destinations. Pick the one that occurs the most frequently in
1463/// the list.
1464static BasicBlock *
1465findMostPopularDest(BasicBlock *BB,
1466 const SmallVectorImpl<std::pair<BasicBlock *,
1467 BasicBlock *>> &PredToDestList) {
1468 assert(!PredToDestList.empty());
1469
1470 // Determine popularity. If there are multiple possible destinations, we
1471 // explicitly choose to ignore 'undef' destinations. We prefer to thread
1472 // blocks with known and real destinations to threading undef. We'll handle
1473 // them later if interesting.
1474 MapVector<BasicBlock *, unsigned> DestPopularity;
1475
1476 // Populate DestPopularity with the successors in the order they appear in the
1477 // successor list. This way, we ensure determinism by iterating it in the
1478 // same order in llvm::max_element below. We map nullptr to 0 so that we can
1479 // return nullptr when PredToDestList contains nullptr only.
1480 DestPopularity[nullptr] = 0;
1481 for (auto *SuccBB : successors(BB))
1482 DestPopularity[SuccBB] = 0;
1483
1484 for (const auto &PredToDest : PredToDestList)
1485 if (PredToDest.second)
1486 DestPopularity[PredToDest.second]++;
1487
1488 // Find the most popular dest.
1489 auto MostPopular = llvm::max_element(Range&: DestPopularity, C: llvm::less_second());
1490
1491 // Okay, we have finally picked the most popular destination.
1492 return MostPopular->first;
1493}
1494
1495// Try to evaluate the value of V when the control flows from PredPredBB to
1496// BB->getSinglePredecessor() and then on to BB.
1497Constant *JumpThreadingPass::evaluateOnPredecessorEdge(BasicBlock *BB,
1498 BasicBlock *PredPredBB,
1499 Value *V,
1500 const DataLayout &DL) {
1501 SmallPtrSet<Value *, 8> Visited;
1502 return evaluateOnPredecessorEdge(BB, PredPredBB, cond: V, DL, Visited);
1503}
1504
1505Constant *JumpThreadingPass::evaluateOnPredecessorEdge(
1506 BasicBlock *BB, BasicBlock *PredPredBB, Value *V, const DataLayout &DL,
1507 SmallPtrSet<Value *, 8> &Visited) {
1508 if (!Visited.insert(Ptr: V).second)
1509 return nullptr;
1510 llvm::scope_exit _([&Visited, V]() { Visited.erase(Ptr: V); });
1511
1512 BasicBlock *PredBB = BB->getSinglePredecessor();
1513 assert(PredBB && "Expected a single predecessor");
1514
1515 if (Constant *Cst = dyn_cast<Constant>(Val: V)) {
1516 return Cst;
1517 }
1518
1519 // Consult LVI if V is not an instruction in BB or PredBB.
1520 Instruction *I = dyn_cast<Instruction>(Val: V);
1521 if (!I || (I->getParent() != BB && I->getParent() != PredBB)) {
1522 return LVI->getConstantOnEdge(V, FromBB: PredPredBB, ToBB: PredBB, CtxI: nullptr);
1523 }
1524
1525 // Look into a PHI argument.
1526 if (PHINode *PHI = dyn_cast<PHINode>(Val: V)) {
1527 if (PHI->getParent() == PredBB)
1528 return dyn_cast<Constant>(Val: PHI->getIncomingValueForBlock(BB: PredPredBB));
1529 return nullptr;
1530 }
1531
1532 // If we have a CmpInst, try to fold it for each incoming edge into PredBB.
1533 // Note that during the execution of the pass, phi nodes may become constant
1534 // and may be removed, which can lead to self-referencing instructions in
1535 // code that becomes unreachable. Consequently, we need to handle those
1536 // instructions in unreachable code and check before going into recursion.
1537 if (CmpInst *CondCmp = dyn_cast<CmpInst>(Val: V)) {
1538 if (CondCmp->getParent() == BB) {
1539 Constant *Op0 = evaluateOnPredecessorEdge(
1540 BB, PredPredBB, V: CondCmp->getOperand(i_nocapture: 0), DL, Visited);
1541 Constant *Op1 = evaluateOnPredecessorEdge(
1542 BB, PredPredBB, V: CondCmp->getOperand(i_nocapture: 1), DL, Visited);
1543 if (Op0 && Op1) {
1544 return ConstantFoldCompareInstOperands(Predicate: CondCmp->getPredicate(), LHS: Op0,
1545 RHS: Op1, DL);
1546 }
1547 }
1548 return nullptr;
1549 }
1550
1551 return nullptr;
1552}
1553
1554bool JumpThreadingPass::processThreadableEdges(Value *Cond, BasicBlock *BB,
1555 ConstantPreference Preference,
1556 Instruction *CtxI) {
1557 // If threading this would thread across a loop header, don't even try to
1558 // thread the edge.
1559 if (LoopHeaders.count(Ptr: BB))
1560 return false;
1561
1562 PredValueInfoTy PredValues;
1563 if (!computeValueKnownInPredecessors(V: Cond, BB, Result&: PredValues, Preference,
1564 CtxI)) {
1565 // We don't have known values in predecessors. See if we can thread through
1566 // BB and its sole predecessor.
1567 return maybethreadThroughTwoBasicBlocks(BB, Cond);
1568 }
1569
1570 assert(!PredValues.empty() &&
1571 "computeValueKnownInPredecessors returned true with no values");
1572
1573 LLVM_DEBUG(dbgs() << "IN BB: " << *BB;
1574 for (const auto &PredValue : PredValues) {
1575 dbgs() << " BB '" << BB->getName()
1576 << "': FOUND condition = " << *PredValue.first
1577 << " for pred '" << PredValue.second->getName() << "'.\n";
1578 });
1579
1580 // Decide what we want to thread through. Convert our list of known values to
1581 // a list of known destinations for each pred. This also discards duplicate
1582 // predecessors and keeps track of the undefined inputs (which are represented
1583 // as a null dest in the PredToDestList).
1584 SmallPtrSet<BasicBlock*, 16> SeenPreds;
1585 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
1586
1587 BasicBlock *OnlyDest = nullptr;
1588 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
1589 Constant *OnlyVal = nullptr;
1590 Constant *MultipleVal = (Constant *)(intptr_t)~0ULL;
1591
1592 for (const auto &PredValue : PredValues) {
1593 BasicBlock *Pred = PredValue.second;
1594 if (!SeenPreds.insert(Ptr: Pred).second)
1595 continue; // Duplicate predecessor entry.
1596
1597 Constant *Val = PredValue.first;
1598
1599 BasicBlock *DestBB;
1600 if (isa<UndefValue>(Val))
1601 DestBB = nullptr;
1602 else if (CondBrInst *BI = dyn_cast<CondBrInst>(Val: BB->getTerminator())) {
1603 assert(isa<ConstantInt>(Val) && "Expecting a constant integer");
1604 DestBB = BI->getSuccessor(i: cast<ConstantInt>(Val)->isZero());
1605 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Val: BB->getTerminator())) {
1606 assert(isa<ConstantInt>(Val) && "Expecting a constant integer");
1607 DestBB = SI->findCaseValue(C: cast<ConstantInt>(Val))->getCaseSuccessor();
1608 } else {
1609 assert(isa<IndirectBrInst>(BB->getTerminator())
1610 && "Unexpected terminator");
1611 assert(isa<BlockAddress>(Val) && "Expecting a constant blockaddress");
1612 DestBB = cast<BlockAddress>(Val)->getBasicBlock();
1613 }
1614
1615 // If we have exactly one destination, remember it for efficiency below.
1616 if (PredToDestList.empty()) {
1617 OnlyDest = DestBB;
1618 OnlyVal = Val;
1619 } else {
1620 if (OnlyDest != DestBB)
1621 OnlyDest = MultipleDestSentinel;
1622 // It possible we have same destination, but different value, e.g. default
1623 // case in switchinst.
1624 if (Val != OnlyVal)
1625 OnlyVal = MultipleVal;
1626 }
1627
1628 // If the predecessor ends with an indirect goto, we can't change its
1629 // destination.
1630 if (isa<IndirectBrInst>(Val: Pred->getTerminator()))
1631 continue;
1632
1633 PredToDestList.emplace_back(Args&: Pred, Args&: DestBB);
1634 }
1635
1636 // If all edges were unthreadable, we fail.
1637 if (PredToDestList.empty())
1638 return false;
1639
1640 // If all the predecessors go to a single known successor, we want to fold,
1641 // not thread. By doing so, we do not need to duplicate the current block and
1642 // also miss potential opportunities in case we dont/cant duplicate.
1643 if (OnlyDest && OnlyDest != MultipleDestSentinel) {
1644 if (BB->hasNPredecessors(N: PredToDestList.size())) {
1645 bool SeenFirstBranchToOnlyDest = false;
1646 std::vector <DominatorTree::UpdateType> Updates;
1647 Updates.reserve(n: BB->getTerminator()->getNumSuccessors() - 1);
1648 for (BasicBlock *SuccBB : successors(BB)) {
1649 if (SuccBB == OnlyDest && !SeenFirstBranchToOnlyDest) {
1650 SeenFirstBranchToOnlyDest = true; // Don't modify the first branch.
1651 } else {
1652 SuccBB->removePredecessor(Pred: BB, KeepOneInputPHIs: true); // This is unreachable successor.
1653 Updates.push_back(x: {DominatorTree::Delete, BB, SuccBB});
1654 }
1655 }
1656
1657 // Finally update the terminator.
1658 Instruction *Term = BB->getTerminator();
1659 Instruction *NewBI = UncondBrInst::Create(Target: OnlyDest, InsertBefore: Term->getIterator());
1660 NewBI->setDebugLoc(Term->getDebugLoc());
1661 ++NumFolds;
1662 Term->eraseFromParent();
1663 DTU->applyUpdatesPermissive(Updates);
1664 if (auto *BPI = getBPI())
1665 BPI->eraseBlock(BB);
1666
1667 // If the condition is now dead due to the removal of the old terminator,
1668 // erase it.
1669 if (auto *CondInst = dyn_cast<Instruction>(Val: Cond)) {
1670 if (CondInst->use_empty() && !CondInst->mayHaveSideEffects())
1671 CondInst->eraseFromParent();
1672 // We can safely replace *some* uses of the CondInst if it has
1673 // exactly one value as returned by LVI. RAUW is incorrect in the
1674 // presence of guards and assumes, that have the `Cond` as the use. This
1675 // is because we use the guards/assume to reason about the `Cond` value
1676 // at the end of block, but RAUW unconditionally replaces all uses
1677 // including the guards/assumes themselves and the uses before the
1678 // guard/assume.
1679 else if (OnlyVal && OnlyVal != MultipleVal)
1680 replaceFoldableUses(Cond: CondInst, ToVal: OnlyVal, KnownAtEndOfBB: BB);
1681 }
1682 return true;
1683 }
1684 }
1685
1686 // Determine which is the most common successor. If we have many inputs and
1687 // this block is a switch, we want to start by threading the batch that goes
1688 // to the most popular destination first. If we only know about one
1689 // threadable destination (the common case) we can avoid this.
1690 BasicBlock *MostPopularDest = OnlyDest;
1691
1692 if (MostPopularDest == MultipleDestSentinel) {
1693 // Remove any loop headers from the Dest list, threadEdge conservatively
1694 // won't process them, but we might have other destination that are eligible
1695 // and we still want to process.
1696 erase_if(C&: PredToDestList,
1697 P: [&](const std::pair<BasicBlock *, BasicBlock *> &PredToDest) {
1698 return LoopHeaders.contains(Ptr: PredToDest.second);
1699 });
1700
1701 if (PredToDestList.empty())
1702 return false;
1703
1704 MostPopularDest = findMostPopularDest(BB, PredToDestList);
1705 }
1706
1707 // Now that we know what the most popular destination is, factor all
1708 // predecessors that will jump to it into a single predecessor.
1709 SmallVector<BasicBlock*, 16> PredsToFactor;
1710 for (const auto &PredToDest : PredToDestList)
1711 if (PredToDest.second == MostPopularDest) {
1712 BasicBlock *Pred = PredToDest.first;
1713
1714 // This predecessor may be a switch or something else that has multiple
1715 // edges to the block. Factor each of these edges by listing them
1716 // according to # occurrences in PredsToFactor.
1717 for (BasicBlock *Succ : successors(BB: Pred))
1718 if (Succ == BB)
1719 PredsToFactor.push_back(Elt: Pred);
1720 }
1721
1722 // If the threadable edges are branching on an undefined value, we get to pick
1723 // the destination that these predecessors should get to.
1724 if (!MostPopularDest)
1725 MostPopularDest = BB->getTerminator()->
1726 getSuccessor(Idx: getBestDestForJumpOnUndef(BB));
1727
1728 // Ok, try to thread it!
1729 return tryThreadEdge(BB, PredBBs: PredsToFactor, SuccBB: MostPopularDest);
1730}
1731
1732/// processBranchOnPHI - We have an otherwise unthreadable conditional branch on
1733/// a PHI node (or freeze PHI) in the current block. See if there are any
1734/// simplifications we can do based on inputs to the phi node.
1735bool JumpThreadingPass::processBranchOnPHI(PHINode *PN) {
1736 BasicBlock *BB = PN->getParent();
1737
1738 // TODO: We could make use of this to do it once for blocks with common PHI
1739 // values.
1740 SmallVector<BasicBlock*, 1> PredBBs;
1741 PredBBs.resize(N: 1);
1742
1743 // If any of the predecessor blocks end in an unconditional branch, we can
1744 // *duplicate* the conditional branch into that block in order to further
1745 // encourage jump threading and to eliminate cases where we have branch on a
1746 // phi of an icmp (branch on icmp is much better).
1747 // This is still beneficial when a frozen phi is used as the branch condition
1748 // because it allows CodeGenPrepare to further canonicalize br(freeze(icmp))
1749 // to br(icmp(freeze ...)).
1750 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1751 BasicBlock *PredBB = PN->getIncomingBlock(i);
1752 if (isa<UncondBrInst>(Val: PredBB->getTerminator())) {
1753 PredBBs[0] = PredBB;
1754 // Try to duplicate BB into PredBB.
1755 if (duplicateCondBranchOnPHIIntoPred(BB, PredBBs))
1756 return true;
1757 }
1758 }
1759
1760 return false;
1761}
1762
1763/// processBranchOnXOR - We have an otherwise unthreadable conditional branch on
1764/// a xor instruction in the current block. See if there are any
1765/// simplifications we can do based on inputs to the xor.
1766bool JumpThreadingPass::processBranchOnXOR(BinaryOperator *BO) {
1767 BasicBlock *BB = BO->getParent();
1768
1769 // If either the LHS or RHS of the xor is a constant, don't do this
1770 // optimization.
1771 if (isa<ConstantInt>(Val: BO->getOperand(i_nocapture: 0)) ||
1772 isa<ConstantInt>(Val: BO->getOperand(i_nocapture: 1)))
1773 return false;
1774
1775 // If the first instruction in BB isn't a phi, we won't be able to infer
1776 // anything special about any particular predecessor.
1777 if (!isa<PHINode>(Val: BB->front()))
1778 return false;
1779
1780 // If this BB is a landing pad, we won't be able to split the edge into it.
1781 if (BB->isEHPad())
1782 return false;
1783
1784 // If we have a xor as the branch input to this block, and we know that the
1785 // LHS or RHS of the xor in any predecessor is true/false, then we can clone
1786 // the condition into the predecessor and fix that value to true, saving some
1787 // logical ops on that path and encouraging other paths to simplify.
1788 //
1789 // This copies something like this:
1790 //
1791 // BB:
1792 // %X = phi i1 [1], [%X']
1793 // %Y = icmp eq i32 %A, %B
1794 // %Z = xor i1 %X, %Y
1795 // br i1 %Z, ...
1796 //
1797 // Into:
1798 // BB':
1799 // %Y = icmp ne i32 %A, %B
1800 // br i1 %Y, ...
1801
1802 PredValueInfoTy XorOpValues;
1803 bool isLHS = true;
1804 if (!computeValueKnownInPredecessors(V: BO->getOperand(i_nocapture: 0), BB, Result&: XorOpValues,
1805 Preference: WantInteger, CtxI: BO)) {
1806 assert(XorOpValues.empty());
1807 if (!computeValueKnownInPredecessors(V: BO->getOperand(i_nocapture: 1), BB, Result&: XorOpValues,
1808 Preference: WantInteger, CtxI: BO))
1809 return false;
1810 isLHS = false;
1811 }
1812
1813 assert(!XorOpValues.empty() &&
1814 "computeValueKnownInPredecessors returned true with no values");
1815
1816 // Scan the information to see which is most popular: true or false. The
1817 // predecessors can be of the set true, false, or undef.
1818 unsigned NumTrue = 0, NumFalse = 0;
1819 for (const auto &XorOpValue : XorOpValues) {
1820 if (isa<UndefValue>(Val: XorOpValue.first))
1821 // Ignore undefs for the count.
1822 continue;
1823 if (cast<ConstantInt>(Val: XorOpValue.first)->isZero())
1824 ++NumFalse;
1825 else
1826 ++NumTrue;
1827 }
1828
1829 // Determine which value to split on, true, false, or undef if neither.
1830 ConstantInt *SplitVal = nullptr;
1831 if (NumTrue > NumFalse)
1832 SplitVal = ConstantInt::getTrue(Context&: BB->getContext());
1833 else if (NumTrue != 0 || NumFalse != 0)
1834 SplitVal = ConstantInt::getFalse(Context&: BB->getContext());
1835
1836 // Collect all of the blocks that this can be folded into so that we can
1837 // factor this once and clone it once.
1838 SmallVector<BasicBlock*, 8> BlocksToFoldInto;
1839 for (const auto &XorOpValue : XorOpValues) {
1840 if (XorOpValue.first != SplitVal && !isa<UndefValue>(Val: XorOpValue.first))
1841 continue;
1842
1843 BlocksToFoldInto.push_back(Elt: XorOpValue.second);
1844 }
1845
1846 // If we inferred a value for all of the predecessors, then duplication won't
1847 // help us. However, we can just replace the LHS or RHS with the constant.
1848 if (BlocksToFoldInto.size() ==
1849 cast<PHINode>(Val&: BB->front()).getNumIncomingValues()) {
1850 if (!SplitVal) {
1851 // If all preds provide undef, just nuke the xor, because it is undef too.
1852 BO->replaceAllUsesWith(V: UndefValue::get(T: BO->getType()));
1853 BO->eraseFromParent();
1854 } else if (SplitVal->isZero() && BO != BO->getOperand(i_nocapture: isLHS)) {
1855 // If all preds provide 0, replace the xor with the other input.
1856 BO->replaceAllUsesWith(V: BO->getOperand(i_nocapture: isLHS));
1857 BO->eraseFromParent();
1858 } else {
1859 // If all preds provide 1, set the computed value to 1.
1860 BO->setOperand(i_nocapture: !isLHS, Val_nocapture: SplitVal);
1861 }
1862
1863 return true;
1864 }
1865
1866 // If any of predecessors end with an indirect goto, we can't change its
1867 // destination.
1868 if (any_of(Range&: BlocksToFoldInto, P: [](BasicBlock *Pred) {
1869 return isa<IndirectBrInst>(Val: Pred->getTerminator());
1870 }))
1871 return false;
1872
1873 // Try to duplicate BB into PredBB.
1874 return duplicateCondBranchOnPHIIntoPred(BB, PredBBs: BlocksToFoldInto);
1875}
1876
1877/// addPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1878/// predecessor to the PHIBB block. If it has PHI nodes, add entries for
1879/// NewPred using the entries from OldPred (suitably mapped).
1880static void addPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1881 BasicBlock *OldPred,
1882 BasicBlock *NewPred,
1883 ValueToValueMapTy &ValueMap) {
1884 for (PHINode &PN : PHIBB->phis()) {
1885 // Ok, we have a PHI node. Figure out what the incoming value was for the
1886 // DestBlock.
1887 Value *IV = PN.getIncomingValueForBlock(BB: OldPred);
1888
1889 // Remap the value if necessary.
1890 if (Instruction *Inst = dyn_cast<Instruction>(Val: IV)) {
1891 ValueToValueMapTy::iterator I = ValueMap.find(Val: Inst);
1892 if (I != ValueMap.end())
1893 IV = I->second;
1894 }
1895
1896 PN.addIncoming(V: IV, BB: NewPred);
1897 }
1898}
1899
1900/// Merge basic block BB into its sole predecessor if possible.
1901bool JumpThreadingPass::maybeMergeBasicBlockIntoOnlyPred(BasicBlock *BB) {
1902 BasicBlock *SinglePred = BB->getSinglePredecessor();
1903 if (!SinglePred)
1904 return false;
1905
1906 const Instruction *TI = SinglePred->getTerminator();
1907 if (TI->isSpecialTerminator() || TI->getNumSuccessors() != 1 ||
1908 SinglePred == BB || hasAddressTakenAndUsed(BB))
1909 return false;
1910
1911 // MergeBasicBlockIntoOnlyPred may delete SinglePred, we need to avoid
1912 // deleting a BB pointer from Unreachable.
1913 if (Unreachable.count(Ptr: SinglePred))
1914 return false;
1915
1916 // Don't merge if both the basic block and the predecessor contain loop or
1917 // entry convergent intrinsics, since there may only be one convergence token
1918 // per block.
1919 if (HasLoopOrEntryConvergenceToken(BB) &&
1920 HasLoopOrEntryConvergenceToken(BB: SinglePred))
1921 return false;
1922
1923 // If SinglePred was a loop header, BB becomes one.
1924 if (LoopHeaders.erase(Ptr: SinglePred))
1925 LoopHeaders.insert(Ptr: BB);
1926
1927 LVI->eraseBlock(BB: SinglePred);
1928 MergeBasicBlockIntoOnlyPred(BB, DTU: DTU.get());
1929
1930 // Now that BB is merged into SinglePred (i.e. SinglePred code followed by
1931 // BB code within one basic block `BB`), we need to invalidate the LVI
1932 // information associated with BB, because the LVI information need not be
1933 // true for all of BB after the merge. For example,
1934 // Before the merge, LVI info and code is as follows:
1935 // SinglePred: <LVI info1 for %p val>
1936 // %y = use of %p
1937 // call @exit() // need not transfer execution to successor.
1938 // assume(%p) // from this point on %p is true
1939 // br label %BB
1940 // BB: <LVI info2 for %p val, i.e. %p is true>
1941 // %x = use of %p
1942 // br label exit
1943 //
1944 // Note that this LVI info for blocks BB and SinglPred is correct for %p
1945 // (info2 and info1 respectively). After the merge and the deletion of the
1946 // LVI info1 for SinglePred. We have the following code:
1947 // BB: <LVI info2 for %p val>
1948 // %y = use of %p
1949 // call @exit()
1950 // assume(%p)
1951 // %x = use of %p <-- LVI info2 is correct from here onwards.
1952 // br label exit
1953 // LVI info2 for BB is incorrect at the beginning of BB.
1954
1955 // Invalidate LVI information for BB if the LVI is not provably true for
1956 // all of BB.
1957 if (!isGuaranteedToTransferExecutionToSuccessor(BB))
1958 LVI->eraseBlock(BB);
1959 return true;
1960}
1961
1962/// Update the SSA form. NewBB contains instructions that are copied from BB.
1963/// ValueMapping maps old values in BB to new ones in NewBB.
1964void JumpThreadingPass::updateSSA(BasicBlock *BB, BasicBlock *NewBB,
1965 ValueToValueMapTy &ValueMapping) {
1966 // If there were values defined in BB that are used outside the block, then we
1967 // now have to update all uses of the value to use either the original value,
1968 // the cloned value, or some PHI derived value. This can require arbitrary
1969 // PHI insertion, of which we are prepared to do, clean these up now.
1970 SSAUpdater SSAUpdate;
1971 SmallVector<Use *, 16> UsesToRename;
1972 SmallVector<DbgVariableRecord *, 4> DbgVariableRecords;
1973
1974 for (Instruction &I : *BB) {
1975 // Scan all uses of this instruction to see if it is used outside of its
1976 // block, and if so, record them in UsesToRename.
1977
1978 SmallVector<Instruction *> LifetimeMarkers;
1979 for (Use &U : I.uses()) {
1980 Instruction *User = cast<Instruction>(Val: U.getUser());
1981 if (User->isLifetimeStartOrEnd()) {
1982 LifetimeMarkers.push_back(Elt: User);
1983 } else {
1984 if (PHINode *UserPN = dyn_cast<PHINode>(Val: User)) {
1985 if (UserPN->getIncomingBlock(U) == BB)
1986 continue;
1987 } else if (User->getParent() == BB)
1988 continue;
1989 }
1990 UsesToRename.push_back(Elt: &U);
1991 }
1992
1993 // Find debug values outside of the block
1994 findDbgValues(V: &I, DbgVariableRecords);
1995 llvm::erase_if(C&: DbgVariableRecords, P: [&](const DbgVariableRecord *DbgVarRec) {
1996 return DbgVarRec->getParent() == BB;
1997 });
1998
1999 // If there are no uses outside the block, we're done with this instruction.
2000 if (UsesToRename.empty() && DbgVariableRecords.empty())
2001 continue;
2002 LLVM_DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n");
2003
2004 // We found a use of I outside of BB. Rename all uses of I that are outside
2005 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
2006 // with the two values we know.
2007 SSAUpdate.Initialize(Ty: I.getType(), Name: I.getName());
2008 SSAUpdate.AddAvailableValue(BB, V: &I);
2009 SSAUpdate.AddAvailableValue(BB: NewBB, V: ValueMapping[&I]);
2010
2011 while (!UsesToRename.empty())
2012 SSAUpdate.RewriteUse(U&: *UsesToRename.pop_back_val());
2013 if (!DbgVariableRecords.empty()) {
2014 SSAUpdate.UpdateDebugValues(I: &I, DbgValues&: DbgVariableRecords);
2015 DbgVariableRecords.clear();
2016 }
2017
2018 // Lifetime markers cannot be rewritten through PHIs. If threading leaves
2019 // one of them pointing at a PHI, drop the whole set.
2020 bool HasPhiArg = any_of(Range&: LifetimeMarkers, P: [](Instruction *User) {
2021 return isa<PHINode>(Val: cast<CallBase>(Val: User)->getOperand(i_nocapture: 0));
2022 });
2023 if (HasPhiArg) {
2024 for (Instruction *User : LifetimeMarkers)
2025 User->eraseFromParent();
2026 }
2027 LLVM_DEBUG(dbgs() << "\n");
2028 }
2029}
2030
2031static void remapSourceAtoms(ValueToValueMapTy &VM, BasicBlock::iterator Begin,
2032 BasicBlock::iterator End) {
2033 if (VM.AtomMap.empty())
2034 return;
2035 for (auto It = Begin; It != End; ++It)
2036 RemapSourceAtom(I: &*It, VM);
2037}
2038
2039/// Clone instructions in range [BI, BE) to NewBB. For PHI nodes, we only clone
2040/// arguments that come from PredBB. Return the map from the variables in the
2041/// source basic block to the variables in the newly created basic block.
2042
2043void JumpThreadingPass::cloneInstructions(ValueToValueMapTy &ValueMapping,
2044 BasicBlock::iterator BI,
2045 BasicBlock::iterator BE,
2046 BasicBlock *NewBB,
2047 BasicBlock *PredBB) {
2048 // We are going to have to map operands from the source basic block to the new
2049 // copy of the block 'NewBB'. If there are PHI nodes in the source basic
2050 // block, evaluate them to account for entry from PredBB.
2051
2052 // Retargets dbg.value to any renamed variables.
2053 auto RetargetDbgVariableRecordIfPossible = [&](DbgVariableRecord *DVR) {
2054 SmallSet<std::pair<Value *, Value *>, 16> OperandsToRemap;
2055 for (auto *Op : DVR->location_ops()) {
2056 Instruction *OpInst = dyn_cast<Instruction>(Val: Op);
2057 if (!OpInst)
2058 continue;
2059
2060 auto I = ValueMapping.find(Val: OpInst);
2061 if (I != ValueMapping.end())
2062 OperandsToRemap.insert(V: {OpInst, I->second});
2063 }
2064
2065 for (auto &[OldOp, MappedOp] : OperandsToRemap)
2066 DVR->replaceVariableLocationOp(OldValue: OldOp, NewValue: MappedOp);
2067 };
2068
2069 BasicBlock *RangeBB = BI->getParent();
2070
2071 // Clone the phi nodes of the source basic block into NewBB. The resulting
2072 // phi nodes are trivial since NewBB only has one predecessor, but SSAUpdater
2073 // might need to rewrite the operand of the cloned phi.
2074 for (; PHINode *PN = dyn_cast<PHINode>(Val&: BI); ++BI) {
2075 PHINode *NewPN = PHINode::Create(Ty: PN->getType(), NumReservedValues: 1, NameStr: PN->getName(), InsertBefore: NewBB);
2076 NewPN->addIncoming(V: PN->getIncomingValueForBlock(BB: PredBB), BB: PredBB);
2077 ValueMapping[PN] = NewPN;
2078 if (const DebugLoc &DL = PN->getDebugLoc())
2079 mapAtomInstance(DL, VMap&: ValueMapping);
2080 }
2081
2082 // Clone noalias scope declarations in the threaded block. When threading a
2083 // loop exit, we would otherwise end up with two idential scope declarations
2084 // visible at the same time.
2085 SmallVector<MDNode *> NoAliasScopes;
2086 DenseMap<MDNode *, MDNode *> ClonedScopes;
2087 LLVMContext &Context = PredBB->getContext();
2088 identifyNoAliasScopesToClone(Start: BI, End: BE, NoAliasDeclScopes&: NoAliasScopes);
2089 cloneNoAliasScopes(NoAliasDeclScopes: NoAliasScopes, ClonedScopes, Ext: "thread", Context);
2090
2091 auto CloneAndRemapDbgInfo = [&](Instruction *NewInst, Instruction *From) {
2092 auto DVRRange = NewInst->cloneDebugInfoFrom(From);
2093 for (DbgVariableRecord &DVR : filterDbgVars(R: DVRRange))
2094 RetargetDbgVariableRecordIfPossible(&DVR);
2095 };
2096
2097 // Clone the non-phi instructions of the source basic block into NewBB,
2098 // keeping track of the mapping and using it to remap operands in the cloned
2099 // instructions.
2100 for (; BI != BE; ++BI) {
2101 Instruction *New = BI->clone();
2102 New->setName(BI->getName());
2103 New->insertInto(ParentBB: NewBB, It: NewBB->end());
2104 ValueMapping[&*BI] = New;
2105 adaptNoAliasScopes(I: New, ClonedScopes, Context);
2106
2107 CloneAndRemapDbgInfo(New, &*BI);
2108 if (const DebugLoc &DL = New->getDebugLoc())
2109 mapAtomInstance(DL, VMap&: ValueMapping);
2110
2111 // Remap operands to patch up intra-block references.
2112 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2113 if (Instruction *Inst = dyn_cast<Instruction>(Val: New->getOperand(i))) {
2114 ValueToValueMapTy::iterator I = ValueMapping.find(Val: Inst);
2115 if (I != ValueMapping.end())
2116 New->setOperand(i, Val: I->second);
2117 }
2118 }
2119
2120 // There may be DbgVariableRecords on the terminator, clone directly from
2121 // marker to marker as there isn't an instruction there.
2122 if (BE != RangeBB->end() && BE->hasDbgRecords()) {
2123 // Dump them at the end.
2124 DbgMarker *Marker = RangeBB->getMarker(It: BE);
2125 DbgMarker *EndMarker = NewBB->createMarker(It: NewBB->end());
2126 auto DVRRange = EndMarker->cloneDebugInfoFrom(From: Marker, FromHere: std::nullopt);
2127 for (DbgVariableRecord &DVR : filterDbgVars(R: DVRRange))
2128 RetargetDbgVariableRecordIfPossible(&DVR);
2129 }
2130}
2131
2132/// Attempt to thread through two successive basic blocks.
2133bool JumpThreadingPass::maybethreadThroughTwoBasicBlocks(BasicBlock *BB,
2134 Value *Cond) {
2135 // Consider:
2136 //
2137 // PredBB:
2138 // %var = phi i32* [ null, %bb1 ], [ @a, %bb2 ]
2139 // %tobool = icmp eq i32 %cond, 0
2140 // br i1 %tobool, label %BB, label ...
2141 //
2142 // BB:
2143 // %cmp = icmp eq i32* %var, null
2144 // br i1 %cmp, label ..., label ...
2145 //
2146 // We don't know the value of %var at BB even if we know which incoming edge
2147 // we take to BB. However, once we duplicate PredBB for each of its incoming
2148 // edges (say, PredBB1 and PredBB2), we know the value of %var in each copy of
2149 // PredBB. Then we can thread edges PredBB1->BB and PredBB2->BB through BB.
2150
2151 // Require that BB end with a Branch for simplicity.
2152 CondBrInst *CondBr = dyn_cast<CondBrInst>(Val: BB->getTerminator());
2153 if (!CondBr)
2154 return false;
2155
2156 // BB must have exactly one predecessor.
2157 BasicBlock *PredBB = BB->getSinglePredecessor();
2158 if (!PredBB)
2159 return false;
2160
2161 // Require that PredBB end with a conditional Branch. If PredBB ends with an
2162 // unconditional branch, we should be merging PredBB and BB instead. For
2163 // simplicity, we don't deal with a switch.
2164 CondBrInst *PredBBBranch = dyn_cast<CondBrInst>(Val: PredBB->getTerminator());
2165 if (!PredBBBranch)
2166 return false;
2167
2168 // If PredBB has exactly one incoming edge, we don't gain anything by copying
2169 // PredBB.
2170 if (PredBB->getSinglePredecessor())
2171 return false;
2172
2173 // Don't thread through PredBB if it contains a successor edge to itself, in
2174 // which case we would infinite loop. Suppose we are threading an edge from
2175 // PredPredBB through PredBB and BB to SuccBB with PredBB containing a
2176 // successor edge to itself. If we allowed jump threading in this case, we
2177 // could duplicate PredBB and BB as, say, PredBB.thread and BB.thread. Since
2178 // PredBB.thread has a successor edge to PredBB, we would immediately come up
2179 // with another jump threading opportunity from PredBB.thread through PredBB
2180 // and BB to SuccBB. This jump threading would repeatedly occur. That is, we
2181 // would keep peeling one iteration from PredBB.
2182 if (llvm::is_contained(Range: successors(BB: PredBB), Element: PredBB))
2183 return false;
2184
2185 // Don't thread across a loop header.
2186 if (LoopHeaders.count(Ptr: PredBB))
2187 return false;
2188
2189 // Avoid complication with duplicating EH pads.
2190 if (PredBB->isEHPad())
2191 return false;
2192
2193 // Find a predecessor that we can thread. For simplicity, we only consider a
2194 // successor edge out of BB to which we thread exactly one incoming edge into
2195 // PredBB.
2196 unsigned ZeroCount = 0;
2197 unsigned OneCount = 0;
2198 BasicBlock *ZeroPred = nullptr;
2199 BasicBlock *OnePred = nullptr;
2200 const DataLayout &DL = BB->getDataLayout();
2201 for (BasicBlock *P : predecessors(BB: PredBB)) {
2202 // If PredPred ends with IndirectBrInst, we can't handle it.
2203 if (isa<IndirectBrInst>(Val: P->getTerminator()))
2204 continue;
2205 if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(
2206 Val: evaluateOnPredecessorEdge(BB, PredPredBB: P, V: Cond, DL))) {
2207 if (CI->isZero()) {
2208 ZeroCount++;
2209 ZeroPred = P;
2210 } else if (CI->isOne()) {
2211 OneCount++;
2212 OnePred = P;
2213 }
2214 }
2215 }
2216
2217 // Disregard complicated cases where we have to thread multiple edges.
2218 BasicBlock *PredPredBB;
2219 if (ZeroCount == 1) {
2220 PredPredBB = ZeroPred;
2221 } else if (OneCount == 1) {
2222 PredPredBB = OnePred;
2223 } else {
2224 return false;
2225 }
2226
2227 BasicBlock *SuccBB = CondBr->getSuccessor(i: PredPredBB == ZeroPred);
2228
2229 // If threading to the same block as we come from, we would infinite loop.
2230 if (SuccBB == BB) {
2231 LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
2232 << "' - would thread to self!\n");
2233 return false;
2234 }
2235
2236 // If threading this would thread across a loop header, don't thread the edge.
2237 // See the comments above findLoopHeaders for justifications and caveats.
2238 if (LoopHeaders.count(Ptr: BB) || LoopHeaders.count(Ptr: SuccBB)) {
2239 LLVM_DEBUG({
2240 bool BBIsHeader = LoopHeaders.count(BB);
2241 bool SuccIsHeader = LoopHeaders.count(SuccBB);
2242 dbgs() << " Not threading across "
2243 << (BBIsHeader ? "loop header BB '" : "block BB '")
2244 << BB->getName() << "' to dest "
2245 << (SuccIsHeader ? "loop header BB '" : "block BB '")
2246 << SuccBB->getName()
2247 << "' - it might create an irreducible loop!\n";
2248 });
2249 return false;
2250 }
2251
2252 // Compute the cost of duplicating BB and PredBB.
2253 unsigned BBCost = getJumpThreadDuplicationCost(
2254 Opts: *Opts, TTI, BB, StopAt: BB->getTerminator(), Threshold: BBDupThreshold);
2255 unsigned PredBBCost = getJumpThreadDuplicationCost(
2256 Opts: *Opts, TTI, BB: PredBB, StopAt: PredBB->getTerminator(), Threshold: BBDupThreshold);
2257
2258 // Give up if costs are too high. We need to check BBCost and PredBBCost
2259 // individually before checking their sum because getJumpThreadDuplicationCost
2260 // return (unsigned)~0 for those basic blocks that cannot be duplicated.
2261 if (BBCost > BBDupThreshold || PredBBCost > BBDupThreshold ||
2262 BBCost + PredBBCost > BBDupThreshold) {
2263 LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName()
2264 << "' - Cost is too high: " << PredBBCost
2265 << " for PredBB, " << BBCost << "for BB\n");
2266 return false;
2267 }
2268
2269 // Now we are ready to duplicate PredBB.
2270 threadThroughTwoBasicBlocks(PredPredBB, PredBB, BB, SuccBB);
2271 return true;
2272}
2273
2274void JumpThreadingPass::threadThroughTwoBasicBlocks(BasicBlock *PredPredBB,
2275 BasicBlock *PredBB,
2276 BasicBlock *BB,
2277 BasicBlock *SuccBB) {
2278 LLVM_DEBUG(dbgs() << " Threading through '" << PredBB->getName() << "' and '"
2279 << BB->getName() << "'\n");
2280
2281 // Build BPI/BFI before any changes are made to IR.
2282 bool HasProfile = doesBlockHaveProfileData(BB);
2283 auto *BFI = getOrCreateBFI(Force: HasProfile);
2284 auto *BPI = getOrCreateBPI(Force: BFI != nullptr);
2285
2286 CondBrInst *CondBr = cast<CondBrInst>(Val: BB->getTerminator());
2287 CondBrInst *PredBBBranch = cast<CondBrInst>(Val: PredBB->getTerminator());
2288
2289 BasicBlock *NewBB =
2290 BasicBlock::Create(Context&: PredBB->getContext(), Name: PredBB->getName() + ".thread",
2291 Parent: PredBB->getParent(), InsertBefore: PredBB);
2292 NewBB->moveAfter(MovePos: PredBB);
2293
2294 // Set the block frequency of NewBB.
2295 if (BFI) {
2296 assert(BPI && "It's expected BPI to exist along with BFI");
2297 auto NewBBFreq = BFI->getBlockFreq(BB: PredPredBB) *
2298 BPI->getEdgeProbability(Src: PredPredBB, Dst: PredBB);
2299 BFI->setBlockFreq(BB: NewBB, Freq: NewBBFreq);
2300 }
2301
2302 // We are going to have to map operands from the original BB block to the new
2303 // copy of the block 'NewBB'. If there are PHI nodes in PredBB, evaluate them
2304 // to account for entry from PredPredBB.
2305 ValueToValueMapTy ValueMapping;
2306 cloneInstructions(ValueMapping, BI: PredBB->begin(), BE: PredBB->end(), NewBB,
2307 PredBB: PredPredBB);
2308
2309 // Copy the edge probabilities from PredBB to NewBB.
2310 if (BPI)
2311 BPI->copyEdgeProbabilities(Src: PredBB, Dst: NewBB);
2312
2313 // Update the terminator of PredPredBB to jump to NewBB instead of PredBB.
2314 // This eliminates predecessors from PredPredBB, which requires us to simplify
2315 // any PHI nodes in PredBB.
2316 Instruction *PredPredTerm = PredPredBB->getTerminator();
2317 for (unsigned i = 0, e = PredPredTerm->getNumSuccessors(); i != e; ++i)
2318 if (PredPredTerm->getSuccessor(Idx: i) == PredBB) {
2319 PredBB->removePredecessor(Pred: PredPredBB, KeepOneInputPHIs: true);
2320 PredPredTerm->setSuccessor(Idx: i, BB: NewBB);
2321 }
2322
2323 addPHINodeEntriesForMappedBlock(PHIBB: PredBBBranch->getSuccessor(i: 0), OldPred: PredBB, NewPred: NewBB,
2324 ValueMap&: ValueMapping);
2325 addPHINodeEntriesForMappedBlock(PHIBB: PredBBBranch->getSuccessor(i: 1), OldPred: PredBB, NewPred: NewBB,
2326 ValueMap&: ValueMapping);
2327
2328 DTU->applyUpdatesPermissive(
2329 Updates: {{DominatorTree::Insert, NewBB, CondBr->getSuccessor(i: 0)},
2330 {DominatorTree::Insert, NewBB, CondBr->getSuccessor(i: 1)},
2331 {DominatorTree::Insert, PredPredBB, NewBB},
2332 {DominatorTree::Delete, PredPredBB, PredBB}});
2333
2334 // Remap source location atoms beacuse we're duplicating control flow.
2335 remapSourceAtoms(VM&: ValueMapping, Begin: NewBB->begin(), End: NewBB->end());
2336
2337 updateSSA(BB: PredBB, NewBB, ValueMapping);
2338
2339 // Clean up things like PHI nodes with single operands, dead instructions,
2340 // etc.
2341 SimplifyInstructionsInBlock(BB: NewBB, TLI);
2342 SimplifyInstructionsInBlock(BB: PredBB, TLI);
2343
2344 SmallVector<BasicBlock *, 1> PredsToFactor;
2345 PredsToFactor.push_back(Elt: NewBB);
2346 threadEdge(BB, PredBBs: PredsToFactor, SuccBB);
2347}
2348
2349/// tryThreadEdge - Thread an edge if it's safe and profitable to do so.
2350bool JumpThreadingPass::tryThreadEdge(
2351 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs,
2352 BasicBlock *SuccBB) {
2353 // If threading to the same block as we come from, we would infinite loop.
2354 if (SuccBB == BB) {
2355 LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
2356 << "' - would thread to self!\n");
2357 return false;
2358 }
2359
2360 // If threading this would thread across a loop header, don't thread the edge.
2361 // See the comments above findLoopHeaders for justifications and caveats.
2362 if (LoopHeaders.count(Ptr: BB) || LoopHeaders.count(Ptr: SuccBB)) {
2363 LLVM_DEBUG({
2364 bool BBIsHeader = LoopHeaders.count(BB);
2365 bool SuccIsHeader = LoopHeaders.count(SuccBB);
2366 dbgs() << " Not threading across "
2367 << (BBIsHeader ? "loop header BB '" : "block BB '") << BB->getName()
2368 << "' to dest " << (SuccIsHeader ? "loop header BB '" : "block BB '")
2369 << SuccBB->getName() << "' - it might create an irreducible loop!\n";
2370 });
2371 return false;
2372 }
2373
2374 unsigned JumpThreadCost = getJumpThreadDuplicationCost(
2375 Opts: *Opts, TTI, BB, StopAt: BB->getTerminator(), Threshold: BBDupThreshold);
2376 if (JumpThreadCost > BBDupThreshold) {
2377 LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName()
2378 << "' - Cost is too high: " << JumpThreadCost << "\n");
2379 return false;
2380 }
2381
2382 threadEdge(BB, PredBBs, SuccBB);
2383 return true;
2384}
2385
2386/// threadEdge - We have decided that it is safe and profitable to factor the
2387/// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
2388/// across BB. Transform the IR to reflect this change.
2389void JumpThreadingPass::threadEdge(BasicBlock *BB,
2390 const SmallVectorImpl<BasicBlock *> &PredBBs,
2391 BasicBlock *SuccBB) {
2392 assert(SuccBB != BB && "Don't create an infinite loop");
2393
2394 assert(!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) &&
2395 "Don't thread across loop headers");
2396
2397 // Build BPI/BFI before any changes are made to IR.
2398 bool HasProfile = doesBlockHaveProfileData(BB);
2399 auto *BFI = getOrCreateBFI(Force: HasProfile);
2400 auto *BPI = getOrCreateBPI(Force: BFI != nullptr);
2401
2402 // And finally, do it! Start by factoring the predecessors if needed.
2403 BasicBlock *PredBB;
2404 if (PredBBs.size() == 1)
2405 PredBB = PredBBs[0];
2406 else {
2407 LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size()
2408 << " common predecessors.\n");
2409 PredBB = splitBlockPreds(BB, Preds: PredBBs, Suffix: ".thr_comm");
2410 }
2411
2412 // And finally, do it!
2413 LLVM_DEBUG(dbgs() << " Threading edge from '" << PredBB->getName()
2414 << "' to '" << SuccBB->getName()
2415 << ", across block:\n " << *BB << "\n");
2416
2417 LVI->threadEdge(PredBB, OldSucc: BB, NewSucc: SuccBB);
2418
2419 BasicBlock *NewBB = BasicBlock::Create(Context&: BB->getContext(),
2420 Name: BB->getName()+".thread",
2421 Parent: BB->getParent(), InsertBefore: BB);
2422 NewBB->moveAfter(MovePos: PredBB);
2423
2424 // Set the block frequency of NewBB.
2425 if (BFI) {
2426 assert(BPI && "It's expected BPI to exist along with BFI");
2427 auto NewBBFreq =
2428 BFI->getBlockFreq(BB: PredBB) * BPI->getEdgeProbability(Src: PredBB, Dst: BB);
2429 BFI->setBlockFreq(BB: NewBB, Freq: NewBBFreq);
2430 }
2431
2432 // Copy all the instructions from BB to NewBB except the terminator.
2433 ValueToValueMapTy ValueMapping;
2434 cloneInstructions(ValueMapping, BI: BB->begin(), BE: std::prev(x: BB->end()), NewBB,
2435 PredBB);
2436
2437 // We didn't copy the terminator from BB over to NewBB, because there is now
2438 // an unconditional jump to SuccBB. Insert the unconditional jump.
2439 UncondBrInst *NewBI = UncondBrInst::Create(Target: SuccBB, InsertBefore: NewBB);
2440 NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
2441
2442 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
2443 // PHI nodes for NewBB now.
2444 addPHINodeEntriesForMappedBlock(PHIBB: SuccBB, OldPred: BB, NewPred: NewBB, ValueMap&: ValueMapping);
2445
2446 // Update the terminator of PredBB to jump to NewBB instead of BB. This
2447 // eliminates predecessors from BB, which requires us to simplify any PHI
2448 // nodes in BB.
2449 Instruction *PredTerm = PredBB->getTerminator();
2450 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
2451 if (PredTerm->getSuccessor(Idx: i) == BB) {
2452 BB->removePredecessor(Pred: PredBB, KeepOneInputPHIs: true);
2453 PredTerm->setSuccessor(Idx: i, BB: NewBB);
2454 }
2455
2456 // Enqueue required DT updates.
2457 DTU->applyUpdatesPermissive(Updates: {{DominatorTree::Insert, NewBB, SuccBB},
2458 {DominatorTree::Insert, PredBB, NewBB},
2459 {DominatorTree::Delete, PredBB, BB}});
2460
2461 remapSourceAtoms(VM&: ValueMapping, Begin: NewBB->begin(), End: NewBB->end());
2462 updateSSA(BB, NewBB, ValueMapping);
2463
2464 // At this point, the IR is fully up to date and consistent. Do a quick scan
2465 // over the new instructions and zap any that are constants or dead. This
2466 // frequently happens because of phi translation.
2467 SimplifyInstructionsInBlock(BB: NewBB, TLI);
2468
2469 // Update the edge weight from BB to SuccBB, which should be less than before.
2470 updateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB, BFI, BPI, HasProfile);
2471
2472 // Threaded an edge!
2473 ++NumThreads;
2474}
2475
2476/// Create a new basic block that will be the predecessor of BB and successor of
2477/// all blocks in Preds. When profile data is available, update the frequency of
2478/// this new block.
2479BasicBlock *JumpThreadingPass::splitBlockPreds(BasicBlock *BB,
2480 ArrayRef<BasicBlock *> Preds,
2481 const char *Suffix) {
2482 SmallVector<BasicBlock *, 2> NewBBs;
2483
2484 // Collect the frequencies of all predecessors of BB, which will be used to
2485 // update the edge weight of the result of splitting predecessors.
2486 DenseMap<BasicBlock *, BlockFrequency> FreqMap;
2487 auto *BFI = getBFI();
2488 if (BFI) {
2489 auto *BPI = getOrCreateBPI(Force: true);
2490 for (auto *Pred : Preds)
2491 FreqMap.insert(KV: std::make_pair(
2492 x&: Pred, y: BFI->getBlockFreq(BB: Pred) * BPI->getEdgeProbability(Src: Pred, Dst: BB)));
2493 }
2494
2495 // In the case when BB is a LandingPad block we create 2 new predecessors
2496 // instead of just one.
2497 if (BB->isLandingPad()) {
2498 std::string NewName = std::string(Suffix) + ".split-lp";
2499 SplitLandingPadPredecessors(OrigBB: BB, Preds, Suffix, Suffix2: NewName.c_str(), NewBBs);
2500 } else {
2501 NewBBs.push_back(Elt: SplitBlockPredecessors(BB, Preds, Suffix));
2502 }
2503
2504 std::vector<DominatorTree::UpdateType> Updates;
2505 Updates.reserve(n: (2 * Preds.size()) + NewBBs.size());
2506 for (auto *NewBB : NewBBs) {
2507 BlockFrequency NewBBFreq(0);
2508 Updates.push_back(x: {DominatorTree::Insert, NewBB, BB});
2509 for (auto *Pred : predecessors(BB: NewBB)) {
2510 Updates.push_back(x: {DominatorTree::Delete, Pred, BB});
2511 Updates.push_back(x: {DominatorTree::Insert, Pred, NewBB});
2512 if (BFI) // Update frequencies between Pred -> NewBB.
2513 NewBBFreq += FreqMap.lookup(Val: Pred);
2514 }
2515 if (BFI) // Apply the summed frequency to NewBB.
2516 BFI->setBlockFreq(BB: NewBB, Freq: NewBBFreq);
2517 }
2518
2519 DTU->applyUpdatesPermissive(Updates);
2520 return NewBBs[0];
2521}
2522
2523bool JumpThreadingPass::doesBlockHaveProfileData(BasicBlock *BB) {
2524 const Instruction *TI = BB->getTerminator();
2525 if (!TI || TI->getNumSuccessors() < 2)
2526 return false;
2527
2528 return hasValidBranchWeightMD(I: *TI);
2529}
2530
2531/// Update the block frequency of BB and branch weight and the metadata on the
2532/// edge BB->SuccBB. This is done by scaling the weight of BB->SuccBB by 1 -
2533/// Freq(PredBB->BB) / Freq(BB->SuccBB).
2534void JumpThreadingPass::updateBlockFreqAndEdgeWeight(BasicBlock *PredBB,
2535 BasicBlock *BB,
2536 BasicBlock *NewBB,
2537 BasicBlock *SuccBB,
2538 BlockFrequencyInfo *BFI,
2539 BranchProbabilityInfo *BPI,
2540 bool HasProfile) {
2541 assert(((BFI && BPI) || (!BFI && !BFI)) &&
2542 "Both BFI & BPI should either be set or unset");
2543
2544 if (!BFI) {
2545 assert(!HasProfile &&
2546 "It's expected to have BFI/BPI when profile info exists");
2547 return;
2548 }
2549
2550 // As the edge from PredBB to BB is deleted, we have to update the block
2551 // frequency of BB.
2552 auto BBOrigFreq = BFI->getBlockFreq(BB);
2553 auto NewBBFreq = BFI->getBlockFreq(BB: NewBB);
2554 auto BBNewFreq = BBOrigFreq - NewBBFreq;
2555 BFI->setBlockFreq(BB, Freq: BBNewFreq);
2556
2557 // Collect updated outgoing edges' frequencies from BB and use them to update
2558 // edge probabilities.
2559 SmallVector<uint64_t, 4> BBSuccFreq;
2560 for (auto It : enumerate(First: successors(BB))) {
2561 auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(Src: BB, IndexInSuccessors: It.index());
2562 auto SuccFreq =
2563 (It.value() == SuccBB) ? BB2SuccBBFreq - NewBBFreq : BB2SuccBBFreq;
2564 BBSuccFreq.push_back(Elt: SuccFreq.getFrequency());
2565 }
2566
2567 uint64_t MaxBBSuccFreq = *llvm::max_element(Range&: BBSuccFreq);
2568
2569 SmallVector<BranchProbability, 4> BBSuccProbs;
2570 if (MaxBBSuccFreq == 0)
2571 BBSuccProbs.assign(NumElts: BBSuccFreq.size(),
2572 Elt: {1, static_cast<unsigned>(BBSuccFreq.size())});
2573 else {
2574 for (uint64_t Freq : BBSuccFreq)
2575 BBSuccProbs.push_back(
2576 Elt: BranchProbability::getBranchProbability(Numerator: Freq, Denominator: MaxBBSuccFreq));
2577 // Normalize edge probabilities so that they sum up to one.
2578 BranchProbability::normalizeProbabilities(Begin: BBSuccProbs.begin(),
2579 End: BBSuccProbs.end());
2580 }
2581
2582 // Update edge probabilities in BPI.
2583 BPI->setEdgeProbability(Src: BB, Probs: BBSuccProbs);
2584
2585 // Update the profile metadata as well.
2586 //
2587 // Don't do this if the profile of the transformed blocks was statically
2588 // estimated. (This could occur despite the function having an entry
2589 // frequency in completely cold parts of the CFG.)
2590 //
2591 // In this case we don't want to suggest to subsequent passes that the
2592 // calculated weights are fully consistent. Consider this graph:
2593 //
2594 // check_1
2595 // 50% / |
2596 // eq_1 | 50%
2597 // \ |
2598 // check_2
2599 // 50% / |
2600 // eq_2 | 50%
2601 // \ |
2602 // check_3
2603 // 50% / |
2604 // eq_3 | 50%
2605 // \ |
2606 //
2607 // Assuming the blocks check_* all compare the same value against 1, 2 and 3,
2608 // the overall probabilities are inconsistent; the total probability that the
2609 // value is either 1, 2 or 3 is 150%.
2610 //
2611 // As a consequence if we thread eq_1 -> check_2 to check_3, check_2->check_3
2612 // becomes 0%. This is even worse if the edge whose probability becomes 0% is
2613 // the loop exit edge. Then based solely on static estimation we would assume
2614 // the loop was extremely hot.
2615 //
2616 // FIXME this locally as well so that BPI and BFI are consistent as well. We
2617 // shouldn't make edges extremely likely or unlikely based solely on static
2618 // estimation.
2619 if (BBSuccProbs.size() >= 2 && HasProfile) {
2620 SmallVector<uint32_t, 4> Weights;
2621 for (auto Prob : BBSuccProbs)
2622 Weights.push_back(Elt: Prob.getNumerator());
2623
2624 auto TI = BB->getTerminator();
2625 setBranchWeights(I&: *TI, Weights, IsExpected: hasBranchWeightOrigin(I: *TI));
2626 }
2627}
2628
2629/// duplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
2630/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
2631/// If we can duplicate the contents of BB up into PredBB do so now, this
2632/// improves the odds that the branch will be on an analyzable instruction like
2633/// a compare.
2634bool JumpThreadingPass::duplicateCondBranchOnPHIIntoPred(
2635 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) {
2636 assert(!PredBBs.empty() && "Can't handle an empty set");
2637
2638 // If BB is a loop header, then duplicating this block outside the loop would
2639 // cause us to transform this into an irreducible loop, don't do this.
2640 // See the comments above findLoopHeaders for justifications and caveats.
2641 if (LoopHeaders.count(Ptr: BB)) {
2642 LLVM_DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName()
2643 << "' into predecessor block '" << PredBBs[0]->getName()
2644 << "' - it might create an irreducible loop!\n");
2645 return false;
2646 }
2647
2648 unsigned DuplicationCost = getJumpThreadDuplicationCost(
2649 Opts: *Opts, TTI, BB, StopAt: BB->getTerminator(), Threshold: BBDupThreshold);
2650 if (DuplicationCost > BBDupThreshold) {
2651 LLVM_DEBUG(dbgs() << " Not duplicating BB '" << BB->getName()
2652 << "' - Cost is too high: " << DuplicationCost << "\n");
2653 return false;
2654 }
2655
2656 // And finally, do it! Start by factoring the predecessors if needed.
2657 std::vector<DominatorTree::UpdateType> Updates;
2658 BasicBlock *PredBB;
2659 if (PredBBs.size() == 1)
2660 PredBB = PredBBs[0];
2661 else {
2662 LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size()
2663 << " common predecessors.\n");
2664 PredBB = splitBlockPreds(BB, Preds: PredBBs, Suffix: ".thr_comm");
2665 }
2666 Updates.push_back(x: {DominatorTree::Delete, PredBB, BB});
2667
2668 // Okay, we decided to do this! Clone all the instructions in BB onto the end
2669 // of PredBB.
2670 LLVM_DEBUG(dbgs() << " Duplicating block '" << BB->getName()
2671 << "' into end of '" << PredBB->getName()
2672 << "' to eliminate branch on phi. Cost: "
2673 << DuplicationCost << " block is:" << *BB << "\n");
2674
2675 // When BB contains PHIs, we need a dedicated PredBB to clone these PHIs into,
2676 // so split the PredBB -> BB edge to create one. Otherwise fall back to
2677 // cloning into PredBB directly, splitting only when it lacks an unconditional
2678 // branch.
2679 BasicBlock *OldPredBB = PredBB;
2680 UncondBrInst *OldPredBranch = dyn_cast<UncondBrInst>(Val: PredBB->getTerminator());
2681 if (isa<PHINode>(Val: BB->front()) || !OldPredBranch) {
2682 PredBB = SplitEdge(From: OldPredBB, To: BB);
2683 Updates.push_back(x: {DominatorTree::Insert, OldPredBB, PredBB});
2684 Updates.push_back(x: {DominatorTree::Insert, PredBB, BB});
2685 OldPredBranch = cast<UncondBrInst>(Val: PredBB->getTerminator());
2686 }
2687
2688 // We are going to have to map operands from the original BB block into the
2689 // PredBB block. Evaluate PHI nodes in BB.
2690 ValueToValueMapTy ValueMapping;
2691
2692 // Remember the position before the inserted instructions.
2693 auto RItBeforeInsertPt = std::next(x: OldPredBranch->getReverseIterator());
2694
2695 BasicBlock::iterator BI = BB->begin();
2696 for (; PHINode *PN = dyn_cast<PHINode>(Val&: BI); ++BI) {
2697 PHINode *NewPN = PHINode::Create(Ty: PN->getType(), NumReservedValues: 1, NameStr: PN->getName() + ".dup");
2698 NewPN->insertBefore(InsertPos: OldPredBranch->getIterator());
2699 NewPN->addIncoming(V: PN->getIncomingValueForBlock(BB: PredBB), BB: OldPredBB);
2700 ValueMapping[PN] = NewPN;
2701 }
2702
2703 // Clone noalias scope declarations in the duplicated instructions. Otherwise
2704 // the duplicate would share the original block's scopes, and alias analysis
2705 // could conclude two accesses on different paths do not alias when they may.
2706 SmallVector<MDNode *> NoAliasScopes;
2707 DenseMap<MDNode *, MDNode *> ClonedScopes;
2708 LLVMContext &Context = PredBB->getContext();
2709 identifyNoAliasScopesToClone(Start: BI, End: BB->end(), NoAliasDeclScopes&: NoAliasScopes);
2710 cloneNoAliasScopes(NoAliasDeclScopes: NoAliasScopes, ClonedScopes, Ext: "thread", Context);
2711
2712 // Clone the non-phi instructions of BB into PredBB, keeping track of the
2713 // mapping and using it to remap operands in the cloned instructions.
2714 for (; BI != BB->end(); ++BI) {
2715 Instruction *New = BI->clone();
2716 New->insertInto(ParentBB: PredBB, It: OldPredBranch->getIterator());
2717 adaptNoAliasScopes(I: New, ClonedScopes, Context);
2718
2719 // Remap operands to patch up intra-block references.
2720 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2721 if (Instruction *Inst = dyn_cast<Instruction>(Val: New->getOperand(i))) {
2722 ValueToValueMapTy::iterator I = ValueMapping.find(Val: Inst);
2723 if (I != ValueMapping.end())
2724 New->setOperand(i, Val: I->second);
2725 }
2726
2727 // Remap debug variable operands.
2728 remapDebugVariable(Mapping&: ValueMapping, Inst: New);
2729 if (const DebugLoc &DL = New->getDebugLoc())
2730 mapAtomInstance(DL, VMap&: ValueMapping);
2731
2732 // If this instruction can be simplified after the operands are updated,
2733 // just use the simplified value instead. This frequently happens due to
2734 // phi translation.
2735 if (Value *IV = simplifyInstruction(
2736 I: New,
2737 Q: {BB->getDataLayout(), TLI, nullptr, nullptr, New})) {
2738 ValueMapping[&*BI] = IV;
2739 if (!New->mayHaveSideEffects()) {
2740 New->eraseFromParent();
2741 New = nullptr;
2742 // Clone debug-info on the elided instruction to the destination
2743 // position.
2744 OldPredBranch->cloneDebugInfoFrom(From: &*BI, FromHere: std::nullopt, InsertAtHead: true);
2745 }
2746 } else {
2747 ValueMapping[&*BI] = New;
2748 }
2749 if (New) {
2750 // Otherwise, insert the new instruction into the block.
2751 New->setName(BI->getName());
2752 // Clone across any debug-info attached to the old instruction.
2753 New->cloneDebugInfoFrom(From: &*BI);
2754 // Update Dominance from simplified New instruction operands.
2755 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2756 if (BasicBlock *SuccBB = dyn_cast<BasicBlock>(Val: New->getOperand(i)))
2757 Updates.push_back(x: {DominatorTree::Insert, PredBB, SuccBB});
2758 }
2759 }
2760
2761 // Check to see if the targets of the branch had PHI nodes. If so, we need to
2762 // add entries to the PHI nodes for branch from PredBB now.
2763 CondBrInst *BBBranch = cast<CondBrInst>(Val: BB->getTerminator());
2764 addPHINodeEntriesForMappedBlock(PHIBB: BBBranch->getSuccessor(i: 0), OldPred: BB, NewPred: PredBB,
2765 ValueMap&: ValueMapping);
2766 addPHINodeEntriesForMappedBlock(PHIBB: BBBranch->getSuccessor(i: 1), OldPred: BB, NewPred: PredBB,
2767 ValueMap&: ValueMapping);
2768
2769 // KeyInstructions: Remap the cloned instructions' atoms only.
2770 remapSourceAtoms(VM&: ValueMapping, Begin: std::prev(x: RItBeforeInsertPt)->getIterator(),
2771 End: OldPredBranch->getIterator());
2772
2773 updateSSA(BB, NewBB: PredBB, ValueMapping);
2774
2775 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
2776 // that we nuked.
2777 BB->removePredecessor(Pred: PredBB, KeepOneInputPHIs: true);
2778
2779 // Remove the unconditional branch at the end of the PredBB block.
2780 OldPredBranch->eraseFromParent();
2781 DTU->applyUpdatesPermissive(Updates);
2782
2783 BasicBlock *ThreadBB = PredBB;
2784 if (PredBB != OldPredBB && MergeBlockIntoPredecessor(BB: PredBB, DTU: DTU.get()))
2785 ThreadBB = OldPredBB;
2786
2787 if (auto *BPI = getBPI())
2788 BPI->copyEdgeProbabilities(Src: BB, Dst: ThreadBB);
2789
2790 ++NumDupes;
2791 return true;
2792}
2793
2794// Pred is a predecessor of BB with an unconditional branch to BB. SI is
2795// a Select instruction in Pred. BB has other predecessors and SI is used in
2796// a PHI node in BB. SI has no other use.
2797// A new basic block, NewBB, is created and SI is converted to compare and
2798// conditional branch. SI is erased from parent.
2799void JumpThreadingPass::unfoldSelectInstr(BasicBlock *Pred, BasicBlock *BB,
2800 SelectInst *SI, PHINode *SIUse,
2801 unsigned Idx) {
2802 // Expand the select.
2803 //
2804 // Pred --
2805 // | v
2806 // | NewBB
2807 // | |
2808 // |-----
2809 // v
2810 // BB
2811 UncondBrInst *PredTerm = cast<UncondBrInst>(Val: Pred->getTerminator());
2812 BasicBlock *NewBB = BasicBlock::Create(Context&: BB->getContext(), Name: "select.unfold",
2813 Parent: BB->getParent(), InsertBefore: BB);
2814 // Move the unconditional branch to NewBB.
2815 PredTerm->removeFromParent();
2816 PredTerm->insertInto(ParentBB: NewBB, It: NewBB->end());
2817 // Create a conditional branch and update PHI nodes.
2818 //
2819 // FIXME: We should `freeze` the condition before using it in a conditional
2820 // branch, unless we can prove it's not poison: select-on-poison isn't UB,
2821 // but branch-on-poison is. But doing this causes performance regressions,
2822 // and we haven't been able to find an end-to-end correctness issue it fixes.
2823 // https://github.com/llvm/llvm-project/pull/199408#issuecomment-4545013881.
2824 auto *BI = CondBrInst::Create(Cond: SI->getCondition(), IfTrue: NewBB, IfFalse: BB, InsertBefore: Pred);
2825 BI->applyMergedLocation(LocA: PredTerm->getDebugLoc(), LocB: SI->getDebugLoc());
2826 BI->copyMetadata(SrcInst: *SI, WL: {LLVMContext::MD_prof});
2827 SIUse->setIncomingValue(i: Idx, V: SI->getFalseValue());
2828 SIUse->addIncoming(V: SI->getTrueValue(), BB: NewBB);
2829
2830 uint64_t TrueWeight = 1;
2831 uint64_t FalseWeight = 1;
2832 // Copy probabilities from 'SI' to created conditional branch in 'Pred'.
2833 if (extractBranchWeights(I: *SI, TrueVal&: TrueWeight, FalseVal&: FalseWeight) &&
2834 (TrueWeight + FalseWeight) != 0) {
2835 SmallVector<BranchProbability, 2> BP;
2836 BP.emplace_back(Args: BranchProbability::getBranchProbability(
2837 Numerator: TrueWeight, Denominator: TrueWeight + FalseWeight));
2838 BP.emplace_back(Args: BranchProbability::getBranchProbability(
2839 Numerator: FalseWeight, Denominator: TrueWeight + FalseWeight));
2840 // Update BPI if exists.
2841 if (auto *BPI = getBPI())
2842 BPI->setEdgeProbability(Src: Pred, Probs: BP);
2843 }
2844 // Set the block frequency of NewBB.
2845 if (auto *BFI = getBFI()) {
2846 if ((TrueWeight + FalseWeight) == 0) {
2847 TrueWeight = 1;
2848 FalseWeight = 1;
2849 }
2850 BranchProbability PredToNewBBProb = BranchProbability::getBranchProbability(
2851 Numerator: TrueWeight, Denominator: TrueWeight + FalseWeight);
2852 auto NewBBFreq = BFI->getBlockFreq(BB: Pred) * PredToNewBBProb;
2853 BFI->setBlockFreq(BB: NewBB, Freq: NewBBFreq);
2854 }
2855
2856 // The select is now dead.
2857 SI->eraseFromParent();
2858 DTU->applyUpdatesPermissive(Updates: {{DominatorTree::Insert, NewBB, BB},
2859 {DominatorTree::Insert, Pred, NewBB}});
2860
2861 // Update any other PHI nodes in BB.
2862 for (BasicBlock::iterator BI = BB->begin();
2863 PHINode *Phi = dyn_cast<PHINode>(Val&: BI); ++BI)
2864 if (Phi != SIUse)
2865 Phi->addIncoming(V: Phi->getIncomingValueForBlock(BB: Pred), BB: NewBB);
2866}
2867
2868bool JumpThreadingPass::tryToUnfoldSelect(SwitchInst *SI, BasicBlock *BB) {
2869 PHINode *CondPHI = dyn_cast<PHINode>(Val: SI->getCondition());
2870
2871 if (!CondPHI || CondPHI->getParent() != BB)
2872 return false;
2873
2874 for (unsigned I = 0, E = CondPHI->getNumIncomingValues(); I != E; ++I) {
2875 BasicBlock *Pred = CondPHI->getIncomingBlock(i: I);
2876 SelectInst *PredSI = dyn_cast<SelectInst>(Val: CondPHI->getIncomingValue(i: I));
2877
2878 // The second and third condition can be potentially relaxed. Currently
2879 // the conditions help to simplify the code and allow us to reuse existing
2880 // code, developed for tryToUnfoldSelect(CmpInst *, BasicBlock *)
2881 if (!PredSI || PredSI->getParent() != Pred || !PredSI->hasOneUse())
2882 continue;
2883
2884 UncondBrInst *PredTerm = dyn_cast<UncondBrInst>(Val: Pred->getTerminator());
2885 if (!PredTerm)
2886 continue;
2887
2888 unfoldSelectInstr(Pred, BB, SI: PredSI, SIUse: CondPHI, Idx: I);
2889 return true;
2890 }
2891 return false;
2892}
2893
2894/// tryToUnfoldSelect - Look for blocks of the form
2895/// bb1:
2896/// %a = select
2897/// br bb2
2898///
2899/// bb2:
2900/// %p = phi [%a, %bb1] ...
2901/// %c = icmp %p
2902/// br i1 %c
2903///
2904/// And expand the select into a branch structure if one of its arms allows %c
2905/// to be folded. This later enables threading from bb1 over bb2.
2906bool JumpThreadingPass::tryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
2907 CondBrInst *CondBr = dyn_cast<CondBrInst>(Val: BB->getTerminator());
2908 PHINode *CondLHS = dyn_cast<PHINode>(Val: CondCmp->getOperand(i_nocapture: 0));
2909 Constant *CondRHS = cast<Constant>(Val: CondCmp->getOperand(i_nocapture: 1));
2910
2911 if (!CondBr || !CondLHS || CondLHS->getParent() != BB)
2912 return false;
2913
2914 for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
2915 BasicBlock *Pred = CondLHS->getIncomingBlock(i: I);
2916 SelectInst *SI = dyn_cast<SelectInst>(Val: CondLHS->getIncomingValue(i: I));
2917
2918 // Look if one of the incoming values is a select in the corresponding
2919 // predecessor.
2920 if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
2921 continue;
2922
2923 UncondBrInst *PredTerm = dyn_cast<UncondBrInst>(Val: Pred->getTerminator());
2924 if (!PredTerm)
2925 continue;
2926
2927 // Now check if one of the select values would allow us to constant fold the
2928 // terminator in BB. We don't do the transform if both sides fold, those
2929 // cases will be threaded in any case.
2930 Constant *LHSRes =
2931 LVI->getPredicateOnEdge(Pred: CondCmp->getPredicate(), V: SI->getOperand(i_nocapture: 1),
2932 C: CondRHS, FromBB: Pred, ToBB: BB, CtxI: CondCmp);
2933 Constant *RHSRes =
2934 LVI->getPredicateOnEdge(Pred: CondCmp->getPredicate(), V: SI->getOperand(i_nocapture: 2),
2935 C: CondRHS, FromBB: Pred, ToBB: BB, CtxI: CondCmp);
2936 if ((LHSRes || RHSRes) && LHSRes != RHSRes) {
2937 unfoldSelectInstr(Pred, BB, SI, SIUse: CondLHS, Idx: I);
2938 return true;
2939 }
2940 }
2941 return false;
2942}
2943
2944/// tryToUnfoldSelectInCurrBB - Look for PHI/Select or PHI/CMP/Select in the
2945/// same BB in the form
2946/// bb:
2947/// %p = phi [false, %bb1], [true, %bb2], [false, %bb3], [true, %bb4], ...
2948/// %s = select %p, trueval, falseval
2949///
2950/// or
2951///
2952/// bb:
2953/// %p = phi [0, %bb1], [1, %bb2], [0, %bb3], [1, %bb4], ...
2954/// %c = cmp %p, 0
2955/// %s = select %c, trueval, falseval
2956///
2957/// And expand the select into a branch structure. This later enables
2958/// jump-threading over bb in this pass.
2959///
2960/// Using the similar approach of SimplifyCFG::FoldCondBranchOnPHI(), unfold
2961/// select if the associated PHI has at least one constant. If the unfolded
2962/// select is not jump-threaded, it will be folded again in the later
2963/// optimizations.
2964bool JumpThreadingPass::tryToUnfoldSelectInCurrBB(BasicBlock *BB) {
2965 // This transform would reduce the quality of msan diagnostics.
2966 // Disable this transform under MemorySanitizer.
2967 if (BB->getParent()->hasFnAttribute(Kind: Attribute::SanitizeMemory))
2968 return false;
2969
2970 // If threading this would thread across a loop header, don't thread the edge.
2971 // See the comments above findLoopHeaders for justifications and caveats.
2972 if (LoopHeaders.count(Ptr: BB))
2973 return false;
2974
2975 for (BasicBlock::iterator BI = BB->begin();
2976 PHINode *PN = dyn_cast<PHINode>(Val&: BI); ++BI) {
2977 // Look for a Phi having at least one constant incoming value.
2978 if (llvm::all_of(Range: PN->incoming_values(),
2979 P: [](Value *V) { return !isa<ConstantInt>(Val: V); }))
2980 continue;
2981
2982 auto isUnfoldCandidate = [BB](SelectInst *SI, Value *V) {
2983 using namespace PatternMatch;
2984
2985 // Check if SI is in BB and use V as condition.
2986 if (SI->getParent() != BB)
2987 return false;
2988 Value *Cond = SI->getCondition();
2989 bool IsAndOr = match(V: SI, P: m_CombineOr(Ps: m_LogicalAnd(), Ps: m_LogicalOr()));
2990 return Cond && Cond == V && Cond->getType()->isIntegerTy(BitWidth: 1) && !IsAndOr;
2991 };
2992
2993 SelectInst *SI = nullptr;
2994 for (Use &U : PN->uses()) {
2995 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(Val: U.getUser())) {
2996 // Look for a ICmp in BB that compares PN with a constant and is the
2997 // condition of a Select.
2998 if (Cmp->getParent() == BB && Cmp->hasOneUse() &&
2999 isa<ConstantInt>(Val: Cmp->getOperand(i_nocapture: 1 - U.getOperandNo())))
3000 if (SelectInst *SelectI = dyn_cast<SelectInst>(Val: Cmp->user_back()))
3001 if (isUnfoldCandidate(SelectI, Cmp->use_begin()->get())) {
3002 SI = SelectI;
3003 break;
3004 }
3005 } else if (SelectInst *SelectI = dyn_cast<SelectInst>(Val: U.getUser())) {
3006 // Look for a Select in BB that uses PN as condition.
3007 if (isUnfoldCandidate(SelectI, U.get())) {
3008 SI = SelectI;
3009 break;
3010 }
3011 }
3012 }
3013
3014 if (!SI)
3015 continue;
3016 // Expand the select.
3017 Value *Cond = SI->getCondition();
3018 if (!isGuaranteedNotToBeUndefOrPoison(V: Cond, AC: nullptr, CtxI: SI)) {
3019 Cond = new FreezeInst(Cond, "cond.fr", SI->getIterator());
3020 cast<FreezeInst>(Val: Cond)->setDebugLoc(DebugLoc::getTemporary());
3021 }
3022 MDNode *BranchWeights = getBranchWeightMDNode(I: *SI);
3023 Instruction *Term =
3024 SplitBlockAndInsertIfThen(Cond, SplitBefore: SI, Unreachable: false, BranchWeights);
3025 BasicBlock *SplitBB = SI->getParent();
3026 BasicBlock *NewBB = Term->getParent();
3027 PHINode *NewPN = PHINode::Create(Ty: SI->getType(), NumReservedValues: 2, NameStr: "", InsertBefore: SI->getIterator());
3028 NewPN->addIncoming(V: SI->getTrueValue(), BB: Term->getParent());
3029 NewPN->addIncoming(V: SI->getFalseValue(), BB);
3030 NewPN->setDebugLoc(SI->getDebugLoc());
3031 SI->replaceAllUsesWith(V: NewPN);
3032
3033 auto *BPI = getBPI();
3034 auto *BFI = getBFI();
3035 if (!ProfcheckDisableMetadataFixes && BranchWeights) {
3036 SmallVector<uint32_t, 2> BW;
3037 [[maybe_unused]] bool Extracted = extractBranchWeights(ProfileData: BranchWeights, Weights&: BW);
3038 assert(Extracted);
3039 uint64_t Denominator =
3040 sum_of(Range: llvm::map_range(C&: BW, F: StaticCastTo<uint64_t>));
3041 // Zero branch_weights do not give a hint for getting branch
3042 // probabilities, and their sum would be a division-by-zero denominator.
3043 if (Denominator > 0) {
3044 BranchProbability TrueProb =
3045 BranchProbability::getBranchProbability(Numerator: BW[0], Denominator);
3046 BranchProbability FalseProb =
3047 BranchProbability::getBranchProbability(Numerator: BW[1], Denominator);
3048 SmallVector<BranchProbability, 2> BP = {TrueProb, FalseProb};
3049
3050 if (BPI)
3051 BPI->setEdgeProbability(Src: BB, Probs: BP);
3052
3053 if (BFI) {
3054 auto BBOrigFreq = BFI->getBlockFreq(BB);
3055 auto NewBBFreq = BBOrigFreq * TrueProb;
3056 BFI->setBlockFreq(BB: NewBB, Freq: NewBBFreq);
3057 BFI->setBlockFreq(BB: SplitBB, Freq: BBOrigFreq);
3058 }
3059 } else {
3060 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *BB->getTerminator(),
3061 DEBUG_TYPE);
3062 }
3063 }
3064 SI->eraseFromParent();
3065 // NewBB and SplitBB are newly created blocks which require insertion.
3066 std::vector<DominatorTree::UpdateType> Updates;
3067 Updates.reserve(n: (2 * SplitBB->getTerminator()->getNumSuccessors()) + 3);
3068 Updates.push_back(x: {DominatorTree::Insert, BB, SplitBB});
3069 Updates.push_back(x: {DominatorTree::Insert, BB, NewBB});
3070 Updates.push_back(x: {DominatorTree::Insert, NewBB, SplitBB});
3071 // BB's successors were moved to SplitBB, update DTU accordingly.
3072 for (auto *Succ : successors(BB: SplitBB)) {
3073 Updates.push_back(x: {DominatorTree::Delete, BB, Succ});
3074 Updates.push_back(x: {DominatorTree::Insert, SplitBB, Succ});
3075 }
3076 DTU->applyUpdatesPermissive(Updates);
3077 return true;
3078 }
3079 return false;
3080}
3081
3082/// Try to propagate a guard from the current BB into one of its predecessors
3083/// in case if another branch of execution implies that the condition of this
3084/// guard is always true. Currently we only process the simplest case that
3085/// looks like:
3086///
3087/// Start:
3088/// %cond = ...
3089/// br i1 %cond, label %T1, label %F1
3090/// T1:
3091/// br label %Merge
3092/// F1:
3093/// br label %Merge
3094/// Merge:
3095/// %condGuard = ...
3096/// call void(i1, ...) @llvm.experimental.guard( i1 %condGuard )[ "deopt"() ]
3097///
3098/// And cond either implies condGuard or !condGuard. In this case all the
3099/// instructions before the guard can be duplicated in both branches, and the
3100/// guard is then threaded to one of them.
3101bool JumpThreadingPass::processGuards(BasicBlock *BB) {
3102 using namespace PatternMatch;
3103
3104 // We only want to deal with two predecessors.
3105 BasicBlock *Pred1, *Pred2;
3106 auto PI = pred_begin(BB), PE = pred_end(BB);
3107 if (PI == PE)
3108 return false;
3109 Pred1 = *PI++;
3110 if (PI == PE)
3111 return false;
3112 Pred2 = *PI++;
3113 if (PI != PE)
3114 return false;
3115 if (Pred1 == Pred2)
3116 return false;
3117
3118 // Try to thread one of the guards of the block.
3119 // TODO: Look up deeper than to immediate predecessor?
3120 auto *Parent = Pred1->getSinglePredecessor();
3121 if (!Parent || Parent != Pred2->getSinglePredecessor())
3122 return false;
3123
3124 if (auto *BI = dyn_cast<CondBrInst>(Val: Parent->getTerminator()))
3125 for (auto &I : *BB)
3126 if (isGuard(U: &I) && threadGuard(BB, Guard: cast<IntrinsicInst>(Val: &I), BI))
3127 return true;
3128
3129 return false;
3130}
3131
3132/// Try to propagate the guard from BB which is the lower block of a diamond
3133/// to one of its branches, in case if diamond's condition implies guard's
3134/// condition.
3135bool JumpThreadingPass::threadGuard(BasicBlock *BB, IntrinsicInst *Guard,
3136 CondBrInst *BI) {
3137 Value *GuardCond = Guard->getArgOperand(i: 0);
3138 Value *BranchCond = BI->getCondition();
3139 BasicBlock *TrueDest = BI->getSuccessor(i: 0);
3140 BasicBlock *FalseDest = BI->getSuccessor(i: 1);
3141
3142 auto &DL = BB->getDataLayout();
3143 bool TrueDestIsSafe = false;
3144 bool FalseDestIsSafe = false;
3145
3146 // True dest is safe if BranchCond => GuardCond.
3147 auto Impl = isImpliedCondition(LHS: BranchCond, RHS: GuardCond, DL);
3148 if (Impl && *Impl)
3149 TrueDestIsSafe = true;
3150 else {
3151 // False dest is safe if !BranchCond => GuardCond.
3152 Impl = isImpliedCondition(LHS: BranchCond, RHS: GuardCond, DL, /* LHSIsTrue */ false);
3153 if (Impl && *Impl)
3154 FalseDestIsSafe = true;
3155 }
3156
3157 if (!TrueDestIsSafe && !FalseDestIsSafe)
3158 return false;
3159
3160 BasicBlock *PredUnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest;
3161 BasicBlock *PredGuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest;
3162
3163 ValueToValueMapTy UnguardedMapping, GuardedMapping;
3164 Instruction *AfterGuard = Guard->getNextNode();
3165 unsigned Cost =
3166 getJumpThreadDuplicationCost(Opts: *Opts, TTI, BB, StopAt: AfterGuard, Threshold: BBDupThreshold);
3167 if (Cost > BBDupThreshold)
3168 return false;
3169 // Duplicate all instructions before the guard and the guard itself to the
3170 // branch where implication is not proved.
3171 BasicBlock *GuardedBlock = DuplicateInstructionsInSplitBetween(
3172 BB, PredBB: PredGuardedBlock, StopAt: AfterGuard, ValueMapping&: GuardedMapping, DTU&: *DTU);
3173 assert(GuardedBlock && "Could not create the guarded block?");
3174 // Duplicate all instructions before the guard in the unguarded branch.
3175 // Since we have successfully duplicated the guarded block and this block
3176 // has fewer instructions, we expect it to succeed.
3177 BasicBlock *UnguardedBlock = DuplicateInstructionsInSplitBetween(
3178 BB, PredBB: PredUnguardedBlock, StopAt: Guard, ValueMapping&: UnguardedMapping, DTU&: *DTU);
3179 assert(UnguardedBlock && "Could not create the unguarded block?");
3180 LLVM_DEBUG(dbgs() << "Moved guard " << *Guard << " to block "
3181 << GuardedBlock->getName() << "\n");
3182 // Some instructions before the guard may still have uses. For them, we need
3183 // to create Phi nodes merging their copies in both guarded and unguarded
3184 // branches. Those instructions that have no uses can be just removed.
3185 SmallVector<Instruction *, 4> ToRemove;
3186 for (auto BI = BB->begin(); &*BI != AfterGuard; ++BI)
3187 if (!isa<PHINode>(Val: &*BI))
3188 ToRemove.push_back(Elt: &*BI);
3189
3190 BasicBlock::iterator InsertionPoint = BB->getFirstInsertionPt();
3191 assert(InsertionPoint != BB->end() && "Empty block?");
3192 // Substitute with Phis & remove.
3193 for (auto *Inst : reverse(C&: ToRemove)) {
3194 if (!Inst->use_empty()) {
3195 PHINode *NewPN = PHINode::Create(Ty: Inst->getType(), NumReservedValues: 2);
3196 NewPN->addIncoming(V: UnguardedMapping[Inst], BB: UnguardedBlock);
3197 NewPN->addIncoming(V: GuardedMapping[Inst], BB: GuardedBlock);
3198 NewPN->setDebugLoc(Inst->getDebugLoc());
3199 NewPN->insertBefore(InsertPos: InsertionPoint);
3200 Inst->replaceAllUsesWith(V: NewPN);
3201 }
3202 Inst->dropDbgRecords();
3203 Inst->eraseFromParent();
3204 }
3205 return true;
3206}
3207
3208PreservedAnalyses JumpThreadingPass::getPreservedAnalysis() const {
3209 PreservedAnalyses PA;
3210 PA.preserve<LazyValueAnalysis>();
3211 PA.preserve<DominatorTreeAnalysis>();
3212
3213 // TODO: We would like to preserve BPI/BFI. Enable once all paths update them.
3214 // TODO: Would be nice to verify BPI/BFI consistency as well.
3215 return PA;
3216}
3217
3218template <typename AnalysisT>
3219typename AnalysisT::Result *JumpThreadingPass::runExternalAnalysis() {
3220 assert(FAM && "Can't run external analysis without FunctionAnalysisManager");
3221
3222 // If there were no changes since last call to 'runExternalAnalysis' then all
3223 // analysis is either up to date or explicitly invalidated. Just go ahead and
3224 // run the "external" analysis.
3225 if (!ChangedSinceLastAnalysisUpdate) {
3226 assert(!DTU->hasPendingUpdates() &&
3227 "Lost update of 'ChangedSinceLastAnalysisUpdate'?");
3228 // Run the "external" analysis.
3229 return &FAM->getResult<AnalysisT>(*F);
3230 }
3231 ChangedSinceLastAnalysisUpdate = false;
3232
3233 auto PA = getPreservedAnalysis();
3234 // TODO: This shouldn't be needed once 'getPreservedAnalysis' reports BPI/BFI
3235 // as preserved.
3236 PA.preserve<BranchProbabilityAnalysis>();
3237 PA.preserve<BlockFrequencyAnalysis>();
3238 // Report everything except explicitly preserved as invalid.
3239 FAM->invalidate(IR&: *F, PA);
3240 // Update DT/PDT.
3241 DTU->flush();
3242 // Make sure DT/PDT are valid before running "external" analysis.
3243 assert(DTU->getDomTree().verify(DominatorTree::VerificationLevel::Fast));
3244 assert((!DTU->hasPostDomTree() ||
3245 DTU->getPostDomTree().verify(
3246 PostDominatorTree::VerificationLevel::Fast)));
3247 // Run the "external" analysis.
3248 auto *Result = &FAM->getResult<AnalysisT>(*F);
3249 // Update analysis JumpThreading depends on and not explicitly preserved.
3250 TTI = &FAM->getResult<TargetIRAnalysis>(IR&: *F);
3251 TLI = &FAM->getResult<TargetLibraryAnalysis>(IR&: *F);
3252 AA = &FAM->getResult<AAManager>(IR&: *F);
3253
3254 return Result;
3255}
3256
3257BranchProbabilityInfo *JumpThreadingPass::getBPI() {
3258 if (!BPI) {
3259 assert(FAM && "Can't create BPI without FunctionAnalysisManager");
3260 BPI = FAM->getCachedResult<BranchProbabilityAnalysis>(IR&: *F);
3261 }
3262 return BPI;
3263}
3264
3265BlockFrequencyInfo *JumpThreadingPass::getBFI() {
3266 if (!BFI) {
3267 assert(FAM && "Can't create BFI without FunctionAnalysisManager");
3268 BFI = FAM->getCachedResult<BlockFrequencyAnalysis>(IR&: *F);
3269 }
3270 return BFI;
3271}
3272
3273// Important note on validity of BPI/BFI. JumpThreading tries to preserve
3274// BPI/BFI as it goes. Thus if cached instance exists it will be updated.
3275// Otherwise, new instance of BPI/BFI is created (up to date by definition).
3276BranchProbabilityInfo *JumpThreadingPass::getOrCreateBPI(bool Force) {
3277 auto *Res = getBPI();
3278 if (Res)
3279 return Res;
3280
3281 if (Force)
3282 BPI = runExternalAnalysis<BranchProbabilityAnalysis>();
3283
3284 return BPI;
3285}
3286
3287BlockFrequencyInfo *JumpThreadingPass::getOrCreateBFI(bool Force) {
3288 auto *Res = getBFI();
3289 if (Res)
3290 return Res;
3291
3292 if (Force)
3293 BFI = runExternalAnalysis<BlockFrequencyAnalysis>();
3294
3295 return BFI;
3296}
3297