Home | History | Annotate | Line # | Download | only in CodeGen
      1 //===-- EHScopeStack.h - Stack for cleanup IR generation --------*- C++ -*-===//
      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 // These classes should be the minimum interface required for other parts of
     10 // CodeGen to emit cleanups.  The implementation is in CGCleanup.cpp and other
     11 // implemenentation details that are not widely needed are in CGCleanup.h.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #ifndef LLVM_CLANG_LIB_CODEGEN_EHSCOPESTACK_H
     16 #define LLVM_CLANG_LIB_CODEGEN_EHSCOPESTACK_H
     17 
     18 #include "clang/Basic/LLVM.h"
     19 #include "llvm/ADT/STLExtras.h"
     20 #include "llvm/ADT/SmallVector.h"
     21 #include "llvm/IR/BasicBlock.h"
     22 #include "llvm/IR/Instructions.h"
     23 #include "llvm/IR/Value.h"
     24 
     25 namespace clang {
     26 namespace CodeGen {
     27 
     28 class CodeGenFunction;
     29 
     30 /// A branch fixup.  These are required when emitting a goto to a
     31 /// label which hasn't been emitted yet.  The goto is optimistically
     32 /// emitted as a branch to the basic block for the label, and (if it
     33 /// occurs in a scope with non-trivial cleanups) a fixup is added to
     34 /// the innermost cleanup.  When a (normal) cleanup is popped, any
     35 /// unresolved fixups in that scope are threaded through the cleanup.
     36 struct BranchFixup {
     37   /// The block containing the terminator which needs to be modified
     38   /// into a switch if this fixup is resolved into the current scope.
     39   /// If null, LatestBranch points directly to the destination.
     40   llvm::BasicBlock *OptimisticBranchBlock;
     41 
     42   /// The ultimate destination of the branch.
     43   ///
     44   /// This can be set to null to indicate that this fixup was
     45   /// successfully resolved.
     46   llvm::BasicBlock *Destination;
     47 
     48   /// The destination index value.
     49   unsigned DestinationIndex;
     50 
     51   /// The initial branch of the fixup.
     52   llvm::BranchInst *InitialBranch;
     53 };
     54 
     55 template <class T> struct InvariantValue {
     56   typedef T type;
     57   typedef T saved_type;
     58   static bool needsSaving(type value) { return false; }
     59   static saved_type save(CodeGenFunction &CGF, type value) { return value; }
     60   static type restore(CodeGenFunction &CGF, saved_type value) { return value; }
     61 };
     62 
     63 /// A metaprogramming class for ensuring that a value will dominate an
     64 /// arbitrary position in a function.
     65 template <class T> struct DominatingValue : InvariantValue<T> {};
     66 
     67 template <class T, bool mightBeInstruction =
     68             std::is_base_of<llvm::Value, T>::value &&
     69             !std::is_base_of<llvm::Constant, T>::value &&
     70             !std::is_base_of<llvm::BasicBlock, T>::value>
     71 struct DominatingPointer;
     72 template <class T> struct DominatingPointer<T,false> : InvariantValue<T*> {};
     73 // template <class T> struct DominatingPointer<T,true> at end of file
     74 
     75 template <class T> struct DominatingValue<T*> : DominatingPointer<T> {};
     76 
     77 enum CleanupKind : unsigned {
     78   /// Denotes a cleanup that should run when a scope is exited using exceptional
     79   /// control flow (a throw statement leading to stack unwinding, ).
     80   EHCleanup = 0x1,
     81 
     82   /// Denotes a cleanup that should run when a scope is exited using normal
     83   /// control flow (falling off the end of the scope, return, goto, ...).
     84   NormalCleanup = 0x2,
     85 
     86   NormalAndEHCleanup = EHCleanup | NormalCleanup,
     87 
     88   LifetimeMarker = 0x8,
     89   NormalEHLifetimeMarker = LifetimeMarker | NormalAndEHCleanup,
     90 };
     91 
     92 /// A stack of scopes which respond to exceptions, including cleanups
     93 /// and catch blocks.
     94 class EHScopeStack {
     95 public:
     96   /* Should switch to alignof(uint64_t) instead of 8, when EHCleanupScope can */
     97   enum { ScopeStackAlignment = 8 };
     98 
     99   /// A saved depth on the scope stack.  This is necessary because
    100   /// pushing scopes onto the stack invalidates iterators.
    101   class stable_iterator {
    102     friend class EHScopeStack;
    103 
    104     /// Offset from StartOfData to EndOfBuffer.
    105     ptrdiff_t Size;
    106 
    107     stable_iterator(ptrdiff_t Size) : Size(Size) {}
    108 
    109   public:
    110     static stable_iterator invalid() { return stable_iterator(-1); }
    111     stable_iterator() : Size(-1) {}
    112 
    113     bool isValid() const { return Size >= 0; }
    114 
    115     /// Returns true if this scope encloses I.
    116     /// Returns false if I is invalid.
    117     /// This scope must be valid.
    118     bool encloses(stable_iterator I) const { return Size <= I.Size; }
    119 
    120     /// Returns true if this scope strictly encloses I: that is,
    121     /// if it encloses I and is not I.
    122     /// Returns false is I is invalid.
    123     /// This scope must be valid.
    124     bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; }
    125 
    126     friend bool operator==(stable_iterator A, stable_iterator B) {
    127       return A.Size == B.Size;
    128     }
    129     friend bool operator!=(stable_iterator A, stable_iterator B) {
    130       return A.Size != B.Size;
    131     }
    132   };
    133 
    134   /// Information for lazily generating a cleanup.  Subclasses must be
    135   /// POD-like: cleanups will not be destructed, and they will be
    136   /// allocated on the cleanup stack and freely copied and moved
    137   /// around.
    138   ///
    139   /// Cleanup implementations should generally be declared in an
    140   /// anonymous namespace.
    141   class Cleanup {
    142     // Anchor the construction vtable.
    143     virtual void anchor();
    144 
    145   protected:
    146     ~Cleanup() = default;
    147 
    148   public:
    149     Cleanup(const Cleanup &) = default;
    150     Cleanup(Cleanup &&) {}
    151     Cleanup() = default;
    152 
    153     virtual bool isRedundantBeforeReturn() { return false; }
    154 
    155     /// Generation flags.
    156     class Flags {
    157       enum {
    158         F_IsForEH = 0x1,
    159         F_IsNormalCleanupKind = 0x2,
    160         F_IsEHCleanupKind = 0x4,
    161         F_HasExitSwitch = 0x8,
    162       };
    163       unsigned flags;
    164 
    165     public:
    166       Flags() : flags(0) {}
    167 
    168       /// isForEH - true if the current emission is for an EH cleanup.
    169       bool isForEHCleanup() const { return flags & F_IsForEH; }
    170       bool isForNormalCleanup() const { return !isForEHCleanup(); }
    171       void setIsForEHCleanup() { flags |= F_IsForEH; }
    172 
    173       bool isNormalCleanupKind() const { return flags & F_IsNormalCleanupKind; }
    174       void setIsNormalCleanupKind() { flags |= F_IsNormalCleanupKind; }
    175 
    176       /// isEHCleanupKind - true if the cleanup was pushed as an EH
    177       /// cleanup.
    178       bool isEHCleanupKind() const { return flags & F_IsEHCleanupKind; }
    179       void setIsEHCleanupKind() { flags |= F_IsEHCleanupKind; }
    180 
    181       bool hasExitSwitch() const { return flags & F_HasExitSwitch; }
    182       void setHasExitSwitch() { flags |= F_HasExitSwitch; }
    183     };
    184 
    185     /// Emit the cleanup.  For normal cleanups, this is run in the
    186     /// same EH context as when the cleanup was pushed, i.e. the
    187     /// immediately-enclosing context of the cleanup scope.  For
    188     /// EH cleanups, this is run in a terminate context.
    189     ///
    190     // \param flags cleanup kind.
    191     virtual void Emit(CodeGenFunction &CGF, Flags flags) = 0;
    192   };
    193 
    194   /// ConditionalCleanup stores the saved form of its parameters,
    195   /// then restores them and performs the cleanup.
    196   template <class T, class... As>
    197   class ConditionalCleanup final : public Cleanup {
    198     typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
    199     SavedTuple Saved;
    200 
    201     template <std::size_t... Is>
    202     T restore(CodeGenFunction &CGF, std::index_sequence<Is...>) {
    203       // It's important that the restores are emitted in order. The braced init
    204       // list guarantees that.
    205       return T{DominatingValue<As>::restore(CGF, std::get<Is>(Saved))...};
    206     }
    207 
    208     void Emit(CodeGenFunction &CGF, Flags flags) override {
    209       restore(CGF, std::index_sequence_for<As...>()).Emit(CGF, flags);
    210     }
    211 
    212   public:
    213     ConditionalCleanup(typename DominatingValue<As>::saved_type... A)
    214         : Saved(A...) {}
    215 
    216     ConditionalCleanup(SavedTuple Tuple) : Saved(std::move(Tuple)) {}
    217   };
    218 
    219 private:
    220   // The implementation for this class is in CGException.h and
    221   // CGException.cpp; the definition is here because it's used as a
    222   // member of CodeGenFunction.
    223 
    224   /// The start of the scope-stack buffer, i.e. the allocated pointer
    225   /// for the buffer.  All of these pointers are either simultaneously
    226   /// null or simultaneously valid.
    227   char *StartOfBuffer;
    228 
    229   /// The end of the buffer.
    230   char *EndOfBuffer;
    231 
    232   /// The first valid entry in the buffer.
    233   char *StartOfData;
    234 
    235   /// The innermost normal cleanup on the stack.
    236   stable_iterator InnermostNormalCleanup;
    237 
    238   /// The innermost EH scope on the stack.
    239   stable_iterator InnermostEHScope;
    240 
    241   /// The CGF this Stack belong to
    242   CodeGenFunction* CGF;
    243 
    244   /// The current set of branch fixups.  A branch fixup is a jump to
    245   /// an as-yet unemitted label, i.e. a label for which we don't yet
    246   /// know the EH stack depth.  Whenever we pop a cleanup, we have
    247   /// to thread all the current branch fixups through it.
    248   ///
    249   /// Fixups are recorded as the Use of the respective branch or
    250   /// switch statement.  The use points to the final destination.
    251   /// When popping out of a cleanup, these uses are threaded through
    252   /// the cleanup and adjusted to point to the new cleanup.
    253   ///
    254   /// Note that branches are allowed to jump into protected scopes
    255   /// in certain situations;  e.g. the following code is legal:
    256   ///     struct A { ~A(); }; // trivial ctor, non-trivial dtor
    257   ///     goto foo;
    258   ///     A a;
    259   ///    foo:
    260   ///     bar();
    261   SmallVector<BranchFixup, 8> BranchFixups;
    262 
    263   char *allocate(size_t Size);
    264   void deallocate(size_t Size);
    265 
    266   void *pushCleanup(CleanupKind K, size_t DataSize);
    267 
    268 public:
    269   EHScopeStack()
    270     : StartOfBuffer(nullptr), EndOfBuffer(nullptr), StartOfData(nullptr),
    271       InnermostNormalCleanup(stable_end()), InnermostEHScope(stable_end()),
    272       CGF(nullptr) {}
    273   ~EHScopeStack() { delete[] StartOfBuffer; }
    274 
    275   /// Push a lazily-created cleanup on the stack.
    276   template <class T, class... As> void pushCleanup(CleanupKind Kind, As... A) {
    277     static_assert(alignof(T) <= ScopeStackAlignment,
    278                   "Cleanup's alignment is too large.");
    279     void *Buffer = pushCleanup(Kind, sizeof(T));
    280     Cleanup *Obj = new (Buffer) T(A...);
    281     (void) Obj;
    282   }
    283 
    284   /// Push a lazily-created cleanup on the stack. Tuple version.
    285   template <class T, class... As>
    286   void pushCleanupTuple(CleanupKind Kind, std::tuple<As...> A) {
    287     static_assert(alignof(T) <= ScopeStackAlignment,
    288                   "Cleanup's alignment is too large.");
    289     void *Buffer = pushCleanup(Kind, sizeof(T));
    290     Cleanup *Obj = new (Buffer) T(std::move(A));
    291     (void) Obj;
    292   }
    293 
    294   // Feel free to add more variants of the following:
    295 
    296   /// Push a cleanup with non-constant storage requirements on the
    297   /// stack.  The cleanup type must provide an additional static method:
    298   ///   static size_t getExtraSize(size_t);
    299   /// The argument to this method will be the value N, which will also
    300   /// be passed as the first argument to the constructor.
    301   ///
    302   /// The data stored in the extra storage must obey the same
    303   /// restrictions as normal cleanup member data.
    304   ///
    305   /// The pointer returned from this method is valid until the cleanup
    306   /// stack is modified.
    307   template <class T, class... As>
    308   T *pushCleanupWithExtra(CleanupKind Kind, size_t N, As... A) {
    309     static_assert(alignof(T) <= ScopeStackAlignment,
    310                   "Cleanup's alignment is too large.");
    311     void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N));
    312     return new (Buffer) T(N, A...);
    313   }
    314 
    315   void pushCopyOfCleanup(CleanupKind Kind, const void *Cleanup, size_t Size) {
    316     void *Buffer = pushCleanup(Kind, Size);
    317     std::memcpy(Buffer, Cleanup, Size);
    318   }
    319 
    320   void setCGF(CodeGenFunction *inCGF) { CGF = inCGF; }
    321 
    322   /// Pops a cleanup scope off the stack.  This is private to CGCleanup.cpp.
    323   void popCleanup();
    324 
    325   /// Push a set of catch handlers on the stack.  The catch is
    326   /// uninitialized and will need to have the given number of handlers
    327   /// set on it.
    328   class EHCatchScope *pushCatch(unsigned NumHandlers);
    329 
    330   /// Pops a catch scope off the stack.  This is private to CGException.cpp.
    331   void popCatch();
    332 
    333   /// Push an exceptions filter on the stack.
    334   class EHFilterScope *pushFilter(unsigned NumFilters);
    335 
    336   /// Pops an exceptions filter off the stack.
    337   void popFilter();
    338 
    339   /// Push a terminate handler on the stack.
    340   void pushTerminate();
    341 
    342   /// Pops a terminate handler off the stack.
    343   void popTerminate();
    344 
    345   // Returns true iff the current scope is either empty or contains only
    346   // lifetime markers, i.e. no real cleanup code
    347   bool containsOnlyLifetimeMarkers(stable_iterator Old) const;
    348 
    349   /// Determines whether the exception-scopes stack is empty.
    350   bool empty() const { return StartOfData == EndOfBuffer; }
    351 
    352   bool requiresLandingPad() const;
    353 
    354   /// Determines whether there are any normal cleanups on the stack.
    355   bool hasNormalCleanups() const {
    356     return InnermostNormalCleanup != stable_end();
    357   }
    358 
    359   /// Returns the innermost normal cleanup on the stack, or
    360   /// stable_end() if there are no normal cleanups.
    361   stable_iterator getInnermostNormalCleanup() const {
    362     return InnermostNormalCleanup;
    363   }
    364   stable_iterator getInnermostActiveNormalCleanup() const;
    365 
    366   stable_iterator getInnermostEHScope() const {
    367     return InnermostEHScope;
    368   }
    369 
    370 
    371   /// An unstable reference to a scope-stack depth.  Invalidated by
    372   /// pushes but not pops.
    373   class iterator;
    374 
    375   /// Returns an iterator pointing to the innermost EH scope.
    376   iterator begin() const;
    377 
    378   /// Returns an iterator pointing to the outermost EH scope.
    379   iterator end() const;
    380 
    381   /// Create a stable reference to the top of the EH stack.  The
    382   /// returned reference is valid until that scope is popped off the
    383   /// stack.
    384   stable_iterator stable_begin() const {
    385     return stable_iterator(EndOfBuffer - StartOfData);
    386   }
    387 
    388   /// Create a stable reference to the bottom of the EH stack.
    389   static stable_iterator stable_end() {
    390     return stable_iterator(0);
    391   }
    392 
    393   /// Translates an iterator into a stable_iterator.
    394   stable_iterator stabilize(iterator it) const;
    395 
    396   /// Turn a stable reference to a scope depth into a unstable pointer
    397   /// to the EH stack.
    398   iterator find(stable_iterator save) const;
    399 
    400   /// Add a branch fixup to the current cleanup scope.
    401   BranchFixup &addBranchFixup() {
    402     assert(hasNormalCleanups() && "adding fixup in scope without cleanups");
    403     BranchFixups.push_back(BranchFixup());
    404     return BranchFixups.back();
    405   }
    406 
    407   unsigned getNumBranchFixups() const { return BranchFixups.size(); }
    408   BranchFixup &getBranchFixup(unsigned I) {
    409     assert(I < getNumBranchFixups());
    410     return BranchFixups[I];
    411   }
    412 
    413   /// Pops lazily-removed fixups from the end of the list.  This
    414   /// should only be called by procedures which have just popped a
    415   /// cleanup or resolved one or more fixups.
    416   void popNullFixups();
    417 
    418   /// Clears the branch-fixups list.  This should only be called by
    419   /// ResolveAllBranchFixups.
    420   void clearFixups() { BranchFixups.clear(); }
    421 };
    422 
    423 } // namespace CodeGen
    424 } // namespace clang
    425 
    426 #endif
    427