1 //===-- CGCleanup.h - Classes for cleanups IR generation --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // These classes support the generation of LLVM IR for cleanups.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LIB_CODEGEN_CGCLEANUP_H
15 #define LLVM_CLANG_LIB_CODEGEN_CGCLEANUP_H
17 #include "EHScopeStack.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
31 /// A protected scope for zero-cost EH handling.
33 llvm::BasicBlock *CachedLandingPad;
34 llvm::BasicBlock *CachedEHDispatchBlock;
36 EHScopeStack::stable_iterator EnclosingEHScope;
38 class CommonBitFields {
42 enum { NumCommonBits = 2 };
45 class CatchBitFields {
46 friend class EHCatchScope;
47 unsigned : NumCommonBits;
49 unsigned NumHandlers : 32 - NumCommonBits;
52 class CleanupBitFields {
53 friend class EHCleanupScope;
54 unsigned : NumCommonBits;
56 /// Whether this cleanup needs to be run along normal edges.
57 unsigned IsNormalCleanup : 1;
59 /// Whether this cleanup needs to be run along exception edges.
60 unsigned IsEHCleanup : 1;
62 /// Whether this cleanup is currently active.
63 unsigned IsActive : 1;
65 /// Whether this cleanup is a lifetime marker
66 unsigned IsLifetimeMarker : 1;
68 /// Whether the normal cleanup should test the activation flag.
69 unsigned TestFlagInNormalCleanup : 1;
71 /// Whether the EH cleanup should test the activation flag.
72 unsigned TestFlagInEHCleanup : 1;
74 /// The amount of extra storage needed by the Cleanup.
75 /// Always a multiple of the scope-stack alignment.
76 unsigned CleanupSize : 12;
78 /// The number of fixups required by enclosing scopes (not including
79 /// this one). If this is the top cleanup scope, all the fixups
80 /// from this index onwards belong to this scope.
81 unsigned FixupDepth : 32 - 18 - NumCommonBits; // currently 13
84 class FilterBitFields {
85 friend class EHFilterScope;
86 unsigned : NumCommonBits;
88 unsigned NumFilters : 32 - NumCommonBits;
92 CommonBitFields CommonBits;
93 CatchBitFields CatchBits;
94 CleanupBitFields CleanupBits;
95 FilterBitFields FilterBits;
99 enum Kind { Cleanup, Catch, Terminate, Filter };
101 EHScope(Kind kind, EHScopeStack::stable_iterator enclosingEHScope)
102 : CachedLandingPad(nullptr), CachedEHDispatchBlock(nullptr),
103 EnclosingEHScope(enclosingEHScope) {
104 CommonBits.Kind = kind;
107 Kind getKind() const { return static_cast<Kind>(CommonBits.Kind); }
109 llvm::BasicBlock *getCachedLandingPad() const {
110 return CachedLandingPad;
113 void setCachedLandingPad(llvm::BasicBlock *block) {
114 CachedLandingPad = block;
117 llvm::BasicBlock *getCachedEHDispatchBlock() const {
118 return CachedEHDispatchBlock;
121 void setCachedEHDispatchBlock(llvm::BasicBlock *block) {
122 CachedEHDispatchBlock = block;
125 bool hasEHBranches() const {
126 if (llvm::BasicBlock *block = getCachedEHDispatchBlock())
127 return !block->use_empty();
131 EHScopeStack::stable_iterator getEnclosingEHScope() const {
132 return EnclosingEHScope;
136 /// A scope which attempts to handle some, possibly all, types of
139 /// Objective C \@finally blocks are represented using a cleanup scope
140 /// after the catch scope.
141 class EHCatchScope : public EHScope {
142 // In effect, we have a flexible array member
143 // Handler Handlers[0];
144 // But that's only standard in C99, not C++, so we have to do
145 // annoying pointer arithmetic instead.
149 /// A type info value, or null (C++ null, not an LLVM null pointer)
151 llvm::Constant *Type;
153 /// The catch handler for this type.
154 llvm::BasicBlock *Block;
156 bool isCatchAll() const { return Type == nullptr; }
160 friend class EHScopeStack;
162 Handler *getHandlers() {
163 return reinterpret_cast<Handler*>(this+1);
166 const Handler *getHandlers() const {
167 return reinterpret_cast<const Handler*>(this+1);
171 static size_t getSizeForNumHandlers(unsigned N) {
172 return sizeof(EHCatchScope) + N * sizeof(Handler);
175 EHCatchScope(unsigned numHandlers,
176 EHScopeStack::stable_iterator enclosingEHScope)
177 : EHScope(Catch, enclosingEHScope) {
178 CatchBits.NumHandlers = numHandlers;
181 unsigned getNumHandlers() const {
182 return CatchBits.NumHandlers;
185 void setCatchAllHandler(unsigned I, llvm::BasicBlock *Block) {
186 setHandler(I, /*catchall*/ nullptr, Block);
189 void setHandler(unsigned I, llvm::Constant *Type, llvm::BasicBlock *Block) {
190 assert(I < getNumHandlers());
191 getHandlers()[I].Type = Type;
192 getHandlers()[I].Block = Block;
195 const Handler &getHandler(unsigned I) const {
196 assert(I < getNumHandlers());
197 return getHandlers()[I];
200 // Clear all handler blocks.
201 // FIXME: it's better to always call clearHandlerBlocks in DTOR and have a
202 // 'takeHandler' or some such function which removes ownership from the
203 // EHCatchScope object if the handlers should live longer than EHCatchScope.
204 void clearHandlerBlocks() {
205 for (unsigned I = 0, N = getNumHandlers(); I != N; ++I)
206 delete getHandler(I).Block;
209 typedef const Handler *iterator;
210 iterator begin() const { return getHandlers(); }
211 iterator end() const { return getHandlers() + getNumHandlers(); }
213 static bool classof(const EHScope *Scope) {
214 return Scope->getKind() == Catch;
218 /// A cleanup scope which generates the cleanup blocks lazily.
219 class EHCleanupScope : public EHScope {
220 /// The nearest normal cleanup scope enclosing this one.
221 EHScopeStack::stable_iterator EnclosingNormal;
223 /// The nearest EH scope enclosing this one.
224 EHScopeStack::stable_iterator EnclosingEH;
226 /// The dual entry/exit block along the normal edge. This is lazily
227 /// created if needed before the cleanup is popped.
228 llvm::BasicBlock *NormalBlock;
230 /// An optional i1 variable indicating whether this cleanup has been
232 llvm::AllocaInst *ActiveFlag;
234 /// Extra information required for cleanups that have resolved
235 /// branches through them. This has to be allocated on the side
236 /// because everything on the cleanup stack has be trivially
239 /// The destinations of normal branch-afters and branch-throughs.
240 llvm::SmallPtrSet<llvm::BasicBlock*, 4> Branches;
242 /// Normal branch-afters.
243 SmallVector<std::pair<llvm::BasicBlock*,llvm::ConstantInt*>, 4>
246 mutable struct ExtInfo *ExtInfo;
248 struct ExtInfo &getExtInfo() {
249 if (!ExtInfo) ExtInfo = new struct ExtInfo();
253 const struct ExtInfo &getExtInfo() const {
254 if (!ExtInfo) ExtInfo = new struct ExtInfo();
259 /// Gets the size required for a lazy cleanup scope with the given
260 /// cleanup-data requirements.
261 static size_t getSizeForCleanupSize(size_t Size) {
262 return sizeof(EHCleanupScope) + Size;
265 size_t getAllocatedSize() const {
266 return sizeof(EHCleanupScope) + CleanupBits.CleanupSize;
269 EHCleanupScope(bool isNormal, bool isEH, bool isActive,
270 unsigned cleanupSize, unsigned fixupDepth,
271 EHScopeStack::stable_iterator enclosingNormal,
272 EHScopeStack::stable_iterator enclosingEH)
273 : EHScope(EHScope::Cleanup, enclosingEH), EnclosingNormal(enclosingNormal),
274 NormalBlock(nullptr), ActiveFlag(nullptr), ExtInfo(nullptr) {
275 CleanupBits.IsNormalCleanup = isNormal;
276 CleanupBits.IsEHCleanup = isEH;
277 CleanupBits.IsActive = isActive;
278 CleanupBits.IsLifetimeMarker = false;
279 CleanupBits.TestFlagInNormalCleanup = false;
280 CleanupBits.TestFlagInEHCleanup = false;
281 CleanupBits.CleanupSize = cleanupSize;
282 CleanupBits.FixupDepth = fixupDepth;
284 assert(CleanupBits.CleanupSize == cleanupSize && "cleanup size overflow");
290 // Objects of EHCleanupScope are not destructed. Use Destroy().
291 ~EHCleanupScope() = delete;
293 bool isNormalCleanup() const { return CleanupBits.IsNormalCleanup; }
294 llvm::BasicBlock *getNormalBlock() const { return NormalBlock; }
295 void setNormalBlock(llvm::BasicBlock *BB) { NormalBlock = BB; }
297 bool isEHCleanup() const { return CleanupBits.IsEHCleanup; }
299 bool isActive() const { return CleanupBits.IsActive; }
300 void setActive(bool A) { CleanupBits.IsActive = A; }
302 bool isLifetimeMarker() const { return CleanupBits.IsLifetimeMarker; }
303 void setLifetimeMarker() { CleanupBits.IsLifetimeMarker = true; }
305 llvm::AllocaInst *getActiveFlag() const { return ActiveFlag; }
306 void setActiveFlag(llvm::AllocaInst *Var) { ActiveFlag = Var; }
308 void setTestFlagInNormalCleanup() {
309 CleanupBits.TestFlagInNormalCleanup = true;
311 bool shouldTestFlagInNormalCleanup() const {
312 return CleanupBits.TestFlagInNormalCleanup;
315 void setTestFlagInEHCleanup() {
316 CleanupBits.TestFlagInEHCleanup = true;
318 bool shouldTestFlagInEHCleanup() const {
319 return CleanupBits.TestFlagInEHCleanup;
322 unsigned getFixupDepth() const { return CleanupBits.FixupDepth; }
323 EHScopeStack::stable_iterator getEnclosingNormalCleanup() const {
324 return EnclosingNormal;
327 size_t getCleanupSize() const { return CleanupBits.CleanupSize; }
328 void *getCleanupBuffer() { return this + 1; }
330 EHScopeStack::Cleanup *getCleanup() {
331 return reinterpret_cast<EHScopeStack::Cleanup*>(getCleanupBuffer());
334 /// True if this cleanup scope has any branch-afters or branch-throughs.
335 bool hasBranches() const { return ExtInfo && !ExtInfo->Branches.empty(); }
337 /// Add a branch-after to this cleanup scope. A branch-after is a
338 /// branch from a point protected by this (normal) cleanup to a
339 /// point in the normal cleanup scope immediately containing it.
341 /// for (;;) { A a; break; }
342 /// contains a branch-after.
344 /// Branch-afters each have their own destination out of the
345 /// cleanup, guaranteed distinct from anything else threaded through
346 /// it. Therefore branch-afters usually force a switch after the
348 void addBranchAfter(llvm::ConstantInt *Index,
349 llvm::BasicBlock *Block) {
350 struct ExtInfo &ExtInfo = getExtInfo();
351 if (ExtInfo.Branches.insert(Block).second)
352 ExtInfo.BranchAfters.push_back(std::make_pair(Block, Index));
355 /// Return the number of unique branch-afters on this scope.
356 unsigned getNumBranchAfters() const {
357 return ExtInfo ? ExtInfo->BranchAfters.size() : 0;
360 llvm::BasicBlock *getBranchAfterBlock(unsigned I) const {
361 assert(I < getNumBranchAfters());
362 return ExtInfo->BranchAfters[I].first;
365 llvm::ConstantInt *getBranchAfterIndex(unsigned I) const {
366 assert(I < getNumBranchAfters());
367 return ExtInfo->BranchAfters[I].second;
370 /// Add a branch-through to this cleanup scope. A branch-through is
371 /// a branch from a scope protected by this (normal) cleanup to an
372 /// enclosing scope other than the immediately-enclosing normal
375 /// In the following example, the branch through B's scope is a
376 /// branch-through, while the branch through A's scope is a
378 /// for (;;) { A a; B b; break; }
380 /// All branch-throughs have a common destination out of the
381 /// cleanup, one possibly shared with the fall-through. Therefore
382 /// branch-throughs usually don't force a switch after the cleanup.
384 /// \return true if the branch-through was new to this scope
385 bool addBranchThrough(llvm::BasicBlock *Block) {
386 return getExtInfo().Branches.insert(Block).second;
389 /// Determines if this cleanup scope has any branch throughs.
390 bool hasBranchThroughs() const {
391 if (!ExtInfo) return false;
392 return (ExtInfo->BranchAfters.size() != ExtInfo->Branches.size());
395 static bool classof(const EHScope *Scope) {
396 return (Scope->getKind() == Cleanup);
400 /// An exceptions scope which filters exceptions thrown through it.
401 /// Only exceptions matching the filter types will be permitted to be
404 /// This is used to implement C++ exception specifications.
405 class EHFilterScope : public EHScope {
406 // Essentially ends in a flexible array member:
407 // llvm::Value *FilterTypes[0];
409 llvm::Value **getFilters() {
410 return reinterpret_cast<llvm::Value**>(this+1);
413 llvm::Value * const *getFilters() const {
414 return reinterpret_cast<llvm::Value* const *>(this+1);
418 EHFilterScope(unsigned numFilters)
419 : EHScope(Filter, EHScopeStack::stable_end()) {
420 FilterBits.NumFilters = numFilters;
423 static size_t getSizeForNumFilters(unsigned numFilters) {
424 return sizeof(EHFilterScope) + numFilters * sizeof(llvm::Value*);
427 unsigned getNumFilters() const { return FilterBits.NumFilters; }
429 void setFilter(unsigned i, llvm::Value *filterValue) {
430 assert(i < getNumFilters());
431 getFilters()[i] = filterValue;
434 llvm::Value *getFilter(unsigned i) const {
435 assert(i < getNumFilters());
436 return getFilters()[i];
439 static bool classof(const EHScope *scope) {
440 return scope->getKind() == Filter;
444 /// An exceptions scope which calls std::terminate if any exception
446 class EHTerminateScope : public EHScope {
448 EHTerminateScope(EHScopeStack::stable_iterator enclosingEHScope)
449 : EHScope(Terminate, enclosingEHScope) {}
450 static size_t getSize() { return sizeof(EHTerminateScope); }
452 static bool classof(const EHScope *scope) {
453 return scope->getKind() == Terminate;
457 /// A non-stable pointer into the scope stack.
458 class EHScopeStack::iterator {
461 friend class EHScopeStack;
462 explicit iterator(char *Ptr) : Ptr(Ptr) {}
465 iterator() : Ptr(nullptr) {}
467 EHScope *get() const {
468 return reinterpret_cast<EHScope*>(Ptr);
471 EHScope *operator->() const { return get(); }
472 EHScope &operator*() const { return *get(); }
474 iterator &operator++() {
475 switch (get()->getKind()) {
477 Ptr += EHCatchScope::getSizeForNumHandlers(
478 static_cast<const EHCatchScope*>(get())->getNumHandlers());
481 case EHScope::Filter:
482 Ptr += EHFilterScope::getSizeForNumFilters(
483 static_cast<const EHFilterScope*>(get())->getNumFilters());
486 case EHScope::Cleanup:
487 Ptr += static_cast<const EHCleanupScope*>(get())
488 ->getAllocatedSize();
491 case EHScope::Terminate:
492 Ptr += EHTerminateScope::getSize();
500 iterator copy = *this;
505 iterator operator++(int) {
506 iterator copy = *this;
511 bool encloses(iterator other) const { return Ptr >= other.Ptr; }
512 bool strictlyEncloses(iterator other) const { return Ptr > other.Ptr; }
514 bool operator==(iterator other) const { return Ptr == other.Ptr; }
515 bool operator!=(iterator other) const { return Ptr != other.Ptr; }
518 inline EHScopeStack::iterator EHScopeStack::begin() const {
519 return iterator(StartOfData);
522 inline EHScopeStack::iterator EHScopeStack::end() const {
523 return iterator(EndOfBuffer);
526 inline void EHScopeStack::popCatch() {
527 assert(!empty() && "popping exception stack when not empty");
529 EHCatchScope &scope = cast<EHCatchScope>(*begin());
530 InnermostEHScope = scope.getEnclosingEHScope();
531 StartOfData += EHCatchScope::getSizeForNumHandlers(scope.getNumHandlers());
534 inline void EHScopeStack::popTerminate() {
535 assert(!empty() && "popping exception stack when not empty");
537 EHTerminateScope &scope = cast<EHTerminateScope>(*begin());
538 InnermostEHScope = scope.getEnclosingEHScope();
539 StartOfData += EHTerminateScope::getSize();
542 inline EHScopeStack::iterator EHScopeStack::find(stable_iterator sp) const {
543 assert(sp.isValid() && "finding invalid savepoint");
544 assert(sp.Size <= stable_begin().Size && "finding savepoint after pop");
545 return iterator(EndOfBuffer - sp.Size);
548 inline EHScopeStack::stable_iterator
549 EHScopeStack::stabilize(iterator ir) const {
550 assert(StartOfData <= ir.Ptr && ir.Ptr <= EndOfBuffer);
551 return stable_iterator(EndOfBuffer - ir.Ptr);