LLVM 23.0.0git
SafepointIRVerifier.cpp
Go to the documentation of this file.
1//===-- SafepointIRVerifier.cpp - Verify gc.statepoint invariants ---------===//
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// Run a basic correctness check on the IR to ensure that Safepoints - if
10// they've been inserted - were inserted correctly. In particular, look for use
11// of non-relocated values after a safepoint. It's primary use is to check the
12// correctness of safepoint insertion immediately after insertion, but it can
13// also be used to verify that later transforms have not found a way to break
14// safepoint semenatics.
15//
16// In its current form, this verify checks a property which is sufficient, but
17// not neccessary for correctness. There are some cases where an unrelocated
18// pointer can be used after the safepoint. Consider this example:
19//
20// a = ...
21// b = ...
22// (a',b') = safepoint(a,b)
23// c = cmp eq a b
24// br c, ..., ....
25//
26// Because it is valid to reorder 'c' above the safepoint, this is legal. In
27// practice, this is a somewhat uncommon transform, but CodeGenPrep does create
28// idioms like this. The verifier knows about these cases and avoids reporting
29// false positives.
30//
31//===----------------------------------------------------------------------===//
32
34#include "llvm/ADT/DenseSet.h"
37#include "llvm/ADT/SetVector.h"
38#include "llvm/IR/BasicBlock.h"
39#include "llvm/IR/Dominators.h"
40#include "llvm/IR/Function.h"
41#include "llvm/IR/InstrTypes.h"
43#include "llvm/IR/Statepoint.h"
44#include "llvm/IR/Value.h"
48#include "llvm/Support/Debug.h"
50
51#define DEBUG_TYPE "safepoint-ir-verifier"
52
53using namespace llvm;
54
55/// This option is used for writing test cases. Instead of crashing the program
56/// when verification fails, report a message to the console (for FileCheck
57/// usage) and continue execution as if nothing happened.
58static cl::opt<bool> PrintOnly("safepoint-ir-verifier-print-only",
59 cl::init(false));
60
61namespace {
62
63/// This CFG Deadness finds dead blocks and edges. Algorithm starts with a set
64/// of blocks unreachable from entry then propagates deadness using foldable
65/// conditional branches without modifying CFG. So GVN does but it changes CFG
66/// by splitting critical edges. In most cases passes rely on SimplifyCFG to
67/// clean up dead blocks, but in some cases, like verification or loop passes
68/// it's not possible.
69class CFGDeadness {
70 const DominatorTree *DT = nullptr;
72 SetVector<const Use *> DeadEdges; // Contains all dead edges from live blocks.
73
74public:
75 /// Return the edge that coresponds to the predecessor.
76 static const Use& getEdge(const_pred_iterator &PredIt) {
77 auto &PU = PredIt.getUse();
78 return PU.getUser()->getOperandUse(PU.getOperandNo());
79 }
80
81 /// Return true if there is at least one live edge that corresponds to the
82 /// basic block InBB listed in the phi node.
83 bool hasLiveIncomingEdge(const PHINode *PN, const BasicBlock *InBB) const {
84 assert(!isDeadBlock(InBB) && "block must be live");
85 const BasicBlock* BB = PN->getParent();
86 bool Listed = false;
87 for (const_pred_iterator PredIt(BB), End(BB, true); PredIt != End; ++PredIt) {
88 if (InBB == *PredIt) {
89 if (!isDeadEdge(&getEdge(PredIt)))
90 return true;
91 Listed = true;
92 }
93 }
94 (void)Listed;
95 assert(Listed && "basic block is not found among incoming blocks");
96 return false;
97 }
98
99
100 bool isDeadBlock(const BasicBlock *BB) const {
101 return DeadBlocks.count(BB);
102 }
103
104 bool isDeadEdge(const Use *U) const {
105 assert(cast<Instruction>(U->getUser())->isTerminator() &&
106 "edge must be operand of terminator");
108 "edge must refer to basic block");
109 assert(!isDeadBlock(cast<Instruction>(U->getUser())->getParent()) &&
110 "isDeadEdge() must be applied to edge from live block");
111 return DeadEdges.count(U);
112 }
113
114 bool hasLiveIncomingEdges(const BasicBlock *BB) const {
115 // Check if all incoming edges are dead.
116 for (const_pred_iterator PredIt(BB), End(BB, true); PredIt != End; ++PredIt) {
117 auto &PU = PredIt.getUse();
118 const Use &U = PU.getUser()->getOperandUse(PU.getOperandNo());
119 if (!isDeadBlock(*PredIt) && !isDeadEdge(&U))
120 return true; // Found a live edge.
121 }
122 return false;
123 }
124
125 void processFunction(const Function &F, const DominatorTree &DT) {
126 this->DT = &DT;
127
128 // Start with all blocks unreachable from entry.
129 for (const BasicBlock &BB : F)
130 if (!DT.isReachableFromEntry(&BB))
131 DeadBlocks.insert(&BB);
132
133 // Top-down walk of the dominator tree
134 ReversePostOrderTraversal<const Function *> RPOT(&F);
135 for (const BasicBlock *BB : RPOT) {
136 const Instruction *TI = BB->getTerminator();
137 assert(TI && "blocks must be well formed");
138
139 // For conditional branches, we can perform simple conditional propagation on
140 // the condition value itself.
141 const CondBrInst *BI = dyn_cast<CondBrInst>(TI);
142 if (!BI || !isa<Constant>(BI->getCondition()))
143 continue;
144
145 // If a branch has two identical successors, we cannot declare either dead.
146 if (BI->getSuccessor(0) == BI->getSuccessor(1))
147 continue;
148
149 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
150 if (!Cond)
151 continue;
152
153 addDeadEdge(BI->getOperandUse(Cond->getZExtValue() ? 1 : 2));
154 }
155 }
156
157protected:
158 void addDeadBlock(const BasicBlock *BB) {
160
161 NewDead.push_back(BB);
162 while (!NewDead.empty()) {
163 const BasicBlock *D = NewDead.pop_back_val();
164 if (isDeadBlock(D))
165 continue;
166
167 // All blocks dominated by D are dead.
168 SmallVector<BasicBlock *, 8> Dom;
169 DT->getDescendants(const_cast<BasicBlock*>(D), Dom);
170 // Do not need to mark all in and out edges dead
171 // because BB is marked dead and this is enough
172 // to run further.
173 DeadBlocks.insert_range(Dom);
174
175 // Figure out the dominance-frontier(D).
176 for (BasicBlock *B : Dom)
177 for (BasicBlock *S : successors(B))
178 if (!isDeadBlock(S) && !hasLiveIncomingEdges(S))
179 NewDead.push_back(S);
180 }
181 }
182
183 void addDeadEdge(const Use &DeadEdge) {
184 if (!DeadEdges.insert(&DeadEdge))
185 return;
186
187 BasicBlock *BB = cast_or_null<BasicBlock>(DeadEdge.get());
188 if (hasLiveIncomingEdges(BB))
189 return;
190
191 addDeadBlock(BB);
192 }
193};
194} // namespace
195
196static void Verify(const Function &F, const DominatorTree &DT,
197 const CFGDeadness &CD);
198
201 const auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
202 CFGDeadness CD;
203 CD.processFunction(F, DT);
204 Verify(F, DT, CD);
205 return PreservedAnalyses::all();
206}
207
208namespace {
209
210struct SafepointIRVerifier : public FunctionPass {
211 static char ID; // Pass identification, replacement for typeid
212 SafepointIRVerifier() : FunctionPass(ID) {}
213
214 bool runOnFunction(Function &F) override {
215 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
216 CFGDeadness CD;
217 CD.processFunction(F, DT);
218 Verify(F, DT, CD);
219 return false; // no modifications
220 }
221
222 void getAnalysisUsage(AnalysisUsage &AU) const override {
224 AU.setPreservesAll();
225 }
226
227 StringRef getPassName() const override { return "safepoint verifier"; }
228};
229} // namespace
230
232 SafepointIRVerifier pass;
233 pass.runOnFunction(F);
234}
235
236char SafepointIRVerifier::ID = 0;
237
239 return new SafepointIRVerifier();
240}
241
242INITIALIZE_PASS_BEGIN(SafepointIRVerifier, "verify-safepoint-ir",
243 "Safepoint IR Verifier", false, false)
245INITIALIZE_PASS_END(SafepointIRVerifier, "verify-safepoint-ir",
246 "Safepoint IR Verifier", false, false)
247
248static bool isGCPointerType(Type *T) {
249 if (auto *PT = dyn_cast<PointerType>(T))
250 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
251 // GC managed heap. We know that a pointer into this heap needs to be
252 // updated and that no other pointer does.
253 return (1 == PT->getAddressSpace());
254 return false;
255}
256
257static bool containsGCPtrType(Type *Ty) {
258 if (isGCPointerType(Ty))
259 return true;
260 if (VectorType *VT = dyn_cast<VectorType>(Ty))
261 return isGCPointerType(VT->getScalarType());
262 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
263 return containsGCPtrType(AT->getElementType());
264 if (StructType *ST = dyn_cast<StructType>(Ty))
265 return llvm::any_of(ST->elements(), containsGCPtrType);
266 return false;
267}
268
269// Debugging aid -- prints a [Begin, End) range of values.
270// Only used inside LLVM_DEBUG below, so it has no instantiations in release
271// builds (NDEBUG); [[maybe_unused]] avoids -Wunused-template in that case.
272template <typename IteratorTy>
273[[maybe_unused]] static void PrintValueSet(raw_ostream &OS, IteratorTy Begin,
274 IteratorTy End) {
275 OS << "[ ";
276 while (Begin != End) {
277 OS << **Begin << " ";
278 ++Begin;
279 }
280 OS << "]";
281}
282
283/// The verifier algorithm is phrased in terms of availability. The set of
284/// values "available" at a given point in the control flow graph is the set of
285/// correctly relocated value at that point, and is a subset of the set of
286/// definitions dominating that point.
287
289
290namespace {
291/// State we compute and track per basic block.
292struct BasicBlockState {
293 // Set of values available coming in, before the phi nodes
294 AvailableValueSet AvailableIn;
295
296 // Set of values available going out
297 AvailableValueSet AvailableOut;
298
299 // AvailableOut minus AvailableIn.
300 // All elements are Instructions
301 AvailableValueSet Contribution;
302
303 // True if this block contains a safepoint and thus AvailableIn does not
304 // contribute to AvailableOut.
305 bool Cleared = false;
306};
307} // namespace
308
309/// A given derived pointer can have multiple base pointers through phi/selects.
310/// This type indicates when the base pointer is exclusively constant
311/// (ExclusivelySomeConstant), and if that constant is proven to be exclusively
312/// null, we record that as ExclusivelyNull. In all other cases, the BaseType is
313/// NonConstant.
315 NonConstant = 1, // Base pointers is not exclusively constant.
317 ExclusivelySomeConstant // Base pointers for a given derived pointer is from a
318 // set of constants, but they are not exclusively
319 // null.
320};
321
322/// Return the baseType for Val which states whether Val is exclusively
323/// derived from constant/null, or not exclusively derived from constant.
324/// Val is exclusively derived off a constant base when all operands of phi and
325/// selects are derived off a constant base.
326static enum BaseType getBaseType(const Value *Val) {
327
330 bool isExclusivelyDerivedFromNull = true;
331 Worklist.push_back(Val);
332 // Strip through all the bitcasts and geps to get base pointer. Also check for
333 // the exclusive value when there can be multiple base pointers (through phis
334 // or selects).
335 while(!Worklist.empty()) {
336 const Value *V = Worklist.pop_back_val();
337 if (!Visited.insert(V).second)
338 continue;
339
340 if (const auto *CI = dyn_cast<CastInst>(V)) {
341 Worklist.push_back(CI->stripPointerCasts());
342 continue;
343 }
344 if (const auto *GEP = dyn_cast<GetElementPtrInst>(V)) {
345 Worklist.push_back(GEP->getPointerOperand());
346 continue;
347 }
348 // Push all the incoming values of phi node into the worklist for
349 // processing.
350 if (const auto *PN = dyn_cast<PHINode>(V)) {
351 append_range(Worklist, PN->incoming_values());
352 continue;
353 }
354 if (const auto *SI = dyn_cast<SelectInst>(V)) {
355 // Push in the true and false values
356 Worklist.push_back(SI->getTrueValue());
357 Worklist.push_back(SI->getFalseValue());
358 continue;
359 }
360 if (const auto *GCRelocate = dyn_cast<GCRelocateInst>(V)) {
361 // GCRelocates do not change null-ness or constant-ness of the value.
362 // So we can continue with derived pointer this instruction relocates.
363 Worklist.push_back(GCRelocate->getDerivedPtr());
364 continue;
365 }
366 if (const auto *FI = dyn_cast<FreezeInst>(V)) {
367 // Freeze does not change null-ness or constant-ness of the value.
368 Worklist.push_back(FI->getOperand(0));
369 continue;
370 }
371 if (isa<Constant>(V)) {
372 // We found at least one base pointer which is non-null, so this derived
373 // pointer is not exclusively derived from null.
374 if (V != Constant::getNullValue(V->getType()))
375 isExclusivelyDerivedFromNull = false;
376 // Continue processing the remaining values to make sure it's exclusively
377 // constant.
378 continue;
379 }
380 // At this point, we know that the base pointer is not exclusively
381 // constant.
383 }
384 // Now, we know that the base pointer is exclusively constant, but we need to
385 // differentiate between exclusive null constant and non-null constant.
386 return isExclusivelyDerivedFromNull ? BaseType::ExclusivelyNull
388}
389
392}
393
394namespace {
395class InstructionVerifier;
396
397/// Builds BasicBlockState for each BB of the function.
398/// It can traverse function for verification and provides all required
399/// information.
400///
401/// GC pointer may be in one of three states: relocated, unrelocated and
402/// poisoned.
403/// Relocated pointer may be used without any restrictions.
404/// Unrelocated pointer cannot be dereferenced, passed as argument to any call
405/// or returned. Unrelocated pointer may be safely compared against another
406/// unrelocated pointer or against a pointer exclusively derived from null.
407/// Poisoned pointers are produced when we somehow derive pointer from relocated
408/// and unrelocated pointers (e.g. phi, select). This pointers may be safely
409/// used in a very limited number of situations. Currently the only way to use
410/// it is comparison against constant exclusively derived from null. All
411/// limitations arise due to their undefined state: this pointers should be
412/// treated as relocated and unrelocated simultaneously.
413/// Rules of deriving:
414/// R + U = P - that's where the poisoned pointers come from
415/// P + X = P
416/// U + U = U
417/// R + R = R
418/// X + C = X
419/// Where "+" - any operation that somehow derive pointer, U - unrelocated,
420/// R - relocated and P - poisoned, C - constant, X - U or R or P or C or
421/// nothing (in case when "+" is unary operation).
422/// Deriving of pointers by itself is always safe.
423/// NOTE: when we are making decision on the status of instruction's result:
424/// a) for phi we need to check status of each input *at the end of
425/// corresponding predecessor BB*.
426/// b) for other instructions we need to check status of each input *at the
427/// current point*.
428///
429/// FIXME: This works fairly well except one case
430/// bb1:
431/// p = *some GC-ptr def*
432/// p1 = gep p, offset
433/// / |
434/// / |
435/// bb2: |
436/// safepoint |
437/// \ |
438/// \ |
439/// bb3:
440/// p2 = phi [p, bb2] [p1, bb1]
441/// p3 = phi [p, bb2] [p, bb1]
442/// here p and p1 is unrelocated
443/// p2 and p3 is poisoned (though they shouldn't be)
444///
445/// This leads to some weird results:
446/// cmp eq p, p2 - illegal instruction (false-positive)
447/// cmp eq p1, p2 - illegal instruction (false-positive)
448/// cmp eq p, p3 - illegal instruction (false-positive)
449/// cmp eq p, p1 - ok
450/// To fix this we need to introduce conception of generations and be able to
451/// check if two values belong to one generation or not. This way p2 will be
452/// considered to be unrelocated and no false alarm will happen.
453class GCPtrTracker {
454 const Function &F;
455 const CFGDeadness &CD;
456 SpecificBumpPtrAllocator<BasicBlockState> BSAllocator;
457 DenseMap<const BasicBlock *, BasicBlockState *> BlockMap;
458 // This set contains defs of unrelocated pointers that are proved to be legal
459 // and don't need verification.
460 DenseSet<const Instruction *> ValidUnrelocatedDefs;
461 // This set contains poisoned defs. They can be safely ignored during
462 // verification too.
463 DenseSet<const Value *> PoisonedDefs;
464
465public:
466 GCPtrTracker(const Function &F, const DominatorTree &DT,
467 const CFGDeadness &CD);
468
469 bool hasLiveIncomingEdge(const PHINode *PN, const BasicBlock *InBB) const {
470 return CD.hasLiveIncomingEdge(PN, InBB);
471 }
472
473 BasicBlockState *getBasicBlockState(const BasicBlock *BB);
474 const BasicBlockState *getBasicBlockState(const BasicBlock *BB) const;
475
476 bool isValuePoisoned(const Value *V) const { return PoisonedDefs.count(V); }
477
478 /// Traverse each BB of the function and call
479 /// InstructionVerifier::verifyInstruction for each possibly invalid
480 /// instruction.
481 /// It destructively modifies GCPtrTracker so it's passed via rvalue reference
482 /// in order to prohibit further usages of GCPtrTracker as it'll be in
483 /// inconsistent state.
484 static void verifyFunction(GCPtrTracker &&Tracker,
485 InstructionVerifier &Verifier);
486
487 /// Returns true for reachable and live blocks.
488 bool isMapped(const BasicBlock *BB) const { return BlockMap.contains(BB); }
489
490private:
491 /// Returns true if the instruction may be safely skipped during verification.
492 bool instructionMayBeSkipped(const Instruction *I) const;
493
494 /// Iterates over all BBs from BlockMap and recalculates AvailableIn/Out for
495 /// each of them until it converges.
496 void recalculateBBsStates();
497
498 /// Remove from Contribution all defs that legally produce unrelocated
499 /// pointers and saves them to ValidUnrelocatedDefs.
500 /// Though Contribution should belong to BBS it is passed separately with
501 /// different const-modifier in order to emphasize (and guarantee) that only
502 /// Contribution will be changed.
503 /// Returns true if Contribution was changed otherwise false.
504 bool removeValidUnrelocatedDefs(const BasicBlock *BB,
505 const BasicBlockState *BBS,
506 AvailableValueSet &Contribution);
507
508 /// Gather all the definitions dominating the start of BB into Result. This is
509 /// simply the defs introduced by every dominating basic block and the
510 /// function arguments.
511 void gatherDominatingDefs(const BasicBlock *BB, AvailableValueSet &Result,
512 const DominatorTree &DT);
513
514 /// Compute the AvailableOut set for BB, based on the BasicBlockState BBS,
515 /// which is the BasicBlockState for BB.
516 /// ContributionChanged is set when the verifier runs for the first time
517 /// (in this case Contribution was changed from 'empty' to its initial state)
518 /// or when Contribution of this BB was changed since last computation.
519 static void transferBlock(const BasicBlock *BB, BasicBlockState &BBS,
520 bool ContributionChanged);
521
522 /// Model the effect of an instruction on the set of available values.
523 static void transferInstruction(const Instruction &I, bool &Cleared,
525};
526
527/// It is a visitor for GCPtrTracker::verifyFunction. It decides if the
528/// instruction (which uses heap reference) is legal or not, given our safepoint
529/// semantics.
530class InstructionVerifier {
531 bool AnyInvalidUses = false;
532
533public:
534 void verifyInstruction(const GCPtrTracker *Tracker, const Instruction &I,
535 const AvailableValueSet &AvailableSet);
536
537 bool hasAnyInvalidUses() const { return AnyInvalidUses; }
538
539private:
540 void reportInvalidUse(const Value &V, const Instruction &I);
541};
542} // end anonymous namespace
543
544GCPtrTracker::GCPtrTracker(const Function &F, const DominatorTree &DT,
545 const CFGDeadness &CD) : F(F), CD(CD) {
546 // Calculate Contribution of each live BB.
547 // Allocate BB states for live blocks.
548 for (const BasicBlock &BB : F)
549 if (!CD.isDeadBlock(&BB)) {
550 BasicBlockState *BBS = new (BSAllocator.Allocate()) BasicBlockState;
551 for (const auto &I : BB)
552 transferInstruction(I, BBS->Cleared, BBS->Contribution);
553 BlockMap[&BB] = BBS;
554 }
555
556 // Initialize AvailableIn/Out sets of each BB using only information about
557 // dominating BBs.
558 for (auto &BBI : BlockMap) {
559 gatherDominatingDefs(BBI.first, BBI.second->AvailableIn, DT);
560 transferBlock(BBI.first, *BBI.second, true);
561 }
562
563 // Simulate the flow of defs through the CFG and recalculate AvailableIn/Out
564 // sets of each BB until it converges. If any def is proved to be an
565 // unrelocated pointer, it will be removed from all BBSs.
566 recalculateBBsStates();
567}
568
569BasicBlockState *GCPtrTracker::getBasicBlockState(const BasicBlock *BB) {
570 return BlockMap.lookup(BB);
571}
572
573const BasicBlockState *GCPtrTracker::getBasicBlockState(
574 const BasicBlock *BB) const {
575 return const_cast<GCPtrTracker *>(this)->getBasicBlockState(BB);
576}
577
578bool GCPtrTracker::instructionMayBeSkipped(const Instruction *I) const {
579 // Poisoned defs are skipped since they are always safe by itself by
580 // definition (for details see comment to this class).
581 return ValidUnrelocatedDefs.count(I) || PoisonedDefs.count(I);
582}
583
584void GCPtrTracker::verifyFunction(GCPtrTracker &&Tracker,
585 InstructionVerifier &Verifier) {
586 // We need RPO here to a) report always the first error b) report errors in
587 // same order from run to run.
588 ReversePostOrderTraversal<const Function *> RPOT(&Tracker.F);
589 for (const BasicBlock *BB : RPOT) {
590 BasicBlockState *BBS = Tracker.getBasicBlockState(BB);
591 if (!BBS)
592 continue;
593
594 // We destructively modify AvailableIn as we traverse the block instruction
595 // by instruction.
596 AvailableValueSet &AvailableSet = BBS->AvailableIn;
597 for (const Instruction &I : *BB) {
598 if (Tracker.instructionMayBeSkipped(&I))
599 continue; // This instruction shouldn't be added to AvailableSet.
600
601 Verifier.verifyInstruction(&Tracker, I, AvailableSet);
602
603 // Model the effect of current instruction on AvailableSet to keep the set
604 // relevant at each point of BB.
605 bool Cleared = false;
606 transferInstruction(I, Cleared, AvailableSet);
607 (void)Cleared;
608 }
609 }
610}
611
612void GCPtrTracker::recalculateBBsStates() {
613 // TODO: This order is suboptimal, it's better to replace it with priority
614 // queue where priority is RPO number of BB.
615 SetVector<const BasicBlock *> Worklist(llvm::from_range,
616 llvm::make_first_range(BlockMap));
617
618 // This loop iterates the AvailableIn/Out sets until it converges.
619 // The AvailableIn and AvailableOut sets decrease as we iterate.
620 while (!Worklist.empty()) {
621 const BasicBlock *BB = Worklist.pop_back_val();
622 BasicBlockState *BBS = getBasicBlockState(BB);
623 if (!BBS)
624 continue; // Ignore dead successors.
625
626 size_t OldInCount = BBS->AvailableIn.size();
627 for (const_pred_iterator PredIt(BB), End(BB, true); PredIt != End; ++PredIt) {
628 const BasicBlock *PBB = *PredIt;
629 BasicBlockState *PBBS = getBasicBlockState(PBB);
630 if (PBBS && !CD.isDeadEdge(&CFGDeadness::getEdge(PredIt)))
631 set_intersect(BBS->AvailableIn, PBBS->AvailableOut);
632 }
633
634 assert(OldInCount >= BBS->AvailableIn.size() && "invariant!");
635
636 bool InputsChanged = OldInCount != BBS->AvailableIn.size();
637 bool ContributionChanged =
638 removeValidUnrelocatedDefs(BB, BBS, BBS->Contribution);
639 if (!InputsChanged && !ContributionChanged)
640 continue;
641
642 size_t OldOutCount = BBS->AvailableOut.size();
643 transferBlock(BB, *BBS, ContributionChanged);
644 if (OldOutCount != BBS->AvailableOut.size()) {
645 assert(OldOutCount > BBS->AvailableOut.size() && "invariant!");
646 Worklist.insert_range(successors(BB));
647 }
648 }
649}
650
651bool GCPtrTracker::removeValidUnrelocatedDefs(const BasicBlock *BB,
652 const BasicBlockState *BBS,
653 AvailableValueSet &Contribution) {
654 assert(&BBS->Contribution == &Contribution &&
655 "Passed Contribution should be from the passed BasicBlockState!");
656 AvailableValueSet AvailableSet = BBS->AvailableIn;
657 bool ContributionChanged = false;
658 // For explanation why instructions are processed this way see
659 // "Rules of deriving" in the comment to this class.
660 for (const Instruction &I : *BB) {
661 bool ValidUnrelocatedPointerDef = false;
662 bool PoisonedPointerDef = false;
663 // TODO: `select` instructions should be handled here too.
664 if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
665 if (containsGCPtrType(PN->getType())) {
666 // If both is true, output is poisoned.
667 bool HasRelocatedInputs = false;
668 bool HasUnrelocatedInputs = false;
669 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
670 const BasicBlock *InBB = PN->getIncomingBlock(i);
671 if (!isMapped(InBB) ||
672 !CD.hasLiveIncomingEdge(PN, InBB))
673 continue; // Skip dead block or dead edge.
674
675 const Value *InValue = PN->getIncomingValue(i);
676
677 if (isNotExclusivelyConstantDerived(InValue)) {
678 if (isValuePoisoned(InValue)) {
679 // If any of inputs is poisoned, output is always poisoned too.
680 HasRelocatedInputs = true;
681 HasUnrelocatedInputs = true;
682 break;
683 }
684 if (BlockMap[InBB]->AvailableOut.count(InValue))
685 HasRelocatedInputs = true;
686 else
687 HasUnrelocatedInputs = true;
688 }
689 }
690 if (HasUnrelocatedInputs) {
691 if (HasRelocatedInputs)
692 PoisonedPointerDef = true;
693 else
694 ValidUnrelocatedPointerDef = true;
695 }
696 }
697 } else if ((isa<GetElementPtrInst>(I) || isa<BitCastInst>(I)) &&
698 containsGCPtrType(I.getType())) {
699 // GEP/bitcast of unrelocated pointer is legal by itself but this def
700 // shouldn't appear in any AvailableSet.
701 for (const Value *V : I.operands())
702 if (containsGCPtrType(V->getType()) &&
703 isNotExclusivelyConstantDerived(V) && !AvailableSet.count(V)) {
704 if (isValuePoisoned(V))
705 PoisonedPointerDef = true;
706 else
707 ValidUnrelocatedPointerDef = true;
708 break;
709 }
710 }
711 assert(!(ValidUnrelocatedPointerDef && PoisonedPointerDef) &&
712 "Value cannot be both unrelocated and poisoned!");
713 if (ValidUnrelocatedPointerDef) {
714 // Remove def of unrelocated pointer from Contribution of this BB and
715 // trigger update of all its successors.
716 Contribution.erase(&I);
717 PoisonedDefs.erase(&I);
718 ValidUnrelocatedDefs.insert(&I);
719 LLVM_DEBUG(dbgs() << "Removing urelocated " << I
720 << " from Contribution of " << BB->getName() << "\n");
721 ContributionChanged = true;
722 } else if (PoisonedPointerDef) {
723 // Mark pointer as poisoned, remove its def from Contribution and trigger
724 // update of all successors.
725 Contribution.erase(&I);
726 PoisonedDefs.insert(&I);
727 LLVM_DEBUG(dbgs() << "Removing poisoned " << I << " from Contribution of "
728 << BB->getName() << "\n");
729 ContributionChanged = true;
730 } else {
731 bool Cleared = false;
732 transferInstruction(I, Cleared, AvailableSet);
733 (void)Cleared;
734 }
735 }
736 return ContributionChanged;
737}
738
739void GCPtrTracker::gatherDominatingDefs(const BasicBlock *BB,
740 AvailableValueSet &Result,
741 const DominatorTree &DT) {
742 DomTreeNode *DTN = DT[const_cast<BasicBlock *>(BB)];
743
744 assert(DTN && "Unreachable blocks are ignored");
745 while (DTN->getIDom()) {
746 DTN = DTN->getIDom();
747 auto BBS = getBasicBlockState(DTN->getBlock());
748 assert(BBS && "immediate dominator cannot be dead for a live block");
749 const auto &Defs = BBS->Contribution;
750 Result.insert_range(Defs);
751 // If this block is 'Cleared', then nothing LiveIn to this block can be
752 // available after this block completes. Note: This turns out to be
753 // really important for reducing memory consuption of the initial available
754 // sets and thus peak memory usage by this verifier.
755 if (BBS->Cleared)
756 return;
757 }
758
759 for (const Argument &A : BB->getParent()->args())
760 if (containsGCPtrType(A.getType()))
761 Result.insert(&A);
762}
763
764void GCPtrTracker::transferBlock(const BasicBlock *BB, BasicBlockState &BBS,
765 bool ContributionChanged) {
766 const AvailableValueSet &AvailableIn = BBS.AvailableIn;
767 AvailableValueSet &AvailableOut = BBS.AvailableOut;
768
769 if (BBS.Cleared) {
770 // AvailableOut will change only when Contribution changed.
771 if (ContributionChanged)
772 AvailableOut = BBS.Contribution;
773 } else {
774 // Otherwise, we need to reduce the AvailableOut set by things which are no
775 // longer in our AvailableIn
776 AvailableValueSet Temp = BBS.Contribution;
777 set_union(Temp, AvailableIn);
778 AvailableOut = std::move(Temp);
779 }
780
781 LLVM_DEBUG(dbgs() << "Transfered block " << BB->getName() << " from ";
782 PrintValueSet(dbgs(), AvailableIn.begin(), AvailableIn.end());
783 dbgs() << " to ";
784 PrintValueSet(dbgs(), AvailableOut.begin(), AvailableOut.end());
785 dbgs() << "\n";);
786}
787
788void GCPtrTracker::transferInstruction(const Instruction &I, bool &Cleared,
791 Cleared = true;
792 Available.clear();
793 } else if (containsGCPtrType(I.getType()))
795}
796
797void InstructionVerifier::verifyInstruction(
798 const GCPtrTracker *Tracker, const Instruction &I,
799 const AvailableValueSet &AvailableSet) {
800 if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
801 if (containsGCPtrType(PN->getType()))
802 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
803 const BasicBlock *InBB = PN->getIncomingBlock(i);
804 const BasicBlockState *InBBS = Tracker->getBasicBlockState(InBB);
805 if (!InBBS ||
806 !Tracker->hasLiveIncomingEdge(PN, InBB))
807 continue; // Skip dead block or dead edge.
808
809 const Value *InValue = PN->getIncomingValue(i);
810
811 if (isNotExclusivelyConstantDerived(InValue) &&
812 !InBBS->AvailableOut.count(InValue))
813 reportInvalidUse(*InValue, *PN);
814 }
815 } else if (isa<CmpInst>(I) &&
816 containsGCPtrType(I.getOperand(0)->getType())) {
817 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
818 enum BaseType baseTyLHS = getBaseType(LHS),
819 baseTyRHS = getBaseType(RHS);
820
821 // Returns true if LHS and RHS are unrelocated pointers and they are
822 // valid unrelocated uses.
823 auto hasValidUnrelocatedUse = [&AvailableSet, Tracker, baseTyLHS, baseTyRHS,
824 &LHS, &RHS] () {
825 // A cmp instruction has valid unrelocated pointer operands only if
826 // both operands are unrelocated pointers.
827 // In the comparison between two pointers, if one is an unrelocated
828 // use, the other *should be* an unrelocated use, for this
829 // instruction to contain valid unrelocated uses. This unrelocated
830 // use can be a null constant as well, or another unrelocated
831 // pointer.
832 if (AvailableSet.count(LHS) || AvailableSet.count(RHS))
833 return false;
834 // Constant pointers (that are not exclusively null) may have
835 // meaning in different VMs, so we cannot reorder the compare
836 // against constant pointers before the safepoint. In other words,
837 // comparison of an unrelocated use against a non-null constant
838 // maybe invalid.
839 if ((baseTyLHS == BaseType::ExclusivelySomeConstant &&
840 baseTyRHS == BaseType::NonConstant) ||
841 (baseTyLHS == BaseType::NonConstant &&
843 return false;
844
845 // If one of pointers is poisoned and other is not exclusively derived
846 // from null it is an invalid expression: it produces poisoned result
847 // and unless we want to track all defs (not only gc pointers) the only
848 // option is to prohibit such instructions.
849 if ((Tracker->isValuePoisoned(LHS) && baseTyRHS != ExclusivelyNull) ||
850 (Tracker->isValuePoisoned(RHS) && baseTyLHS != ExclusivelyNull))
851 return false;
852
853 // All other cases are valid cases enumerated below:
854 // 1. Comparison between an exclusively derived null pointer and a
855 // constant base pointer.
856 // 2. Comparison between an exclusively derived null pointer and a
857 // non-constant unrelocated base pointer.
858 // 3. Comparison between 2 unrelocated pointers.
859 // 4. Comparison between a pointer exclusively derived from null and a
860 // non-constant poisoned pointer.
861 return true;
862 };
863 if (!hasValidUnrelocatedUse()) {
864 // Print out all non-constant derived pointers that are unrelocated
865 // uses, which are invalid.
866 if (baseTyLHS == BaseType::NonConstant && !AvailableSet.count(LHS))
867 reportInvalidUse(*LHS, I);
868 if (baseTyRHS == BaseType::NonConstant && !AvailableSet.count(RHS))
869 reportInvalidUse(*RHS, I);
870 }
871 } else {
872 for (const Value *V : I.operands())
873 if (containsGCPtrType(V->getType()) &&
874 isNotExclusivelyConstantDerived(V) && !AvailableSet.count(V))
875 reportInvalidUse(*V, I);
876 }
877}
878
879void InstructionVerifier::reportInvalidUse(const Value &V,
880 const Instruction &I) {
881 errs() << "Illegal use of unrelocated value found!\n";
882 errs() << "Def: " << V << "\n";
883 errs() << "Use: " << I << "\n";
884 if (!PrintOnly)
885 abort();
886 AnyInvalidUses = true;
887}
888
889static void Verify(const Function &F, const DominatorTree &DT,
890 const CFGDeadness &CD) {
891 LLVM_DEBUG(dbgs() << "Verifying gc pointers in function: " << F.getName()
892 << "\n");
893 if (PrintOnly)
894 dbgs() << "Verifying gc pointers in function: " << F.getName() << "\n";
895
896 GCPtrTracker Tracker(F, DT, CD);
897
898 // We now have all the information we need to decide if the use of a heap
899 // reference is legal or not, given our safepoint semantics.
900
901 InstructionVerifier Verifier;
902 GCPtrTracker::verifyFunction(std::move(Tracker), Verifier);
903
904 if (PrintOnly && !Verifier.hasAnyInvalidUses()) {
905 dbgs() << "No illegal uses found by SafepointIRVerifier in: " << F.getName()
906 << "\n";
907 }
908}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseSet and SmallDenseSet classes.
static bool runOnFunction(Function &F, bool PostInlining)
@ Available
We know the block is fully available. This is a fixpoint.
Definition GVN.cpp:947
Hexagon Common GEP
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
modulo schedule Modulo Schedule test pass
static bool processFunction(Function &F, NVPTXTargetMachine &TM)
ppc ctr loops PowerPC CTR Loops Verify
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< bool > PrintOnly("safepoint-ir-verifier-print-only", cl::init(false))
This option is used for writing test cases.
verify safepoint Safepoint IR static false bool isGCPointerType(Type *T)
static bool isNotExclusivelyConstantDerived(const Value *V)
static enum BaseType getBaseType(const Value *Val)
Return the baseType for Val which states whether Val is exclusively derived from constant/null,...
static bool containsGCPtrType(Type *Ty)
DenseSet< const Value * > AvailableValueSet
The verifier algorithm is phrased in terms of availability.
static void PrintValueSet(raw_ostream &OS, IteratorTy Begin, IteratorTy End)
verify safepoint Safepoint IR Verifier
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
@ ExclusivelySomeConstant
@ ExclusivelyNull
This file defines generic set operations that may be used on set's of different types,...
This file implements a set that has insertion order iteration characteristics.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM_ABI AnalysisUsage & addRequiredID(const void *ID)
Definition Pass.cpp:289
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
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:252
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:216
Implements a dense probed hash-table based set.
Definition DenseSet.h:289
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:270
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:306
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:151
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
iterator_range< arg_iterator > args()
Definition Function.h:892
op_range incoming_values()
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.
Use & getUse() const
getUse - Return the operand Use in the predecessor's terminator of the successor.
Definition CFG.h:88
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
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
A vector that has set insertion semantics.
Definition SetVector.h:57
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Class to represent struct types.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Value * get() const
Definition Use.h:55
const Use & getOperandUse(unsigned i) const
Definition User.h:220
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:212
size_type size() const
Definition DenseSet.h:87
bool erase(const ValueT &V)
Definition DenseSet.h:100
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:190
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
initializer< Ty > init(const Ty &Val)
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
void set_intersect(S1Ty &S1, const S2Ty &S2)
set_intersect(A, B) - Compute A := A ^ B Identical to set_intersection, except that it works on set<>...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
constexpr from_range_t from_range
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2207
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI void verifySafepointIR(Function &F)
Run the safepoint verifier over a single function. Crashes on failure.
PredIterator< const BasicBlock, Value::const_user_iterator > const_pred_iterator
Definition CFG.h:94
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:94
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:1745
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI FunctionPass * createSafepointIRVerifierPass()
Create an instance of the safepoint verifier pass which can be added to a pass pipeline to check for ...
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1398
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
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 raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.