clang  5.0.0
CGException.cpp
Go to the documentation of this file.
1 //===--- CGException.cpp - Emit LLVM Code for C++ exceptions ----*- 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 // This contains code dealing with C++ exception related code generation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CGCXXABI.h"
16 #include "CGCleanup.h"
17 #include "CGObjCRuntime.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/Mangle.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/AST/StmtObjC.h"
22 #include "clang/AST/StmtVisitor.h"
24 #include "llvm/IR/CallSite.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/Support/SaveAndRestore.h"
28 
29 using namespace clang;
30 using namespace CodeGen;
31 
32 static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
33  // void __cxa_free_exception(void *thrown_exception);
34 
35  llvm::FunctionType *FTy =
36  llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
37 
38  return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
39 }
40 
41 static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
42  // void __cxa_call_unexpected(void *thrown_exception);
43 
44  llvm::FunctionType *FTy =
45  llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
46 
47  return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
48 }
49 
50 llvm::Constant *CodeGenModule::getTerminateFn() {
51  // void __terminate();
52 
53  llvm::FunctionType *FTy =
54  llvm::FunctionType::get(VoidTy, /*IsVarArgs=*/false);
55 
56  StringRef name;
57 
58  // In C++, use std::terminate().
59  if (getLangOpts().CPlusPlus &&
60  getTarget().getCXXABI().isItaniumFamily()) {
61  name = "_ZSt9terminatev";
62  } else if (getLangOpts().CPlusPlus &&
63  getTarget().getCXXABI().isMicrosoft()) {
64  if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
65  name = "__std_terminate";
66  else
67  name = "\01?terminate@@YAXXZ";
68  } else if (getLangOpts().ObjC1 &&
70  name = "objc_terminate";
71  else
72  name = "abort";
73  return CreateRuntimeFunction(FTy, name);
74 }
75 
76 static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
77  StringRef Name) {
78  llvm::FunctionType *FTy =
79  llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
80 
81  return CGM.CreateRuntimeFunction(FTy, Name);
82 }
83 
84 const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
85 const EHPersonality
86 EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
87 const EHPersonality
88 EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
89 const EHPersonality
90 EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
91 const EHPersonality
92 EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
93 const EHPersonality
94 EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
95 const EHPersonality
96 EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
97 const EHPersonality
98 EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
99 const EHPersonality
100 EHPersonality::GNU_ObjC_SJLJ = {"__gnu_objc_personality_sj0", "objc_exception_throw"};
101 const EHPersonality
102 EHPersonality::GNU_ObjC_SEH = {"__gnu_objc_personality_seh0", "objc_exception_throw"};
103 const EHPersonality
104 EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
105 const EHPersonality
106 EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
107 const EHPersonality
108 EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
109 const EHPersonality
110 EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
111 const EHPersonality
112 EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
113 
114 /// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
115 /// other platforms, unless the user asked for SjLj exceptions.
116 static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
117  return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
118 }
119 
120 static const EHPersonality &getCPersonality(const llvm::Triple &T,
121  const LangOptions &L) {
122  if (L.SjLjExceptions)
124  else if (useLibGCCSEHPersonality(T))
126  return EHPersonality::GNU_C;
127 }
128 
129 static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
130  const LangOptions &L) {
131  switch (L.ObjCRuntime.getKind()) {
133  return getCPersonality(T, L);
134  case ObjCRuntime::MacOSX:
135  case ObjCRuntime::iOS:
139  if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
141  // fallthrough
142  case ObjCRuntime::GCC:
143  case ObjCRuntime::ObjFW:
144  if (L.SjLjExceptions)
146  else if (useLibGCCSEHPersonality(T))
149  }
150  llvm_unreachable("bad runtime kind");
151 }
152 
153 static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
154  const LangOptions &L) {
155  if (L.SjLjExceptions)
157  else if (useLibGCCSEHPersonality(T))
160 }
161 
162 /// Determines the personality function to use when both C++
163 /// and Objective-C exceptions are being caught.
164 static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
165  const LangOptions &L) {
166  switch (L.ObjCRuntime.getKind()) {
167  // The ObjC personality defers to the C++ personality for non-ObjC
168  // handlers. Unlike the C++ case, we use the same personality
169  // function on targets using (backend-driven) SJLJ EH.
170  case ObjCRuntime::MacOSX:
171  case ObjCRuntime::iOS:
174 
175  // In the fragile ABI, just use C++ exception handling and hope
176  // they're not doing crazy exception mixing.
178  return getCXXPersonality(T, L);
179 
180  // The GCC runtime's personality function inherently doesn't support
181  // mixed EH. Use the C++ personality just to avoid returning null.
182  case ObjCRuntime::GCC:
183  case ObjCRuntime::ObjFW:
184  return getObjCPersonality(T, L);
187  }
188  llvm_unreachable("bad runtime kind");
189 }
190 
191 static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
192  if (T.getArch() == llvm::Triple::x86)
195 }
196 
198  const FunctionDecl *FD) {
199  const llvm::Triple &T = CGM.getTarget().getTriple();
200  const LangOptions &L = CGM.getLangOpts();
201 
202  // Functions using SEH get an SEH personality.
203  if (FD && FD->usesSEHTry())
204  return getSEHPersonalityMSVC(T);
205 
206  // Try to pick a personality function that is compatible with MSVC if we're
207  // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
208  // the GCC-style personality function.
209  if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
210  if (L.SjLjExceptions)
212  else
214  }
215 
216  if (L.CPlusPlus && L.ObjC1)
217  return getObjCXXPersonality(T, L);
218  else if (L.CPlusPlus)
219  return getCXXPersonality(T, L);
220  else if (L.ObjC1)
221  return getObjCPersonality(T, L);
222  else
223  return getCPersonality(T, L);
224 }
225 
227  return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
228 }
229 
230 static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
231  const EHPersonality &Personality) {
232  return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
233  Personality.PersonalityFn,
234  llvm::AttributeList(), /*Local=*/true);
235 }
236 
237 static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
238  const EHPersonality &Personality) {
239  llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
240  return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
241 }
242 
243 /// Check whether a landingpad instruction only uses C++ features.
244 static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
245  for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
246  // Look for something that would've been returned by the ObjC
247  // runtime's GetEHType() method.
248  llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
249  if (LPI->isCatch(I)) {
250  // Check if the catch value has the ObjC prefix.
251  if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
252  // ObjC EH selector entries are always global variables with
253  // names starting like this.
254  if (GV->getName().startswith("OBJC_EHTYPE"))
255  return false;
256  } else {
257  // Check if any of the filter values have the ObjC prefix.
258  llvm::Constant *CVal = cast<llvm::Constant>(Val);
259  for (llvm::User::op_iterator
260  II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
261  if (llvm::GlobalVariable *GV =
262  cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
263  // ObjC EH selector entries are always global variables with
264  // names starting like this.
265  if (GV->getName().startswith("OBJC_EHTYPE"))
266  return false;
267  }
268  }
269  }
270  return true;
271 }
272 
273 /// Check whether a personality function could reasonably be swapped
274 /// for a C++ personality function.
275 static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
276  for (llvm::User *U : Fn->users()) {
277  // Conditionally white-list bitcasts.
278  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
279  if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
280  if (!PersonalityHasOnlyCXXUses(CE))
281  return false;
282  continue;
283  }
284 
285  // Otherwise it must be a function.
286  llvm::Function *F = dyn_cast<llvm::Function>(U);
287  if (!F) return false;
288 
289  for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
290  if (BB->isLandingPad())
291  if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
292  return false;
293  }
294  }
295 
296  return true;
297 }
298 
299 /// Try to use the C++ personality function in ObjC++. Not doing this
300 /// can cause some incompatibilities with gcc, which is more
301 /// aggressive about only using the ObjC++ personality in a function
302 /// when it really needs it.
303 void CodeGenModule::SimplifyPersonality() {
304  // If we're not in ObjC++ -fexceptions, there's nothing to do.
305  if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
306  return;
307 
308  // Both the problem this endeavors to fix and the way the logic
309  // above works is specific to the NeXT runtime.
310  if (!LangOpts.ObjCRuntime.isNeXTFamily())
311  return;
312 
313  const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
314  const EHPersonality &CXX =
315  getCXXPersonality(getTarget().getTriple(), LangOpts);
316  if (&ObjCXX == &CXX)
317  return;
318 
319  assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
320  "Different EHPersonalities using the same personality function.");
321 
322  llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
323 
324  // Nothing to do if it's unused.
325  if (!Fn || Fn->use_empty()) return;
326 
327  // Can't do the optimization if it has non-C++ uses.
328  if (!PersonalityHasOnlyCXXUses(Fn)) return;
329 
330  // Create the C++ personality function and kill off the old
331  // function.
332  llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
333 
334  // This can happen if the user is screwing with us.
335  if (Fn->getType() != CXXFn->getType()) return;
336 
337  Fn->replaceAllUsesWith(CXXFn);
338  Fn->eraseFromParent();
339 }
340 
341 /// Returns the value to inject into a selector to indicate the
342 /// presence of a catch-all.
343 static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
344  // Possibly we should use @llvm.eh.catch.all.value here.
345  return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
346 }
347 
348 namespace {
349  /// A cleanup to free the exception object if its initialization
350  /// throws.
351  struct FreeException final : EHScopeStack::Cleanup {
352  llvm::Value *exn;
353  FreeException(llvm::Value *exn) : exn(exn) {}
354  void Emit(CodeGenFunction &CGF, Flags flags) override {
356  }
357  };
358 } // end anonymous namespace
359 
360 // Emits an exception expression into the given location. This
361 // differs from EmitAnyExprToMem only in that, if a final copy-ctor
362 // call is required, an exception within that copy ctor causes
363 // std::terminate to be invoked.
365  // Make sure the exception object is cleaned up if there's an
366  // exception during initialization.
367  pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
369 
370  // __cxa_allocate_exception returns a void*; we need to cast this
371  // to the appropriate type for the object.
372  llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
373  Address typedAddr = Builder.CreateBitCast(addr, ty);
374 
375  // FIXME: this isn't quite right! If there's a final unelided call
376  // to a copy constructor, then according to [except.terminate]p1 we
377  // must call std::terminate() if that constructor throws, because
378  // technically that copy occurs after the exception expression is
379  // evaluated but before the exception is caught. But the best way
380  // to handle that is to teach EmitAggExpr to do the final copy
381  // differently if it can't be elided.
382  EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
383  /*IsInit*/ true);
384 
385  // Deactivate the cleanup block.
386  DeactivateCleanupBlock(cleanup,
387  cast<llvm::Instruction>(typedAddr.getPointer()));
388 }
389 
391  if (!ExceptionSlot)
394 }
395 
397  if (!EHSelectorSlot)
398  EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
400 }
401 
403  return Builder.CreateLoad(getExceptionSlot(), "exn");
404 }
405 
407  return Builder.CreateLoad(getEHSelectorSlot(), "sel");
408 }
409 
411  bool KeepInsertionPoint) {
412  if (const Expr *SubExpr = E->getSubExpr()) {
413  QualType ThrowType = SubExpr->getType();
414  if (ThrowType->isObjCObjectPointerType()) {
415  const Stmt *ThrowStmt = E->getSubExpr();
416  const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
417  CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
418  } else {
419  CGM.getCXXABI().emitThrow(*this, E);
420  }
421  } else {
422  CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
423  }
424 
425  // throw is an expression, and the expression emitters expect us
426  // to leave ourselves at a valid insertion point.
427  if (KeepInsertionPoint)
428  EmitBlock(createBasicBlock("throw.cont"));
429 }
430 
432  if (!CGM.getLangOpts().CXXExceptions)
433  return;
434 
435  const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
436  if (!FD) {
437  // Check if CapturedDecl is nothrow and create terminate scope for it.
438  if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
439  if (CD->isNothrow())
441  }
442  return;
443  }
444  const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
445  if (!Proto)
446  return;
447 
449  if (isNoexceptExceptionSpec(EST)) {
451  // noexcept functions are simple terminate scopes.
453  }
454  } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
455  // TODO: Revisit exception specifications for the MS ABI. There is a way to
456  // encode these in an object file but MSVC doesn't do anything with it.
457  if (getTarget().getCXXABI().isMicrosoft())
458  return;
459  unsigned NumExceptions = Proto->getNumExceptions();
460  EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
461 
462  for (unsigned I = 0; I != NumExceptions; ++I) {
463  QualType Ty = Proto->getExceptionType(I);
464  QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
465  llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
466  /*ForEH=*/true);
467  Filter->setFilter(I, EHType);
468  }
469  }
470 }
471 
472 /// Emit the dispatch block for a filter scope if necessary.
474  EHFilterScope &filterScope) {
475  llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
476  if (!dispatchBlock) return;
477  if (dispatchBlock->use_empty()) {
478  delete dispatchBlock;
479  return;
480  }
481 
482  CGF.EmitBlockAfterUses(dispatchBlock);
483 
484  // If this isn't a catch-all filter, we need to check whether we got
485  // here because the filter triggered.
486  if (filterScope.getNumFilters()) {
487  // Load the selector value.
488  llvm::Value *selector = CGF.getSelectorFromSlot();
489  llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
490 
491  llvm::Value *zero = CGF.Builder.getInt32(0);
492  llvm::Value *failsFilter =
493  CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
494  CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
495  CGF.getEHResumeBlock(false));
496 
497  CGF.EmitBlock(unexpectedBB);
498  }
499 
500  // Call __cxa_call_unexpected. This doesn't need to be an invoke
501  // because __cxa_call_unexpected magically filters exceptions
502  // according to the last landing pad the exception was thrown
503  // into. Seriously.
504  llvm::Value *exn = CGF.getExceptionFromSlot();
505  CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
506  ->setDoesNotReturn();
507  CGF.Builder.CreateUnreachable();
508 }
509 
511  if (!CGM.getLangOpts().CXXExceptions)
512  return;
513 
514  const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
515  if (!FD) {
516  // Check if CapturedDecl is nothrow and pop terminate scope for it.
517  if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
518  if (CD->isNothrow())
520  }
521  return;
522  }
523  const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
524  if (!Proto)
525  return;
526 
528  if (isNoexceptExceptionSpec(EST)) {
531  }
532  } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
533  // TODO: Revisit exception specifications for the MS ABI. There is a way to
534  // encode these in an object file but MSVC doesn't do anything with it.
535  if (getTarget().getCXXABI().isMicrosoft())
536  return;
537  EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
538  emitFilterDispatchBlock(*this, filterScope);
539  EHStack.popFilter();
540  }
541 }
542 
544  EnterCXXTryStmt(S);
545  EmitStmt(S.getTryBlock());
546  ExitCXXTryStmt(S);
547 }
548 
549 void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
550  unsigned NumHandlers = S.getNumHandlers();
551  EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
552 
553  for (unsigned I = 0; I != NumHandlers; ++I) {
554  const CXXCatchStmt *C = S.getHandler(I);
555 
556  llvm::BasicBlock *Handler = createBasicBlock("catch");
557  if (C->getExceptionDecl()) {
558  // FIXME: Dropping the reference type on the type into makes it
559  // impossible to correctly implement catch-by-reference
560  // semantics for pointers. Unfortunately, this is what all
561  // existing compilers do, and it's not clear that the standard
562  // personality routine is capable of doing this right. See C++ DR 388:
563  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
564  Qualifiers CaughtTypeQuals;
566  C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
567 
568  CatchTypeInfo TypeInfo{nullptr, 0};
569  if (CaughtType->isObjCObjectPointerType())
570  TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
571  else
573  CaughtType, C->getCaughtType());
574  CatchScope->setHandler(I, TypeInfo, Handler);
575  } else {
576  // No exception decl indicates '...', a catch-all.
577  CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
578  }
579  }
580 }
581 
582 llvm::BasicBlock *
584  if (EHPersonality::get(*this).usesFuncletPads())
585  return getMSVCDispatchBlock(si);
586 
587  // The dispatch block for the end of the scope chain is a block that
588  // just resumes unwinding.
589  if (si == EHStack.stable_end())
590  return getEHResumeBlock(true);
591 
592  // Otherwise, we should look at the actual scope.
593  EHScope &scope = *EHStack.find(si);
594 
595  llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
596  if (!dispatchBlock) {
597  switch (scope.getKind()) {
598  case EHScope::Catch: {
599  // Apply a special case to a single catch-all.
600  EHCatchScope &catchScope = cast<EHCatchScope>(scope);
601  if (catchScope.getNumHandlers() == 1 &&
602  catchScope.getHandler(0).isCatchAll()) {
603  dispatchBlock = catchScope.getHandler(0).Block;
604 
605  // Otherwise, make a dispatch block.
606  } else {
607  dispatchBlock = createBasicBlock("catch.dispatch");
608  }
609  break;
610  }
611 
612  case EHScope::Cleanup:
613  dispatchBlock = createBasicBlock("ehcleanup");
614  break;
615 
616  case EHScope::Filter:
617  dispatchBlock = createBasicBlock("filter.dispatch");
618  break;
619 
620  case EHScope::Terminate:
621  dispatchBlock = getTerminateHandler();
622  break;
623 
624  case EHScope::PadEnd:
625  llvm_unreachable("PadEnd unnecessary for Itanium!");
626  }
627  scope.setCachedEHDispatchBlock(dispatchBlock);
628  }
629  return dispatchBlock;
630 }
631 
632 llvm::BasicBlock *
634  // Returning nullptr indicates that the previous dispatch block should unwind
635  // to caller.
636  if (SI == EHStack.stable_end())
637  return nullptr;
638 
639  // Otherwise, we should look at the actual scope.
640  EHScope &EHS = *EHStack.find(SI);
641 
642  llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
643  if (DispatchBlock)
644  return DispatchBlock;
645 
646  if (EHS.getKind() == EHScope::Terminate)
647  DispatchBlock = getTerminateHandler();
648  else
649  DispatchBlock = createBasicBlock();
650  CGBuilderTy Builder(*this, DispatchBlock);
651 
652  switch (EHS.getKind()) {
653  case EHScope::Catch:
654  DispatchBlock->setName("catch.dispatch");
655  break;
656 
657  case EHScope::Cleanup:
658  DispatchBlock->setName("ehcleanup");
659  break;
660 
661  case EHScope::Filter:
662  llvm_unreachable("exception specifications not handled yet!");
663 
664  case EHScope::Terminate:
665  DispatchBlock->setName("terminate");
666  break;
667 
668  case EHScope::PadEnd:
669  llvm_unreachable("PadEnd dispatch block missing!");
670  }
671  EHS.setCachedEHDispatchBlock(DispatchBlock);
672  return DispatchBlock;
673 }
674 
675 /// Check whether this is a non-EH scope, i.e. a scope which doesn't
676 /// affect exception handling. Currently, the only non-EH scopes are
677 /// normal-only cleanup scopes.
678 static bool isNonEHScope(const EHScope &S) {
679  switch (S.getKind()) {
680  case EHScope::Cleanup:
681  return !cast<EHCleanupScope>(S).isEHCleanup();
682  case EHScope::Filter:
683  case EHScope::Catch:
684  case EHScope::Terminate:
685  case EHScope::PadEnd:
686  return false;
687  }
688 
689  llvm_unreachable("Invalid EHScope Kind!");
690 }
691 
693  assert(EHStack.requiresLandingPad());
694  assert(!EHStack.empty());
695 
696  // If exceptions are disabled and SEH is not in use, then there is no invoke
697  // destination. SEH "works" even if exceptions are off. In practice, this
698  // means that C++ destructors and other EH cleanups don't run, which is
699  // consistent with MSVC's behavior.
700  const LangOptions &LO = CGM.getLangOpts();
701  if (!LO.Exceptions) {
702  if (!LO.Borland && !LO.MicrosoftExt)
703  return nullptr;
705  return nullptr;
706  }
707 
708  // CUDA device code doesn't have exceptions.
709  if (LO.CUDA && LO.CUDAIsDevice)
710  return nullptr;
711 
712  // Check the innermost scope for a cached landing pad. If this is
713  // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
714  llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
715  if (LP) return LP;
716 
717  const EHPersonality &Personality = EHPersonality::get(*this);
718 
719  if (!CurFn->hasPersonalityFn())
720  CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
721 
722  if (Personality.usesFuncletPads()) {
723  // We don't need separate landing pads in the funclet model.
725  } else {
726  // Build the landing pad for this scope.
727  LP = EmitLandingPad();
728  }
729 
730  assert(LP);
731 
732  // Cache the landing pad on the innermost scope. If this is a
733  // non-EH scope, cache the landing pad on the enclosing scope, too.
734  for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
735  ir->setCachedLandingPad(LP);
736  if (!isNonEHScope(*ir)) break;
737  }
738 
739  return LP;
740 }
741 
742 llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
743  assert(EHStack.requiresLandingPad());
744 
745  EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
746  switch (innermostEHScope.getKind()) {
747  case EHScope::Terminate:
748  return getTerminateLandingPad();
749 
750  case EHScope::PadEnd:
751  llvm_unreachable("PadEnd unnecessary for Itanium!");
752 
753  case EHScope::Catch:
754  case EHScope::Cleanup:
755  case EHScope::Filter:
756  if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
757  return lpad;
758  }
759 
760  // Save the current IR generation state.
761  CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
762  auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
763 
764  // Create and configure the landing pad.
765  llvm::BasicBlock *lpad = createBasicBlock("lpad");
766  EmitBlock(lpad);
767 
768  llvm::LandingPadInst *LPadInst =
769  Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
770 
771  llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
773  llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
775 
776  // Save the exception pointer. It's safe to use a single exception
777  // pointer per function because EH cleanups can never have nested
778  // try/catches.
779  // Build the landingpad instruction.
780 
781  // Accumulate all the handlers in scope.
782  bool hasCatchAll = false;
783  bool hasCleanup = false;
784  bool hasFilter = false;
785  SmallVector<llvm::Value*, 4> filterTypes;
786  llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
787  for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
788  ++I) {
789 
790  switch (I->getKind()) {
791  case EHScope::Cleanup:
792  // If we have a cleanup, remember that.
793  hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
794  continue;
795 
796  case EHScope::Filter: {
797  assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
798  assert(!hasCatchAll && "EH filter reached after catch-all");
799 
800  // Filter scopes get added to the landingpad in weird ways.
801  EHFilterScope &filter = cast<EHFilterScope>(*I);
802  hasFilter = true;
803 
804  // Add all the filter values.
805  for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
806  filterTypes.push_back(filter.getFilter(i));
807  goto done;
808  }
809 
810  case EHScope::Terminate:
811  // Terminate scopes are basically catch-alls.
812  assert(!hasCatchAll);
813  hasCatchAll = true;
814  goto done;
815 
816  case EHScope::Catch:
817  break;
818 
819  case EHScope::PadEnd:
820  llvm_unreachable("PadEnd unnecessary for Itanium!");
821  }
822 
823  EHCatchScope &catchScope = cast<EHCatchScope>(*I);
824  for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
825  EHCatchScope::Handler handler = catchScope.getHandler(hi);
826  assert(handler.Type.Flags == 0 &&
827  "landingpads do not support catch handler flags");
828 
829  // If this is a catch-all, register that and abort.
830  if (!handler.Type.RTTI) {
831  assert(!hasCatchAll);
832  hasCatchAll = true;
833  goto done;
834  }
835 
836  // Check whether we already have a handler for this type.
837  if (catchTypes.insert(handler.Type.RTTI).second)
838  // If not, add it directly to the landingpad.
839  LPadInst->addClause(handler.Type.RTTI);
840  }
841  }
842 
843  done:
844  // If we have a catch-all, add null to the landingpad.
845  assert(!(hasCatchAll && hasFilter));
846  if (hasCatchAll) {
847  LPadInst->addClause(getCatchAllValue(*this));
848 
849  // If we have an EH filter, we need to add those handlers in the
850  // right place in the landingpad, which is to say, at the end.
851  } else if (hasFilter) {
852  // Create a filter expression: a constant array indicating which filter
853  // types there are. The personality routine only lands here if the filter
854  // doesn't match.
856  llvm::ArrayType *AType =
857  llvm::ArrayType::get(!filterTypes.empty() ?
858  filterTypes[0]->getType() : Int8PtrTy,
859  filterTypes.size());
860 
861  for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
862  Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
863  llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
864  LPadInst->addClause(FilterArray);
865 
866  // Also check whether we need a cleanup.
867  if (hasCleanup)
868  LPadInst->setCleanup(true);
869 
870  // Otherwise, signal that we at least have cleanups.
871  } else if (hasCleanup) {
872  LPadInst->setCleanup(true);
873  }
874 
875  assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
876  "landingpad instruction has no clauses!");
877 
878  // Tell the backend how to generate the landing pad.
880 
881  // Restore the old IR generation state.
882  Builder.restoreIP(savedIP);
883 
884  return lpad;
885 }
886 
887 static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
888  llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
889  assert(DispatchBlock);
890 
891  CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
892  CGF.EmitBlockAfterUses(DispatchBlock);
893 
894  llvm::Value *ParentPad = CGF.CurrentFuncletPad;
895  if (!ParentPad)
896  ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
897  llvm::BasicBlock *UnwindBB =
898  CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
899 
900  unsigned NumHandlers = CatchScope.getNumHandlers();
901  llvm::CatchSwitchInst *CatchSwitch =
902  CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
903 
904  // Test against each of the exception types we claim to catch.
905  for (unsigned I = 0; I < NumHandlers; ++I) {
906  const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
907 
908  CatchTypeInfo TypeInfo = Handler.Type;
909  if (!TypeInfo.RTTI)
910  TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
911 
912  CGF.Builder.SetInsertPoint(Handler.Block);
913 
914  if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
915  CGF.Builder.CreateCatchPad(
916  CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
917  llvm::Constant::getNullValue(CGF.VoidPtrTy)});
918  } else {
919  CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
920  }
921 
922  CatchSwitch->addHandler(Handler.Block);
923  }
924  CGF.Builder.restoreIP(SavedIP);
925 }
926 
927 /// Emit the structure of the dispatch block for the given catch scope.
928 /// It is an invariant that the dispatch block already exists.
930  EHCatchScope &catchScope) {
931  if (EHPersonality::get(CGF).usesFuncletPads())
932  return emitCatchPadBlock(CGF, catchScope);
933 
934  llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
935  assert(dispatchBlock);
936 
937  // If there's only a single catch-all, getEHDispatchBlock returned
938  // that catch-all as the dispatch block.
939  if (catchScope.getNumHandlers() == 1 &&
940  catchScope.getHandler(0).isCatchAll()) {
941  assert(dispatchBlock == catchScope.getHandler(0).Block);
942  return;
943  }
944 
945  CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
946  CGF.EmitBlockAfterUses(dispatchBlock);
947 
948  // Select the right handler.
949  llvm::Value *llvm_eh_typeid_for =
950  CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
951 
952  // Load the selector value.
953  llvm::Value *selector = CGF.getSelectorFromSlot();
954 
955  // Test against each of the exception types we claim to catch.
956  for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
957  assert(i < e && "ran off end of handlers!");
958  const EHCatchScope::Handler &handler = catchScope.getHandler(i);
959 
960  llvm::Value *typeValue = handler.Type.RTTI;
961  assert(handler.Type.Flags == 0 &&
962  "landingpads do not support catch handler flags");
963  assert(typeValue && "fell into catch-all case!");
964  typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
965 
966  // Figure out the next block.
967  bool nextIsEnd;
968  llvm::BasicBlock *nextBlock;
969 
970  // If this is the last handler, we're at the end, and the next
971  // block is the block for the enclosing EH scope.
972  if (i + 1 == e) {
973  nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
974  nextIsEnd = true;
975 
976  // If the next handler is a catch-all, we're at the end, and the
977  // next block is that handler.
978  } else if (catchScope.getHandler(i+1).isCatchAll()) {
979  nextBlock = catchScope.getHandler(i+1).Block;
980  nextIsEnd = true;
981 
982  // Otherwise, we're not at the end and we need a new block.
983  } else {
984  nextBlock = CGF.createBasicBlock("catch.fallthrough");
985  nextIsEnd = false;
986  }
987 
988  // Figure out the catch type's index in the LSDA's type table.
989  llvm::CallInst *typeIndex =
990  CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
991  typeIndex->setDoesNotThrow();
992 
993  llvm::Value *matchesTypeIndex =
994  CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
995  CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
996 
997  // If the next handler is a catch-all, we're completely done.
998  if (nextIsEnd) {
999  CGF.Builder.restoreIP(savedIP);
1000  return;
1001  }
1002  // Otherwise we need to emit and continue at that block.
1003  CGF.EmitBlock(nextBlock);
1004  }
1005 }
1006 
1008  EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1009  if (catchScope.hasEHBranches())
1010  emitCatchDispatchBlock(*this, catchScope);
1011  EHStack.popCatch();
1012 }
1013 
1014 void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
1015  unsigned NumHandlers = S.getNumHandlers();
1016  EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1017  assert(CatchScope.getNumHandlers() == NumHandlers);
1018 
1019  // If the catch was not required, bail out now.
1020  if (!CatchScope.hasEHBranches()) {
1021  CatchScope.clearHandlerBlocks();
1022  EHStack.popCatch();
1023  return;
1024  }
1025 
1026  // Emit the structure of the EH dispatch for this catch.
1027  emitCatchDispatchBlock(*this, CatchScope);
1028 
1029  // Copy the handler blocks off before we pop the EH stack. Emitting
1030  // the handlers might scribble on this memory.
1032  CatchScope.begin(), CatchScope.begin() + NumHandlers);
1033 
1034  EHStack.popCatch();
1035 
1036  // The fall-through block.
1037  llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1038 
1039  // We just emitted the body of the try; jump to the continue block.
1040  if (HaveInsertPoint())
1041  Builder.CreateBr(ContBB);
1042 
1043  // Determine if we need an implicit rethrow for all these catch handlers;
1044  // see the comment below.
1045  bool doImplicitRethrow = false;
1046  if (IsFnTryBlock)
1047  doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1048  isa<CXXConstructorDecl>(CurCodeDecl);
1049 
1050  // Perversely, we emit the handlers backwards precisely because we
1051  // want them to appear in source order. In all of these cases, the
1052  // catch block will have exactly one predecessor, which will be a
1053  // particular block in the catch dispatch. However, in the case of
1054  // a catch-all, one of the dispatch blocks will branch to two
1055  // different handlers, and EmitBlockAfterUses will cause the second
1056  // handler to be moved before the first.
1057  for (unsigned I = NumHandlers; I != 0; --I) {
1058  llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1059  EmitBlockAfterUses(CatchBlock);
1060 
1061  // Catch the exception if this isn't a catch-all.
1062  const CXXCatchStmt *C = S.getHandler(I-1);
1063 
1064  // Enter a cleanup scope, including the catch variable and the
1065  // end-catch.
1066  RunCleanupsScope CatchScope(*this);
1067 
1068  // Initialize the catch variable and set up the cleanups.
1069  SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1071  CGM.getCXXABI().emitBeginCatch(*this, C);
1072 
1073  // Emit the PGO counter increment.
1075 
1076  // Perform the body of the catch.
1077  EmitStmt(C->getHandlerBlock());
1078 
1079  // [except.handle]p11:
1080  // The currently handled exception is rethrown if control
1081  // reaches the end of a handler of the function-try-block of a
1082  // constructor or destructor.
1083 
1084  // It is important that we only do this on fallthrough and not on
1085  // return. Note that it's illegal to put a return in a
1086  // constructor function-try-block's catch handler (p14), so this
1087  // really only applies to destructors.
1088  if (doImplicitRethrow && HaveInsertPoint()) {
1089  CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
1090  Builder.CreateUnreachable();
1091  Builder.ClearInsertionPoint();
1092  }
1093 
1094  // Fall out through the catch cleanups.
1095  CatchScope.ForceCleanup();
1096 
1097  // Branch out of the try.
1098  if (HaveInsertPoint())
1099  Builder.CreateBr(ContBB);
1100  }
1101 
1102  EmitBlock(ContBB);
1104 }
1105 
1106 namespace {
1107  struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
1108  llvm::Value *ForEHVar;
1109  llvm::Value *EndCatchFn;
1110  CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1111  : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1112 
1113  void Emit(CodeGenFunction &CGF, Flags flags) override {
1114  llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1115  llvm::BasicBlock *CleanupContBB =
1116  CGF.createBasicBlock("finally.cleanup.cont");
1117 
1118  llvm::Value *ShouldEndCatch =
1119  CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
1120  CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1121  CGF.EmitBlock(EndCatchBB);
1122  CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
1123  CGF.EmitBlock(CleanupContBB);
1124  }
1125  };
1126 
1127  struct PerformFinally final : EHScopeStack::Cleanup {
1128  const Stmt *Body;
1129  llvm::Value *ForEHVar;
1130  llvm::Value *EndCatchFn;
1131  llvm::Value *RethrowFn;
1132  llvm::Value *SavedExnVar;
1133 
1134  PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1135  llvm::Value *EndCatchFn,
1136  llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1137  : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1138  RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1139 
1140  void Emit(CodeGenFunction &CGF, Flags flags) override {
1141  // Enter a cleanup to call the end-catch function if one was provided.
1142  if (EndCatchFn)
1143  CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1144  ForEHVar, EndCatchFn);
1145 
1146  // Save the current cleanup destination in case there are
1147  // cleanups in the finally block.
1148  llvm::Value *SavedCleanupDest =
1150  "cleanup.dest.saved");
1151 
1152  // Emit the finally block.
1153  CGF.EmitStmt(Body);
1154 
1155  // If the end of the finally is reachable, check whether this was
1156  // for EH. If so, rethrow.
1157  if (CGF.HaveInsertPoint()) {
1158  llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1159  llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1160 
1161  llvm::Value *ShouldRethrow =
1162  CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
1163  CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1164 
1165  CGF.EmitBlock(RethrowBB);
1166  if (SavedExnVar) {
1167  CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1168  CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
1169  } else {
1170  CGF.EmitRuntimeCallOrInvoke(RethrowFn);
1171  }
1172  CGF.Builder.CreateUnreachable();
1173 
1174  CGF.EmitBlock(ContBB);
1175 
1176  // Restore the cleanup destination.
1177  CGF.Builder.CreateStore(SavedCleanupDest,
1178  CGF.getNormalCleanupDestSlot());
1179  }
1180 
1181  // Leave the end-catch cleanup. As an optimization, pretend that
1182  // the fallthrough path was inaccessible; we've dynamically proven
1183  // that we're not in the EH case along that path.
1184  if (EndCatchFn) {
1185  CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1186  CGF.PopCleanupBlock();
1187  CGF.Builder.restoreIP(SavedIP);
1188  }
1189 
1190  // Now make sure we actually have an insertion point or the
1191  // cleanup gods will hate us.
1192  CGF.EnsureInsertPoint();
1193  }
1194  };
1195 } // end anonymous namespace
1196 
1197 /// Enters a finally block for an implementation using zero-cost
1198 /// exceptions. This is mostly general, but hard-codes some
1199 /// language/ABI-specific behavior in the catch-all sections.
1201  const Stmt *body,
1202  llvm::Constant *beginCatchFn,
1203  llvm::Constant *endCatchFn,
1204  llvm::Constant *rethrowFn) {
1205  assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
1206  "begin/end catch functions not paired");
1207  assert(rethrowFn && "rethrow function is required");
1208 
1209  BeginCatchFn = beginCatchFn;
1210 
1211  // The rethrow function has one of the following two types:
1212  // void (*)()
1213  // void (*)(void*)
1214  // In the latter case we need to pass it the exception object.
1215  // But we can't use the exception slot because the @finally might
1216  // have a landing pad (which would overwrite the exception slot).
1217  llvm::FunctionType *rethrowFnTy =
1218  cast<llvm::FunctionType>(
1219  cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1220  SavedExnVar = nullptr;
1221  if (rethrowFnTy->getNumParams())
1222  SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1223 
1224  // A finally block is a statement which must be executed on any edge
1225  // out of a given scope. Unlike a cleanup, the finally block may
1226  // contain arbitrary control flow leading out of itself. In
1227  // addition, finally blocks should always be executed, even if there
1228  // are no catch handlers higher on the stack. Therefore, we
1229  // surround the protected scope with a combination of a normal
1230  // cleanup (to catch attempts to break out of the block via normal
1231  // control flow) and an EH catch-all (semantically "outside" any try
1232  // statement to which the finally block might have been attached).
1233  // The finally block itself is generated in the context of a cleanup
1234  // which conditionally leaves the catch-all.
1235 
1236  // Jump destination for performing the finally block on an exception
1237  // edge. We'll never actually reach this block, so unreachable is
1238  // fine.
1239  RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1240 
1241  // Whether the finally block is being executed for EH purposes.
1242  ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1243  CGF.Builder.CreateFlagStore(false, ForEHVar);
1244 
1245  // Enter a normal cleanup which will perform the @finally block.
1246  CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1247  ForEHVar, endCatchFn,
1248  rethrowFn, SavedExnVar);
1249 
1250  // Enter a catch-all scope.
1251  llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1252  EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1253  catchScope->setCatchAllHandler(0, catchBB);
1254 }
1255 
1257  // Leave the finally catch-all.
1258  EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1259  llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1260 
1261  CGF.popCatchScope();
1262 
1263  // If there are any references to the catch-all block, emit it.
1264  if (catchBB->use_empty()) {
1265  delete catchBB;
1266  } else {
1267  CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1268  CGF.EmitBlock(catchBB);
1269 
1270  llvm::Value *exn = nullptr;
1271 
1272  // If there's a begin-catch function, call it.
1273  if (BeginCatchFn) {
1274  exn = CGF.getExceptionFromSlot();
1275  CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
1276  }
1277 
1278  // If we need to remember the exception pointer to rethrow later, do so.
1279  if (SavedExnVar) {
1280  if (!exn) exn = CGF.getExceptionFromSlot();
1281  CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
1282  }
1283 
1284  // Tell the cleanups in the finally block that we're do this for EH.
1285  CGF.Builder.CreateFlagStore(true, ForEHVar);
1286 
1287  // Thread a jump through the finally cleanup.
1288  CGF.EmitBranchThroughCleanup(RethrowDest);
1289 
1290  CGF.Builder.restoreIP(savedIP);
1291  }
1292 
1293  // Finally, leave the @finally cleanup.
1294  CGF.PopCleanupBlock();
1295 }
1296 
1298  if (TerminateLandingPad)
1299  return TerminateLandingPad;
1300 
1301  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1302 
1303  // This will get inserted at the end of the function.
1304  TerminateLandingPad = createBasicBlock("terminate.lpad");
1305  Builder.SetInsertPoint(TerminateLandingPad);
1306 
1307  // Tell the backend that this is a landing pad.
1308  const EHPersonality &Personality = EHPersonality::get(*this);
1309 
1310  if (!CurFn->hasPersonalityFn())
1311  CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1312 
1313  llvm::LandingPadInst *LPadInst =
1314  Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
1315  LPadInst->addClause(getCatchAllValue(*this));
1316 
1317  llvm::Value *Exn = nullptr;
1318  if (getLangOpts().CPlusPlus)
1319  Exn = Builder.CreateExtractValue(LPadInst, 0);
1320  llvm::CallInst *terminateCall =
1322  terminateCall->setDoesNotReturn();
1323  Builder.CreateUnreachable();
1324 
1325  // Restore the saved insertion state.
1326  Builder.restoreIP(SavedIP);
1327 
1328  return TerminateLandingPad;
1329 }
1330 
1332  if (TerminateHandler)
1333  return TerminateHandler;
1334 
1335  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1336 
1337  // Set up the terminate handler. This block is inserted at the very
1338  // end of the function by FinishFunction.
1339  TerminateHandler = createBasicBlock("terminate.handler");
1340  Builder.SetInsertPoint(TerminateHandler);
1341  llvm::Value *Exn = nullptr;
1342  SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1344  if (EHPersonality::get(*this).usesFuncletPads()) {
1345  llvm::Value *ParentPad = CurrentFuncletPad;
1346  if (!ParentPad)
1347  ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1348  CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
1349  } else {
1350  if (getLangOpts().CPlusPlus)
1351  Exn = getExceptionFromSlot();
1352  }
1353  llvm::CallInst *terminateCall =
1355  terminateCall->setDoesNotReturn();
1356  Builder.CreateUnreachable();
1357 
1358  // Restore the saved insertion state.
1359  Builder.restoreIP(SavedIP);
1360 
1361  return TerminateHandler;
1362 }
1363 
1364 llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
1365  if (EHResumeBlock) return EHResumeBlock;
1366 
1367  CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1368 
1369  // We emit a jump to a notional label at the outermost unwind state.
1370  EHResumeBlock = createBasicBlock("eh.resume");
1371  Builder.SetInsertPoint(EHResumeBlock);
1372 
1373  const EHPersonality &Personality = EHPersonality::get(*this);
1374 
1375  // This can always be a call because we necessarily didn't find
1376  // anything on the EH stack which needs our help.
1377  const char *RethrowName = Personality.CatchallRethrowFn;
1378  if (RethrowName != nullptr && !isCleanup) {
1380  getExceptionFromSlot())->setDoesNotReturn();
1381  Builder.CreateUnreachable();
1382  Builder.restoreIP(SavedIP);
1383  return EHResumeBlock;
1384  }
1385 
1386  // Recreate the landingpad's return value for the 'resume' instruction.
1389 
1390  llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
1391  llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1392  LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1393  LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1394 
1395  Builder.CreateResume(LPadVal);
1396  Builder.restoreIP(SavedIP);
1397  return EHResumeBlock;
1398 }
1399 
1401  EnterSEHTryStmt(S);
1402  {
1403  JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
1404 
1405  SEHTryEpilogueStack.push_back(&TryExit);
1406  EmitStmt(S.getTryBlock());
1407  SEHTryEpilogueStack.pop_back();
1408 
1409  if (!TryExit.getBlock()->use_empty())
1410  EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1411  else
1412  delete TryExit.getBlock();
1413  }
1414  ExitSEHTryStmt(S);
1415 }
1416 
1417 namespace {
1418 struct PerformSEHFinally final : EHScopeStack::Cleanup {
1419  llvm::Function *OutlinedFinally;
1420  PerformSEHFinally(llvm::Function *OutlinedFinally)
1421  : OutlinedFinally(OutlinedFinally) {}
1422 
1423  void Emit(CodeGenFunction &CGF, Flags F) override {
1424  ASTContext &Context = CGF.getContext();
1425  CodeGenModule &CGM = CGF.CGM;
1426 
1427  CallArgList Args;
1428 
1429  // Compute the two argument values.
1430  QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
1431  llvm::Value *LocalAddrFn = CGM.getIntrinsic(llvm::Intrinsic::localaddress);
1432  llvm::Value *FP = CGF.Builder.CreateCall(LocalAddrFn);
1433  llvm::Value *IsForEH =
1434  llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1435  Args.add(RValue::get(IsForEH), ArgTys[0]);
1436  Args.add(RValue::get(FP), ArgTys[1]);
1437 
1438  // Arrange a two-arg function info and type.
1439  const CGFunctionInfo &FnInfo =
1440  CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
1441 
1442  auto Callee = CGCallee::forDirect(OutlinedFinally);
1443  CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
1444  }
1445 };
1446 } // end anonymous namespace
1447 
1448 namespace {
1449 /// Find all local variable captures in the statement.
1450 struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1451  CodeGenFunction &ParentCGF;
1452  const VarDecl *ParentThis;
1454  Address SEHCodeSlot = Address::invalid();
1455  CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1456  : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1457 
1458  // Return true if we need to do any capturing work.
1459  bool foundCaptures() {
1460  return !Captures.empty() || SEHCodeSlot.isValid();
1461  }
1462 
1463  void Visit(const Stmt *S) {
1464  // See if this is a capture, then recurse.
1466  for (const Stmt *Child : S->children())
1467  if (Child)
1468  Visit(Child);
1469  }
1470 
1471  void VisitDeclRefExpr(const DeclRefExpr *E) {
1472  // If this is already a capture, just make sure we capture 'this'.
1474  Captures.insert(ParentThis);
1475  return;
1476  }
1477 
1478  const auto *D = dyn_cast<VarDecl>(E->getDecl());
1479  if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
1480  Captures.insert(D);
1481  }
1482 
1483  void VisitCXXThisExpr(const CXXThisExpr *E) {
1484  Captures.insert(ParentThis);
1485  }
1486 
1487  void VisitCallExpr(const CallExpr *E) {
1488  // We only need to add parent frame allocations for these builtins in x86.
1489  if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1490  return;
1491 
1492  unsigned ID = E->getBuiltinCallee();
1493  switch (ID) {
1494  case Builtin::BI__exception_code:
1495  case Builtin::BI_exception_code:
1496  // This is the simple case where we are the outermost finally. All we
1497  // have to do here is make sure we escape this and recover it in the
1498  // outlined handler.
1499  if (!SEHCodeSlot.isValid())
1500  SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1501  break;
1502  }
1503  }
1504 };
1505 } // end anonymous namespace
1506 
1508  Address ParentVar,
1509  llvm::Value *ParentFP) {
1510  llvm::CallInst *RecoverCall = nullptr;
1512  if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
1513  // Mark the variable escaped if nobody else referenced it and compute the
1514  // localescape index.
1515  auto InsertPair = ParentCGF.EscapedLocals.insert(
1516  std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1517  int FrameEscapeIdx = InsertPair.first->second;
1518  // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
1519  llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1520  &CGM.getModule(), llvm::Intrinsic::localrecover);
1521  llvm::Constant *ParentI8Fn =
1522  llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1523  RecoverCall = Builder.CreateCall(
1524  FrameRecoverFn, {ParentI8Fn, ParentFP,
1525  llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1526 
1527  } else {
1528  // If the parent didn't have an alloca, we're doing some nested outlining.
1529  // Just clone the existing localrecover call, but tweak the FP argument to
1530  // use our FP value. All other arguments are constants.
1531  auto *ParentRecover =
1532  cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
1533  assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1534  "expected alloca or localrecover in parent LocalDeclMap");
1535  RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1536  RecoverCall->setArgOperand(1, ParentFP);
1537  RecoverCall->insertBefore(AllocaInsertPt);
1538  }
1539 
1540  // Bitcast the variable, rename it, and insert it in the local decl map.
1541  llvm::Value *ChildVar =
1542  Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1543  ChildVar->setName(ParentVar.getName());
1544  return Address(ChildVar, ParentVar.getAlignment());
1545 }
1546 
1548  const Stmt *OutlinedStmt,
1549  bool IsFilter) {
1550  // Find all captures in the Stmt.
1551  CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1552  Finder.Visit(OutlinedStmt);
1553 
1554  // We can exit early on x86_64 when there are no captures. We just have to
1555  // save the exception code in filters so that __exception_code() works.
1556  if (!Finder.foundCaptures() &&
1557  CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1558  if (IsFilter)
1559  EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
1560  return;
1561  }
1562 
1563  llvm::Value *EntryFP = nullptr;
1565  if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1566  // 32-bit SEH filters need to be careful about FP recovery. The end of the
1567  // EH registration is passed in as the EBP physical register. We can
1568  // recover that with llvm.frameaddress(1).
1569  EntryFP = Builder.CreateCall(
1570  CGM.getIntrinsic(llvm::Intrinsic::frameaddress), {Builder.getInt32(1)});
1571  } else {
1572  // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1573  // second parameter.
1574  auto AI = CurFn->arg_begin();
1575  ++AI;
1576  EntryFP = &*AI;
1577  }
1578 
1579  llvm::Value *ParentFP = EntryFP;
1580  if (IsFilter) {
1581  // Given whatever FP the runtime provided us in EntryFP, recover the true
1582  // frame pointer of the parent function. We only need to do this in filters,
1583  // since finally funclets recover the parent FP for us.
1584  llvm::Function *RecoverFPIntrin =
1585  CGM.getIntrinsic(llvm::Intrinsic::x86_seh_recoverfp);
1586  llvm::Constant *ParentI8Fn =
1587  llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1588  ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
1589  }
1590 
1591  // Create llvm.localrecover calls for all captures.
1592  for (const VarDecl *VD : Finder.Captures) {
1593  if (isa<ImplicitParamDecl>(VD)) {
1594  CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1595  CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1596  continue;
1597  }
1598  if (VD->getType()->isVariablyModifiedType()) {
1599  CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1600  continue;
1601  }
1602  assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1603  "captured non-local variable");
1604 
1605  // If this decl hasn't been declared yet, it will be declared in the
1606  // OutlinedStmt.
1607  auto I = ParentCGF.LocalDeclMap.find(VD);
1608  if (I == ParentCGF.LocalDeclMap.end())
1609  continue;
1610 
1611  Address ParentVar = I->second;
1612  setAddrOfLocalVar(
1613  VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
1614  }
1615 
1616  if (Finder.SEHCodeSlot.isValid()) {
1617  SEHCodeSlotStack.push_back(
1618  recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1619  }
1620 
1621  if (IsFilter)
1622  EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
1623 }
1624 
1625 /// Arrange a function prototype that can be called by Windows exception
1626 /// handling personalities. On Win64, the prototype looks like:
1627 /// RetTy func(void *EHPtrs, void *ParentFP);
1629  bool IsFilter,
1630  const Stmt *OutlinedStmt) {
1631  SourceLocation StartLoc = OutlinedStmt->getLocStart();
1632 
1633  // Get the mangled function name.
1635  {
1636  llvm::raw_svector_ostream OS(Name);
1637  const FunctionDecl *ParentSEHFn = ParentCGF.CurSEHParent;
1638  assert(ParentSEHFn && "No CurSEHParent!");
1639  MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1640  if (IsFilter)
1641  Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
1642  else
1643  Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
1644  }
1645 
1646  FunctionArgList Args;
1647  if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1648  // All SEH finally functions take two parameters. Win64 filters take two
1649  // parameters. Win32 filters take no parameters.
1650  if (IsFilter) {
1651  Args.push_back(ImplicitParamDecl::Create(
1652  getContext(), /*DC=*/nullptr, StartLoc,
1653  &getContext().Idents.get("exception_pointers"),
1655  } else {
1656  Args.push_back(ImplicitParamDecl::Create(
1657  getContext(), /*DC=*/nullptr, StartLoc,
1658  &getContext().Idents.get("abnormal_termination"),
1660  }
1661  Args.push_back(ImplicitParamDecl::Create(
1662  getContext(), /*DC=*/nullptr, StartLoc,
1663  &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
1665  }
1666 
1667  QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1668 
1669  const CGFunctionInfo &FnInfo =
1670  CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
1671 
1672  llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1673  llvm::Function *Fn = llvm::Function::Create(
1674  FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
1675 
1676  IsOutlinedSEHHelper = true;
1677 
1678  StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1679  OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
1680  CurSEHParent = ParentCGF.CurSEHParent;
1681 
1682  CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
1683  EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
1684 }
1685 
1686 /// Create a stub filter function that will ultimately hold the code of the
1687 /// filter expression. The EH preparation passes in LLVM will outline the code
1688 /// from the main function body into this stub.
1689 llvm::Function *
1691  const SEHExceptStmt &Except) {
1692  const Expr *FilterExpr = Except.getFilterExpr();
1693  startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
1694 
1695  // Emit the original filter expression, convert to i32, and return.
1696  llvm::Value *R = EmitScalarExpr(FilterExpr);
1697  R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
1698  FilterExpr->getType()->isSignedIntegerType());
1700 
1701  FinishFunction(FilterExpr->getLocEnd());
1702 
1703  return CurFn;
1704 }
1705 
1706 llvm::Function *
1708  const SEHFinallyStmt &Finally) {
1709  const Stmt *FinallyBlock = Finally.getBlock();
1710  startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
1711 
1712  // Emit the original filter expression, convert to i32, and return.
1713  EmitStmt(FinallyBlock);
1714 
1715  FinishFunction(FinallyBlock->getLocEnd());
1716 
1717  return CurFn;
1718 }
1719 
1721  llvm::Value *ParentFP,
1722  llvm::Value *EntryFP) {
1723  // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1724  // __exception_info intrinsic.
1725  if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1726  // On Win64, the info is passed as the first parameter to the filter.
1727  SEHInfo = &*CurFn->arg_begin();
1728  SEHCodeSlotStack.push_back(
1729  CreateMemTemp(getContext().IntTy, "__exception_code"));
1730  } else {
1731  // On Win32, the EBP on entry to the filter points to the end of an
1732  // exception registration object. It contains 6 32-bit fields, and the info
1733  // pointer is stored in the second field. So, GEP 20 bytes backwards and
1734  // load the pointer.
1735  SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
1736  SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
1739  ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1740  }
1741 
1742  // Save the exception code in the exception slot to unify exception access in
1743  // the filter function and the landing pad.
1744  // struct EXCEPTION_POINTERS {
1745  // EXCEPTION_RECORD *ExceptionRecord;
1746  // CONTEXT *ContextRecord;
1747  // };
1748  // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
1749  llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1750  llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
1751  llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
1752  llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
1755  assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1756  Builder.CreateStore(Code, SEHCodeSlotStack.back());
1757 }
1758 
1760  // Sema should diagnose calling this builtin outside of a filter context, but
1761  // don't crash if we screw up.
1762  if (!SEHInfo)
1763  return llvm::UndefValue::get(Int8PtrTy);
1764  assert(SEHInfo->getType() == Int8PtrTy);
1765  return SEHInfo;
1766 }
1767 
1769  assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1770  return Builder.CreateLoad(SEHCodeSlotStack.back());
1771 }
1772 
1774  // Abnormal termination is just the first parameter to the outlined finally
1775  // helper.
1776  auto AI = CurFn->arg_begin();
1777  return Builder.CreateZExt(&*AI, Int32Ty);
1778 }
1779 
1781  CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1782  if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
1783  // Outline the finally block.
1784  llvm::Function *FinallyFunc =
1785  HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
1786 
1787  // Push a cleanup for __finally blocks.
1788  EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
1789  return;
1790  }
1791 
1792  // Otherwise, we must have an __except block.
1793  const SEHExceptStmt *Except = S.getExceptHandler();
1794  assert(Except);
1795  EHCatchScope *CatchScope = EHStack.pushCatch(1);
1796  SEHCodeSlotStack.push_back(
1797  CreateMemTemp(getContext().IntTy, "__exception_code"));
1798 
1799  // If the filter is known to evaluate to 1, then we can use the clause
1800  // "catch i8* null". We can't do this on x86 because the filter has to save
1801  // the exception code.
1802  llvm::Constant *C =
1803  CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
1804  if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
1805  C->isOneValue()) {
1806  CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1807  return;
1808  }
1809 
1810  // In general, we have to emit an outlined filter function. Use the function
1811  // in place of the RTTI typeinfo global that C++ EH uses.
1812  llvm::Function *FilterFunc =
1813  HelperCGF.GenerateSEHFilterFunction(*this, *Except);
1814  llvm::Constant *OpaqueFunc =
1815  llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1816  CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
1817 }
1818 
1820  // Just pop the cleanup if it's a __finally block.
1821  if (S.getFinallyHandler()) {
1822  PopCleanupBlock();
1823  return;
1824  }
1825 
1826  // Otherwise, we must have an __except block.
1827  const SEHExceptStmt *Except = S.getExceptHandler();
1828  assert(Except && "__try must have __finally xor __except");
1829  EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1830 
1831  // Don't emit the __except block if the __try block lacked invokes.
1832  // TODO: Model unwind edges from instructions, either with iload / istore or
1833  // a try body function.
1834  if (!CatchScope.hasEHBranches()) {
1835  CatchScope.clearHandlerBlocks();
1836  EHStack.popCatch();
1837  SEHCodeSlotStack.pop_back();
1838  return;
1839  }
1840 
1841  // The fall-through block.
1842  llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1843 
1844  // We just emitted the body of the __try; jump to the continue block.
1845  if (HaveInsertPoint())
1846  Builder.CreateBr(ContBB);
1847 
1848  // Check if our filter function returned true.
1849  emitCatchDispatchBlock(*this, CatchScope);
1850 
1851  // Grab the block before we pop the handler.
1852  llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
1853  EHStack.popCatch();
1854 
1855  EmitBlockAfterUses(CatchPadBB);
1856 
1857  // __except blocks don't get outlined into funclets, so immediately do a
1858  // catchret.
1859  llvm::CatchPadInst *CPI =
1860  cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
1861  llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
1862  Builder.CreateCatchRet(CPI, ExceptBB);
1863  EmitBlock(ExceptBB);
1864 
1865  // On Win64, the exception code is returned in EAX. Copy it into the slot.
1866  if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1867  llvm::Function *SEHCodeIntrin =
1868  CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
1869  llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
1870  Builder.CreateStore(Code, SEHCodeSlotStack.back());
1871  }
1872 
1873  // Emit the __except body.
1874  EmitStmt(Except->getBlock());
1875 
1876  // End the lifetime of the exception code.
1877  SEHCodeSlotStack.pop_back();
1878 
1879  if (HaveInsertPoint())
1880  Builder.CreateBr(ContBB);
1881 
1882  EmitBlock(ContBB);
1883 }
1884 
1886  // If this code is reachable then emit a stop point (if generating
1887  // debug info). We have to do this ourselves because we are on the
1888  // "simple" statement path.
1889  if (HaveInsertPoint())
1890  EmitStopPoint(&S);
1891 
1892  // This must be a __leave from a __finally block, which we warn on and is UB.
1893  // Just emit unreachable.
1894  if (!isSEHTryScope()) {
1895  Builder.CreateUnreachable();
1896  Builder.ClearInsertionPoint();
1897  return;
1898  }
1899 
1901 }
virtual void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl, raw_ostream &Out)=0
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition: CGCall.cpp:636
void pushTerminate()
Push a terminate handler on the stack.
Definition: CGCleanup.cpp:259
ReturnValueSlot - Contains the address where the return value of a function can be stored...
Definition: CGCall.h:281
QualType getExceptionType(unsigned i) const
Definition: Type.h:3402
iterator end() const
Returns an iterator pointing to the outermost EH scope.
Definition: CGCleanup.h:571
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1618
llvm::IntegerType * IntTy
int
Parameter for captured context.
Definition: Decl.h:1395
virtual void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E)=0
void setCatchAllHandler(unsigned I, llvm::BasicBlock *Block)
Definition: CGCleanup.h:193
CanQualType VoidPtrTy
Definition: ASTContext.h:978
A (possibly-)qualified type.
Definition: Type.h:616
void EmitSEHLeaveStmt(const SEHLeaveStmt &S)
llvm::Type * ConvertTypeForMem(QualType T)
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:26
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:187
llvm::Module & getModule() const
llvm::LLVMContext & getLLVMContext()
static const EHPersonality GNU_C_SJLJ
Definition: CGCleanup.h:616
void EmitCXXTryStmt(const CXXTryStmt &S)
Stmt - This represents one statement.
Definition: Stmt.h:60
CXXCatchStmt * getHandler(unsigned i)
Definition: StmtCXX.h:104
static const EHPersonality MSVC_C_specific_handler
Definition: CGCleanup.h:628
const TargetInfo & getTarget() const
llvm::Value * getFilter(unsigned i) const
Definition: CGCleanup.h:468
static const EHPersonality MSVC_CxxFrameHandler3
Definition: CGCleanup.h:629
static stable_iterator stable_end()
Create a stable reference to the bottom of the EH stack.
Definition: EHScopeStack.h:384
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition: Format.cpp:1948
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:81
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
static const EHPersonality GNU_C
Definition: CGCleanup.h:615
virtual void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl, raw_ostream &Out)=0
Represents Objective-C's @throw statement.
Definition: StmtObjC.h:313
CanQualType LongTy
Definition: ASTContext.h:971
static llvm::Constant * getUnexpectedFn(CodeGenModule &CGM)
Definition: CGException.cpp:41
void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF, llvm::Value *ParentFP, llvm::Value *EntryEBP)
static llvm::Constant * getPersonalityFn(CodeGenModule &CGM, const EHPersonality &Personality)
void ForceCleanup(std::initializer_list< llvm::Value ** > ValuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
const LangOptions & getLangOpts() const
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
CompoundStmt * getBlock() const
Definition: Stmt.h:1936
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI ...
Definition: ObjCRuntime.h:50
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:758
llvm::BasicBlock * EmitLandingPad()
Emits a landing pad for the current EH stack.
A protected scope for zero-cost EH handling.
Definition: CGCleanup.h:44
Defines the Objective-C statement AST node classes.
llvm::BasicBlock * getCachedEHDispatchBlock() const
Definition: CGCleanup.h:124
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:928
static bool useLibGCCSEHPersonality(const llvm::Triple &T)
On Win64, use libgcc's SEH personality function.
A scope which attempts to handle some, possibly all, types of exceptions.
Definition: CGCleanup.h:148
The collection of all-type qualifiers we support.
Definition: Type.h:118
A jump destination is an abstract label, branching to which may require a jump out through normal cle...
bool isNoexceptExceptionSpec(ExceptionSpecificationType ESpecType)
void popCatchScope()
popCatchScope - Pops the catch scope at the top of the EHScope stack, emitting any required code (oth...
llvm::BasicBlock * getTerminateHandler()
getTerminateHandler - Return a handler (not a landing pad, just a catch handler) that just calls term...
bool requiresLandingPad() const
Definition: CGCleanup.cpp:159
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition: ObjCRuntime.h:37
const char * CatchallRethrowFn
Definition: CGCleanup.h:610
Kind getKind() const
Definition: CGCleanup.h:114
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1813
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:128
SmallVector< Address, 1 > SEHCodeSlotStack
A stack of exception code slots.
static const EHPersonality GNU_CPlusPlus_SJLJ
Definition: CGCleanup.h:625
const FunctionDecl * CurSEHParent
llvm::CallInst * EmitRuntimeCall(llvm::Value *callee, const Twine &name="")
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:81
llvm::Value * SEHInfo
Value returned by __exception_info intrinsic.
bool hasEHBranches() const
Definition: CGCleanup.h:132
static const EHPersonality & get(CodeGenModule &CGM, const FunctionDecl *FD)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
Address getExceptionSlot()
Returns a pointer to the function's exception object and selector slot, which is assigned in every la...
Expr * getFilterExpr() const
Definition: Stmt.h:1896
void setFilter(unsigned i, llvm::Value *filterValue)
Definition: CGCleanup.h:463
class EHCatchScope * pushCatch(unsigned NumHandlers)
Push a set of catch handlers on the stack.
Definition: CGCleanup.cpp:251
const Handler & getHandler(unsigned I) const
Definition: CGCleanup.h:209
iterator begin() const
Returns an iterator pointing to the innermost EH scope.
Definition: CGCleanup.h:567
static llvm::Constant * getFreeExceptionFn(CodeGenModule &CGM)
Definition: CGException.cpp:32
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1043
static llvm::Constant * getCatchAllValue(CodeGenFunction &CGF)
Returns the value to inject into a selector to indicate the presence of a catch-all.
void ExitSEHTryStmt(const SEHTryStmt &S)
Stmt * getHandlerBlock() const
Definition: StmtCXX.h:52
child_range children()
Definition: Stmt.cpp:208
static const EHPersonality GNUstep_ObjC
Definition: CGCleanup.h:621
bool IsOutlinedSEHHelper
True if the current function is an outlined SEH helper.
llvm::Constant * getTerminateFn()
Get the declaration of std::terminate for the platform.
Definition: CGException.cpp:50
llvm::BasicBlock * getInvokeDestImpl()
llvm::Function * GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF, const SEHFinallyStmt &Finally)
void EmitStmt(const Stmt *S)
EmitStmt - Emit the code for the statement.
Definition: CGStmt.cpp:48
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
Definition: EHScopeStack.h:85
void popFilter()
Pops an exceptions filter off the stack.
Definition: CGCleanup.cpp:242
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1279
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
This represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:3726
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition: CGExpr.cpp:90
detail::InMemoryDirectory::const_iterator I
llvm::AllocaInst * EHSelectorSlot
The selector slot.
CanQualType UnsignedCharTy
Definition: ASTContext.h:972
QualType getType() const
Definition: Decl.h:589
Represents the this expression in C++.
Definition: ExprCXX.h:888
iterator find(stable_iterator save) const
Turn a stable reference to a scope depth into a unstable pointer to the EH stack. ...
Definition: CGCleanup.h:591
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false)
Create a new runtime function with the specified type and name.
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition: Decl.cpp:4161
llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, ArrayRef< llvm::Value * > args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
Definition: CGCall.cpp:3644
'watchos' is a variant of iOS for Apple's watchOS.
Definition: ObjCRuntime.h:46
bool hasTerminate() const
Does this runtime provide an objc_terminate function?
Definition: ObjCRuntime.h:257
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3129
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:3371
llvm::CallInst * EmitNounwindRuntimeCall(llvm::Value *callee, const Twine &name="")
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
Definition: CGExpr.cpp:198
static const EHPersonality MSVC_except_handler
Definition: CGCleanup.h:627
static llvm::Constant * getOpaquePersonalityFn(CodeGenModule &CGM, const EHPersonality &Personality)
const TargetInfo & getTarget() const
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Stmt.cpp:270
ASTContext * Context
bool usesSEHTry() const
Indicates the function uses __try.
Definition: Decl.h:1957
iterator begin() const
Definition: CGCleanup.h:224
llvm::Value * ExceptionSlot
The exception slot.
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
void SetLLVMFunctionAttributes(const Decl *D, const CGFunctionInfo &Info, llvm::Function *F)
Set the LLVM function attributes (sext, zext, etc).
bool isNeXTFamily() const
Is this runtime basically of the NeXT family of runtimes?
Definition: ObjCRuntime.h:133
llvm::Value * getPointer() const
Definition: Address.h:38
llvm::BasicBlock * EHResumeBlock
EHResumeBlock - Unified block containing a call to llvm.eh.resume.
bool empty() const
Determines whether the exception-scopes stack is empty.
Definition: EHScopeStack.h:345
CatchTypeInfo Type
A type info value, or null (C++ null, not an LLVM null pointer) for a catch-all.
Definition: CGCleanup.h:158
void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt, bool IsFilter)
Scan the outlined statement for captures from the parent function.
Expr - This represents one expression.
Definition: Expr.h:105
void enter(CodeGenFunction &CGF, const Stmt *Finally, llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn, llvm::Constant *rethrowFn)
Enters a finally block for an implementation using zero-cost exceptions.
static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn)
Check whether a personality function could reasonably be swapped for a C++ personality function...
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Definition: ObjCRuntime.h:32
static Address invalid()
Definition: Address.h:35
CGCXXABI & getCXXABI() const
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited...
llvm::Function * GenerateSEHFilterFunction(CodeGenFunction &ParentCGF, const SEHExceptStmt &Except)
Create a stub filter function that will ultimately hold the code of the filter expression.
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:125
virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S, bool ClearInsertionPoint=true)=0
void EmitSEHTryStmt(const SEHTryStmt &S)
ASTContext & getContext() const
llvm::BasicBlock * getBlock() const
llvm::BasicBlock * Block
The catch handler for this type.
Definition: CGCleanup.h:161
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
CXXTryStmt - A C++ try block, including all handlers.
Definition: StmtCXX.h:65
void add(RValue rvalue, QualType type, bool needscopy=false)
Definition: CGCall.h:207
llvm::Value * getExceptionFromSlot()
Returns the contents of the function's exception object and selector slots.
static void emitCatchDispatchBlock(CodeGenFunction &CGF, EHCatchScope &catchScope)
Emit the structure of the dispatch block for the given catch scope.
EHScopeStack::stable_iterator getEnclosingEHScope() const
Definition: CGCleanup.h:138
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:379
llvm::BasicBlock * getCachedLandingPad() const
Definition: CGCleanup.h:116
llvm::LLVMContext & getLLVMContext()
const CGFunctionInfo & arrangeBuiltinFunctionCall(QualType resultType, const CallArgList &args)
Definition: CGCall.cpp:623
static const EHPersonality & getObjCXXPersonality(const llvm::Triple &T, const LangOptions &L)
Determines the personality function to use when both C++ and Objective-C exceptions are being caught...
static const EHPersonality GNU_ObjCXX
Definition: CGCleanup.h:622
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:116
static const EHPersonality GNU_ObjC_SEH
Definition: CGCleanup.h:620
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys=None)
bool usesFuncletPads() const
Does this personality use landingpads or the family of pad instructions designed to form funclets...
Definition: CGCleanup.h:633
ValueDecl * getDecl()
Definition: Expr.h:1038
virtual CatchTypeInfo getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType)=0
'gnustep' is the modern non-fragile GNUstep runtime.
Definition: ObjCRuntime.h:53
llvm::StoreInst * CreateFlagStore(bool Value, llvm::Value *Addr)
Emit a store to an i1 flag variable.
Definition: CGBuilder.h:136
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:29
void popCatch()
Pops a catch scope off the stack. This is private to CGException.cpp.
Definition: CGCleanup.h:575
llvm::BasicBlock * getEHDispatchBlock(EHScopeStack::stable_iterator scope)
The l-value was considered opaque, so the alignment was determined from a type.
static void emitFilterDispatchBlock(CodeGenFunction &CGF, EHFilterScope &filterScope)
Emit the dispatch block for a filter scope if necessary.
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF, Address ParentVar, llvm::Value *ParentFP)
Recovers the address of a local in a parent function.
ASTMatchFinder *const Finder
Enumerates target-specific builtins in their own namespaces within namespace clang.
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Definition: CGBuilder.h:142
virtual void emitRethrow(CodeGenFunction &CGF, bool isNoReturn)=0
static const EHPersonality & getObjCPersonality(const llvm::Triple &T, const LangOptions &L)
llvm::Constant * EmitConstantExpr(const Expr *E, QualType DestType, CodeGenFunction *CGF=nullptr)
Try to emit the given expression as a constant; returns 0 if the expression cannot be emitted as a co...
ASTContext & getContext() const
Encodes a location in the source.
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go...
A saved depth on the scope stack.
Definition: EHScopeStack.h:107
'objfw' is the Objective-C runtime included in ObjFW
Definition: ObjCRuntime.h:56
llvm::BasicBlock * getUnreachableBlock()
const std::string ID
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr * > VL, ArrayRef< Expr * > PL, ArrayRef< Expr * > IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1162
void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *DominatingIP)
DeactivateCleanupBlock - Deactivates the given cleanup block.
Definition: CGCleanup.cpp:1230
CompoundStmt * getBlock() const
Definition: Stmt.h:1900
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:42
virtual CatchTypeInfo getCatchAllTypeInfo()
Definition: CGCXXABI.cpp:298
The noexcept specifier evaluates to true.
Definition: Type.h:3397
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
CanQualType VoidTy
Definition: ASTContext.h:963
An aligned address.
Definition: Address.h:25
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
const LangOptions & getLangOpts() const
llvm::BasicBlock * getEHResumeBlock(bool isCleanup)
SEHExceptStmt * getExceptHandler() const
Returns 0 if not defined.
Definition: Stmt.cpp:930
const VersionTuple & getVersion() const
Definition: ObjCRuntime.h:76
NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const
Get the meaning of the noexcept spec on this function, if any.
Definition: Type.cpp:2779
void setCachedEHDispatchBlock(llvm::BasicBlock *block)
Definition: CGCleanup.h:128
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:96
llvm::Instruction * CurrentFuncletPad
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
llvm::StringRef getName() const
Return the IR name of the pointer value.
Definition: Address.h:62
void EmitStartEHSpec(const Decl *D)
EmitStartEHSpec - Emit the start of the exception spec.
unsigned getNumHandlers() const
Definition: CGCleanup.h:189
The MS C++ ABI needs a pointer to RTTI data plus some flags to describe the type of a catch handler...
Definition: CGCleanup.h:38
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
static const EHPersonality & getCXXPersonality(const llvm::Triple &T, const LangOptions &L)
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
static const EHPersonality NeXT_ObjC
Definition: CGCleanup.h:623
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type, returning the result.
FunctionArgList - Type for representing both the decl and type of parameters to a function...
Definition: CGCall.h:276
QualType getType() const
Definition: Expr.h:127
llvm::BasicBlock * getMSVCDispatchBlock(EHScopeStack::stable_iterator scope)
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
CGFunctionInfo - Class to encapsulate the information about a function definition.
CharUnits getAlignment() const
Return the alignment of this pointer.
Definition: Address.h:67
This class organizes the cross-function state that is used while generating LLVM code.
class EHFilterScope * pushFilter(unsigned NumFilters)
Push an exceptions filter on the stack.
Definition: CGCleanup.cpp:234
const Expr * getSubExpr() const
Definition: ExprCXX.h:948
static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF, SourceLocation TemporaryLocation)
Apply TemporaryLocation if it is valid.
Definition: CGDebugInfo.h:655
static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI)
Check whether a landingpad instruction only uses C++ features.
StringRef Name
Definition: USRFinder.cpp:123
static const EHPersonality GNU_CPlusPlus_SEH
Definition: CGCleanup.h:626
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:25
static const EHPersonality GNU_ObjC
Definition: CGCleanup.h:618
Address CreateStructGEP(Address Addr, unsigned Index, CharUnits Offset, const llvm::Twine &Name="")
Definition: CGBuilder.h:165
static bool isNonEHScope(const EHScope &S)
Check whether this is a non-EH scope, i.e.
void EmitAnyExprToExn(const Expr *E, Address Addr)
llvm::LoadInst * CreateAlignedLoad(llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:91
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:70
unsigned getNumHandlers() const
Definition: StmtCXX.h:103
QualType getCaughtType() const
Definition: StmtCXX.cpp:20
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:792
detail::InMemoryDirectory::const_iterator E
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:108
bool isSEHTryScope() const
Returns true inside SEH __try blocks.
Represents a __leave statement.
Definition: Stmt.h:1998
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:5662
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
Definition: ObjCRuntime.h:42
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:44
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:6042
static const EHPersonality GNU_CPlusPlus
Definition: CGCleanup.h:624
llvm::LoadInst * CreateFlagLoad(llvm::Value *Addr, const llvm::Twine &Name="")
Emit a load from an i1 flag variable.
Definition: CGBuilder.h:129
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
static const EHPersonality GNU_ObjC_SJLJ
Definition: CGCleanup.h:619
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:33
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:436
void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock=false)
void EmitStopPoint(const Stmt *S)
EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
Definition: CGStmt.cpp:38
Kind getKind() const
Definition: ObjCRuntime.h:75
static const EHPersonality & getSEHPersonalityMSVC(const llvm::Triple &T)
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5569
bool isObjCObjectPointerType() const
Definition: Type.h:5784
llvm::BasicBlock * getTerminateLandingPad()
getTerminateLandingPad - Return a landing pad that just calls terminate.
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:29
llvm::Type * ConvertType(QualType T)
static const EHPersonality GNU_C_SEH
Definition: CGCleanup.h:617
static const EHPersonality & getCPersonality(const llvm::Triple &T, const LangOptions &L)
The exceptions personality for a function.
Definition: CGCleanup.h:604
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
void popTerminate()
Pops a terminate handler off the stack.
Definition: CGCleanup.h:583
llvm::Constant * RTTI
Definition: CGCleanup.h:39
CompoundStmt * getTryBlock()
Definition: StmtCXX.h:96
llvm::Value * EmitSEHAbnormalTermination()
virtual llvm::CallInst * emitTerminateForUnexpectedException(CodeGenFunction &CGF, llvm::Value *Exn)
Definition: CGCXXABI.cpp:292
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2206
void EnterSEHTryStmt(const SEHTryStmt &S)
void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter, const Stmt *OutlinedStmt)
Arrange a function prototype that can be called by Windows exception handling personalities.
unsigned getNumFilters() const
Definition: CGCleanup.h:461
stable_iterator getInnermostEHScope() const
Definition: EHScopeStack.h:361
CanQualType IntTy
Definition: ASTContext.h:971
An exceptions scope which filters exceptions thrown through it.
Definition: CGCleanup.h:438
VarDecl * getExceptionDecl() const
Definition: StmtCXX.h:50
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:953
static RValue get(llvm::Value *V)
Definition: CGValue.h:85
const llvm::Triple & getTriple() const
void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock=false)
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
Definition: CGCleanup.cpp:1034
void EmitEndEHSpec(const Decl *D)
EmitEndEHSpec - Emit the end of the exception spec.
virtual void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C)=0
static llvm::Constant * getCatchallRethrowFn(CodeGenModule &CGM, StringRef Name)
Definition: CGException.cpp:76
llvm::StoreInst * CreateAlignedStore(llvm::Value *Val, llvm::Value *Addr, CharUnits Align, bool IsVolatile=false)
Definition: CGBuilder.h:115
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:147
CompoundStmt * getTryBlock() const
Definition: Stmt.h:1977
A non-stable pointer into the scope stack.
Definition: CGCleanup.h:503
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
Definition: Type.cpp:1744
void EmitBlockAfterUses(llvm::BasicBlock *BB)
EmitBlockAfterUses - Emit the given block somewhere hopefully near its uses, and leave the insertion ...
Definition: CGStmt.cpp:473
static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope)
virtual llvm::Constant * GetEHType(QualType T)=0
Get the type constant to catch for the given ObjC pointer type.
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:257
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:182
Address CreateMemTemp(QualType T, const Twine &Name="tmp", bool CastToDefaultAddrSpace=true)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignment...
Definition: CGExpr.cpp:123
void PopCleanupBlock(bool FallThroughIsBranchThrough=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
Definition: CGCleanup.cpp:640
void setHandler(unsigned I, llvm::Constant *Type, llvm::BasicBlock *Block)
Definition: CGCleanup.h:197
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals...
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::Instruction **callOrInvoke=nullptr)
EmitCall - Generate a call of the given function, expecting the given result type, and using the given argument list which specifies both the LLVM arguments and the types they were derived from.
Definition: CGCall.cpp:3695
llvm::SmallVector< const JumpDest *, 2 > SEHTryEpilogueStack
SEHFinallyStmt * getFinallyHandler() const
Definition: Stmt.cpp:934
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5516
unsigned getNumExceptions() const
Definition: Type.h:3401
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1519