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