EHScopeStack.h 14 KB

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