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