LLVM 24.0.0git
GuardWidening.cpp
Go to the documentation of this file.
1//===- GuardWidening.cpp - ---- Guard widening ----------------------------===//
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 guard widening pass. The semantics of the
10// @llvm.experimental.guard intrinsic lets LLVM transform it so that it fails
11// more often that it did before the transform. This optimization is called
12// "widening" and can be used hoist and common runtime checks in situations like
13// these:
14//
15// %cmp0 = 7 u< Length
16// call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
17// call @unknown_side_effects()
18// %cmp1 = 9 u< Length
19// call @llvm.experimental.guard(i1 %cmp1) [ "deopt"(...) ]
20// ...
21//
22// =>
23//
24// %cmp0 = 9 u< Length
25// call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
26// call @unknown_side_effects()
27// ...
28//
29// If %cmp0 is false, @llvm.experimental.guard will "deoptimize" back to a
30// generic implementation of the same function, which will have the correct
31// semantics from that point onward. It is always _legal_ to deoptimize (so
32// replacing %cmp0 with false is "correct"), though it may not always be
33// profitable to do so.
34//
35// NB! This pass is a work in progress. It hasn't been tuned to be "production
36// ready" yet. It is known to have quadriatic running time and will not scale
37// to large numbers of guards
38//
39//===----------------------------------------------------------------------===//
40
42#include "ScalarOptions.h"
43#include "llvm/ADT/DenseMap.h"
45#include "llvm/ADT/Statistic.h"
53#include "llvm/IR/Dominators.h"
54#include "llvm/IR/IRBuilder.h"
57#include "llvm/Support/Debug.h"
62#include <functional>
63
64using namespace llvm;
65
66#define DEBUG_TYPE "guard-widening"
67
68STATISTIC(GuardsEliminated, "Number of eliminated guards");
69STATISTIC(CondBranchEliminated, "Number of eliminated conditional branches");
70STATISTIC(FreezeAdded, "Number of freeze instruction introduced");
71
72// Get the condition of \p I. It can either be a guard or a conditional branch.
75 assert(GI->getIntrinsicID() == Intrinsic::experimental_guard &&
76 "Bad guard intrinsic?");
77 return GI->getArgOperand(0);
78 }
79 Value *Cond, *WC;
80 BasicBlock *IfTrueBB, *IfFalseBB;
81 if (parseWidenableBranch(I, Cond, WC, IfTrueBB, IfFalseBB))
82 return Cond;
83
84 return cast<CondBrInst>(I)->getCondition();
85}
86
87// Set the condition for \p I to \p NewCond. \p I can either be a guard or a
88// conditional branch.
89static void setCondition(Instruction *I, Value *NewCond) {
91 assert(GI->getIntrinsicID() == Intrinsic::experimental_guard &&
92 "Bad guard intrinsic?");
93 GI->setArgOperand(0, NewCond);
94 return;
95 }
96 cast<CondBrInst>(I)->setCondition(NewCond);
97}
98
99// Eliminates the guard instruction properly.
100static void eliminateGuard(Instruction *GuardInst, MemorySSAUpdater *MSSAU) {
101 GuardInst->eraseFromParent();
102 if (MSSAU)
103 MSSAU->removeMemoryAccess(GuardInst);
104 ++GuardsEliminated;
105}
106
107/// Find a point at which the widened condition of \p Guard should be inserted.
108/// When it is represented as intrinsic call, we can do it right before the call
109/// instruction. However, when we are dealing with widenable branch, we must
110/// account for the following situation: widening should not turn a
111/// loop-invariant condition into a loop-variant. It means that if
112/// widenable.condition() call is invariant (w.r.t. any loop), the new wide
113/// condition should stay invariant. Otherwise there can be a miscompile, like
114/// the one described at https://github.com/llvm/llvm-project/issues/60234. The
115/// safest way to do it is to expand the new condition at WC's block.
116static std::optional<BasicBlock::iterator>
118 if (isGuard(WCOrGuard))
119 return WCOrGuard->getIterator();
120 if (auto WC = extractWidenableCondition(WCOrGuard))
121 return cast<Instruction>(WC)->getIterator();
122 return std::nullopt;
123}
124
125namespace {
126
127class GuardWideningImpl {
128 const ScalarOptions &Opts;
129 DominatorTree &DT;
130 PostDominatorTree *PDT;
131 LoopInfo &LI;
132 AssumptionCache &AC;
133 MemorySSAUpdater *MSSAU;
134
135 /// Together, these describe the region of interest. This might be all of
136 /// the blocks within a function, or only a given loop's blocks and preheader.
137 DomTreeNode *Root;
138 std::function<bool(BasicBlock*)> BlockFilter;
139
140 /// The set of guards and conditional branches whose conditions have been
141 /// widened into dominating guards.
142 SmallVector<Instruction *, 16> EliminatedGuardsAndBranches;
143
144 /// The set of guards which have been widened to include conditions to other
145 /// guards.
146 DenseSet<Instruction *> WidenedGuards;
147
148 /// Try to eliminate instruction \p Instr by widening it into an earlier
149 /// dominating guard. \p DFSI is the DFS iterator on the dominator tree that
150 /// is currently visiting the block containing \p Guard, and \p GuardsPerBlock
151 /// maps BasicBlocks to the set of guards seen in that block.
152 bool eliminateInstrViaWidening(
153 Instruction *Instr, const df_iterator<DomTreeNode *> &DFSI,
154 const DenseMap<BasicBlock *, SmallVector<Instruction *, 8>>
155 &GuardsPerBlock);
156
157 /// Used to keep track of which widening potential is more effective.
158 enum WideningScore {
159 /// Don't widen.
160 WS_IllegalOrNegative,
161
162 /// Widening is performance neutral as far as the cycles spent in check
163 /// conditions goes (but can still help, e.g., code layout, having less
164 /// deopt state).
165 WS_Neutral,
166
167 /// Widening is profitable.
168 WS_Positive,
169
170 /// Widening is very profitable. Not significantly different from \c
171 /// WS_Positive, except by the order.
172 WS_VeryPositive
173 };
174
175 static StringRef scoreTypeToString(WideningScore WS);
176
177 /// Compute the score for widening the condition in \p DominatedInstr
178 /// into \p WideningPoint.
179 WideningScore computeWideningScore(Instruction *DominatedInstr,
180 Instruction *ToWiden,
181 BasicBlock::iterator WideningPoint,
182 SmallVectorImpl<Value *> &ChecksToHoist,
183 SmallVectorImpl<Value *> &ChecksToWiden);
184
185 /// Helper to check if \p V can be hoisted to \p InsertPos.
186 bool canBeHoistedTo(const Value *V, BasicBlock::iterator InsertPos) const {
187 SmallPtrSet<const Instruction *, 8> Visited;
188 return canBeHoistedTo(V, InsertPos, Visited);
189 }
190
191 bool canBeHoistedTo(const Value *V, BasicBlock::iterator InsertPos,
192 SmallPtrSetImpl<const Instruction *> &Visited) const;
193
194 bool canBeHoistedTo(const SmallVectorImpl<Value *> &Checks,
195 BasicBlock::iterator InsertPos) const {
196 return all_of(Checks,
197 [&](const Value *V) { return canBeHoistedTo(V, InsertPos); });
198 }
199 /// Helper to hoist \p V to \p InsertPos. Guaranteed to succeed if \c
200 /// canBeHoistedTo returned true.
201 void makeAvailableAt(Value *V, BasicBlock::iterator InsertPos) const;
202
203 void makeAvailableAt(const SmallVectorImpl<Value *> &Checks,
204 BasicBlock::iterator InsertPos) const {
205 for (Value *V : Checks)
206 makeAvailableAt(V, InsertPos);
207 }
208
209 /// Common helper used by \c widenGuard and \c isWideningCondProfitable. Try
210 /// to generate an expression computing the logical AND of \p ChecksToHoist
211 /// and \p ChecksToWiden. Return true if the expression computing the AND is
212 /// only as expensive as computing one of the set of expressions. If \p
213 /// InsertPt is true then actually generate the resulting expression, make it
214 /// available at \p InsertPt and return it in \p Result (else no change to the
215 /// IR is made).
216 std::optional<Value *>
217 mergeChecks(SmallVectorImpl<Value *> &ChecksToHoist,
218 SmallVectorImpl<Value *> &ChecksToWiden,
219 std::optional<BasicBlock::iterator> InsertPt);
220
221 /// Generate the logical AND of \p ChecksToHoist and \p OldCondition and make
222 /// it available at InsertPt
223 Value *hoistChecks(SmallVectorImpl<Value *> &ChecksToHoist,
224 Value *OldCondition, BasicBlock::iterator InsertPt);
225
226 /// Adds freeze to Orig and push it as far as possible very aggressively.
227 /// Also replaces all uses of frozen instruction with frozen version.
228 Value *freezeAndPush(Value *Orig, BasicBlock::iterator InsertPt);
229
230 /// Represents a range check of the form \c Base + \c Offset u< \c Length,
231 /// with the constraint that \c Length is not negative. \c CheckInst is the
232 /// pre-existing instruction in the IR that computes the result of this range
233 /// check.
234 class RangeCheck {
235 const Value *Base;
236 const ConstantInt *Offset;
237 const Value *Length;
238 ICmpInst *CheckInst;
239
240 public:
241 explicit RangeCheck(const Value *Base, const ConstantInt *Offset,
242 const Value *Length, ICmpInst *CheckInst)
243 : Base(Base), Offset(Offset), Length(Length), CheckInst(CheckInst) {}
244
245 void setBase(const Value *NewBase) { Base = NewBase; }
246 void setOffset(const ConstantInt *NewOffset) { Offset = NewOffset; }
247
248 const Value *getBase() const { return Base; }
249 const ConstantInt *getOffset() const { return Offset; }
250 const APInt &getOffsetValue() const { return getOffset()->getValue(); }
251 const Value *getLength() const { return Length; };
252 ICmpInst *getCheckInst() const { return CheckInst; }
253
254 void print(raw_ostream &OS, bool PrintTypes = false) {
255 OS << "Base: ";
256 Base->printAsOperand(OS, PrintTypes);
257 OS << " Offset: ";
258 Offset->printAsOperand(OS, PrintTypes);
259 OS << " Length: ";
260 Length->printAsOperand(OS, PrintTypes);
261 }
262
263 LLVM_DUMP_METHOD void dump() {
264 print(dbgs());
265 dbgs() << "\n";
266 }
267 };
268
269 /// Parse \p ToParse into a conjunction (logical-and) of range checks; and
270 /// append them to \p Checks. Returns true on success, may clobber \c Checks
271 /// on failure.
272 bool parseRangeChecks(SmallVectorImpl<Value *> &ToParse,
273 SmallVectorImpl<RangeCheck> &Checks) {
274 for (auto CheckCond : ToParse) {
275 if (!parseRangeChecks(CheckCond, Checks))
276 return false;
277 }
278 return true;
279 }
280
281 bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks);
282
283 /// Combine the checks in \p Checks into a smaller set of checks and append
284 /// them into \p CombinedChecks. Return true on success (i.e. all of checks
285 /// in \p Checks were combined into \p CombinedChecks). Clobbers \p Checks
286 /// and \p CombinedChecks on success and on failure.
287 bool combineRangeChecks(SmallVectorImpl<RangeCheck> &Checks,
288 SmallVectorImpl<RangeCheck> &CombinedChecks) const;
289
290 /// Can we compute the logical AND of \p ChecksToHoist and \p ChecksToWiden
291 /// for the price of computing only one of the set of expressions?
292 bool isWideningCondProfitable(SmallVectorImpl<Value *> &ChecksToHoist,
293 SmallVectorImpl<Value *> &ChecksToWiden) {
294 return mergeChecks(ChecksToHoist, ChecksToWiden, /*InsertPt=*/std::nullopt)
295 .has_value();
296 }
297
298 /// Widen \p ChecksToWiden to fail if any of \p ChecksToHoist is false
299 void widenGuard(SmallVectorImpl<Value *> &ChecksToHoist,
300 SmallVectorImpl<Value *> &ChecksToWiden,
301 Instruction *ToWiden) {
302 auto InsertPt = findInsertionPointForWideCondition(ToWiden);
303 auto MergedCheck = mergeChecks(ChecksToHoist, ChecksToWiden, InsertPt);
304 Value *Result = MergedCheck ? *MergedCheck
305 : hoistChecks(ChecksToHoist,
306 getCondition(ToWiden), *InsertPt);
307
308 if (isGuardAsWidenableBranch(ToWiden)) {
310 return;
311 }
312 setCondition(ToWiden, Result);
313 }
314
315public:
316 explicit GuardWideningImpl(const ScalarOptions &Opts, DominatorTree &DT,
317 PostDominatorTree *PDT, LoopInfo &LI,
318 AssumptionCache &AC, MemorySSAUpdater *MSSAU,
319 DomTreeNode *Root,
320 std::function<bool(BasicBlock *)> BlockFilter)
321 : Opts(Opts), DT(DT), PDT(PDT), LI(LI), AC(AC), MSSAU(MSSAU), Root(Root),
322 BlockFilter(BlockFilter) {}
323
324 /// The entry point for this pass.
325 bool run();
326};
327} // namespace
328
329static bool isSupportedGuardInstruction(const ScalarOptions &Opts,
330 const Instruction *Insn) {
331 if (isGuard(Insn))
332 return true;
333 if (Opts.guard_widening_widen_branch_guards && isGuardAsWidenableBranch(Insn))
334 return true;
335 return false;
336}
337
338bool GuardWideningImpl::run() {
339 DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> GuardsInBlock;
340 bool Changed = false;
341 for (auto DFI = df_begin(Root), DFE = df_end(Root);
342 DFI != DFE; ++DFI) {
343 auto *BB = (*DFI)->getBlock();
344 if (!BlockFilter(BB))
345 continue;
346
347 auto &CurrentList = GuardsInBlock[BB];
348
349 for (auto &I : *BB)
350 if (isSupportedGuardInstruction(Opts, &I))
351 CurrentList.push_back(cast<Instruction>(&I));
352
353 for (auto *II : CurrentList)
354 Changed |= eliminateInstrViaWidening(II, DFI, GuardsInBlock);
355 }
356
357 assert(EliminatedGuardsAndBranches.empty() || Changed);
358 for (auto *I : EliminatedGuardsAndBranches)
359 if (!WidenedGuards.count(I)) {
360 assert(isa<ConstantInt>(getCondition(I)) && "Should be!");
362 eliminateGuard(I, MSSAU);
363 else {
365 "Eliminated something other than guard or branch?");
366 ++CondBranchEliminated;
367 }
368 }
369
370 return Changed;
371}
372
373bool GuardWideningImpl::eliminateInstrViaWidening(
374 Instruction *Instr, const df_iterator<DomTreeNode *> &DFSI,
375 const DenseMap<BasicBlock *, SmallVector<Instruction *, 8>>
376 &GuardsInBlock) {
377 SmallVector<Value *> ChecksToHoist;
378 parseWidenableGuard(Instr, ChecksToHoist);
379 // Ignore trivial true or false conditions. These instructions will be
380 // trivially eliminated by any cleanup pass. Do not erase them because other
381 // guards can possibly be widened into them.
382 if (ChecksToHoist.empty() ||
383 (ChecksToHoist.size() == 1 && isa<ConstantInt>(ChecksToHoist.front())))
384 return false;
385
386 Instruction *BestSoFar = nullptr;
387 auto BestScoreSoFar = WS_IllegalOrNegative;
388
389 // In the set of dominating guards, find the one we can merge GuardInst with
390 // for the most profit.
391 for (unsigned i = 0, e = DFSI.getPathLength(); i != e; ++i) {
392 auto *CurBB = DFSI.getPath(i)->getBlock();
393 if (!BlockFilter(CurBB))
394 break;
395 assert(GuardsInBlock.count(CurBB) && "Must have been populated by now!");
396 const auto &GuardsInCurBB = GuardsInBlock.find(CurBB)->second;
397
398 auto I = GuardsInCurBB.begin();
399 auto E = Instr->getParent() == CurBB ? find(GuardsInCurBB, Instr)
400 : GuardsInCurBB.end();
401
402#ifndef NDEBUG
403 {
404 unsigned Index = 0;
405 for (auto &I : *CurBB) {
406 if (Index == GuardsInCurBB.size())
407 break;
408 if (GuardsInCurBB[Index] == &I)
409 Index++;
410 }
411 assert(Index == GuardsInCurBB.size() &&
412 "Guards expected to be in order!");
413 }
414#endif
415
416 assert((i == (e - 1)) == (Instr->getParent() == CurBB) && "Bad DFS?");
417
418 for (auto *Candidate : make_range(I, E)) {
419 auto WideningPoint = findInsertionPointForWideCondition(Candidate);
420 if (!WideningPoint)
421 continue;
422 SmallVector<Value *> CandidateChecks;
423 parseWidenableGuard(Candidate, CandidateChecks);
424 auto Score = computeWideningScore(Instr, Candidate, *WideningPoint,
425 ChecksToHoist, CandidateChecks);
426 LLVM_DEBUG(dbgs() << "Score between " << *Instr << " and " << *Candidate
427 << " is " << scoreTypeToString(Score) << "\n");
428 if (Score > BestScoreSoFar) {
429 BestScoreSoFar = Score;
430 BestSoFar = Candidate;
431 }
432 }
433 }
434
435 if (BestScoreSoFar == WS_IllegalOrNegative) {
436 LLVM_DEBUG(dbgs() << "Did not eliminate guard " << *Instr << "\n");
437 return false;
438 }
439
440 assert(BestSoFar != Instr && "Should have never visited same guard!");
441 assert(DT.dominates(BestSoFar, Instr) && "Should be!");
442
443 LLVM_DEBUG(dbgs() << "Widening " << *Instr << " into " << *BestSoFar
444 << " with score " << scoreTypeToString(BestScoreSoFar)
445 << "\n");
446 SmallVector<Value *> ChecksToWiden;
447 parseWidenableGuard(BestSoFar, ChecksToWiden);
448 widenGuard(ChecksToHoist, ChecksToWiden, BestSoFar);
449 auto NewGuardCondition = ConstantInt::getTrue(Instr->getContext());
450 setCondition(Instr, NewGuardCondition);
451 EliminatedGuardsAndBranches.push_back(Instr);
452 WidenedGuards.insert(BestSoFar);
453 return true;
454}
455
456GuardWideningImpl::WideningScore GuardWideningImpl::computeWideningScore(
457 Instruction *DominatedInstr, Instruction *ToWiden,
458 BasicBlock::iterator WideningPoint, SmallVectorImpl<Value *> &ChecksToHoist,
459 SmallVectorImpl<Value *> &ChecksToWiden) {
460 Loop *DominatedInstrLoop = LI.getLoopFor(DominatedInstr->getParent());
461 Loop *DominatingGuardLoop = LI.getLoopFor(WideningPoint->getParent());
462 bool HoistingOutOfLoop = false;
463
464 if (DominatingGuardLoop != DominatedInstrLoop) {
465 // Be conservative and don't widen into a sibling loop. TODO: If the
466 // sibling is colder, we should consider allowing this.
467 if (DominatingGuardLoop &&
468 !DominatingGuardLoop->contains(DominatedInstrLoop))
469 return WS_IllegalOrNegative;
470
471 HoistingOutOfLoop = true;
472 }
473
474 if (!canBeHoistedTo(ChecksToHoist, WideningPoint))
475 return WS_IllegalOrNegative;
476 // Further in the GuardWideningImpl::hoistChecks the entire condition might be
477 // widened, not the parsed list of checks. So we need to check the possibility
478 // of that condition hoisting.
479 if (!canBeHoistedTo(getCondition(ToWiden), WideningPoint))
480 return WS_IllegalOrNegative;
481
482 // If the guard was conditional executed, it may never be reached
483 // dynamically. There are two potential downsides to hoisting it out of the
484 // conditionally executed region: 1) we may spuriously deopt without need and
485 // 2) we have the extra cost of computing the guard condition in the common
486 // case. At the moment, we really only consider the second in our heuristic
487 // here. TODO: evaluate cost model for spurious deopt
488 // NOTE: As written, this also lets us hoist right over another guard which
489 // is essentially just another spelling for control flow.
490 if (isWideningCondProfitable(ChecksToHoist, ChecksToWiden))
491 return HoistingOutOfLoop ? WS_VeryPositive : WS_Positive;
492
493 if (HoistingOutOfLoop)
494 return WS_Positive;
495
496 // For a given basic block \p BB, return its successor which is guaranteed or
497 // highly likely will be taken as its successor.
498 auto GetLikelySuccessor = [](const BasicBlock * BB)->const BasicBlock * {
499 if (auto *UniqueSucc = BB->getUniqueSuccessor())
500 return UniqueSucc;
501 auto *Term = BB->getTerminator();
502 Value *Cond = nullptr;
503 const BasicBlock *IfTrue = nullptr, *IfFalse = nullptr;
504 using namespace PatternMatch;
505 if (!match(Term, m_Br(m_Value(Cond), m_BasicBlock(IfTrue),
506 m_BasicBlock(IfFalse))))
507 return nullptr;
508 // For constant conditions, only one dynamical successor is possible
509 if (auto *ConstCond = dyn_cast<ConstantInt>(Cond))
510 return ConstCond->isAllOnesValue() ? IfTrue : IfFalse;
511 // If one of successors ends with deopt, another one is likely.
512 if (IfFalse->getPostdominatingDeoptimizeCall())
513 return IfTrue;
515 return IfFalse;
516 // TODO: Use branch frequency metatada to allow hoisting through non-deopt
517 // branches?
518 return nullptr;
519 };
520
521 // Returns true if we might be hoisting above explicit control flow into a
522 // considerably hotter block. Note that this completely ignores implicit
523 // control flow (guards, calls which throw, etc...). That choice appears
524 // arbitrary (we assume that implicit control flow exits are all rare).
525 auto MaybeHoistingToHotterBlock = [&]() {
526 const auto *DominatingBlock = WideningPoint->getParent();
527 const auto *DominatedBlock = DominatedInstr->getParent();
528
529 // Descend as low as we can, always taking the likely successor.
530 assert(DT.isReachableFromEntry(DominatingBlock) && "Unreached code");
531 assert(DT.isReachableFromEntry(DominatedBlock) && "Unreached code");
532 assert(DT.dominates(DominatingBlock, DominatedBlock) && "No dominance");
533 while (DominatedBlock != DominatingBlock) {
534 auto *LikelySucc = GetLikelySuccessor(DominatingBlock);
535 // No likely successor?
536 if (!LikelySucc)
537 break;
538 // Only go down the dominator tree.
539 if (!DT.properlyDominates(DominatingBlock, LikelySucc))
540 break;
541 DominatingBlock = LikelySucc;
542 }
543
544 // Found?
545 if (DominatedBlock == DominatingBlock)
546 return false;
547 // We followed the likely successor chain and went past the dominated
548 // block. It means that the dominated guard is in dead/very cold code.
549 if (!DT.dominates(DominatingBlock, DominatedBlock))
550 return true;
551 // TODO: diamond, triangle cases
552 if (!PDT)
553 return true;
554 return !PDT->dominates(DominatedBlock, DominatingBlock);
555 };
556
557 return MaybeHoistingToHotterBlock() ? WS_IllegalOrNegative : WS_Neutral;
558}
559
560bool GuardWideningImpl::canBeHoistedTo(
561 const Value *V, BasicBlock::iterator Loc,
562 SmallPtrSetImpl<const Instruction *> &Visited) const {
563 auto *Inst = dyn_cast<Instruction>(V);
564 if (!Inst || DT.dominates(Inst, Loc) || Visited.count(Inst))
565 return true;
566
567 if (!isSafeToSpeculativelyExecute(Inst, Loc, &AC, &DT) ||
568 Inst->mayReadFromMemory())
569 return false;
570
571 Visited.insert(Inst);
572
573 // We only want to go _up_ the dominance chain when recursing.
574 assert(!isa<PHINode>(Loc) &&
575 "PHIs should return false for isSafeToSpeculativelyExecute");
576 assert(DT.isReachableFromEntry(Inst->getParent()) &&
577 "We did a DFS from the block entry!");
578 return all_of(Inst->operands(),
579 [&](Value *Op) { return canBeHoistedTo(Op, Loc, Visited); });
580}
581
582void GuardWideningImpl::makeAvailableAt(Value *V,
583 BasicBlock::iterator Loc) const {
584 auto *Inst = dyn_cast<Instruction>(V);
585 if (!Inst || DT.dominates(Inst, Loc))
586 return;
587
588 assert(isSafeToSpeculativelyExecute(Inst, Loc, &AC, &DT) &&
589 !Inst->mayReadFromMemory() &&
590 "Should've checked with canBeHoistedTo!");
591
592 for (Value *Op : Inst->operands())
593 makeAvailableAt(Op, Loc);
594
595 Inst->moveBefore(*Loc->getParent(), Loc);
596}
597
598// Return Instruction before which we can insert freeze for the value V as close
599// to def as possible. If there is no place to add freeze, return empty.
600static std::optional<BasicBlock::iterator>
602 auto *I = dyn_cast<Instruction>(V);
603 if (!I)
604 return DT.getRoot()->getFirstNonPHIOrAlloca()->getIterator();
605
606 std::optional<BasicBlock::iterator> Res = I->getInsertionPointAfterDef();
607 // If there is no place to add freeze - return nullptr.
608 if (!Res || !DT.dominates(I, &**Res))
609 return std::nullopt;
610
611 Instruction *ResInst = &**Res;
612
613 // If there is a User dominated by original I, then it should be dominated
614 // by Freeze instruction as well.
615 if (any_of(I->users(), [&](User *U) {
616 Instruction *User = cast<Instruction>(U);
617 return ResInst != User && DT.dominates(I, User) &&
618 !DT.dominates(ResInst, User);
619 }))
620 return std::nullopt;
621 return Res;
622}
623
624Value *GuardWideningImpl::freezeAndPush(Value *Orig,
625 BasicBlock::iterator InsertPt) {
626 if (isGuaranteedNotToBePoison(Orig, nullptr, InsertPt, &DT))
627 return Orig;
628 std::optional<BasicBlock::iterator> InsertPtAtDef =
629 getFreezeInsertPt(Orig, DT);
630 if (!InsertPtAtDef) {
631 FreezeInst *FI = new FreezeInst(Orig, "gw.freeze");
632 FI->insertBefore(*InsertPt->getParent(), InsertPt);
633 return FI;
634 }
635 if (isa<Constant>(Orig) || isa<GlobalValue>(Orig)) {
636 BasicBlock::iterator InsertPt = *InsertPtAtDef;
637 FreezeInst *FI = new FreezeInst(Orig, "gw.freeze");
638 FI->insertBefore(*InsertPt->getParent(), InsertPt);
639 return FI;
640 }
641
642 SmallPtrSet<Value *, 16> Visited;
643 SmallVector<Value *, 16> Worklist;
644 SmallPtrSet<Instruction *, 16> DropPoisonFlags;
645 SmallVector<Value *, 16> NeedFreeze;
646 DenseMap<Value *, FreezeInst *> CacheOfFreezes;
647
648 // A bit overloaded data structures. Visited contains constant/GV
649 // if we already met it. In this case CacheOfFreezes has a freeze if it is
650 // required.
651 auto handleConstantOrGlobal = [&](Use &U) {
652 Value *Def = U.get();
653 if (!isa<Constant>(Def) && !isa<GlobalValue>(Def))
654 return false;
655
656 if (Visited.insert(Def).second) {
657 if (isGuaranteedNotToBePoison(Def, nullptr, InsertPt, &DT))
658 return true;
659 BasicBlock::iterator InsertPt = *getFreezeInsertPt(Def, DT);
660 FreezeInst *FI = new FreezeInst(Def, Def->getName() + ".gw.fr");
661 FI->insertBefore(*InsertPt->getParent(), InsertPt);
662 CacheOfFreezes[Def] = FI;
663 }
664
665 if (auto It = CacheOfFreezes.find(Def); It != CacheOfFreezes.end())
666 U.set(It->second);
667 return true;
668 };
669
670 Worklist.push_back(Orig);
671 while (!Worklist.empty()) {
672 Value *V = Worklist.pop_back_val();
673 if (!Visited.insert(V).second)
674 continue;
675
676 if (isGuaranteedNotToBePoison(V, nullptr, InsertPt, &DT))
677 continue;
678
681 /*ConsiderFlagsAndMetadata*/ false)) {
682 NeedFreeze.push_back(V);
683 continue;
684 }
685 // Check all operands. If for any of them we cannot insert Freeze,
686 // stop here. Otherwise, iterate.
687 if (any_of(I->operands(), [&](Value *Op) {
688 return isa<Instruction>(Op) && !getFreezeInsertPt(Op, DT);
689 })) {
690 NeedFreeze.push_back(I);
691 continue;
692 }
693 DropPoisonFlags.insert(I);
694 for (Use &U : I->operands())
695 if (!handleConstantOrGlobal(U))
696 Worklist.push_back(U.get());
697 }
698 for (Instruction *I : DropPoisonFlags)
699 I->dropPoisonGeneratingAnnotations();
700
701 Value *Result = Orig;
702 for (Value *V : NeedFreeze) {
703 BasicBlock::iterator FreezeInsertPt = *getFreezeInsertPt(V, DT);
704 FreezeInst *FI = new FreezeInst(V, V->getName() + ".gw.fr");
705 FI->insertBefore(*FreezeInsertPt->getParent(), FreezeInsertPt);
706 ++FreezeAdded;
707 if (V == Orig)
708 Result = FI;
709 V->replaceUsesWithIf(
710 FI, [&](const Use & U)->bool { return U.getUser() != FI; });
711 }
712
713 return Result;
714}
715
716std::optional<Value *>
717GuardWideningImpl::mergeChecks(SmallVectorImpl<Value *> &ChecksToHoist,
718 SmallVectorImpl<Value *> &ChecksToWiden,
719 std::optional<BasicBlock::iterator> InsertPt) {
720 using namespace llvm::PatternMatch;
721
722 Value *Result = nullptr;
723 {
724 // L >u C0 && L >u C1 -> L >u max(C0, C1)
725 ConstantInt *RHS0, *RHS1;
726 Value *LHS;
727 CmpPredicate Pred0, Pred1;
728 // TODO: Support searching for pairs to merge from both whole lists of
729 // ChecksToHoist and ChecksToWiden.
730 if (ChecksToWiden.size() == 1 && ChecksToHoist.size() == 1 &&
731 match(ChecksToWiden.front(),
732 m_ICmp(Pred0, m_Value(LHS), m_ConstantInt(RHS0))) &&
733 match(ChecksToHoist.front(),
734 m_ICmp(Pred1, m_Specific(LHS), m_ConstantInt(RHS1)))) {
735
736 ConstantRange CR0 =
738 ConstantRange CR1 =
740
741 // Given what we're doing here and the semantics of guards, it would
742 // be correct to use a subset intersection, but that may be too
743 // aggressive in cases we care about.
744 if (std::optional<ConstantRange> Intersect =
745 CR0.exactIntersectWith(CR1)) {
746 APInt NewRHSAP;
748 if (Intersect->getEquivalentICmp(Pred, NewRHSAP)) {
749 if (InsertPt) {
750 ConstantInt *NewRHS =
751 ConstantInt::get((*InsertPt)->getContext(), NewRHSAP);
752 assert(canBeHoistedTo(LHS, *InsertPt) && "must be");
753 makeAvailableAt(LHS, *InsertPt);
754 Result = new ICmpInst(*InsertPt, Pred, LHS, NewRHS, "wide.chk");
755 }
756 return Result;
757 }
758 }
759 }
760 }
761
762 {
764 if (parseRangeChecks(ChecksToWiden, Checks) &&
765 parseRangeChecks(ChecksToHoist, Checks) &&
766 combineRangeChecks(Checks, CombinedChecks)) {
767 if (InsertPt) {
768 for (auto &RC : CombinedChecks) {
769 makeAvailableAt(RC.getCheckInst(), *InsertPt);
770 if (Result)
771 Result = BinaryOperator::CreateAnd(RC.getCheckInst(), Result, "",
772 *InsertPt);
773 else
774 Result = RC.getCheckInst();
775 }
776 assert(Result && "Failed to find result value");
777 Result->setName("wide.chk");
778 Result = freezeAndPush(Result, *InsertPt);
779 }
780 return Result;
781 }
782 }
783 // We were not able to compute ChecksToHoist AND ChecksToWiden for the price
784 // of one.
785 return std::nullopt;
786}
787
788Value *GuardWideningImpl::hoistChecks(SmallVectorImpl<Value *> &ChecksToHoist,
789 Value *OldCondition,
790 BasicBlock::iterator InsertPt) {
791 assert(!ChecksToHoist.empty());
792 IRBuilder<> Builder(InsertPt);
793 makeAvailableAt(ChecksToHoist, InsertPt);
794 makeAvailableAt(OldCondition, InsertPt);
795 Value *Result = Builder.CreateAnd(ChecksToHoist);
796 Result = freezeAndPush(Result, InsertPt);
797 Result = Builder.CreateAnd(OldCondition, Result);
798 Result->setName("wide.chk");
799 return Result;
800}
801
802bool GuardWideningImpl::parseRangeChecks(
803 Value *CheckCond, SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks) {
804 using namespace llvm::PatternMatch;
805
806 auto *IC = dyn_cast<ICmpInst>(CheckCond);
807 if (!IC || !IC->getOperand(0)->getType()->isIntegerTy() ||
808 (IC->getPredicate() != ICmpInst::ICMP_ULT &&
809 IC->getPredicate() != ICmpInst::ICMP_UGT))
810 return false;
811
812 const Value *CmpLHS = IC->getOperand(0), *CmpRHS = IC->getOperand(1);
813 if (IC->getPredicate() == ICmpInst::ICMP_UGT)
814 std::swap(CmpLHS, CmpRHS);
815
816 auto &DL = IC->getDataLayout();
817
818 GuardWideningImpl::RangeCheck Check(
819 CmpLHS, cast<ConstantInt>(ConstantInt::getNullValue(CmpRHS->getType())),
820 CmpRHS, IC);
821
822 if (!isKnownNonNegative(Check.getLength(), DL))
823 return false;
824
825 // What we have in \c Check now is a correct interpretation of \p CheckCond.
826 // Try to see if we can move some constant offsets into the \c Offset field.
827
828 bool Changed;
829 auto &Ctx = CheckCond->getContext();
830
831 do {
832 Value *OpLHS;
833 ConstantInt *OpRHS;
834 Changed = false;
835
836#ifndef NDEBUG
837 auto *BaseInst = dyn_cast<Instruction>(Check.getBase());
838 assert((!BaseInst || DT.isReachableFromEntry(BaseInst->getParent())) &&
839 "Unreachable instruction?");
840#endif
841
842 if (match(Check.getBase(), m_Add(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
843 Check.setBase(OpLHS);
844 APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
845 Check.setOffset(ConstantInt::get(Ctx, NewOffset));
846 Changed = true;
847 } else if (match(Check.getBase(),
848 m_Or(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
849 KnownBits Known = computeKnownBits(OpLHS, DL);
850 if ((OpRHS->getValue() & Known.Zero) == OpRHS->getValue()) {
851 Check.setBase(OpLHS);
852 APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
853 Check.setOffset(ConstantInt::get(Ctx, NewOffset));
854 Changed = true;
855 }
856 }
857 } while (Changed);
858
859 Checks.push_back(Check);
860 return true;
861}
862
863bool GuardWideningImpl::combineRangeChecks(
864 SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
865 SmallVectorImpl<GuardWideningImpl::RangeCheck> &RangeChecksOut) const {
866 unsigned OldCount = Checks.size();
867 while (!Checks.empty()) {
868 // Pick all of the range checks with a specific base and length, and try to
869 // merge them.
870 const Value *CurrentBase = Checks.front().getBase();
871 const Value *CurrentLength = Checks.front().getLength();
872
874
875 auto IsCurrentCheck = [&](GuardWideningImpl::RangeCheck &RC) {
876 return RC.getBase() == CurrentBase && RC.getLength() == CurrentLength;
877 };
878
879 copy_if(Checks, std::back_inserter(CurrentChecks), IsCurrentCheck);
880 erase_if(Checks, IsCurrentCheck);
881
882 assert(CurrentChecks.size() != 0 && "We know we have at least one!");
883
884 if (CurrentChecks.size() < 3) {
885 llvm::append_range(RangeChecksOut, CurrentChecks);
886 continue;
887 }
888
889 // CurrentChecks.size() will typically be 3 here, but so far there has been
890 // no need to hard-code that fact.
891
892 llvm::sort(CurrentChecks, [&](const GuardWideningImpl::RangeCheck &LHS,
893 const GuardWideningImpl::RangeCheck &RHS) {
894 return LHS.getOffsetValue().slt(RHS.getOffsetValue());
895 });
896
897 // Note: std::sort should not invalidate the ChecksStart iterator.
898
899 const ConstantInt *MinOffset = CurrentChecks.front().getOffset();
900 const ConstantInt *MaxOffset = CurrentChecks.back().getOffset();
901
902 unsigned BitWidth = MaxOffset->getValue().getBitWidth();
903 if ((MaxOffset->getValue() - MinOffset->getValue())
905 return false;
906
907 APInt MaxDiff = MaxOffset->getValue() - MinOffset->getValue();
908 const APInt &HighOffset = MaxOffset->getValue();
909 auto OffsetOK = [&](const GuardWideningImpl::RangeCheck &RC) {
910 return (HighOffset - RC.getOffsetValue()).ult(MaxDiff);
911 };
912
913 if (MaxDiff.isMinValue() || !all_of(drop_begin(CurrentChecks), OffsetOK))
914 return false;
915
916 // We have a series of f+1 checks as:
917 //
918 // I+k_0 u< L ... Chk_0
919 // I+k_1 u< L ... Chk_1
920 // ...
921 // I+k_f u< L ... Chk_f
922 //
923 // with forall i in [0,f]: k_f-k_i u< k_f-k_0 ... Precond_0
924 // k_f-k_0 u< INT_MIN+k_f ... Precond_1
925 // k_f != k_0 ... Precond_2
926 //
927 // Claim:
928 // Chk_0 AND Chk_f implies all the other checks
929 //
930 // Informal proof sketch:
931 //
932 // We will show that the integer range [I+k_0,I+k_f] does not unsigned-wrap
933 // (i.e. going from I+k_0 to I+k_f does not cross the -1,0 boundary) and
934 // thus I+k_f is the greatest unsigned value in that range.
935 //
936 // This combined with Ckh_(f+1) shows that everything in that range is u< L.
937 // Via Precond_0 we know that all of the indices in Chk_0 through Chk_(f+1)
938 // lie in [I+k_0,I+k_f], this proving our claim.
939 //
940 // To see that [I+k_0,I+k_f] is not a wrapping range, note that there are
941 // two possibilities: I+k_0 u< I+k_f or I+k_0 >u I+k_f (they can't be equal
942 // since k_0 != k_f). In the former case, [I+k_0,I+k_f] is not a wrapping
943 // range by definition, and the latter case is impossible:
944 //
945 // 0-----I+k_f---I+k_0----L---INT_MAX,INT_MIN------------------(-1)
946 // xxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
947 //
948 // For Chk_0 to succeed, we'd have to have k_f-k_0 (the range highlighted
949 // with 'x' above) to be at least >u INT_MIN.
950
951 RangeChecksOut.emplace_back(CurrentChecks.front());
952 RangeChecksOut.emplace_back(CurrentChecks.back());
953 }
954
955 assert(RangeChecksOut.size() <= OldCount && "We pessimized!");
956 return RangeChecksOut.size() != OldCount;
957}
958
959#ifndef NDEBUG
960StringRef GuardWideningImpl::scoreTypeToString(WideningScore WS) {
961 switch (WS) {
962 case WS_IllegalOrNegative:
963 return "IllegalOrNegative";
964 case WS_Neutral:
965 return "Neutral";
966 case WS_Positive:
967 return "Positive";
968 case WS_VeryPositive:
969 return "VeryPositive";
970 }
971
972 llvm_unreachable("Fully covered switch above!");
973}
974#endif
975
978 // Avoid requesting analyses if there are no guards or widenable conditions.
979 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
980 F.getParent(), Intrinsic::experimental_guard);
981 bool HasIntrinsicGuards = GuardDecl && !GuardDecl->use_empty();
983 F.getParent(), Intrinsic::experimental_widenable_condition);
984 bool HasWidenableConditions = WCDecl && !WCDecl->use_empty();
985 if (!HasIntrinsicGuards && !HasWidenableConditions)
986 return PreservedAnalyses::all();
987 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
988 auto &LI = AM.getResult<LoopAnalysis>(F);
989 auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
990 auto &AC = AM.getResult<AssumptionAnalysis>(F);
991 auto *MSSAA = AM.getCachedResult<MemorySSAAnalysis>(F);
992 std::unique_ptr<MemorySSAUpdater> MSSAU;
993 if (MSSAA)
994 MSSAU = std::make_unique<MemorySSAUpdater>(&MSSAA->getMSSA());
995 const ScalarOptions &Opts =
996 F.getContext().getLibraryOptions().get<ScalarOptions>();
997 if (!GuardWideningImpl(Opts, DT, &PDT, LI, AC, MSSAU ? MSSAU.get() : nullptr,
998 DT.getRootNode(), [](BasicBlock *) { return true; })
999 .run())
1000 return PreservedAnalyses::all();
1001
1005 return PA;
1006}
1007
1010 LPMUpdater &U) {
1011 BasicBlock *RootBB = L.getLoopPredecessor();
1012 if (!RootBB)
1013 RootBB = L.getHeader();
1014 auto BlockFilter = [&](BasicBlock *BB) {
1015 return BB == RootBB || L.contains(BB);
1016 };
1017 std::unique_ptr<MemorySSAUpdater> MSSAU;
1018 if (AR.MSSA)
1019 MSSAU = std::make_unique<MemorySSAUpdater>(AR.MSSA);
1020 const ScalarOptions &Opts =
1021 L.getHeader()->getContext().getLibraryOptions().get<ScalarOptions>();
1022 if (!GuardWideningImpl(Opts, AR.DT, nullptr, AR.LI, AR.AC,
1023 MSSAU ? MSSAU.get() : nullptr, AR.DT.getNode(RootBB),
1024 BlockFilter)
1025 .run())
1026 return PreservedAnalyses::all();
1027
1028 auto PA = getLoopPassPreservedAnalyses();
1029 if (AR.MSSA)
1030 PA.preserve<MemorySSAAnalysis>();
1031 return PA;
1032}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:682
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
#define Check(C,...)
static bool isSupportedGuardInstruction(const ScalarOptions &Opts, const Instruction *Insn)
static void eliminateGuard(Instruction *GuardInst, MemorySSAUpdater *MSSAU)
static std::optional< BasicBlock::iterator > findInsertionPointForWideCondition(Instruction *WCOrGuard)
Find a point at which the widened condition of Guard should be inserted.
static Value * getCondition(Instruction *I)
static void setCondition(Instruction *I, Value *NewCond)
static std::optional< BasicBlock::iterator > getFreezeInsertPt(Value *V, const DominatorTree &DT)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
const SmallVectorImpl< MachineOperand > & Cond
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
Value * RHS
Value * LHS
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool isMinValue() const
Determine if this is the smallest unsigned value.
Definition APInt.h:413
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI const_iterator getFirstNonPHIOrAlloca() const
Returns an iterator to the first instruction in this block that is not a PHINode, a static alloca,...
LLVM_ABI const CallInst * getPostdominatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize that is present either in current ...
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
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 std::optional< ConstantRange > exactIntersectWith(const ConstantRange &CR) const
Intersect the two ranges and return the result if it can be represented exactly, otherwise return std...
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
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.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
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.
A wrapper class for inspecting calls to intrinsic functions.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:922
LLVM_ABI void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
Analysis pass which computes a PostDominatorTree.
LLVM_ABI bool dominates(const Instruction *I1, const Instruction *I2) const
Return true if I1 dominates I2.
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 & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
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.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
LLVM Value Representation.
Definition Value.h:75
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
unsigned getPathLength() const
Return the length of the path from the entry node to the current node, counting both nodes.
NodeRef getPath(unsigned n) const
Return the n'th node in the path from the entry node to the current node.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
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.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
iterator end() const
Definition BasicBlock.h:89
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
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
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
df_iterator< T > df_begin(const T &G)
LLVM_ABI Value * extractWidenableCondition(const User *U)
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI void parseWidenableGuard(const User *U, llvm::SmallVectorImpl< Value * > &Checks)
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 ...
OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P)
Provide wrappers to std::copy_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1807
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
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 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 parseWidenableBranch(const User *U, Value *&Condition, Value *&WidenableCondition, BasicBlock *&IfTrueBB, BasicBlock *&IfFalseBB)
If U is widenable branch looking like: cond = ... wc = call i1 @llvm.experimental....
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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 bool isGuardAsWidenableBranch(const User *U)
Returns true iff U has semantics of a guard expressed in a form of a widenable conditional branch to ...
LLVM_ABI void setWidenableBranchCond(CondBrInst *WidenableBR, Value *Cond)
Given a branch we know is widenable (defined per Analysis/GuardUtils.h), set it's condition such that...
DWARFExpression::Operation Op
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
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
df_iterator< T > df_end(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...