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 16 #ifndef LLVM_CLANG_LIB_CODEGEN_EHSCOPESTACK_H 17 #define LLVM_CLANG_LIB_CODEGEN_EHSCOPESTACK_H 18 19 #include "clang/Basic/LLVM.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 EHCleanup = 0x1, 79 NormalCleanup = 0x2, 80 NormalAndEHCleanup = EHCleanup | NormalCleanup, 81 82 InactiveCleanup = 0x4, 83 InactiveEHCleanup = EHCleanup | InactiveCleanup, 84 InactiveNormalCleanup = NormalCleanup | InactiveCleanup, 85 InactiveNormalAndEHCleanup = NormalAndEHCleanup | InactiveCleanup 86 }; 87 88 /// A stack of scopes which respond to exceptions, including cleanups 89 /// and catch blocks. 90 class EHScopeStack { 91 public: 92 /// A saved depth on the scope stack. This is necessary because 93 /// pushing scopes onto the stack invalidates iterators. 94 class stable_iterator { 95 friend class EHScopeStack; 96 97 /// Offset from StartOfData to EndOfBuffer. 98 ptrdiff_t Size; 99 100 stable_iterator(ptrdiff_t Size) : Size(Size) {} 101 102 public: 103 static stable_iterator invalid() { return stable_iterator(-1); } 104 stable_iterator() : Size(-1) {} 105 106 bool isValid() const { return Size >= 0; } 107 108 /// Returns true if this scope encloses I. 109 /// Returns false if I is invalid. 110 /// This scope must be valid. 111 bool encloses(stable_iterator I) const { return Size <= I.Size; } 112 113 /// Returns true if this scope strictly encloses I: that is, 114 /// if it encloses I and is not I. 115 /// Returns false is I is invalid. 116 /// This scope must be valid. 117 bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; } 118 119 friend bool operator==(stable_iterator A, stable_iterator B) { 120 return A.Size == B.Size; 121 } 122 friend bool operator!=(stable_iterator A, stable_iterator B) { 123 return A.Size != B.Size; 124 } 125 }; 126 127 /// Information for lazily generating a cleanup. Subclasses must be 128 /// POD-like: cleanups will not be destructed, and they will be 129 /// allocated on the cleanup stack and freely copied and moved 130 /// around. 131 /// 132 /// Cleanup implementations should generally be declared in an 133 /// anonymous namespace. 134 class Cleanup { 135 // Anchor the construction vtable. 136 virtual void anchor(); 137 public: 138 /// Generation flags. 139 class Flags { 140 enum { 141 F_IsForEH = 0x1, 142 F_IsNormalCleanupKind = 0x2, 143 F_IsEHCleanupKind = 0x4 144 }; 145 unsigned flags; 146 147 public: 148 Flags() : flags(0) {} 149 150 /// isForEH - true if the current emission is for an EH cleanup. 151 bool isForEHCleanup() const { return flags & F_IsForEH; } 152 bool isForNormalCleanup() const { return !isForEHCleanup(); } 153 void setIsForEHCleanup() { flags |= F_IsForEH; } 154 155 bool isNormalCleanupKind() const { return flags & F_IsNormalCleanupKind; } 156 void setIsNormalCleanupKind() { flags |= F_IsNormalCleanupKind; } 157 158 /// isEHCleanupKind - true if the cleanup was pushed as an EH 159 /// cleanup. 160 bool isEHCleanupKind() const { return flags & F_IsEHCleanupKind; } 161 void setIsEHCleanupKind() { flags |= F_IsEHCleanupKind; } 162 }; 163 164 // Provide a virtual destructor to suppress a very common warning 165 // that unfortunately cannot be suppressed without this. Cleanups 166 // should not rely on this destructor ever being called. 167 virtual ~Cleanup() {} 168 169 /// Emit the cleanup. For normal cleanups, this is run in the 170 /// same EH context as when the cleanup was pushed, i.e. the 171 /// immediately-enclosing context of the cleanup scope. For 172 /// EH cleanups, this is run in a terminate context. 173 /// 174 // \param flags cleanup kind. 175 virtual void Emit(CodeGenFunction &CGF, Flags flags) = 0; 176 }; 177 178 /// ConditionalCleanupN stores the saved form of its N parameters, 179 /// then restores them and performs the cleanup. 180 template <class T, class A0> 181 class ConditionalCleanup1 : public Cleanup { 182 typedef typename DominatingValue<A0>::saved_type A0_saved; 183 A0_saved a0_saved; 184 185 void Emit(CodeGenFunction &CGF, Flags flags) override { 186 A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved); 187 T(a0).Emit(CGF, flags); 188 } 189 190 public: 191 ConditionalCleanup1(A0_saved a0) 192 : a0_saved(a0) {} 193 }; 194 195 template <class T, class A0, class A1> 196 class ConditionalCleanup2 : public Cleanup { 197 typedef typename DominatingValue<A0>::saved_type A0_saved; 198 typedef typename DominatingValue<A1>::saved_type A1_saved; 199 A0_saved a0_saved; 200 A1_saved a1_saved; 201 202 void Emit(CodeGenFunction &CGF, Flags flags) override { 203 A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved); 204 A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved); 205 T(a0, a1).Emit(CGF, flags); 206 } 207 208 public: 209 ConditionalCleanup2(A0_saved a0, A1_saved a1) 210 : a0_saved(a0), a1_saved(a1) {} 211 }; 212 213 template <class T, class A0, class A1, class A2> 214 class ConditionalCleanup3 : public Cleanup { 215 typedef typename DominatingValue<A0>::saved_type A0_saved; 216 typedef typename DominatingValue<A1>::saved_type A1_saved; 217 typedef typename DominatingValue<A2>::saved_type A2_saved; 218 A0_saved a0_saved; 219 A1_saved a1_saved; 220 A2_saved a2_saved; 221 222 void Emit(CodeGenFunction &CGF, Flags flags) override { 223 A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved); 224 A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved); 225 A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved); 226 T(a0, a1, a2).Emit(CGF, flags); 227 } 228 229 public: 230 ConditionalCleanup3(A0_saved a0, A1_saved a1, A2_saved a2) 231 : a0_saved(a0), a1_saved(a1), a2_saved(a2) {} 232 }; 233 234 template <class T, class A0, class A1, class A2, class A3> 235 class ConditionalCleanup4 : public Cleanup { 236 typedef typename DominatingValue<A0>::saved_type A0_saved; 237 typedef typename DominatingValue<A1>::saved_type A1_saved; 238 typedef typename DominatingValue<A2>::saved_type A2_saved; 239 typedef typename DominatingValue<A3>::saved_type A3_saved; 240 A0_saved a0_saved; 241 A1_saved a1_saved; 242 A2_saved a2_saved; 243 A3_saved a3_saved; 244 245 void Emit(CodeGenFunction &CGF, Flags flags) override { 246 A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved); 247 A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved); 248 A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved); 249 A3 a3 = DominatingValue<A3>::restore(CGF, a3_saved); 250 T(a0, a1, a2, a3).Emit(CGF, flags); 251 } 252 253 public: 254 ConditionalCleanup4(A0_saved a0, A1_saved a1, A2_saved a2, A3_saved a3) 255 : a0_saved(a0), a1_saved(a1), a2_saved(a2), a3_saved(a3) {} 256 }; 257 258 private: 259 // The implementation for this class is in CGException.h and 260 // CGException.cpp; the definition is here because it's used as a 261 // member of CodeGenFunction. 262 263 /// The start of the scope-stack buffer, i.e. the allocated pointer 264 /// for the buffer. All of these pointers are either simultaneously 265 /// null or simultaneously valid. 266 char *StartOfBuffer; 267 268 /// The end of the buffer. 269 char *EndOfBuffer; 270 271 /// The first valid entry in the buffer. 272 char *StartOfData; 273 274 /// The innermost normal cleanup on the stack. 275 stable_iterator InnermostNormalCleanup; 276 277 /// The innermost EH scope on the stack. 278 stable_iterator InnermostEHScope; 279 280 /// The current set of branch fixups. A branch fixup is a jump to 281 /// an as-yet unemitted label, i.e. a label for which we don't yet 282 /// know the EH stack depth. Whenever we pop a cleanup, we have 283 /// to thread all the current branch fixups through it. 284 /// 285 /// Fixups are recorded as the Use of the respective branch or 286 /// switch statement. The use points to the final destination. 287 /// When popping out of a cleanup, these uses are threaded through 288 /// the cleanup and adjusted to point to the new cleanup. 289 /// 290 /// Note that branches are allowed to jump into protected scopes 291 /// in certain situations; e.g. the following code is legal: 292 /// struct A { ~A(); }; // trivial ctor, non-trivial dtor 293 /// goto foo; 294 /// A a; 295 /// foo: 296 /// bar(); 297 SmallVector<BranchFixup, 8> BranchFixups; 298 299 char *allocate(size_t Size); 300 301 void *pushCleanup(CleanupKind K, size_t DataSize); 302 303 public: 304 EHScopeStack() : StartOfBuffer(nullptr), EndOfBuffer(nullptr), 305 StartOfData(nullptr), InnermostNormalCleanup(stable_end()), 306 InnermostEHScope(stable_end()) {} 307 ~EHScopeStack() { delete[] StartOfBuffer; } 308 309 // Variadic templates would make this not terrible. 310 311 /// Push a lazily-created cleanup on the stack. 312 template <class T, class... As> void pushCleanup(CleanupKind Kind, As... A) { 313 void *Buffer = pushCleanup(Kind, sizeof(T)); 314 Cleanup *Obj = new (Buffer) T(A...); 315 (void) Obj; 316 } 317 318 // Feel free to add more variants of the following: 319 320 /// Push a cleanup with non-constant storage requirements on the 321 /// stack. The cleanup type must provide an additional static method: 322 /// static size_t getExtraSize(size_t); 323 /// The argument to this method will be the value N, which will also 324 /// be passed as the first argument to the constructor. 325 /// 326 /// The data stored in the extra storage must obey the same 327 /// restrictions as normal cleanup member data. 328 /// 329 /// The pointer returned from this method is valid until the cleanup 330 /// stack is modified. 331 template <class T, class... As> 332 T *pushCleanupWithExtra(CleanupKind Kind, size_t N, As... A) { 333 void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N)); 334 return new (Buffer) T(N, A...); 335 } 336 337 void pushCopyOfCleanup(CleanupKind Kind, const void *Cleanup, size_t Size) { 338 void *Buffer = pushCleanup(Kind, Size); 339 std::memcpy(Buffer, Cleanup, Size); 340 } 341 342 /// Pops a cleanup scope off the stack. This is private to CGCleanup.cpp. 343 void popCleanup(); 344 345 /// Push a set of catch handlers on the stack. The catch is 346 /// uninitialized and will need to have the given number of handlers 347 /// set on it. 348 class EHCatchScope *pushCatch(unsigned NumHandlers); 349 350 /// Pops a catch scope off the stack. This is private to CGException.cpp. 351 void popCatch(); 352 353 /// Push an exceptions filter on the stack. 354 class EHFilterScope *pushFilter(unsigned NumFilters); 355 356 /// Pops an exceptions filter off the stack. 357 void popFilter(); 358 359 /// Push a terminate handler on the stack. 360 void pushTerminate(); 361 362 /// Pops a terminate handler off the stack. 363 void popTerminate(); 364 365 /// Determines whether the exception-scopes stack is empty. 366 bool empty() const { return StartOfData == EndOfBuffer; } 367 368 bool requiresLandingPad() const { 369 return InnermostEHScope != stable_end(); 370 } 371 372 /// Determines whether there are any normal cleanups on the stack. 373 bool hasNormalCleanups() const { 374 return InnermostNormalCleanup != stable_end(); 375 } 376 377 /// Returns the innermost normal cleanup on the stack, or 378 /// stable_end() if there are no normal cleanups. 379 stable_iterator getInnermostNormalCleanup() const { 380 return InnermostNormalCleanup; 381 } 382 stable_iterator getInnermostActiveNormalCleanup() const; 383 384 stable_iterator getInnermostEHScope() const { 385 return InnermostEHScope; 386 } 387 388 stable_iterator getInnermostActiveEHScope() const; 389 390 /// An unstable reference to a scope-stack depth. Invalidated by 391 /// pushes but not pops. 392 class iterator; 393 394 /// Returns an iterator pointing to the innermost EH scope. 395 iterator begin() const; 396 397 /// Returns an iterator pointing to the outermost EH scope. 398 iterator end() const; 399 400 /// Create a stable reference to the top of the EH stack. The 401 /// returned reference is valid until that scope is popped off the 402 /// stack. 403 stable_iterator stable_begin() const { 404 return stable_iterator(EndOfBuffer - StartOfData); 405 } 406 407 /// Create a stable reference to the bottom of the EH stack. 408 static stable_iterator stable_end() { 409 return stable_iterator(0); 410 } 411 412 /// Translates an iterator into a stable_iterator. 413 stable_iterator stabilize(iterator it) const; 414 415 /// Turn a stable reference to a scope depth into a unstable pointer 416 /// to the EH stack. 417 iterator find(stable_iterator save) const; 418 419 /// Removes the cleanup pointed to by the given stable_iterator. 420 void removeCleanup(stable_iterator save); 421 422 /// Add a branch fixup to the current cleanup scope. 423 BranchFixup &addBranchFixup() { 424 assert(hasNormalCleanups() && "adding fixup in scope without cleanups"); 425 BranchFixups.push_back(BranchFixup()); 426 return BranchFixups.back(); 427 } 428 429 unsigned getNumBranchFixups() const { return BranchFixups.size(); } 430 BranchFixup &getBranchFixup(unsigned I) { 431 assert(I < getNumBranchFixups()); 432 return BranchFixups[I]; 433 } 434 435 /// Pops lazily-removed fixups from the end of the list. This 436 /// should only be called by procedures which have just popped a 437 /// cleanup or resolved one or more fixups. 438 void popNullFixups(); 439 440 /// Clears the branch-fixups list. This should only be called by 441 /// ResolveAllBranchFixups. 442 void clearFixups() { BranchFixups.clear(); } 443 }; 444 445 } // namespace CodeGen 446 } // namespace clang 447 448 #endif 449