xref: /freebsd/contrib/llvm-project/llvm/lib/IR/SafepointIRVerifier.cpp (revision 5956d97f4b3204318ceb6aa9c77bd0bc6ea87a41)
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 
33 #include "llvm/IR/SafepointIRVerifier.h"
34 #include "llvm/ADT/DenseSet.h"
35 #include "llvm/ADT/PostOrderIterator.h"
36 #include "llvm/ADT/SetOperations.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"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Statepoint.h"
44 #include "llvm/IR/Value.h"
45 #include "llvm/InitializePasses.h"
46 #include "llvm/Support/Allocator.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/raw_ostream.h"
50 
51 #define DEBUG_TYPE "safepoint-ir-verifier"
52 
53 using 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.
58 static cl::opt<bool> PrintOnly("safepoint-ir-verifier-print-only",
59                                cl::init(false));
60 
61 namespace {
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.
69 class CFGDeadness {
70   const DominatorTree *DT = nullptr;
71   SetVector<const BasicBlock *> DeadBlocks;
72   SetVector<const Use *> DeadEdges; // Contains all dead edges from live blocks.
73 
74 public:
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");
107     assert(cast_or_null<BasicBlock>(U->get()) &&
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 BranchInst *BI = dyn_cast<BranchInst>(TI);
142       if (!BI || !BI->isConditional() || !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 
157 protected:
158   void addDeadBlock(const BasicBlock *BB) {
159     SmallVector<const BasicBlock *, 4> NewDead;
160     SmallSetVector<const BasicBlock *, 4> DF;
161 
162     NewDead.push_back(BB);
163     while (!NewDead.empty()) {
164       const BasicBlock *D = NewDead.pop_back_val();
165       if (isDeadBlock(D))
166         continue;
167 
168       // All blocks dominated by D are dead.
169       SmallVector<BasicBlock *, 8> Dom;
170       DT->getDescendants(const_cast<BasicBlock*>(D), Dom);
171       // Do not need to mark all in and out edges dead
172       // because BB is marked dead and this is enough
173       // to run further.
174       DeadBlocks.insert(Dom.begin(), Dom.end());
175 
176       // Figure out the dominance-frontier(D).
177       for (BasicBlock *B : Dom)
178         for (BasicBlock *S : successors(B))
179           if (!isDeadBlock(S) && !hasLiveIncomingEdges(S))
180             NewDead.push_back(S);
181     }
182   }
183 
184   void addDeadEdge(const Use &DeadEdge) {
185     if (!DeadEdges.insert(&DeadEdge))
186       return;
187 
188     BasicBlock *BB = cast_or_null<BasicBlock>(DeadEdge.get());
189     if (hasLiveIncomingEdges(BB))
190       return;
191 
192     addDeadBlock(BB);
193   }
194 };
195 } // namespace
196 
197 static void Verify(const Function &F, const DominatorTree &DT,
198                    const CFGDeadness &CD);
199 
200 namespace llvm {
201 PreservedAnalyses SafepointIRVerifierPass::run(Function &F,
202                                                FunctionAnalysisManager &AM) {
203   const auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
204   CFGDeadness CD;
205   CD.processFunction(F, DT);
206   Verify(F, DT, CD);
207   return PreservedAnalyses::all();
208 }
209 } // namespace llvm
210 
211 namespace {
212 
213 struct SafepointIRVerifier : public FunctionPass {
214   static char ID; // Pass identification, replacement for typeid
215   SafepointIRVerifier() : FunctionPass(ID) {
216     initializeSafepointIRVerifierPass(*PassRegistry::getPassRegistry());
217   }
218 
219   bool runOnFunction(Function &F) override {
220     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
221     CFGDeadness CD;
222     CD.processFunction(F, DT);
223     Verify(F, DT, CD);
224     return false; // no modifications
225   }
226 
227   void getAnalysisUsage(AnalysisUsage &AU) const override {
228     AU.addRequiredID(DominatorTreeWrapperPass::ID);
229     AU.setPreservesAll();
230   }
231 
232   StringRef getPassName() const override { return "safepoint verifier"; }
233 };
234 } // namespace
235 
236 void llvm::verifySafepointIR(Function &F) {
237   SafepointIRVerifier pass;
238   pass.runOnFunction(F);
239 }
240 
241 char SafepointIRVerifier::ID = 0;
242 
243 FunctionPass *llvm::createSafepointIRVerifierPass() {
244   return new SafepointIRVerifier();
245 }
246 
247 INITIALIZE_PASS_BEGIN(SafepointIRVerifier, "verify-safepoint-ir",
248                       "Safepoint IR Verifier", false, false)
249 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
250 INITIALIZE_PASS_END(SafepointIRVerifier, "verify-safepoint-ir",
251                     "Safepoint IR Verifier", false, false)
252 
253 static bool isGCPointerType(Type *T) {
254   if (auto *PT = dyn_cast<PointerType>(T))
255     // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
256     // GC managed heap.  We know that a pointer into this heap needs to be
257     // updated and that no other pointer does.
258     return (1 == PT->getAddressSpace());
259   return false;
260 }
261 
262 static bool containsGCPtrType(Type *Ty) {
263   if (isGCPointerType(Ty))
264     return true;
265   if (VectorType *VT = dyn_cast<VectorType>(Ty))
266     return isGCPointerType(VT->getScalarType());
267   if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
268     return containsGCPtrType(AT->getElementType());
269   if (StructType *ST = dyn_cast<StructType>(Ty))
270     return llvm::any_of(ST->elements(), containsGCPtrType);
271   return false;
272 }
273 
274 // Debugging aid -- prints a [Begin, End) range of values.
275 template<typename IteratorTy>
276 static void PrintValueSet(raw_ostream &OS, IteratorTy Begin, IteratorTy End) {
277   OS << "[ ";
278   while (Begin != End) {
279     OS << **Begin << " ";
280     ++Begin;
281   }
282   OS << "]";
283 }
284 
285 /// The verifier algorithm is phrased in terms of availability.  The set of
286 /// values "available" at a given point in the control flow graph is the set of
287 /// correctly relocated value at that point, and is a subset of the set of
288 /// definitions dominating that point.
289 
290 using AvailableValueSet = DenseSet<const Value *>;
291 
292 /// State we compute and track per basic block.
293 struct BasicBlockState {
294   // Set of values available coming in, before the phi nodes
295   AvailableValueSet AvailableIn;
296 
297   // Set of values available going out
298   AvailableValueSet AvailableOut;
299 
300   // AvailableOut minus AvailableIn.
301   // All elements are Instructions
302   AvailableValueSet Contribution;
303 
304   // True if this block contains a safepoint and thus AvailableIn does not
305   // contribute to AvailableOut.
306   bool Cleared = false;
307 };
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.
314 enum BaseType {
315   NonConstant = 1, // Base pointers is not exclusively constant.
316   ExclusivelyNull,
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.
326 static enum BaseType getBaseType(const Value *Val) {
327 
328   SmallVector<const Value *, 32> Worklist;
329   DenseSet<const Value *> Visited;
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 (isa<Constant>(V)) {
361       // We found at least one base pointer which is non-null, so this derived
362       // pointer is not exclusively derived from null.
363       if (V != Constant::getNullValue(V->getType()))
364         isExclusivelyDerivedFromNull = false;
365       // Continue processing the remaining values to make sure it's exclusively
366       // constant.
367       continue;
368     }
369     // At this point, we know that the base pointer is not exclusively
370     // constant.
371     return BaseType::NonConstant;
372   }
373   // Now, we know that the base pointer is exclusively constant, but we need to
374   // differentiate between exclusive null constant and non-null constant.
375   return isExclusivelyDerivedFromNull ? BaseType::ExclusivelyNull
376                                       : BaseType::ExclusivelySomeConstant;
377 }
378 
379 static bool isNotExclusivelyConstantDerived(const Value *V) {
380   return getBaseType(V) == BaseType::NonConstant;
381 }
382 
383 namespace {
384 class InstructionVerifier;
385 
386 /// Builds BasicBlockState for each BB of the function.
387 /// It can traverse function for verification and provides all required
388 /// information.
389 ///
390 /// GC pointer may be in one of three states: relocated, unrelocated and
391 /// poisoned.
392 /// Relocated pointer may be used without any restrictions.
393 /// Unrelocated pointer cannot be dereferenced, passed as argument to any call
394 /// or returned. Unrelocated pointer may be safely compared against another
395 /// unrelocated pointer or against a pointer exclusively derived from null.
396 /// Poisoned pointers are produced when we somehow derive pointer from relocated
397 /// and unrelocated pointers (e.g. phi, select). This pointers may be safely
398 /// used in a very limited number of situations. Currently the only way to use
399 /// it is comparison against constant exclusively derived from null. All
400 /// limitations arise due to their undefined state: this pointers should be
401 /// treated as relocated and unrelocated simultaneously.
402 /// Rules of deriving:
403 /// R + U = P - that's where the poisoned pointers come from
404 /// P + X = P
405 /// U + U = U
406 /// R + R = R
407 /// X + C = X
408 /// Where "+" - any operation that somehow derive pointer, U - unrelocated,
409 /// R - relocated and P - poisoned, C - constant, X - U or R or P or C or
410 /// nothing (in case when "+" is unary operation).
411 /// Deriving of pointers by itself is always safe.
412 /// NOTE: when we are making decision on the status of instruction's result:
413 /// a) for phi we need to check status of each input *at the end of
414 ///    corresponding predecessor BB*.
415 /// b) for other instructions we need to check status of each input *at the
416 ///    current point*.
417 ///
418 /// FIXME: This works fairly well except one case
419 ///     bb1:
420 ///     p = *some GC-ptr def*
421 ///     p1 = gep p, offset
422 ///         /     |
423 ///        /      |
424 ///    bb2:       |
425 ///    safepoint  |
426 ///        \      |
427 ///         \     |
428 ///      bb3:
429 ///      p2 = phi [p, bb2] [p1, bb1]
430 ///      p3 = phi [p, bb2] [p, bb1]
431 ///      here p and p1 is unrelocated
432 ///           p2 and p3 is poisoned (though they shouldn't be)
433 ///
434 /// This leads to some weird results:
435 ///      cmp eq p, p2 - illegal instruction (false-positive)
436 ///      cmp eq p1, p2 - illegal instruction (false-positive)
437 ///      cmp eq p, p3 - illegal instruction (false-positive)
438 ///      cmp eq p, p1 - ok
439 /// To fix this we need to introduce conception of generations and be able to
440 /// check if two values belong to one generation or not. This way p2 will be
441 /// considered to be unrelocated and no false alarm will happen.
442 class GCPtrTracker {
443   const Function &F;
444   const CFGDeadness &CD;
445   SpecificBumpPtrAllocator<BasicBlockState> BSAllocator;
446   DenseMap<const BasicBlock *, BasicBlockState *> BlockMap;
447   // This set contains defs of unrelocated pointers that are proved to be legal
448   // and don't need verification.
449   DenseSet<const Instruction *> ValidUnrelocatedDefs;
450   // This set contains poisoned defs. They can be safely ignored during
451   // verification too.
452   DenseSet<const Value *> PoisonedDefs;
453 
454 public:
455   GCPtrTracker(const Function &F, const DominatorTree &DT,
456                const CFGDeadness &CD);
457 
458   bool hasLiveIncomingEdge(const PHINode *PN, const BasicBlock *InBB) const {
459     return CD.hasLiveIncomingEdge(PN, InBB);
460   }
461 
462   BasicBlockState *getBasicBlockState(const BasicBlock *BB);
463   const BasicBlockState *getBasicBlockState(const BasicBlock *BB) const;
464 
465   bool isValuePoisoned(const Value *V) const { return PoisonedDefs.count(V); }
466 
467   /// Traverse each BB of the function and call
468   /// InstructionVerifier::verifyInstruction for each possibly invalid
469   /// instruction.
470   /// It destructively modifies GCPtrTracker so it's passed via rvalue reference
471   /// in order to prohibit further usages of GCPtrTracker as it'll be in
472   /// inconsistent state.
473   static void verifyFunction(GCPtrTracker &&Tracker,
474                              InstructionVerifier &Verifier);
475 
476   /// Returns true for reachable and live blocks.
477   bool isMapped(const BasicBlock *BB) const {
478     return BlockMap.find(BB) != BlockMap.end();
479   }
480 
481 private:
482   /// Returns true if the instruction may be safely skipped during verification.
483   bool instructionMayBeSkipped(const Instruction *I) const;
484 
485   /// Iterates over all BBs from BlockMap and recalculates AvailableIn/Out for
486   /// each of them until it converges.
487   void recalculateBBsStates();
488 
489   /// Remove from Contribution all defs that legally produce unrelocated
490   /// pointers and saves them to ValidUnrelocatedDefs.
491   /// Though Contribution should belong to BBS it is passed separately with
492   /// different const-modifier in order to emphasize (and guarantee) that only
493   /// Contribution will be changed.
494   /// Returns true if Contribution was changed otherwise false.
495   bool removeValidUnrelocatedDefs(const BasicBlock *BB,
496                                   const BasicBlockState *BBS,
497                                   AvailableValueSet &Contribution);
498 
499   /// Gather all the definitions dominating the start of BB into Result. This is
500   /// simply the defs introduced by every dominating basic block and the
501   /// function arguments.
502   void gatherDominatingDefs(const BasicBlock *BB, AvailableValueSet &Result,
503                             const DominatorTree &DT);
504 
505   /// Compute the AvailableOut set for BB, based on the BasicBlockState BBS,
506   /// which is the BasicBlockState for BB.
507   /// ContributionChanged is set when the verifier runs for the first time
508   /// (in this case Contribution was changed from 'empty' to its initial state)
509   /// or when Contribution of this BB was changed since last computation.
510   static void transferBlock(const BasicBlock *BB, BasicBlockState &BBS,
511                             bool ContributionChanged);
512 
513   /// Model the effect of an instruction on the set of available values.
514   static void transferInstruction(const Instruction &I, bool &Cleared,
515                                   AvailableValueSet &Available);
516 };
517 
518 /// It is a visitor for GCPtrTracker::verifyFunction. It decides if the
519 /// instruction (which uses heap reference) is legal or not, given our safepoint
520 /// semantics.
521 class InstructionVerifier {
522   bool AnyInvalidUses = false;
523 
524 public:
525   void verifyInstruction(const GCPtrTracker *Tracker, const Instruction &I,
526                          const AvailableValueSet &AvailableSet);
527 
528   bool hasAnyInvalidUses() const { return AnyInvalidUses; }
529 
530 private:
531   void reportInvalidUse(const Value &V, const Instruction &I);
532 };
533 } // end anonymous namespace
534 
535 GCPtrTracker::GCPtrTracker(const Function &F, const DominatorTree &DT,
536                            const CFGDeadness &CD) : F(F), CD(CD) {
537   // Calculate Contribution of each live BB.
538   // Allocate BB states for live blocks.
539   for (const BasicBlock &BB : F)
540     if (!CD.isDeadBlock(&BB)) {
541       BasicBlockState *BBS = new (BSAllocator.Allocate()) BasicBlockState;
542       for (const auto &I : BB)
543         transferInstruction(I, BBS->Cleared, BBS->Contribution);
544       BlockMap[&BB] = BBS;
545     }
546 
547   // Initialize AvailableIn/Out sets of each BB using only information about
548   // dominating BBs.
549   for (auto &BBI : BlockMap) {
550     gatherDominatingDefs(BBI.first, BBI.second->AvailableIn, DT);
551     transferBlock(BBI.first, *BBI.second, true);
552   }
553 
554   // Simulate the flow of defs through the CFG and recalculate AvailableIn/Out
555   // sets of each BB until it converges. If any def is proved to be an
556   // unrelocated pointer, it will be removed from all BBSs.
557   recalculateBBsStates();
558 }
559 
560 BasicBlockState *GCPtrTracker::getBasicBlockState(const BasicBlock *BB) {
561   return BlockMap.lookup(BB);
562 }
563 
564 const BasicBlockState *GCPtrTracker::getBasicBlockState(
565     const BasicBlock *BB) const {
566   return const_cast<GCPtrTracker *>(this)->getBasicBlockState(BB);
567 }
568 
569 bool GCPtrTracker::instructionMayBeSkipped(const Instruction *I) const {
570   // Poisoned defs are skipped since they are always safe by itself by
571   // definition (for details see comment to this class).
572   return ValidUnrelocatedDefs.count(I) || PoisonedDefs.count(I);
573 }
574 
575 void GCPtrTracker::verifyFunction(GCPtrTracker &&Tracker,
576                                   InstructionVerifier &Verifier) {
577   // We need RPO here to a) report always the first error b) report errors in
578   // same order from run to run.
579   ReversePostOrderTraversal<const Function *> RPOT(&Tracker.F);
580   for (const BasicBlock *BB : RPOT) {
581     BasicBlockState *BBS = Tracker.getBasicBlockState(BB);
582     if (!BBS)
583       continue;
584 
585     // We destructively modify AvailableIn as we traverse the block instruction
586     // by instruction.
587     AvailableValueSet &AvailableSet = BBS->AvailableIn;
588     for (const Instruction &I : *BB) {
589       if (Tracker.instructionMayBeSkipped(&I))
590         continue; // This instruction shouldn't be added to AvailableSet.
591 
592       Verifier.verifyInstruction(&Tracker, I, AvailableSet);
593 
594       // Model the effect of current instruction on AvailableSet to keep the set
595       // relevant at each point of BB.
596       bool Cleared = false;
597       transferInstruction(I, Cleared, AvailableSet);
598       (void)Cleared;
599     }
600   }
601 }
602 
603 void GCPtrTracker::recalculateBBsStates() {
604   SetVector<const BasicBlock *> Worklist;
605   // TODO: This order is suboptimal, it's better to replace it with priority
606   // queue where priority is RPO number of BB.
607   for (auto &BBI : BlockMap)
608     Worklist.insert(BBI.first);
609 
610   // This loop iterates the AvailableIn/Out sets until it converges.
611   // The AvailableIn and AvailableOut sets decrease as we iterate.
612   while (!Worklist.empty()) {
613     const BasicBlock *BB = Worklist.pop_back_val();
614     BasicBlockState *BBS = getBasicBlockState(BB);
615     if (!BBS)
616       continue; // Ignore dead successors.
617 
618     size_t OldInCount = BBS->AvailableIn.size();
619     for (const_pred_iterator PredIt(BB), End(BB, true); PredIt != End; ++PredIt) {
620       const BasicBlock *PBB = *PredIt;
621       BasicBlockState *PBBS = getBasicBlockState(PBB);
622       if (PBBS && !CD.isDeadEdge(&CFGDeadness::getEdge(PredIt)))
623         set_intersect(BBS->AvailableIn, PBBS->AvailableOut);
624     }
625 
626     assert(OldInCount >= BBS->AvailableIn.size() && "invariant!");
627 
628     bool InputsChanged = OldInCount != BBS->AvailableIn.size();
629     bool ContributionChanged =
630         removeValidUnrelocatedDefs(BB, BBS, BBS->Contribution);
631     if (!InputsChanged && !ContributionChanged)
632       continue;
633 
634     size_t OldOutCount = BBS->AvailableOut.size();
635     transferBlock(BB, *BBS, ContributionChanged);
636     if (OldOutCount != BBS->AvailableOut.size()) {
637       assert(OldOutCount > BBS->AvailableOut.size() && "invariant!");
638       Worklist.insert(succ_begin(BB), succ_end(BB));
639     }
640   }
641 }
642 
643 bool GCPtrTracker::removeValidUnrelocatedDefs(const BasicBlock *BB,
644                                               const BasicBlockState *BBS,
645                                               AvailableValueSet &Contribution) {
646   assert(&BBS->Contribution == &Contribution &&
647          "Passed Contribution should be from the passed BasicBlockState!");
648   AvailableValueSet AvailableSet = BBS->AvailableIn;
649   bool ContributionChanged = false;
650   // For explanation why instructions are processed this way see
651   // "Rules of deriving" in the comment to this class.
652   for (const Instruction &I : *BB) {
653     bool ValidUnrelocatedPointerDef = false;
654     bool PoisonedPointerDef = false;
655     // TODO: `select` instructions should be handled here too.
656     if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
657       if (containsGCPtrType(PN->getType())) {
658         // If both is true, output is poisoned.
659         bool HasRelocatedInputs = false;
660         bool HasUnrelocatedInputs = false;
661         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
662           const BasicBlock *InBB = PN->getIncomingBlock(i);
663           if (!isMapped(InBB) ||
664               !CD.hasLiveIncomingEdge(PN, InBB))
665             continue; // Skip dead block or dead edge.
666 
667           const Value *InValue = PN->getIncomingValue(i);
668 
669           if (isNotExclusivelyConstantDerived(InValue)) {
670             if (isValuePoisoned(InValue)) {
671               // If any of inputs is poisoned, output is always poisoned too.
672               HasRelocatedInputs = true;
673               HasUnrelocatedInputs = true;
674               break;
675             }
676             if (BlockMap[InBB]->AvailableOut.count(InValue))
677               HasRelocatedInputs = true;
678             else
679               HasUnrelocatedInputs = true;
680           }
681         }
682         if (HasUnrelocatedInputs) {
683           if (HasRelocatedInputs)
684             PoisonedPointerDef = true;
685           else
686             ValidUnrelocatedPointerDef = true;
687         }
688       }
689     } else if ((isa<GetElementPtrInst>(I) || isa<BitCastInst>(I)) &&
690                containsGCPtrType(I.getType())) {
691       // GEP/bitcast of unrelocated pointer is legal by itself but this def
692       // shouldn't appear in any AvailableSet.
693       for (const Value *V : I.operands())
694         if (containsGCPtrType(V->getType()) &&
695             isNotExclusivelyConstantDerived(V) && !AvailableSet.count(V)) {
696           if (isValuePoisoned(V))
697             PoisonedPointerDef = true;
698           else
699             ValidUnrelocatedPointerDef = true;
700           break;
701         }
702     }
703     assert(!(ValidUnrelocatedPointerDef && PoisonedPointerDef) &&
704            "Value cannot be both unrelocated and poisoned!");
705     if (ValidUnrelocatedPointerDef) {
706       // Remove def of unrelocated pointer from Contribution of this BB and
707       // trigger update of all its successors.
708       Contribution.erase(&I);
709       PoisonedDefs.erase(&I);
710       ValidUnrelocatedDefs.insert(&I);
711       LLVM_DEBUG(dbgs() << "Removing urelocated " << I
712                         << " from Contribution of " << BB->getName() << "\n");
713       ContributionChanged = true;
714     } else if (PoisonedPointerDef) {
715       // Mark pointer as poisoned, remove its def from Contribution and trigger
716       // update of all successors.
717       Contribution.erase(&I);
718       PoisonedDefs.insert(&I);
719       LLVM_DEBUG(dbgs() << "Removing poisoned " << I << " from Contribution of "
720                         << BB->getName() << "\n");
721       ContributionChanged = true;
722     } else {
723       bool Cleared = false;
724       transferInstruction(I, Cleared, AvailableSet);
725       (void)Cleared;
726     }
727   }
728   return ContributionChanged;
729 }
730 
731 void GCPtrTracker::gatherDominatingDefs(const BasicBlock *BB,
732                                         AvailableValueSet &Result,
733                                         const DominatorTree &DT) {
734   DomTreeNode *DTN = DT[const_cast<BasicBlock *>(BB)];
735 
736   assert(DTN && "Unreachable blocks are ignored");
737   while (DTN->getIDom()) {
738     DTN = DTN->getIDom();
739     auto BBS = getBasicBlockState(DTN->getBlock());
740     assert(BBS && "immediate dominator cannot be dead for a live block");
741     const auto &Defs = BBS->Contribution;
742     Result.insert(Defs.begin(), Defs.end());
743     // If this block is 'Cleared', then nothing LiveIn to this block can be
744     // available after this block completes.  Note: This turns out to be
745     // really important for reducing memory consuption of the initial available
746     // sets and thus peak memory usage by this verifier.
747     if (BBS->Cleared)
748       return;
749   }
750 
751   for (const Argument &A : BB->getParent()->args())
752     if (containsGCPtrType(A.getType()))
753       Result.insert(&A);
754 }
755 
756 void GCPtrTracker::transferBlock(const BasicBlock *BB, BasicBlockState &BBS,
757                                  bool ContributionChanged) {
758   const AvailableValueSet &AvailableIn = BBS.AvailableIn;
759   AvailableValueSet &AvailableOut = BBS.AvailableOut;
760 
761   if (BBS.Cleared) {
762     // AvailableOut will change only when Contribution changed.
763     if (ContributionChanged)
764       AvailableOut = BBS.Contribution;
765   } else {
766     // Otherwise, we need to reduce the AvailableOut set by things which are no
767     // longer in our AvailableIn
768     AvailableValueSet Temp = BBS.Contribution;
769     set_union(Temp, AvailableIn);
770     AvailableOut = std::move(Temp);
771   }
772 
773   LLVM_DEBUG(dbgs() << "Transfered block " << BB->getName() << " from ";
774              PrintValueSet(dbgs(), AvailableIn.begin(), AvailableIn.end());
775              dbgs() << " to ";
776              PrintValueSet(dbgs(), AvailableOut.begin(), AvailableOut.end());
777              dbgs() << "\n";);
778 }
779 
780 void GCPtrTracker::transferInstruction(const Instruction &I, bool &Cleared,
781                                        AvailableValueSet &Available) {
782   if (isa<GCStatepointInst>(I)) {
783     Cleared = true;
784     Available.clear();
785   } else if (containsGCPtrType(I.getType()))
786     Available.insert(&I);
787 }
788 
789 void InstructionVerifier::verifyInstruction(
790     const GCPtrTracker *Tracker, const Instruction &I,
791     const AvailableValueSet &AvailableSet) {
792   if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
793     if (containsGCPtrType(PN->getType()))
794       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
795         const BasicBlock *InBB = PN->getIncomingBlock(i);
796         const BasicBlockState *InBBS = Tracker->getBasicBlockState(InBB);
797         if (!InBBS ||
798             !Tracker->hasLiveIncomingEdge(PN, InBB))
799           continue; // Skip dead block or dead edge.
800 
801         const Value *InValue = PN->getIncomingValue(i);
802 
803         if (isNotExclusivelyConstantDerived(InValue) &&
804             !InBBS->AvailableOut.count(InValue))
805           reportInvalidUse(*InValue, *PN);
806       }
807   } else if (isa<CmpInst>(I) &&
808              containsGCPtrType(I.getOperand(0)->getType())) {
809     Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
810     enum BaseType baseTyLHS = getBaseType(LHS),
811                   baseTyRHS = getBaseType(RHS);
812 
813     // Returns true if LHS and RHS are unrelocated pointers and they are
814     // valid unrelocated uses.
815     auto hasValidUnrelocatedUse = [&AvailableSet, Tracker, baseTyLHS, baseTyRHS,
816                                    &LHS, &RHS] () {
817         // A cmp instruction has valid unrelocated pointer operands only if
818         // both operands are unrelocated pointers.
819         // In the comparison between two pointers, if one is an unrelocated
820         // use, the other *should be* an unrelocated use, for this
821         // instruction to contain valid unrelocated uses. This unrelocated
822         // use can be a null constant as well, or another unrelocated
823         // pointer.
824         if (AvailableSet.count(LHS) || AvailableSet.count(RHS))
825           return false;
826         // Constant pointers (that are not exclusively null) may have
827         // meaning in different VMs, so we cannot reorder the compare
828         // against constant pointers before the safepoint. In other words,
829         // comparison of an unrelocated use against a non-null constant
830         // maybe invalid.
831         if ((baseTyLHS == BaseType::ExclusivelySomeConstant &&
832              baseTyRHS == BaseType::NonConstant) ||
833             (baseTyLHS == BaseType::NonConstant &&
834              baseTyRHS == BaseType::ExclusivelySomeConstant))
835           return false;
836 
837         // If one of pointers is poisoned and other is not exclusively derived
838         // from null it is an invalid expression: it produces poisoned result
839         // and unless we want to track all defs (not only gc pointers) the only
840         // option is to prohibit such instructions.
841         if ((Tracker->isValuePoisoned(LHS) && baseTyRHS != ExclusivelyNull) ||
842             (Tracker->isValuePoisoned(RHS) && baseTyLHS != ExclusivelyNull))
843             return false;
844 
845         // All other cases are valid cases enumerated below:
846         // 1. Comparison between an exclusively derived null pointer and a
847         // constant base pointer.
848         // 2. Comparison between an exclusively derived null pointer and a
849         // non-constant unrelocated base pointer.
850         // 3. Comparison between 2 unrelocated pointers.
851         // 4. Comparison between a pointer exclusively derived from null and a
852         // non-constant poisoned pointer.
853         return true;
854     };
855     if (!hasValidUnrelocatedUse()) {
856       // Print out all non-constant derived pointers that are unrelocated
857       // uses, which are invalid.
858       if (baseTyLHS == BaseType::NonConstant && !AvailableSet.count(LHS))
859         reportInvalidUse(*LHS, I);
860       if (baseTyRHS == BaseType::NonConstant && !AvailableSet.count(RHS))
861         reportInvalidUse(*RHS, I);
862     }
863   } else {
864     for (const Value *V : I.operands())
865       if (containsGCPtrType(V->getType()) &&
866           isNotExclusivelyConstantDerived(V) && !AvailableSet.count(V))
867         reportInvalidUse(*V, I);
868   }
869 }
870 
871 void InstructionVerifier::reportInvalidUse(const Value &V,
872                                            const Instruction &I) {
873   errs() << "Illegal use of unrelocated value found!\n";
874   errs() << "Def: " << V << "\n";
875   errs() << "Use: " << I << "\n";
876   if (!PrintOnly)
877     abort();
878   AnyInvalidUses = true;
879 }
880 
881 static void Verify(const Function &F, const DominatorTree &DT,
882                    const CFGDeadness &CD) {
883   LLVM_DEBUG(dbgs() << "Verifying gc pointers in function: " << F.getName()
884                     << "\n");
885   if (PrintOnly)
886     dbgs() << "Verifying gc pointers in function: " << F.getName() << "\n";
887 
888   GCPtrTracker Tracker(F, DT, CD);
889 
890   // We now have all the information we need to decide if the use of a heap
891   // reference is legal or not, given our safepoint semantics.
892 
893   InstructionVerifier Verifier;
894   GCPtrTracker::verifyFunction(std::move(Tracker), Verifier);
895 
896   if (PrintOnly && !Verifier.hasAnyInvalidUses()) {
897     dbgs() << "No illegal uses found by SafepointIRVerifier in: " << F.getName()
898            << "\n";
899   }
900 }
901