xref: /freebsd-src/contrib/llvm-project/clang/lib/CodeGen/CGCleanup.h (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
1 //===-- CGCleanup.h - Classes for cleanups 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 support the generation of LLVM IR for cleanups.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_LIB_CODEGEN_CGCLEANUP_H
14 #define LLVM_CLANG_LIB_CODEGEN_CGCLEANUP_H
15 
16 #include "EHScopeStack.h"
17 
18 #include "Address.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 
22 namespace llvm {
23 class BasicBlock;
24 class Value;
25 class ConstantInt;
26 class AllocaInst;
27 }
28 
29 namespace clang {
30 class FunctionDecl;
31 namespace CodeGen {
32 class CodeGenModule;
33 class CodeGenFunction;
34 
35 /// The MS C++ ABI needs a pointer to RTTI data plus some flags to describe the
36 /// type of a catch handler, so we use this wrapper.
37 struct CatchTypeInfo {
38   llvm::Constant *RTTI;
39   unsigned Flags;
40 };
41 
42 /// A protected scope for zero-cost EH handling.
43 class EHScope {
44   llvm::BasicBlock *CachedLandingPad;
45   llvm::BasicBlock *CachedEHDispatchBlock;
46 
47   EHScopeStack::stable_iterator EnclosingEHScope;
48 
49   class CommonBitFields {
50     friend class EHScope;
51     unsigned Kind : 3;
52   };
53   enum { NumCommonBits = 3 };
54 
55 protected:
56   class CatchBitFields {
57     friend class EHCatchScope;
58     unsigned : NumCommonBits;
59 
60     unsigned NumHandlers : 32 - NumCommonBits;
61   };
62 
63   class CleanupBitFields {
64     friend class EHCleanupScope;
65     unsigned : NumCommonBits;
66 
67     /// Whether this cleanup needs to be run along normal edges.
68     unsigned IsNormalCleanup : 1;
69 
70     /// Whether this cleanup needs to be run along exception edges.
71     unsigned IsEHCleanup : 1;
72 
73     /// Whether this cleanup is currently active.
74     unsigned IsActive : 1;
75 
76     /// Whether this cleanup is a lifetime marker
77     unsigned IsLifetimeMarker : 1;
78 
79     /// Whether the normal cleanup should test the activation flag.
80     unsigned TestFlagInNormalCleanup : 1;
81 
82     /// Whether the EH cleanup should test the activation flag.
83     unsigned TestFlagInEHCleanup : 1;
84 
85     /// The amount of extra storage needed by the Cleanup.
86     /// Always a multiple of the scope-stack alignment.
87     unsigned CleanupSize : 12;
88   };
89 
90   class FilterBitFields {
91     friend class EHFilterScope;
92     unsigned : NumCommonBits;
93 
94     unsigned NumFilters : 32 - NumCommonBits;
95   };
96 
97   union {
98     CommonBitFields CommonBits;
99     CatchBitFields CatchBits;
100     CleanupBitFields CleanupBits;
101     FilterBitFields FilterBits;
102   };
103 
104 public:
105   enum Kind { Cleanup, Catch, Terminate, Filter };
106 
107   EHScope(Kind kind, EHScopeStack::stable_iterator enclosingEHScope)
108     : CachedLandingPad(nullptr), CachedEHDispatchBlock(nullptr),
109       EnclosingEHScope(enclosingEHScope) {
110     CommonBits.Kind = kind;
111   }
112 
113   Kind getKind() const { return static_cast<Kind>(CommonBits.Kind); }
114 
115   llvm::BasicBlock *getCachedLandingPad() const {
116     return CachedLandingPad;
117   }
118 
119   void setCachedLandingPad(llvm::BasicBlock *block) {
120     CachedLandingPad = block;
121   }
122 
123   llvm::BasicBlock *getCachedEHDispatchBlock() const {
124     return CachedEHDispatchBlock;
125   }
126 
127   void setCachedEHDispatchBlock(llvm::BasicBlock *block) {
128     CachedEHDispatchBlock = block;
129   }
130 
131   bool hasEHBranches() const {
132     if (llvm::BasicBlock *block = getCachedEHDispatchBlock())
133       return !block->use_empty();
134     return false;
135   }
136 
137   EHScopeStack::stable_iterator getEnclosingEHScope() const {
138     return EnclosingEHScope;
139   }
140 };
141 
142 /// A scope which attempts to handle some, possibly all, types of
143 /// exceptions.
144 ///
145 /// Objective C \@finally blocks are represented using a cleanup scope
146 /// after the catch scope.
147 class EHCatchScope : public EHScope {
148   // In effect, we have a flexible array member
149   //   Handler Handlers[0];
150   // But that's only standard in C99, not C++, so we have to do
151   // annoying pointer arithmetic instead.
152 
153 public:
154   struct Handler {
155     /// A type info value, or null (C++ null, not an LLVM null pointer)
156     /// for a catch-all.
157     CatchTypeInfo Type;
158 
159     /// The catch handler for this type.
160     llvm::BasicBlock *Block;
161 
162     bool isCatchAll() const { return Type.RTTI == nullptr; }
163   };
164 
165 private:
166   friend class EHScopeStack;
167 
168   Handler *getHandlers() {
169     return reinterpret_cast<Handler*>(this+1);
170   }
171 
172   const Handler *getHandlers() const {
173     return reinterpret_cast<const Handler*>(this+1);
174   }
175 
176 public:
177   static size_t getSizeForNumHandlers(unsigned N) {
178     return sizeof(EHCatchScope) + N * sizeof(Handler);
179   }
180 
181   EHCatchScope(unsigned numHandlers,
182                EHScopeStack::stable_iterator enclosingEHScope)
183     : EHScope(Catch, enclosingEHScope) {
184     CatchBits.NumHandlers = numHandlers;
185     assert(CatchBits.NumHandlers == numHandlers && "NumHandlers overflow?");
186   }
187 
188   unsigned getNumHandlers() const {
189     return CatchBits.NumHandlers;
190   }
191 
192   void setCatchAllHandler(unsigned I, llvm::BasicBlock *Block) {
193     setHandler(I, CatchTypeInfo{nullptr, 0}, Block);
194   }
195 
196   void setHandler(unsigned I, llvm::Constant *Type, llvm::BasicBlock *Block) {
197     assert(I < getNumHandlers());
198     getHandlers()[I].Type = CatchTypeInfo{Type, 0};
199     getHandlers()[I].Block = Block;
200   }
201 
202   void setHandler(unsigned I, CatchTypeInfo Type, llvm::BasicBlock *Block) {
203     assert(I < getNumHandlers());
204     getHandlers()[I].Type = Type;
205     getHandlers()[I].Block = Block;
206   }
207 
208   const Handler &getHandler(unsigned I) const {
209     assert(I < getNumHandlers());
210     return getHandlers()[I];
211   }
212 
213   // Clear all handler blocks.
214   // FIXME: it's better to always call clearHandlerBlocks in DTOR and have a
215   // 'takeHandler' or some such function which removes ownership from the
216   // EHCatchScope object if the handlers should live longer than EHCatchScope.
217   void clearHandlerBlocks() {
218     for (unsigned I = 0, N = getNumHandlers(); I != N; ++I)
219       delete getHandler(I).Block;
220   }
221 
222   typedef const Handler *iterator;
223   iterator begin() const { return getHandlers(); }
224   iterator end() const { return getHandlers() + getNumHandlers(); }
225 
226   static bool classof(const EHScope *Scope) {
227     return Scope->getKind() == Catch;
228   }
229 };
230 
231 /// A cleanup scope which generates the cleanup blocks lazily.
232 class alignas(8) EHCleanupScope : public EHScope {
233   /// The nearest normal cleanup scope enclosing this one.
234   EHScopeStack::stable_iterator EnclosingNormal;
235 
236   /// The nearest EH scope enclosing this one.
237   EHScopeStack::stable_iterator EnclosingEH;
238 
239   /// The dual entry/exit block along the normal edge.  This is lazily
240   /// created if needed before the cleanup is popped.
241   llvm::BasicBlock *NormalBlock;
242 
243   /// An optional i1 variable indicating whether this cleanup has been
244   /// activated yet.
245   Address ActiveFlag;
246 
247   /// Extra information required for cleanups that have resolved
248   /// branches through them.  This has to be allocated on the side
249   /// because everything on the cleanup stack has be trivially
250   /// movable.
251   struct ExtInfo {
252     /// The destinations of normal branch-afters and branch-throughs.
253     llvm::SmallPtrSet<llvm::BasicBlock*, 4> Branches;
254 
255     /// Normal branch-afters.
256     SmallVector<std::pair<llvm::BasicBlock*,llvm::ConstantInt*>, 4>
257       BranchAfters;
258   };
259   mutable struct ExtInfo *ExtInfo;
260 
261   /// The number of fixups required by enclosing scopes (not including
262   /// this one).  If this is the top cleanup scope, all the fixups
263   /// from this index onwards belong to this scope.
264   unsigned FixupDepth;
265 
266   struct ExtInfo &getExtInfo() {
267     if (!ExtInfo) ExtInfo = new struct ExtInfo();
268     return *ExtInfo;
269   }
270 
271   const struct ExtInfo &getExtInfo() const {
272     if (!ExtInfo) ExtInfo = new struct ExtInfo();
273     return *ExtInfo;
274   }
275 
276 public:
277   /// Gets the size required for a lazy cleanup scope with the given
278   /// cleanup-data requirements.
279   static size_t getSizeForCleanupSize(size_t Size) {
280     return sizeof(EHCleanupScope) + Size;
281   }
282 
283   size_t getAllocatedSize() const {
284     return sizeof(EHCleanupScope) + CleanupBits.CleanupSize;
285   }
286 
287   EHCleanupScope(bool isNormal, bool isEH, unsigned cleanupSize,
288                  unsigned fixupDepth,
289                  EHScopeStack::stable_iterator enclosingNormal,
290                  EHScopeStack::stable_iterator enclosingEH)
291       : EHScope(EHScope::Cleanup, enclosingEH),
292         EnclosingNormal(enclosingNormal), NormalBlock(nullptr),
293         ActiveFlag(Address::invalid()), ExtInfo(nullptr),
294         FixupDepth(fixupDepth) {
295     CleanupBits.IsNormalCleanup = isNormal;
296     CleanupBits.IsEHCleanup = isEH;
297     CleanupBits.IsActive = true;
298     CleanupBits.IsLifetimeMarker = false;
299     CleanupBits.TestFlagInNormalCleanup = false;
300     CleanupBits.TestFlagInEHCleanup = false;
301     CleanupBits.CleanupSize = cleanupSize;
302 
303     assert(CleanupBits.CleanupSize == cleanupSize && "cleanup size overflow");
304   }
305 
306   void Destroy() {
307     delete ExtInfo;
308   }
309   // Objects of EHCleanupScope are not destructed. Use Destroy().
310   ~EHCleanupScope() = delete;
311 
312   bool isNormalCleanup() const { return CleanupBits.IsNormalCleanup; }
313   llvm::BasicBlock *getNormalBlock() const { return NormalBlock; }
314   void setNormalBlock(llvm::BasicBlock *BB) { NormalBlock = BB; }
315 
316   bool isEHCleanup() const { return CleanupBits.IsEHCleanup; }
317 
318   bool isActive() const { return CleanupBits.IsActive; }
319   void setActive(bool A) { CleanupBits.IsActive = A; }
320 
321   bool isLifetimeMarker() const { return CleanupBits.IsLifetimeMarker; }
322   void setLifetimeMarker() { CleanupBits.IsLifetimeMarker = true; }
323 
324   bool hasActiveFlag() const { return ActiveFlag.isValid(); }
325   Address getActiveFlag() const {
326     return ActiveFlag;
327   }
328   void setActiveFlag(Address Var) {
329     assert(Var.getAlignment().isOne());
330     ActiveFlag = Var;
331   }
332 
333   void setTestFlagInNormalCleanup() {
334     CleanupBits.TestFlagInNormalCleanup = true;
335   }
336   bool shouldTestFlagInNormalCleanup() const {
337     return CleanupBits.TestFlagInNormalCleanup;
338   }
339 
340   void setTestFlagInEHCleanup() {
341     CleanupBits.TestFlagInEHCleanup = true;
342   }
343   bool shouldTestFlagInEHCleanup() const {
344     return CleanupBits.TestFlagInEHCleanup;
345   }
346 
347   unsigned getFixupDepth() const { return FixupDepth; }
348   EHScopeStack::stable_iterator getEnclosingNormalCleanup() const {
349     return EnclosingNormal;
350   }
351 
352   size_t getCleanupSize() const { return CleanupBits.CleanupSize; }
353   void *getCleanupBuffer() { return this + 1; }
354 
355   EHScopeStack::Cleanup *getCleanup() {
356     return reinterpret_cast<EHScopeStack::Cleanup*>(getCleanupBuffer());
357   }
358 
359   /// True if this cleanup scope has any branch-afters or branch-throughs.
360   bool hasBranches() const { return ExtInfo && !ExtInfo->Branches.empty(); }
361 
362   /// Add a branch-after to this cleanup scope.  A branch-after is a
363   /// branch from a point protected by this (normal) cleanup to a
364   /// point in the normal cleanup scope immediately containing it.
365   /// For example,
366   ///   for (;;) { A a; break; }
367   /// contains a branch-after.
368   ///
369   /// Branch-afters each have their own destination out of the
370   /// cleanup, guaranteed distinct from anything else threaded through
371   /// it.  Therefore branch-afters usually force a switch after the
372   /// cleanup.
373   void addBranchAfter(llvm::ConstantInt *Index,
374                       llvm::BasicBlock *Block) {
375     struct ExtInfo &ExtInfo = getExtInfo();
376     if (ExtInfo.Branches.insert(Block).second)
377       ExtInfo.BranchAfters.push_back(std::make_pair(Block, Index));
378   }
379 
380   /// Return the number of unique branch-afters on this scope.
381   unsigned getNumBranchAfters() const {
382     return ExtInfo ? ExtInfo->BranchAfters.size() : 0;
383   }
384 
385   llvm::BasicBlock *getBranchAfterBlock(unsigned I) const {
386     assert(I < getNumBranchAfters());
387     return ExtInfo->BranchAfters[I].first;
388   }
389 
390   llvm::ConstantInt *getBranchAfterIndex(unsigned I) const {
391     assert(I < getNumBranchAfters());
392     return ExtInfo->BranchAfters[I].second;
393   }
394 
395   /// Add a branch-through to this cleanup scope.  A branch-through is
396   /// a branch from a scope protected by this (normal) cleanup to an
397   /// enclosing scope other than the immediately-enclosing normal
398   /// cleanup scope.
399   ///
400   /// In the following example, the branch through B's scope is a
401   /// branch-through, while the branch through A's scope is a
402   /// branch-after:
403   ///   for (;;) { A a; B b; break; }
404   ///
405   /// All branch-throughs have a common destination out of the
406   /// cleanup, one possibly shared with the fall-through.  Therefore
407   /// branch-throughs usually don't force a switch after the cleanup.
408   ///
409   /// \return true if the branch-through was new to this scope
410   bool addBranchThrough(llvm::BasicBlock *Block) {
411     return getExtInfo().Branches.insert(Block).second;
412   }
413 
414   /// Determines if this cleanup scope has any branch throughs.
415   bool hasBranchThroughs() const {
416     if (!ExtInfo) return false;
417     return (ExtInfo->BranchAfters.size() != ExtInfo->Branches.size());
418   }
419 
420   static bool classof(const EHScope *Scope) {
421     return (Scope->getKind() == Cleanup);
422   }
423 };
424 // NOTE: there's a bunch of different data classes tacked on after an
425 // EHCleanupScope. It is asserted (in EHScopeStack::pushCleanup*) that
426 // they don't require greater alignment than ScopeStackAlignment. So,
427 // EHCleanupScope ought to have alignment equal to that -- not more
428 // (would be misaligned by the stack allocator), and not less (would
429 // break the appended classes).
430 static_assert(alignof(EHCleanupScope) == EHScopeStack::ScopeStackAlignment,
431               "EHCleanupScope expected alignment");
432 
433 /// An exceptions scope which filters exceptions thrown through it.
434 /// Only exceptions matching the filter types will be permitted to be
435 /// thrown.
436 ///
437 /// This is used to implement C++ exception specifications.
438 class EHFilterScope : public EHScope {
439   // Essentially ends in a flexible array member:
440   // llvm::Value *FilterTypes[0];
441 
442   llvm::Value **getFilters() {
443     return reinterpret_cast<llvm::Value**>(this+1);
444   }
445 
446   llvm::Value * const *getFilters() const {
447     return reinterpret_cast<llvm::Value* const *>(this+1);
448   }
449 
450 public:
451   EHFilterScope(unsigned numFilters)
452     : EHScope(Filter, EHScopeStack::stable_end()) {
453     FilterBits.NumFilters = numFilters;
454     assert(FilterBits.NumFilters == numFilters && "NumFilters overflow");
455   }
456 
457   static size_t getSizeForNumFilters(unsigned numFilters) {
458     return sizeof(EHFilterScope) + numFilters * sizeof(llvm::Value*);
459   }
460 
461   unsigned getNumFilters() const { return FilterBits.NumFilters; }
462 
463   void setFilter(unsigned i, llvm::Value *filterValue) {
464     assert(i < getNumFilters());
465     getFilters()[i] = filterValue;
466   }
467 
468   llvm::Value *getFilter(unsigned i) const {
469     assert(i < getNumFilters());
470     return getFilters()[i];
471   }
472 
473   static bool classof(const EHScope *scope) {
474     return scope->getKind() == Filter;
475   }
476 };
477 
478 /// An exceptions scope which calls std::terminate if any exception
479 /// reaches it.
480 class EHTerminateScope : public EHScope {
481 public:
482   EHTerminateScope(EHScopeStack::stable_iterator enclosingEHScope)
483     : EHScope(Terminate, enclosingEHScope) {}
484   static size_t getSize() { return sizeof(EHTerminateScope); }
485 
486   static bool classof(const EHScope *scope) {
487     return scope->getKind() == Terminate;
488   }
489 };
490 
491 /// A non-stable pointer into the scope stack.
492 class EHScopeStack::iterator {
493   char *Ptr;
494 
495   friend class EHScopeStack;
496   explicit iterator(char *Ptr) : Ptr(Ptr) {}
497 
498 public:
499   iterator() : Ptr(nullptr) {}
500 
501   EHScope *get() const {
502     return reinterpret_cast<EHScope*>(Ptr);
503   }
504 
505   EHScope *operator->() const { return get(); }
506   EHScope &operator*() const { return *get(); }
507 
508   iterator &operator++() {
509     size_t Size;
510     switch (get()->getKind()) {
511     case EHScope::Catch:
512       Size = EHCatchScope::getSizeForNumHandlers(
513           static_cast<const EHCatchScope *>(get())->getNumHandlers());
514       break;
515 
516     case EHScope::Filter:
517       Size = EHFilterScope::getSizeForNumFilters(
518           static_cast<const EHFilterScope *>(get())->getNumFilters());
519       break;
520 
521     case EHScope::Cleanup:
522       Size = static_cast<const EHCleanupScope *>(get())->getAllocatedSize();
523       break;
524 
525     case EHScope::Terminate:
526       Size = EHTerminateScope::getSize();
527       break;
528     }
529     Ptr += llvm::alignTo(Size, ScopeStackAlignment);
530     return *this;
531   }
532 
533   iterator next() {
534     iterator copy = *this;
535     ++copy;
536     return copy;
537   }
538 
539   iterator operator++(int) {
540     iterator copy = *this;
541     operator++();
542     return copy;
543   }
544 
545   bool encloses(iterator other) const { return Ptr >= other.Ptr; }
546   bool strictlyEncloses(iterator other) const { return Ptr > other.Ptr; }
547 
548   bool operator==(iterator other) const { return Ptr == other.Ptr; }
549   bool operator!=(iterator other) const { return Ptr != other.Ptr; }
550 };
551 
552 inline EHScopeStack::iterator EHScopeStack::begin() const {
553   return iterator(StartOfData);
554 }
555 
556 inline EHScopeStack::iterator EHScopeStack::end() const {
557   return iterator(EndOfBuffer);
558 }
559 
560 inline void EHScopeStack::popCatch() {
561   assert(!empty() && "popping exception stack when not empty");
562 
563   EHCatchScope &scope = cast<EHCatchScope>(*begin());
564   InnermostEHScope = scope.getEnclosingEHScope();
565   deallocate(EHCatchScope::getSizeForNumHandlers(scope.getNumHandlers()));
566 }
567 
568 inline void EHScopeStack::popTerminate() {
569   assert(!empty() && "popping exception stack when not empty");
570 
571   EHTerminateScope &scope = cast<EHTerminateScope>(*begin());
572   InnermostEHScope = scope.getEnclosingEHScope();
573   deallocate(EHTerminateScope::getSize());
574 }
575 
576 inline EHScopeStack::iterator EHScopeStack::find(stable_iterator sp) const {
577   assert(sp.isValid() && "finding invalid savepoint");
578   assert(sp.Size <= stable_begin().Size && "finding savepoint after pop");
579   return iterator(EndOfBuffer - sp.Size);
580 }
581 
582 inline EHScopeStack::stable_iterator
583 EHScopeStack::stabilize(iterator ir) const {
584   assert(StartOfData <= ir.Ptr && ir.Ptr <= EndOfBuffer);
585   return stable_iterator(EndOfBuffer - ir.Ptr);
586 }
587 
588 /// The exceptions personality for a function.
589 struct EHPersonality {
590   const char *PersonalityFn;
591 
592   // If this is non-null, this personality requires a non-standard
593   // function for rethrowing an exception after a catchall cleanup.
594   // This function must have prototype void(void*).
595   const char *CatchallRethrowFn;
596 
597   static const EHPersonality &get(CodeGenModule &CGM, const FunctionDecl *FD);
598   static const EHPersonality &get(CodeGenFunction &CGF);
599 
600   static const EHPersonality GNU_C;
601   static const EHPersonality GNU_C_SJLJ;
602   static const EHPersonality GNU_C_SEH;
603   static const EHPersonality GNU_ObjC;
604   static const EHPersonality GNU_ObjC_SJLJ;
605   static const EHPersonality GNU_ObjC_SEH;
606   static const EHPersonality GNUstep_ObjC;
607   static const EHPersonality GNU_ObjCXX;
608   static const EHPersonality NeXT_ObjC;
609   static const EHPersonality GNU_CPlusPlus;
610   static const EHPersonality GNU_CPlusPlus_SJLJ;
611   static const EHPersonality GNU_CPlusPlus_SEH;
612   static const EHPersonality MSVC_except_handler;
613   static const EHPersonality MSVC_C_specific_handler;
614   static const EHPersonality MSVC_CxxFrameHandler3;
615   static const EHPersonality GNU_Wasm_CPlusPlus;
616   static const EHPersonality XL_CPlusPlus;
617 
618   /// Does this personality use landingpads or the family of pad instructions
619   /// designed to form funclets?
620   bool usesFuncletPads() const {
621     return isMSVCPersonality() || isWasmPersonality();
622   }
623 
624   bool isMSVCPersonality() const {
625     return this == &MSVC_except_handler || this == &MSVC_C_specific_handler ||
626            this == &MSVC_CxxFrameHandler3;
627   }
628 
629   bool isWasmPersonality() const { return this == &GNU_Wasm_CPlusPlus; }
630 
631   bool isMSVCXXPersonality() const { return this == &MSVC_CxxFrameHandler3; }
632 };
633 }
634 }
635 
636 #endif
637