Coverage Report

Created: 2020-09-22 08:39

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGException.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGException.cpp - Emit LLVM Code for C++ exceptions ----*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This contains code dealing with C++ exception related code generation.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGCXXABI.h"
14
#include "CGCleanup.h"
15
#include "CGObjCRuntime.h"
16
#include "CodeGenFunction.h"
17
#include "ConstantEmitter.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"
23
#include "clang/Basic/DiagnosticSema.h"
24
#include "clang/Basic/TargetBuiltins.h"
25
#include "llvm/IR/IntrinsicInst.h"
26
#include "llvm/IR/Intrinsics.h"
27
#include "llvm/IR/IntrinsicsWebAssembly.h"
28
#include "llvm/Support/SaveAndRestore.h"
29
30
using namespace clang;
31
using namespace CodeGen;
32
33
275
static llvm::FunctionCallee getFreeExceptionFn(CodeGenModule &CGM) {
34
  // void __cxa_free_exception(void *thrown_exception);
35
36
275
  llvm::FunctionType *FTy =
37
275
    llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
38
39
275
  return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
40
275
}
41
42
28
static llvm::FunctionCallee getUnexpectedFn(CodeGenModule &CGM) {
43
  // void __cxa_call_unexpected(void *thrown_exception);
44
45
28
  llvm::FunctionType *FTy =
46
28
    llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
47
48
28
  return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
49
28
}
50
51
659
llvm::FunctionCallee CodeGenModule::getTerminateFn() {
52
  // void __terminate();
53
54
659
  llvm::FunctionType *FTy =
55
659
    llvm::FunctionType::get(VoidTy, /*isVarArg=*/false);
56
57
659
  StringRef name;
58
59
  // In C++, use std::terminate().
60
659
  if (getLangOpts().CPlusPlus &&
61
656
      getTarget().getCXXABI().isItaniumFamily()) {
62
644
    name = "_ZSt9terminatev";
63
15
  } else if (getLangOpts().CPlusPlus &&
64
12
             getTarget().getCXXABI().isMicrosoft()) {
65
12
    if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
66
3
      name = "__std_terminate";
67
9
    else
68
9
      name = "?terminate@@YAXXZ";
69
3
  } else if (getLangOpts().ObjC &&
70
3
             getLangOpts().ObjCRuntime.hasTerminate())
71
2
    name = "objc_terminate";
72
1
  else
73
1
    name = "abort";
74
659
  return CreateRuntimeFunction(FTy, name);
75
659
}
76
77
static llvm::FunctionCallee getCatchallRethrowFn(CodeGenModule &CGM,
78
0
                                                 StringRef Name) {
79
0
  llvm::FunctionType *FTy =
80
0
    llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
81
82
0
  return CGM.CreateRuntimeFunction(FTy, Name);
83
0
}
84
85
const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
86
const EHPersonality
87
EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
88
const EHPersonality
89
EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
90
const EHPersonality
91
EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
92
const EHPersonality
93
EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
94
const EHPersonality
95
EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
96
const EHPersonality
97
EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
98
const EHPersonality
99
EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
100
const EHPersonality
101
EHPersonality::GNU_ObjC_SJLJ = {"__gnu_objc_personality_sj0", "objc_exception_throw"};
102
const EHPersonality
103
EHPersonality::GNU_ObjC_SEH = {"__gnu_objc_personality_seh0", "objc_exception_throw"};
104
const EHPersonality
105
EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
106
const EHPersonality
107
EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
108
const EHPersonality
109
EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
110
const EHPersonality
111
EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
112
const EHPersonality
113
EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
114
const EHPersonality
115
EHPersonality::GNU_Wasm_CPlusPlus = { "__gxx_wasm_personality_v0", nullptr };
116
117
static const EHPersonality &getCPersonality(const TargetInfo &Target,
118
151
                                            const LangOptions &L) {
119
151
  const llvm::Triple &T = Target.getTriple();
120
151
  if (T.isWindowsMSVCEnvironment())
121
12
    return EHPersonality::MSVC_CxxFrameHandler3;
122
139
  if (L.SjLjExceptions)
123
25
    return EHPersonality::GNU_C_SJLJ;
124
114
  if (L.DWARFExceptions)
125
15
    return EHPersonality::GNU_C;
126
99
  if (L.SEHExceptions)
127
15
    return EHPersonality::GNU_C_SEH;
128
84
  return EHPersonality::GNU_C;
129
84
}
130
131
static const EHPersonality &getObjCPersonality(const TargetInfo &Target,
132
2.20k
                                               const LangOptions &L) {
133
2.20k
  const llvm::Triple &T = Target.getTriple();
134
2.20k
  if (T.isWindowsMSVCEnvironment())
135
54
    return EHPersonality::MSVC_CxxFrameHandler3;
136
137
2.15k
  switch (L.ObjCRuntime.getKind()) {
138
79
  case ObjCRuntime::FragileMacOSX:
139
79
    return getCPersonality(Target, L);
140
1.85k
  case ObjCRuntime::MacOSX:
141
1.85k
  case ObjCRuntime::iOS:
142
1.85k
  case ObjCRuntime::WatchOS:
143
1.85k
    return EHPersonality::NeXT_ObjC;
144
31
  case ObjCRuntime::GNUstep:
145
31
    if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
146
21
      return EHPersonality::GNUstep_ObjC;
147
10
    LLVM_FALLTHROUGH;
148
191
  case ObjCRuntime::GCC:
149
191
  case ObjCRuntime::ObjFW:
150
191
    if (L.SjLjExceptions)
151
52
      return EHPersonality::GNU_ObjC_SJLJ;
152
139
    if (L.SEHExceptions)
153
44
      return EHPersonality::GNU_ObjC_SEH;
154
95
    return EHPersonality::GNU_ObjC;
155
0
  }
156
0
  llvm_unreachable("bad runtime kind");
157
0
}
158
159
static const EHPersonality &getCXXPersonality(const TargetInfo &Target,
160
37.4k
                                              const LangOptions &L) {
161
37.4k
  const llvm::Triple &T = Target.getTriple();
162
37.4k
  if (T.isWindowsMSVCEnvironment())
163
601
    return EHPersonality::MSVC_CxxFrameHandler3;
164
36.8k
  if (L.SjLjExceptions)
165
32
    return EHPersonality::GNU_CPlusPlus_SJLJ;
166
36.7k
  if (L.DWARFExceptions)
167
37
    return EHPersonality::GNU_CPlusPlus;
168
36.7k
  if (L.SEHExceptions)
169
37
    return EHPersonality::GNU_CPlusPlus_SEH;
170
36.7k
  if (L.WasmExceptions)
171
822
    return EHPersonality::GNU_Wasm_CPlusPlus;
172
35.8k
  return EHPersonality::GNU_CPlusPlus;
173
35.8k
}
174
175
/// Determines the personality function to use when both C++
176
/// and Objective-C exceptions are being caught.
177
static const EHPersonality &getObjCXXPersonality(const TargetInfo &Target,
178
1.61k
                                                 const LangOptions &L) {
179
1.61k
  if (Target.getTriple().isWindowsMSVCEnvironment())
180
78
    return EHPersonality::MSVC_CxxFrameHandler3;
181
182
1.53k
  switch (L.ObjCRuntime.getKind()) {
183
  // In the fragile ABI, just use C++ exception handling and hope
184
  // they're not doing crazy exception mixing.
185
91
  case ObjCRuntime::FragileMacOSX:
186
91
    return getCXXPersonality(Target, L);
187
188
  // The ObjC personality defers to the C++ personality for non-ObjC
189
  // handlers.  Unlike the C++ case, we use the same personality
190
  // function on targets using (backend-driven) SJLJ EH.
191
1.28k
  case ObjCRuntime::MacOSX:
192
1.28k
  case ObjCRuntime::iOS:
193
1.28k
  case ObjCRuntime::WatchOS:
194
1.28k
    return getObjCPersonality(Target, L);
195
196
44
  case ObjCRuntime::GNUstep:
197
44
    return EHPersonality::GNU_ObjCXX;
198
199
  // The GCC runtime's personality function inherently doesn't support
200
  // mixed EH.  Use the ObjC personality just to avoid returning null.
201
112
  case ObjCRuntime::GCC:
202
112
  case ObjCRuntime::ObjFW:
203
112
    return getObjCPersonality(Target, L);
204
0
  }
205
0
  llvm_unreachable("bad runtime kind");
206
0
}
207
208
486
static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
209
486
  if (T.getArch() == llvm::Triple::x86)
210
128
    return EHPersonality::MSVC_except_handler;
211
358
  return EHPersonality::MSVC_C_specific_handler;
212
358
}
213
214
const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
215
40.1k
                                        const FunctionDecl *FD) {
216
40.1k
  const llvm::Triple &T = CGM.getTarget().getTriple();
217
40.1k
  const LangOptions &L = CGM.getLangOpts();
218
40.1k
  const TargetInfo &Target = CGM.getTarget();
219
220
  // Functions using SEH get an SEH personality.
221
40.1k
  if (FD && 
FD->usesSEHTry()38.6k
)
222
486
    return getSEHPersonalityMSVC(T);
223
224
39.6k
  if (L.ObjC)
225
2.41k
    return L.CPlusPlus ? 
getObjCXXPersonality(Target, L)1.61k
226
805
                       : getObjCPersonality(Target, L);
227
37.2k
  return L.CPlusPlus ? 
getCXXPersonality(Target, L)37.1k
228
72
                     : getCPersonality(Target, L);
229
37.2k
}
230
231
40.0k
const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
232
40.0k
  const auto *FD = CGF.CurCodeDecl;
233
  // For outlined finallys and filters, use the SEH personality in case they
234
  // contain more SEH. This mostly only affects finallys. Filters could
235
  // hypothetically use gnu statement expressions to sneak in nested SEH.
236
39.9k
  FD = FD ? FD : 
CGF.CurSEHParent89
;
237
40.0k
  return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(FD));
238
40.0k
}
239
240
static llvm::FunctionCallee getPersonalityFn(CodeGenModule &CGM,
241
7.42k
                                             const EHPersonality &Personality) {
242
7.42k
  return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
243
7.42k
                                   Personality.PersonalityFn,
244
7.42k
                                   llvm::AttributeList(), /*Local=*/true);
245
7.42k
}
246
247
static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
248
7.40k
                                        const EHPersonality &Personality) {
249
7.40k
  llvm::FunctionCallee Fn = getPersonalityFn(CGM, Personality);
250
7.40k
  llvm::PointerType* Int8PtrTy = llvm::PointerType::get(
251
7.40k
      llvm::Type::getInt8Ty(CGM.getLLVMContext()),
252
7.40k
      CGM.getDataLayout().getProgramAddressSpace());
253
254
7.40k
  return llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(Fn.getCallee()),
255
7.40k
                                        Int8PtrTy);
256
7.40k
}
257
258
/// Check whether a landingpad instruction only uses C++ features.
259
148
static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
260
179
  for (unsigned I = 0, E = LPI->getNumClauses(); I != E; 
++I31
) {
261
    // Look for something that would've been returned by the ObjC
262
    // runtime's GetEHType() method.
263
67
    llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
264
67
    if (LPI->isCatch(I)) {
265
      // Check if the catch value has the ObjC prefix.
266
67
      if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
267
        // ObjC EH selector entries are always global variables with
268
        // names starting like this.
269
38
        if (GV->getName().startswith("OBJC_EHTYPE"))
270
36
          return false;
271
0
    } else {
272
      // Check if any of the filter values have the ObjC prefix.
273
0
      llvm::Constant *CVal = cast<llvm::Constant>(Val);
274
0
      for (llvm::User::op_iterator
275
0
              II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
276
0
        if (llvm::GlobalVariable *GV =
277
0
            cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
278
          // ObjC EH selector entries are always global variables with
279
          // names starting like this.
280
0
          if (GV->getName().startswith("OBJC_EHTYPE"))
281
0
            return false;
282
0
      }
283
0
    }
284
67
  }
285
112
  return true;
286
148
}
287
288
/// Check whether a personality function could reasonably be swapped
289
/// for a C++ personality function.
290
107
static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
291
164
  for (llvm::User *U : Fn->users()) {
292
    // Conditionally white-list bitcasts.
293
164
    if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
294
54
      if (CE->getOpcode() != llvm::Instruction::BitCast) 
return false0
;
295
54
      if (!PersonalityHasOnlyCXXUses(CE))
296
37
        return false;
297
17
      continue;
298
17
    }
299
300
    // Otherwise it must be a function.
301
110
    llvm::Function *F = dyn_cast<llvm::Function>(U);
302
110
    if (!F) 
return false1
;
303
304
684
    
for (auto BB = F->begin(), E = F->end(); 109
BB != E;
++BB575
) {
305
611
      if (BB->isLandingPad())
306
148
        if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
307
36
          return false;
308
611
    }
309
109
  }
310
311
33
  return true;
312
107
}
313
314
/// Try to use the C++ personality function in ObjC++.  Not doing this
315
/// can cause some incompatibilities with gcc, which is more
316
/// aggressive about only using the ObjC++ personality in a function
317
/// when it really needs it.
318
28.8k
void CodeGenModule::SimplifyPersonality() {
319
  // If we're not in ObjC++ -fexceptions, there's nothing to do.
320
28.8k
  if (!LangOpts.CPlusPlus || 
!LangOpts.ObjC21.7k
||
!LangOpts.Exceptions10.9k
)
321
28.7k
    return;
322
323
  // Both the problem this endeavors to fix and the way the logic
324
  // above works is specific to the NeXT runtime.
325
171
  if (!LangOpts.ObjCRuntime.isNeXTFamily())
326
26
    return;
327
328
145
  const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
329
145
  const EHPersonality &CXX = getCXXPersonality(getTarget(), LangOpts);
330
145
  if (&ObjCXX == &CXX)
331
16
    return;
332
333
129
  assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
334
129
         "Different EHPersonalities using the same personality function.");
335
336
129
  llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
337
338
  // Nothing to do if it's unused.
339
129
  if (!Fn || 
Fn->use_empty()53
)
return76
;
340
341
  // Can't do the optimization if it has non-C++ uses.
342
53
  if (!PersonalityHasOnlyCXXUses(Fn)) 
return37
;
343
344
  // Create the C++ personality function and kill off the old
345
  // function.
346
16
  llvm::FunctionCallee CXXFn = getPersonalityFn(*this, CXX);
347
348
  // This can happen if the user is screwing with us.
349
16
  if (Fn->getType() != CXXFn.getCallee()->getType())
350
0
    return;
351
352
16
  Fn->replaceAllUsesWith(CXXFn.getCallee());
353
16
  Fn->eraseFromParent();
354
16
}
355
356
/// Returns the value to inject into a selector to indicate the
357
/// presence of a catch-all.
358
4.40k
static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
359
  // Possibly we should use @llvm.eh.catch.all.value here.
360
4.40k
  return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
361
4.40k
}
362
363
namespace {
364
  /// A cleanup to free the exception object if its initialization
365
  /// throws.
366
  struct FreeException final : EHScopeStack::Cleanup {
367
    llvm::Value *exn;
368
417
    FreeException(llvm::Value *exn) : exn(exn) {}
369
275
    void Emit(CodeGenFunction &CGF, Flags flags) override {
370
275
      CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
371
275
    }
372
  };
373
} // end anonymous namespace
374
375
// Emits an exception expression into the given location.  This
376
// differs from EmitAnyExprToMem only in that, if a final copy-ctor
377
// call is required, an exception within that copy ctor causes
378
// std::terminate to be invoked.
379
428
void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
380
  // Make sure the exception object is cleaned up if there's an
381
  // exception during initialization.
382
428
  pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
383
428
  EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
384
385
  // __cxa_allocate_exception returns a void*;  we need to cast this
386
  // to the appropriate type for the object.
387
428
  llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
388
428
  Address typedAddr = Builder.CreateBitCast(addr, ty);
389
390
  // FIXME: this isn't quite right!  If there's a final unelided call
391
  // to a copy constructor, then according to [except.terminate]p1 we
392
  // must call std::terminate() if that constructor throws, because
393
  // technically that copy occurs after the exception expression is
394
  // evaluated but before the exception is caught.  But the best way
395
  // to handle that is to teach EmitAggExpr to do the final copy
396
  // differently if it can't be elided.
397
428
  EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
398
428
                   /*IsInit*/ true);
399
400
  // Deactivate the cleanup block.
401
428
  DeactivateCleanupBlock(cleanup,
402
428
                         cast<llvm::Instruction>(typedAddr.getPointer()));
403
428
}
404
405
10.4k
Address CodeGenFunction::getExceptionSlot() {
406
10.4k
  if (!ExceptionSlot)
407
3.71k
    ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
408
10.4k
  return Address(ExceptionSlot, getPointerAlign());
409
10.4k
}
410
411
9.79k
Address CodeGenFunction::getEHSelectorSlot() {
412
9.79k
  if (!EHSelectorSlot)
413
3.63k
    EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
414
9.79k
  return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
415
9.79k
}
416
417
4.15k
llvm::Value *CodeGenFunction::getExceptionFromSlot() {
418
4.15k
  return Builder.CreateLoad(getExceptionSlot(), "exn");
419
4.15k
}
420
421
3.56k
llvm::Value *CodeGenFunction::getSelectorFromSlot() {
422
3.56k
  return Builder.CreateLoad(getEHSelectorSlot(), "sel");
423
3.56k
}
424
425
void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
426
514
                                       bool KeepInsertionPoint) {
427
514
  if (const Expr *SubExpr = E->getSubExpr()) {
428
469
    QualType ThrowType = SubExpr->getType();
429
469
    if (ThrowType->isObjCObjectPointerType()) {
430
1
      const Stmt *ThrowStmt = E->getSubExpr();
431
1
      const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
432
1
      CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
433
468
    } else {
434
468
      CGM.getCXXABI().emitThrow(*this, E);
435
468
    }
436
45
  } else {
437
45
    CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
438
45
  }
439
440
  // throw is an expression, and the expression emitters expect us
441
  // to leave ourselves at a valid insertion point.
442
514
  if (KeepInsertionPoint)
443
512
    EmitBlock(createBasicBlock("throw.cont"));
444
514
}
445
446
287k
void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
447
287k
  if (!CGM.getLangOpts().CXXExceptions)
448
203k
    return;
449
450
84.4k
  const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
451
84.4k
  if (!FD) {
452
    // Check if CapturedDecl is nothrow and create terminate scope for it.
453
2.24k
    if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
454
718
      if (CD->isNothrow())
455
704
        EHStack.pushTerminate();
456
718
    }
457
2.24k
    return;
458
2.24k
  }
459
82.2k
  const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
460
82.2k
  if (!Proto)
461
0
    return;
462
463
82.2k
  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
464
82.2k
  if (isNoexceptExceptionSpec(EST) && 
Proto->canThrow() == CT_Cannot44.5k
) {
465
    // noexcept functions are simple terminate scopes.
466
44.0k
    EHStack.pushTerminate();
467
38.1k
  } else if (EST == EST_Dynamic || 
EST == EST_DynamicNone38.1k
) {
468
    // TODO: Revisit exception specifications for the MS ABI.  There is a way to
469
    // encode these in an object file but MSVC doesn't do anything with it.
470
102
    if (getTarget().getCXXABI().isMicrosoft())
471
1
      return;
472
    // In wasm we currently treat 'throw()' in the same way as 'noexcept'. In
473
    // case of throw with types, we ignore it and print a warning for now.
474
    // TODO Correctly handle exception specification in wasm
475
101
    if (CGM.getLangOpts().WasmExceptions) {
476
12
      if (EST == EST_DynamicNone)
477
6
        EHStack.pushTerminate();
478
6
      else
479
6
        CGM.getDiags().Report(D->getLocation(),
480
6
                              diag::warn_wasm_dynamic_exception_spec_ignored)
481
6
            << FD->getExceptionSpecSourceRange();
482
12
      return;
483
12
    }
484
89
    unsigned NumExceptions = Proto->getNumExceptions();
485
89
    EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
486
487
115
    for (unsigned I = 0; I != NumExceptions; 
++I26
) {
488
26
      QualType Ty = Proto->getExceptionType(I);
489
26
      QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
490
26
      llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
491
26
                                                        /*ForEH=*/true);
492
26
      Filter->setFilter(I, EHType);
493
26
    }
494
89
  }
495
82.2k
}
496
497
/// Emit the dispatch block for a filter scope if necessary.
498
static void emitFilterDispatchBlock(CodeGenFunction &CGF,
499
89
                                    EHFilterScope &filterScope) {
500
89
  llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
501
89
  if (!dispatchBlock) 
return61
;
502
28
  if (dispatchBlock->use_empty()) {
503
0
    delete dispatchBlock;
504
0
    return;
505
0
  }
506
507
28
  CGF.EmitBlockAfterUses(dispatchBlock);
508
509
  // If this isn't a catch-all filter, we need to check whether we got
510
  // here because the filter triggered.
511
28
  if (filterScope.getNumFilters()) {
512
    // Load the selector value.
513
25
    llvm::Value *selector = CGF.getSelectorFromSlot();
514
25
    llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
515
516
25
    llvm::Value *zero = CGF.Builder.getInt32(0);
517
25
    llvm::Value *failsFilter =
518
25
        CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
519
25
    CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
520
25
                             CGF.getEHResumeBlock(false));
521
522
25
    CGF.EmitBlock(unexpectedBB);
523
25
  }
524
525
  // Call __cxa_call_unexpected.  This doesn't need to be an invoke
526
  // because __cxa_call_unexpected magically filters exceptions
527
  // according to the last landing pad the exception was thrown
528
  // into.  Seriously.
529
28
  llvm::Value *exn = CGF.getExceptionFromSlot();
530
28
  CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
531
28
    ->setDoesNotReturn();
532
28
  CGF.Builder.CreateUnreachable();
533
28
}
534
535
287k
void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
536
287k
  if (!CGM.getLangOpts().CXXExceptions)
537
203k
    return;
538
539
84.4k
  const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
540
84.4k
  if (!FD) {
541
    // Check if CapturedDecl is nothrow and pop terminate scope for it.
542
2.24k
    if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
543
718
      if (CD->isNothrow())
544
704
        EHStack.popTerminate();
545
718
    }
546
2.24k
    return;
547
2.24k
  }
548
82.2k
  const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
549
82.2k
  if (!Proto)
550
0
    return;
551
552
82.2k
  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
553
82.2k
  if (isNoexceptExceptionSpec(EST) && 
Proto->canThrow() == CT_Cannot44.5k
) {
554
44.0k
    EHStack.popTerminate();
555
38.1k
  } else if (EST == EST_Dynamic || 
EST == EST_DynamicNone38.1k
) {
556
    // TODO: Revisit exception specifications for the MS ABI.  There is a way to
557
    // encode these in an object file but MSVC doesn't do anything with it.
558
102
    if (getTarget().getCXXABI().isMicrosoft())
559
1
      return;
560
    // In wasm we currently treat 'throw()' in the same way as 'noexcept'. In
561
    // case of throw with types, we ignore it and print a warning for now.
562
    // TODO Correctly handle exception specification in wasm
563
101
    if (CGM.getLangOpts().WasmExceptions) {
564
12
      if (EST == EST_DynamicNone)
565
6
        EHStack.popTerminate();
566
12
      return;
567
12
    }
568
89
    EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
569
89
    emitFilterDispatchBlock(*this, filterScope);
570
89
    EHStack.popFilter();
571
89
  }
572
82.2k
}
573
574
326
void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
575
326
  EnterCXXTryStmt(S);
576
326
  EmitStmt(S.getTryBlock());
577
326
  ExitCXXTryStmt(S);
578
326
}
579
580
359
void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
581
359
  unsigned NumHandlers = S.getNumHandlers();
582
359
  EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
583
584
771
  for (unsigned I = 0; I != NumHandlers; 
++I412
) {
585
412
    const CXXCatchStmt *C = S.getHandler(I);
586
587
412
    llvm::BasicBlock *Handler = createBasicBlock("catch");
588
412
    if (C->getExceptionDecl()) {
589
      // FIXME: Dropping the reference type on the type into makes it
590
      // impossible to correctly implement catch-by-reference
591
      // semantics for pointers.  Unfortunately, this is what all
592
      // existing compilers do, and it's not clear that the standard
593
      // personality routine is capable of doing this right.  See C++ DR 388:
594
      //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
595
183
      Qualifiers CaughtTypeQuals;
596
183
      QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
597
183
          C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
598
599
183
      CatchTypeInfo TypeInfo{nullptr, 0};
600
183
      if (CaughtType->isObjCObjectPointerType())
601
8
        TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
602
175
      else
603
175
        TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
604
175
            CaughtType, C->getCaughtType());
605
183
      CatchScope->setHandler(I, TypeInfo, Handler);
606
229
    } else {
607
      // No exception decl indicates '...', a catch-all.
608
229
      CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
609
229
    }
610
412
  }
611
359
}
612
613
llvm::BasicBlock *
614
13.5k
CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
615
13.5k
  if (EHPersonality::get(*this).usesFuncletPads())
616
762
    return getFuncletEHDispatchBlock(si);
617
618
  // The dispatch block for the end of the scope chain is a block that
619
  // just resumes unwinding.
620
12.8k
  if (si == EHStack.stable_end())
621
3.74k
    return getEHResumeBlock(true);
622
623
  // Otherwise, we should look at the actual scope.
624
9.07k
  EHScope &scope = *EHStack.find(si);
625
626
9.07k
  llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
627
9.07k
  if (!dispatchBlock) {
628
7.05k
    switch (scope.getKind()) {
629
382
    case EHScope::Catch: {
630
      // Apply a special case to a single catch-all.
631
382
      EHCatchScope &catchScope = cast<EHCatchScope>(scope);
632
382
      if (catchScope.getNumHandlers() == 1 &&
633
358
          catchScope.getHandler(0).isCatchAll()) {
634
187
        dispatchBlock = catchScope.getHandler(0).Block;
635
636
      // Otherwise, make a dispatch block.
637
195
      } else {
638
195
        dispatchBlock = createBasicBlock("catch.dispatch");
639
195
      }
640
382
      break;
641
0
    }
642
643
6.40k
    case EHScope::Cleanup:
644
6.40k
      dispatchBlock = createBasicBlock("ehcleanup");
645
6.40k
      break;
646
647
28
    case EHScope::Filter:
648
28
      dispatchBlock = createBasicBlock("filter.dispatch");
649
28
      break;
650
651
237
    case EHScope::Terminate:
652
237
      dispatchBlock = getTerminateHandler();
653
237
      break;
654
7.05k
    }
655
7.05k
    scope.setCachedEHDispatchBlock(dispatchBlock);
656
7.05k
  }
657
9.07k
  return dispatchBlock;
658
9.07k
}
659
660
llvm::BasicBlock *
661
762
CodeGenFunction::getFuncletEHDispatchBlock(EHScopeStack::stable_iterator SI) {
662
  // Returning nullptr indicates that the previous dispatch block should unwind
663
  // to caller.
664
762
  if (SI == EHStack.stable_end())
665
254
    return nullptr;
666
667
  // Otherwise, we should look at the actual scope.
668
508
  EHScope &EHS = *EHStack.find(SI);
669
670
508
  llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
671
508
  if (DispatchBlock)
672
91
    return DispatchBlock;
673
674
417
  if (EHS.getKind() == EHScope::Terminate)
675
30
    DispatchBlock = getTerminateFunclet();
676
387
  else
677
387
    DispatchBlock = createBasicBlock();
678
417
  CGBuilderTy Builder(*this, DispatchBlock);
679
680
417
  switch (EHS.getKind()) {
681
144
  case EHScope::Catch:
682
144
    DispatchBlock->setName("catch.dispatch");
683
144
    break;
684
685
243
  case EHScope::Cleanup:
686
243
    DispatchBlock->setName("ehcleanup");
687
243
    break;
688
689
0
  case EHScope::Filter:
690
0
    llvm_unreachable("exception specifications not handled yet!");
691
692
30
  case EHScope::Terminate:
693
30
    DispatchBlock->setName("terminate");
694
30
    break;
695
417
  }
696
417
  EHS.setCachedEHDispatchBlock(DispatchBlock);
697
417
  return DispatchBlock;
698
417
}
699
700
/// Check whether this is a non-EH scope, i.e. a scope which doesn't
701
/// affect exception handling.  Currently, the only non-EH scopes are
702
/// normal-only cleanup scopes.
703
10.5k
static bool isNonEHScope(const EHScope &S) {
704
10.5k
  switch (S.getKind()) {
705
6.08k
  case EHScope::Cleanup:
706
6.08k
    return !cast<EHCleanupScope>(S).isEHCleanup();
707
4.50k
  case EHScope::Filter:
708
4.50k
  case EHScope::Catch:
709
4.50k
  case EHScope::Terminate:
710
4.50k
    return false;
711
0
  }
712
713
0
  llvm_unreachable("Invalid EHScope Kind!");
714
0
}
715
716
36.5k
llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
717
36.5k
  assert(EHStack.requiresLandingPad());
718
36.5k
  assert(!EHStack.empty());
719
720
  // If exceptions are disabled/ignored and SEH is not in use, then there is no
721
  // invoke destination. SEH "works" even if exceptions are off. In practice,
722
  // this means that C++ destructors and other EH cleanups don't run, which is
723
  // consistent with MSVC's behavior.
724
36.5k
  const LangOptions &LO = CGM.getLangOpts();
725
36.5k
  if (!LO.Exceptions || 
LO.IgnoreExceptions27.9k
) {
726
8.67k
    if (!LO.Borland && !LO.MicrosoftExt)
727
8.43k
      return nullptr;
728
236
    if (!currentFunctionUsesSEHTry())
729
148
      return nullptr;
730
27.9k
  }
731
732
  // CUDA device code doesn't have exceptions.
733
27.9k
  if (LO.CUDA && 
LO.CUDAIsDevice0
)
734
0
    return nullptr;
735
736
  // Check the innermost scope for a cached landing pad.  If this is
737
  // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
738
27.9k
  llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
739
27.9k
  if (LP) 
return LP17.4k
;
740
741
10.5k
  const EHPersonality &Personality = EHPersonality::get(*this);
742
743
10.5k
  if (!CurFn->hasPersonalityFn())
744
7.40k
    CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
745
746
10.5k
  if (Personality.usesFuncletPads()) {
747
    // We don't need separate landing pads in the funclet model.
748
375
    LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
749
10.1k
  } else {
750
    // Build the landing pad for this scope.
751
10.1k
    LP = EmitLandingPad();
752
10.1k
  }
753
754
10.5k
  assert(LP);
755
756
  // Cache the landing pad on the innermost scope.  If this is a
757
  // non-EH scope, cache the landing pad on the enclosing scope, too.
758
10.5k
  for (EHScopeStack::iterator ir = EHStack.begin(); true; 
++ir20
) {
759
10.5k
    ir->setCachedLandingPad(LP);
760
10.5k
    if (!isNonEHScope(*ir)) 
break10.5k
;
761
10.5k
  }
762
763
10.5k
  return LP;
764
10.5k
}
765
766
10.1k
llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
767
10.1k
  assert(EHStack.requiresLandingPad());
768
10.1k
  assert(!CGM.getLangOpts().IgnoreExceptions &&
769
10.1k
         "LandingPad should not be emitted when -fignore-exceptions are in "
770
10.1k
         "effect.");
771
10.1k
  EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
772
10.1k
  switch (innermostEHScope.getKind()) {
773
3.96k
  case EHScope::Terminate:
774
3.96k
    return getTerminateLandingPad();
775
776
6.23k
  case EHScope::Catch:
777
6.23k
  case EHScope::Cleanup:
778
6.23k
  case EHScope::Filter:
779
6.23k
    if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
780
0
      return lpad;
781
6.23k
  }
782
783
  // Save the current IR generation state.
784
6.23k
  CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
785
6.23k
  auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
786
787
  // Create and configure the landing pad.
788
6.23k
  llvm::BasicBlock *lpad = createBasicBlock("lpad");
789
6.23k
  EmitBlock(lpad);
790
791
6.23k
  llvm::LandingPadInst *LPadInst =
792
6.23k
      Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
793
794
6.23k
  llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
795
6.23k
  Builder.CreateStore(LPadExn, getExceptionSlot());
796
6.23k
  llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
797
6.23k
  Builder.CreateStore(LPadSel, getEHSelectorSlot());
798
799
  // Save the exception pointer.  It's safe to use a single exception
800
  // pointer per function because EH cleanups can never have nested
801
  // try/catches.
802
  // Build the landingpad instruction.
803
804
  // Accumulate all the handlers in scope.
805
6.23k
  bool hasCatchAll = false;
806
6.23k
  bool hasCleanup = false;
807
6.23k
  bool hasFilter = false;
808
6.23k
  SmallVector<llvm::Value*, 4> filterTypes;
809
6.23k
  llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
810
16.6k
  for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
811
11.0k
       
++I10.4k
) {
812
813
11.0k
    switch (I->getKind()) {
814
10.2k
    case EHScope::Cleanup:
815
      // If we have a cleanup, remember that.
816
10.2k
      hasCleanup = (hasCleanup || 
cast<EHCleanupScope>(*I).isEHCleanup()5.85k
);
817
10.2k
      continue;
818
819
28
    case EHScope::Filter: {
820
28
      assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
821
28
      assert(!hasCatchAll && "EH filter reached after catch-all");
822
823
      // Filter scopes get added to the landingpad in weird ways.
824
28
      EHFilterScope &filter = cast<EHFilterScope>(*I);
825
28
      hasFilter = true;
826
827
      // Add all the filter values.
828
53
      for (unsigned i = 0, e = filter.getNumFilters(); i != e; 
++i25
)
829
25
        filterTypes.push_back(filter.getFilter(i));
830
28
      goto done;
831
0
    }
832
833
338
    case EHScope::Terminate:
834
      // Terminate scopes are basically catch-alls.
835
338
      assert(!hasCatchAll);
836
338
      hasCatchAll = true;
837
338
      goto done;
838
839
499
    case EHScope::Catch:
840
499
      break;
841
499
    }
842
843
499
    EHCatchScope &catchScope = cast<EHCatchScope>(*I);
844
774
    for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; 
++hi275
) {
845
532
      EHCatchScope::Handler handler = catchScope.getHandler(hi);
846
532
      assert(handler.Type.Flags == 0 &&
847
532
             "landingpads do not support catch handler flags");
848
849
      // If this is a catch-all, register that and abort.
850
532
      if (!handler.Type.RTTI) {
851
257
        assert(!hasCatchAll);
852
257
        hasCatchAll = true;
853
257
        goto done;
854
257
      }
855
856
      // Check whether we already have a handler for this type.
857
275
      if (catchTypes.insert(handler.Type.RTTI).second)
858
        // If not, add it directly to the landingpad.
859
274
        LPadInst->addClause(handler.Type.RTTI);
860
275
    }
861
499
  }
862
863
6.23k
 done:
864
  // If we have a catch-all, add null to the landingpad.
865
6.23k
  assert(!(hasCatchAll && hasFilter));
866
6.23k
  if (hasCatchAll) {
867
595
    LPadInst->addClause(getCatchAllValue(*this));
868
869
  // If we have an EH filter, we need to add those handlers in the
870
  // right place in the landingpad, which is to say, at the end.
871
5.63k
  } else if (hasFilter) {
872
    // Create a filter expression: a constant array indicating which filter
873
    // types there are. The personality routine only lands here if the filter
874
    // doesn't match.
875
28
    SmallVector<llvm::Constant*, 8> Filters;
876
28
    llvm::ArrayType *AType =
877
28
      llvm::ArrayType::get(!filterTypes.empty() ?
878
25
                             filterTypes[0]->getType() : 
Int8PtrTy3
,
879
28
                           filterTypes.size());
880
881
53
    for (unsigned i = 0, e = filterTypes.size(); i != e; 
++i25
)
882
25
      Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
883
28
    llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
884
28
    LPadInst->addClause(FilterArray);
885
886
    // Also check whether we need a cleanup.
887
28
    if (hasCleanup)
888
2
      LPadInst->setCleanup(true);
889
890
  // Otherwise, signal that we at least have cleanups.
891
5.60k
  } else if (hasCleanup) {
892
5.44k
    LPadInst->setCleanup(true);
893
5.44k
  }
894
895
6.23k
  assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
896
6.23k
         "landingpad instruction has no clauses!");
897
898
  // Tell the backend how to generate the landing pad.
899
6.23k
  Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
900
901
  // Restore the old IR generation state.
902
6.23k
  Builder.restoreIP(savedIP);
903
904
6.23k
  return lpad;
905
6.23k
}
906
907
84
static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
908
84
  llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
909
84
  assert(DispatchBlock);
910
911
84
  CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
912
84
  CGF.EmitBlockAfterUses(DispatchBlock);
913
914
84
  llvm::Value *ParentPad = CGF.CurrentFuncletPad;
915
84
  if (!ParentPad)
916
83
    ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
917
84
  llvm::BasicBlock *UnwindBB =
918
84
      CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
919
920
84
  unsigned NumHandlers = CatchScope.getNumHandlers();
921
84
  llvm::CatchSwitchInst *CatchSwitch =
922
84
      CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
923
924
  // Test against each of the exception types we claim to catch.
925
171
  for (unsigned I = 0; I < NumHandlers; 
++I87
) {
926
87
    const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
927
928
87
    CatchTypeInfo TypeInfo = Handler.Type;
929
87
    if (!TypeInfo.RTTI)
930
39
      TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
931
932
87
    CGF.Builder.SetInsertPoint(Handler.Block);
933
934
87
    if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
935
40
      CGF.Builder.CreateCatchPad(
936
40
          CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
937
40
                        llvm::Constant::getNullValue(CGF.VoidPtrTy)});
938
47
    } else {
939
47
      CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
940
47
    }
941
942
87
    CatchSwitch->addHandler(Handler.Block);
943
87
  }
944
84
  CGF.Builder.restoreIP(SavedIP);
945
84
}
946
947
// Wasm uses Windows-style EH instructions, but it merges all catch clauses into
948
// one big catchpad, within which we use Itanium's landingpad-style selector
949
// comparison instructions.
950
static void emitWasmCatchPadBlock(CodeGenFunction &CGF,
951
60
                                  EHCatchScope &CatchScope) {
952
60
  llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
953
60
  assert(DispatchBlock);
954
955
60
  CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
956
60
  CGF.EmitBlockAfterUses(DispatchBlock);
957
958
60
  llvm::Value *ParentPad = CGF.CurrentFuncletPad;
959
60
  if (!ParentPad)
960
54
    ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
961
60
  llvm::BasicBlock *UnwindBB =
962
60
      CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
963
964
60
  unsigned NumHandlers = CatchScope.getNumHandlers();
965
60
  llvm::CatchSwitchInst *CatchSwitch =
966
60
      CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
967
968
  // We don't use a landingpad instruction, so generate intrinsic calls to
969
  // provide exception and selector values.
970
60
  llvm::BasicBlock *WasmCatchStartBlock = CGF.createBasicBlock("catch.start");
971
60
  CatchSwitch->addHandler(WasmCatchStartBlock);
972
60
  CGF.EmitBlockAfterUses(WasmCatchStartBlock);
973
974
  // Create a catchpad instruction.
975
60
  SmallVector<llvm::Value *, 4> CatchTypes;
976
144
  for (unsigned I = 0, E = NumHandlers; I < E; 
++I84
) {
977
84
    const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
978
84
    CatchTypeInfo TypeInfo = Handler.Type;
979
84
    if (!TypeInfo.RTTI)
980
24
      TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
981
84
    CatchTypes.push_back(TypeInfo.RTTI);
982
84
  }
983
60
  auto *CPI = CGF.Builder.CreateCatchPad(CatchSwitch, CatchTypes);
984
985
  // Create calls to wasm.get.exception and wasm.get.ehselector intrinsics.
986
  // Before they are lowered appropriately later, they provide values for the
987
  // exception and selector.
988
60
  llvm::Function *GetExnFn =
989
60
      CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_exception);
990
60
  llvm::Function *GetSelectorFn =
991
60
      CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_ehselector);
992
60
  llvm::CallInst *Exn = CGF.Builder.CreateCall(GetExnFn, CPI);
993
60
  CGF.Builder.CreateStore(Exn, CGF.getExceptionSlot());
994
60
  llvm::CallInst *Selector = CGF.Builder.CreateCall(GetSelectorFn, CPI);
995
996
60
  llvm::Function *TypeIDFn = CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
997
998
  // If there's only a single catch-all, branch directly to its handler.
999
60
  if (CatchScope.getNumHandlers() == 1 &&
1000
36
      CatchScope.getHandler(0).isCatchAll()) {
1001
12
    CGF.Builder.CreateBr(CatchScope.getHandler(0).Block);
1002
12
    CGF.Builder.restoreIP(SavedIP);
1003
12
    return;
1004
12
  }
1005
1006
  // Test against each of the exception types we claim to catch.
1007
60
  
for (unsigned I = 0, E = NumHandlers;; 48
++I12
) {
1008
60
    assert(I < E && "ran off end of handlers!");
1009
60
    const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
1010
60
    CatchTypeInfo TypeInfo = Handler.Type;
1011
60
    if (!TypeInfo.RTTI)
1012
0
      TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
1013
1014
    // Figure out the next block.
1015
60
    llvm::BasicBlock *NextBlock;
1016
1017
60
    bool EmitNextBlock = false, NextIsEnd = false;
1018
1019
    // If this is the last handler, we're at the end, and the next block is a
1020
    // block that contains a call to the rethrow function, so we can unwind to
1021
    // the enclosing EH scope. The call itself will be generated later.
1022
60
    if (I + 1 == E) {
1023
36
      NextBlock = CGF.createBasicBlock("rethrow");
1024
36
      EmitNextBlock = true;
1025
36
      NextIsEnd = true;
1026
1027
      // If the next handler is a catch-all, we're at the end, and the
1028
      // next block is that handler.
1029
24
    } else if (CatchScope.getHandler(I + 1).isCatchAll()) {
1030
12
      NextBlock = CatchScope.getHandler(I + 1).Block;
1031
12
      NextIsEnd = true;
1032
1033
      // Otherwise, we're not at the end and we need a new block.
1034
12
    } else {
1035
12
      NextBlock = CGF.createBasicBlock("catch.fallthrough");
1036
12
      EmitNextBlock = true;
1037
12
    }
1038
1039
    // Figure out the catch type's index in the LSDA's type table.
1040
60
    llvm::CallInst *TypeIndex = CGF.Builder.CreateCall(TypeIDFn, TypeInfo.RTTI);
1041
60
    TypeIndex->setDoesNotThrow();
1042
1043
60
    llvm::Value *MatchesTypeIndex =
1044
60
        CGF.Builder.CreateICmpEQ(Selector, TypeIndex, "matches");
1045
60
    CGF.Builder.CreateCondBr(MatchesTypeIndex, Handler.Block, NextBlock);
1046
1047
60
    if (EmitNextBlock)
1048
48
      CGF.EmitBlock(NextBlock);
1049
60
    if (NextIsEnd)
1050
48
      break;
1051
60
  }
1052
1053
48
  CGF.Builder.restoreIP(SavedIP);
1054
48
}
1055
1056
/// Emit the structure of the dispatch block for the given catch scope.
1057
/// It is an invariant that the dispatch block already exists.
1058
static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1059
526
                                   EHCatchScope &catchScope) {
1060
526
  if (EHPersonality::get(CGF).isWasmPersonality())
1061
60
    return emitWasmCatchPadBlock(CGF, catchScope);
1062
466
  if (EHPersonality::get(CGF).usesFuncletPads())
1063
84
    return emitCatchPadBlock(CGF, catchScope);
1064
1065
382
  llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1066
382
  assert(dispatchBlock);
1067
1068
  // If there's only a single catch-all, getEHDispatchBlock returned
1069
  // that catch-all as the dispatch block.
1070
382
  if (catchScope.getNumHandlers() == 1 &&
1071
358
      catchScope.getHandler(0).isCatchAll()) {
1072
187
    assert(dispatchBlock == catchScope.getHandler(0).Block);
1073
187
    return;
1074
187
  }
1075
1076
195
  CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1077
195
  CGF.EmitBlockAfterUses(dispatchBlock);
1078
1079
  // Select the right handler.
1080
195
  llvm::Function *llvm_eh_typeid_for =
1081
195
    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1082
1083
  // Load the selector value.
1084
195
  llvm::Value *selector = CGF.getSelectorFromSlot();
1085
1086
  // Test against each of the exception types we claim to catch.
1087
208
  for (unsigned i = 0, e = catchScope.getNumHandlers(); ; 
++i13
) {
1088
208
    assert(i < e && "ran off end of handlers!");
1089
208
    const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1090
1091
208
    llvm::Value *typeValue = handler.Type.RTTI;
1092
208
    assert(handler.Type.Flags == 0 &&
1093
208
           "landingpads do not support catch handler flags");
1094
208
    assert(typeValue && "fell into catch-all case!");
1095
208
    typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1096
1097
    // Figure out the next block.
1098
208
    bool nextIsEnd;
1099
208
    llvm::BasicBlock *nextBlock;
1100
1101
    // If this is the last handler, we're at the end, and the next
1102
    // block is the block for the enclosing EH scope.
1103
208
    if (i + 1 == e) {
1104
178
      nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1105
178
      nextIsEnd = true;
1106
1107
    // If the next handler is a catch-all, we're at the end, and the
1108
    // next block is that handler.
1109
30
    } else if (catchScope.getHandler(i+1).isCatchAll()) {
1110
17
      nextBlock = catchScope.getHandler(i+1).Block;
1111
17
      nextIsEnd = true;
1112
1113
    // Otherwise, we're not at the end and we need a new block.
1114
13
    } else {
1115
13
      nextBlock = CGF.createBasicBlock("catch.fallthrough");
1116
13
      nextIsEnd = false;
1117
13
    }
1118
1119
    // Figure out the catch type's index in the LSDA's type table.
1120
208
    llvm::CallInst *typeIndex =
1121
208
      CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1122
208
    typeIndex->setDoesNotThrow();
1123
1124
208
    llvm::Value *matchesTypeIndex =
1125
208
      CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1126
208
    CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1127
1128
    // If the next handler is a catch-all, we're completely done.
1129
208
    if (nextIsEnd) {
1130
195
      CGF.Builder.restoreIP(savedIP);
1131
195
      return;
1132
195
    }
1133
    // Otherwise we need to emit and continue at that block.
1134
13
    CGF.EmitBlock(nextBlock);
1135
13
  }
1136
195
}
1137
1138
189
void CodeGenFunction::popCatchScope() {
1139
189
  EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1140
189
  if (catchScope.hasEHBranches())
1141
164
    emitCatchDispatchBlock(*this, catchScope);
1142
189
  EHStack.popCatch();
1143
189
}
1144
1145
359
void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
1146
359
  unsigned NumHandlers = S.getNumHandlers();
1147
359
  EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1148
359
  assert(CatchScope.getNumHandlers() == NumHandlers);
1149
359
  llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
1150
1151
  // If the catch was not required, bail out now.
1152
359
  if (!CatchScope.hasEHBranches()) {
1153
44
    CatchScope.clearHandlerBlocks();
1154
44
    EHStack.popCatch();
1155
44
    return;
1156
44
  }
1157
1158
  // Emit the structure of the EH dispatch for this catch.
1159
315
  emitCatchDispatchBlock(*this, CatchScope);
1160
1161
  // Copy the handler blocks off before we pop the EH stack.  Emitting
1162
  // the handlers might scribble on this memory.
1163
315
  SmallVector<EHCatchScope::Handler, 8> Handlers(
1164
315
      CatchScope.begin(), CatchScope.begin() + NumHandlers);
1165
1166
315
  EHStack.popCatch();
1167
1168
  // The fall-through block.
1169
315
  llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1170
1171
  // We just emitted the body of the try; jump to the continue block.
1172
315
  if (HaveInsertPoint())
1173
281
    Builder.CreateBr(ContBB);
1174
1175
  // Determine if we need an implicit rethrow for all these catch handlers;
1176
  // see the comment below.
1177
315
  bool doImplicitRethrow = false;
1178
315
  if (IsFnTryBlock)
1179
17
    doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1180
2
                        isa<CXXConstructorDecl>(CurCodeDecl);
1181
1182
  // Wasm uses Windows-style EH instructions, but merges all catch clauses into
1183
  // one big catchpad. So we save the old funclet pad here before we traverse
1184
  // each catch handler.
1185
315
  SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1186
315
      CurrentFuncletPad);
1187
315
  llvm::BasicBlock *WasmCatchStartBlock = nullptr;
1188
315
  if (EHPersonality::get(*this).isWasmPersonality()) {
1189
60
    auto *CatchSwitch =
1190
60
        cast<llvm::CatchSwitchInst>(DispatchBlock->getFirstNonPHI());
1191
60
    WasmCatchStartBlock = CatchSwitch->hasUnwindDest()
1192
24
                              ? CatchSwitch->getSuccessor(1)
1193
36
                              : CatchSwitch->getSuccessor(0);
1194
60
    auto *CPI = cast<llvm::CatchPadInst>(WasmCatchStartBlock->getFirstNonPHI());
1195
60
    CurrentFuncletPad = CPI;
1196
60
  }
1197
1198
  // Perversely, we emit the handlers backwards precisely because we
1199
  // want them to appear in source order.  In all of these cases, the
1200
  // catch block will have exactly one predecessor, which will be a
1201
  // particular block in the catch dispatch.  However, in the case of
1202
  // a catch-all, one of the dispatch blocks will branch to two
1203
  // different handlers, and EmitBlockAfterUses will cause the second
1204
  // handler to be moved before the first.
1205
315
  bool HasCatchAll = false;
1206
682
  for (unsigned I = NumHandlers; I != 0; 
--I367
) {
1207
367
    HasCatchAll |= Handlers[I - 1].isCatchAll();
1208
367
    llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1209
367
    EmitBlockAfterUses(CatchBlock);
1210
1211
    // Catch the exception if this isn't a catch-all.
1212
367
    const CXXCatchStmt *C = S.getHandler(I-1);
1213
1214
    // Enter a cleanup scope, including the catch variable and the
1215
    // end-catch.
1216
367
    RunCleanupsScope CatchScope(*this);
1217
1218
    // Initialize the catch variable and set up the cleanups.
1219
367
    SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1220
367
        CurrentFuncletPad);
1221
367
    CGM.getCXXABI().emitBeginCatch(*this, C);
1222
1223
    // Emit the PGO counter increment.
1224
367
    incrementProfileCounter(C);
1225
1226
    // Perform the body of the catch.
1227
367
    EmitStmt(C->getHandlerBlock());
1228
1229
    // [except.handle]p11:
1230
    //   The currently handled exception is rethrown if control
1231
    //   reaches the end of a handler of the function-try-block of a
1232
    //   constructor or destructor.
1233
1234
    // It is important that we only do this on fallthrough and not on
1235
    // return.  Note that it's illegal to put a return in a
1236
    // constructor function-try-block's catch handler (p14), so this
1237
    // really only applies to destructors.
1238
367
    if (doImplicitRethrow && 
HaveInsertPoint()17
) {
1239
13
      CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
1240
13
      Builder.CreateUnreachable();
1241
13
      Builder.ClearInsertionPoint();
1242
13
    }
1243
1244
    // Fall out through the catch cleanups.
1245
367
    CatchScope.ForceCleanup();
1246
1247
    // Branch out of the try.
1248
367
    if (HaveInsertPoint())
1249
275
      Builder.CreateBr(ContBB);
1250
367
  }
1251
1252
  // Because in wasm we merge all catch clauses into one big catchpad, in case
1253
  // none of the types in catch handlers matches after we test against each of
1254
  // them, we should unwind to the next EH enclosing scope. We generate a call
1255
  // to rethrow function here to do that.
1256
315
  if (EHPersonality::get(*this).isWasmPersonality() && 
!HasCatchAll60
) {
1257
36
    assert(WasmCatchStartBlock);
1258
    // Navigate for the "rethrow" block we created in emitWasmCatchPadBlock().
1259
    // Wasm uses landingpad-style conditional branches to compare selectors, so
1260
    // we follow the false destination for each of the cond branches to reach
1261
    // the rethrow block.
1262
36
    llvm::BasicBlock *RethrowBlock = WasmCatchStartBlock;
1263
84
    while (llvm::Instruction *TI = RethrowBlock->getTerminator()) {
1264
48
      auto *BI = cast<llvm::BranchInst>(TI);
1265
48
      assert(BI->isConditional());
1266
48
      RethrowBlock = BI->getSuccessor(1);
1267
48
    }
1268
36
    assert(RethrowBlock != WasmCatchStartBlock && RethrowBlock->empty());
1269
36
    Builder.SetInsertPoint(RethrowBlock);
1270
36
    llvm::Function *RethrowInCatchFn =
1271
36
        CGM.getIntrinsic(llvm::Intrinsic::wasm_rethrow_in_catch);
1272
36
    EmitNoreturnRuntimeCallOrInvoke(RethrowInCatchFn, {});
1273
36
  }
1274
1275
315
  EmitBlock(ContBB);
1276
315
  incrementProfileCounter(&S);
1277
315
}
1278
1279
namespace {
1280
  struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
1281
    llvm::Value *ForEHVar;
1282
    llvm::FunctionCallee EndCatchFn;
1283
    CallEndCatchForFinally(llvm::Value *ForEHVar,
1284
                           llvm::FunctionCallee EndCatchFn)
1285
8
        : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1286
1287
4
    void Emit(CodeGenFunction &CGF, Flags flags) override {
1288
4
      llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1289
4
      llvm::BasicBlock *CleanupContBB =
1290
4
        CGF.createBasicBlock("finally.cleanup.cont");
1291
1292
4
      llvm::Value *ShouldEndCatch =
1293
4
        CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
1294
4
      CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1295
4
      CGF.EmitBlock(EndCatchBB);
1296
4
      CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
1297
4
      CGF.EmitBlock(CleanupContBB);
1298
4
    }
1299
  };
1300
1301
  struct PerformFinally final : EHScopeStack::Cleanup {
1302
    const Stmt *Body;
1303
    llvm::Value *ForEHVar;
1304
    llvm::FunctionCallee EndCatchFn;
1305
    llvm::FunctionCallee RethrowFn;
1306
    llvm::Value *SavedExnVar;
1307
1308
    PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1309
                   llvm::FunctionCallee EndCatchFn,
1310
                   llvm::FunctionCallee RethrowFn, llvm::Value *SavedExnVar)
1311
        : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1312
10
          RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1313
1314
9
    void Emit(CodeGenFunction &CGF, Flags flags) override {
1315
      // Enter a cleanup to call the end-catch function if one was provided.
1316
9
      if (EndCatchFn)
1317
8
        CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1318
8
                                                        ForEHVar, EndCatchFn);
1319
1320
      // Save the current cleanup destination in case there are
1321
      // cleanups in the finally block.
1322
9
      llvm::Value *SavedCleanupDest =
1323
9
        CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1324
9
                               "cleanup.dest.saved");
1325
1326
      // Emit the finally block.
1327
9
      CGF.EmitStmt(Body);
1328
1329
      // If the end of the finally is reachable, check whether this was
1330
      // for EH.  If so, rethrow.
1331
9
      if (CGF.HaveInsertPoint()) {
1332
9
        llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1333
9
        llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1334
1335
9
        llvm::Value *ShouldRethrow =
1336
9
          CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
1337
9
        CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1338
1339
9
        CGF.EmitBlock(RethrowBB);
1340
9
        if (SavedExnVar) {
1341
1
          CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1342
1
            CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
1343
8
        } else {
1344
8
          CGF.EmitRuntimeCallOrInvoke(RethrowFn);
1345
8
        }
1346
9
        CGF.Builder.CreateUnreachable();
1347
1348
9
        CGF.EmitBlock(ContBB);
1349
1350
        // Restore the cleanup destination.
1351
9
        CGF.Builder.CreateStore(SavedCleanupDest,
1352
9
                                CGF.getNormalCleanupDestSlot());
1353
9
      }
1354
1355
      // Leave the end-catch cleanup.  As an optimization, pretend that
1356
      // the fallthrough path was inaccessible; we've dynamically proven
1357
      // that we're not in the EH case along that path.
1358
9
      if (EndCatchFn) {
1359
8
        CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1360
8
        CGF.PopCleanupBlock();
1361
8
        CGF.Builder.restoreIP(SavedIP);
1362
8
      }
1363
1364
      // Now make sure we actually have an insertion point or the
1365
      // cleanup gods will hate us.
1366
9
      CGF.EnsureInsertPoint();
1367
9
    }
1368
  };
1369
} // end anonymous namespace
1370
1371
/// Enters a finally block for an implementation using zero-cost
1372
/// exceptions.  This is mostly general, but hard-codes some
1373
/// language/ABI-specific behavior in the catch-all sections.
1374
void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF, const Stmt *body,
1375
                                         llvm::FunctionCallee beginCatchFn,
1376
                                         llvm::FunctionCallee endCatchFn,
1377
10
                                         llvm::FunctionCallee rethrowFn) {
1378
10
  assert((!!beginCatchFn) == (!!endCatchFn) &&
1379
10
         "begin/end catch functions not paired");
1380
10
  assert(rethrowFn && "rethrow function is required");
1381
1382
10
  BeginCatchFn = beginCatchFn;
1383
1384
  // The rethrow function has one of the following two types:
1385
  //   void (*)()
1386
  //   void (*)(void*)
1387
  // In the latter case we need to pass it the exception object.
1388
  // But we can't use the exception slot because the @finally might
1389
  // have a landing pad (which would overwrite the exception slot).
1390
10
  llvm::FunctionType *rethrowFnTy = rethrowFn.getFunctionType();
1391
10
  SavedExnVar = nullptr;
1392
10
  if (rethrowFnTy->getNumParams())
1393
1
    SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1394
1395
  // A finally block is a statement which must be executed on any edge
1396
  // out of a given scope.  Unlike a cleanup, the finally block may
1397
  // contain arbitrary control flow leading out of itself.  In
1398
  // addition, finally blocks should always be executed, even if there
1399
  // are no catch handlers higher on the stack.  Therefore, we
1400
  // surround the protected scope with a combination of a normal
1401
  // cleanup (to catch attempts to break out of the block via normal
1402
  // control flow) and an EH catch-all (semantically "outside" any try
1403
  // statement to which the finally block might have been attached).
1404
  // The finally block itself is generated in the context of a cleanup
1405
  // which conditionally leaves the catch-all.
1406
1407
  // Jump destination for performing the finally block on an exception
1408
  // edge.  We'll never actually reach this block, so unreachable is
1409
  // fine.
1410
10
  RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1411
1412
  // Whether the finally block is being executed for EH purposes.
1413
10
  ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1414
10
  CGF.Builder.CreateFlagStore(false, ForEHVar);
1415
1416
  // Enter a normal cleanup which will perform the @finally block.
1417
10
  CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1418
10
                                          ForEHVar, endCatchFn,
1419
10
                                          rethrowFn, SavedExnVar);
1420
1421
  // Enter a catch-all scope.
1422
10
  llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1423
10
  EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1424
10
  catchScope->setCatchAllHandler(0, catchBB);
1425
10
}
1426
1427
10
void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
1428
  // Leave the finally catch-all.
1429
10
  EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1430
10
  llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1431
1432
10
  CGF.popCatchScope();
1433
1434
  // If there are any references to the catch-all block, emit it.
1435
10
  if (catchBB->use_empty()) {
1436
8
    delete catchBB;
1437
2
  } else {
1438
2
    CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1439
2
    CGF.EmitBlock(catchBB);
1440
1441
2
    llvm::Value *exn = nullptr;
1442
1443
    // If there's a begin-catch function, call it.
1444
2
    if (BeginCatchFn) {
1445
2
      exn = CGF.getExceptionFromSlot();
1446
2
      CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
1447
2
    }
1448
1449
    // If we need to remember the exception pointer to rethrow later, do so.
1450
2
    if (SavedExnVar) {
1451
0
      if (!exn) exn = CGF.getExceptionFromSlot();
1452
0
      CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
1453
0
    }
1454
1455
    // Tell the cleanups in the finally block that we're do this for EH.
1456
2
    CGF.Builder.CreateFlagStore(true, ForEHVar);
1457
1458
    // Thread a jump through the finally cleanup.
1459
2
    CGF.EmitBranchThroughCleanup(RethrowDest);
1460
1461
2
    CGF.Builder.restoreIP(savedIP);
1462
2
  }
1463
1464
  // Finally, leave the @finally cleanup.
1465
10
  CGF.PopCleanupBlock();
1466
10
}
1467
1468
3.96k
llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1469
3.96k
  if (TerminateLandingPad)
1470
150
    return TerminateLandingPad;
1471
1472
3.81k
  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1473
1474
  // This will get inserted at the end of the function.
1475
3.81k
  TerminateLandingPad = createBasicBlock("terminate.lpad");
1476
3.81k
  Builder.SetInsertPoint(TerminateLandingPad);
1477
1478
  // Tell the backend that this is a landing pad.
1479
3.81k
  const EHPersonality &Personality = EHPersonality::get(*this);
1480
1481
3.81k
  if (!CurFn->hasPersonalityFn())
1482
0
    CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1483
1484
3.81k
  llvm::LandingPadInst *LPadInst =
1485
3.81k
      Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
1486
3.81k
  LPadInst->addClause(getCatchAllValue(*this));
1487
1488
3.81k
  llvm::Value *Exn = nullptr;
1489
3.81k
  if (getLangOpts().CPlusPlus)
1490
3.80k
    Exn = Builder.CreateExtractValue(LPadInst, 0);
1491
3.81k
  llvm::CallInst *terminateCall =
1492
3.81k
      CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1493
3.81k
  terminateCall->setDoesNotReturn();
1494
3.81k
  Builder.CreateUnreachable();
1495
1496
  // Restore the saved insertion state.
1497
3.81k
  Builder.restoreIP(SavedIP);
1498
1499
3.81k
  return TerminateLandingPad;
1500
3.81k
}
1501
1502
237
llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1503
237
  if (TerminateHandler)
1504
25
    return TerminateHandler;
1505
1506
  // Set up the terminate handler.  This block is inserted at the very
1507
  // end of the function by FinishFunction.
1508
212
  TerminateHandler = createBasicBlock("terminate.handler");
1509
212
  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1510
212
  Builder.SetInsertPoint(TerminateHandler);
1511
1512
212
  llvm::Value *Exn = nullptr;
1513
212
  if (getLangOpts().CPlusPlus)
1514
212
    Exn = getExceptionFromSlot();
1515
212
  llvm::CallInst *terminateCall =
1516
212
      CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1517
212
  terminateCall->setDoesNotReturn();
1518
212
  Builder.CreateUnreachable();
1519
1520
  // Restore the saved insertion state.
1521
212
  Builder.restoreIP(SavedIP);
1522
1523
212
  return TerminateHandler;
1524
212
}
1525
1526
30
llvm::BasicBlock *CodeGenFunction::getTerminateFunclet() {
1527
30
  assert(EHPersonality::get(*this).usesFuncletPads() &&
1528
30
         "use getTerminateLandingPad for non-funclet EH");
1529
1530
30
  llvm::BasicBlock *&TerminateFunclet = TerminateFunclets[CurrentFuncletPad];
1531
30
  if (TerminateFunclet)
1532
0
    return TerminateFunclet;
1533
1534
30
  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1535
1536
  // Set up the terminate handler.  This block is inserted at the very
1537
  // end of the function by FinishFunction.
1538
30
  TerminateFunclet = createBasicBlock("terminate.handler");
1539
30
  Builder.SetInsertPoint(TerminateFunclet);
1540
1541
  // Create the cleanuppad using the current parent pad as its token. Use 'none'
1542
  // if this is a top-level terminate scope, which is the common case.
1543
30
  SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1544
30
      CurrentFuncletPad);
1545
30
  llvm::Value *ParentPad = CurrentFuncletPad;
1546
30
  if (!ParentPad)
1547
17
    ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1548
30
  CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
1549
1550
  // Emit the __std_terminate call.
1551
30
  llvm::Value *Exn = nullptr;
1552
  // In case of wasm personality, we need to pass the exception value to
1553
  // __clang_call_terminate function.
1554
30
  if (getLangOpts().CPlusPlus &&
1555
30
      EHPersonality::get(*this).isWasmPersonality()) {
1556
18
    llvm::Function *GetExnFn =
1557
18
        CGM.getIntrinsic(llvm::Intrinsic::wasm_get_exception);
1558
18
    Exn = Builder.CreateCall(GetExnFn, CurrentFuncletPad);
1559
18
  }
1560
30
  llvm::CallInst *terminateCall =
1561
30
      CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1562
30
  terminateCall->setDoesNotReturn();
1563
30
  Builder.CreateUnreachable();
1564
1565
  // Restore the saved insertion state.
1566
30
  Builder.restoreIP(SavedIP);
1567
1568
30
  return TerminateFunclet;
1569
30
}
1570
1571
3.77k
llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
1572
3.77k
  if (EHResumeBlock) 
return EHResumeBlock431
;
1573
1574
3.34k
  CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1575
1576
  // We emit a jump to a notional label at the outermost unwind state.
1577
3.34k
  EHResumeBlock = createBasicBlock("eh.resume");
1578
3.34k
  Builder.SetInsertPoint(EHResumeBlock);
1579
1580
3.34k
  const EHPersonality &Personality = EHPersonality::get(*this);
1581
1582
  // This can always be a call because we necessarily didn't find
1583
  // anything on the EH stack which needs our help.
1584
3.34k
  const char *RethrowName = Personality.CatchallRethrowFn;
1585
3.34k
  if (RethrowName != nullptr && 
!isCleanup11
) {
1586
0
    EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
1587
0
                    getExceptionFromSlot())->setDoesNotReturn();
1588
0
    Builder.CreateUnreachable();
1589
0
    Builder.restoreIP(SavedIP);
1590
0
    return EHResumeBlock;
1591
0
  }
1592
1593
  // Recreate the landingpad's return value for the 'resume' instruction.
1594
3.34k
  llvm::Value *Exn = getExceptionFromSlot();
1595
3.34k
  llvm::Value *Sel = getSelectorFromSlot();
1596
1597
3.34k
  llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
1598
3.34k
  llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1599
3.34k
  LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1600
3.34k
  LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1601
1602
3.34k
  Builder.CreateResume(LPadVal);
1603
3.34k
  Builder.restoreIP(SavedIP);
1604
3.34k
  return EHResumeBlock;
1605
3.34k
}
1606
1607
128
void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1608
128
  EnterSEHTryStmt(S);
1609
128
  {
1610
128
    JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
1611
1612
128
    SEHTryEpilogueStack.push_back(&TryExit);
1613
128
    EmitStmt(S.getTryBlock());
1614
128
    SEHTryEpilogueStack.pop_back();
1615
1616
128
    if (!TryExit.getBlock()->use_empty())
1617
8
      EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1618
120
    else
1619
120
      delete TryExit.getBlock();
1620
128
  }
1621
128
  ExitSEHTryStmt(S);
1622
128
}
1623
1624
namespace {
1625
struct PerformSEHFinally final : EHScopeStack::Cleanup {
1626
  llvm::Function *OutlinedFinally;
1627
  PerformSEHFinally(llvm::Function *OutlinedFinally)
1628
77
      : OutlinedFinally(OutlinedFinally) {}
1629
1630
130
  void Emit(CodeGenFunction &CGF, Flags F) override {
1631
130
    ASTContext &Context = CGF.getContext();
1632
130
    CodeGenModule &CGM = CGF.CGM;
1633
1634
130
    CallArgList Args;
1635
1636
    // Compute the two argument values.
1637
130
    QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
1638
130
    llvm::Value *FP = nullptr;
1639
    // If CFG.IsOutlinedSEHHelper is true, then we are within a finally block.
1640
130
    if (CGF.IsOutlinedSEHHelper) {
1641
13
      FP = &CGF.CurFn->arg_begin()[1];
1642
117
    } else {
1643
117
      llvm::Function *LocalAddrFn =
1644
117
          CGM.getIntrinsic(llvm::Intrinsic::localaddress);
1645
117
      FP = CGF.Builder.CreateCall(LocalAddrFn);
1646
117
    }
1647
1648
130
    llvm::Value *IsForEH =
1649
130
        llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1650
1651
    // Except _leave and fall-through at the end, all other exits in a _try
1652
    //   (return/goto/continue/break) are considered as abnormal terminations
1653
    //   since _leave/fall-through is always Indexed 0,
1654
    //   just use NormalCleanupDestSlot (>= 1 for goto/return/..),
1655
    //   as 1st Arg to indicate abnormal termination
1656
130
    if (!F.isForEHCleanup() && 
F.hasExitSwitch()77
) {
1657
1
      Address Addr = CGF.getNormalCleanupDestSlot();
1658
1
      llvm::Value *Load = CGF.Builder.CreateLoad(Addr, "cleanup.dest");
1659
1
      llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int32Ty);
1660
1
      IsForEH = CGF.Builder.CreateICmpNE(Load, Zero);
1661
1
    }
1662
1663
130
    Args.add(RValue::get(IsForEH), ArgTys[0]);
1664
130
    Args.add(RValue::get(FP), ArgTys[1]);
1665
1666
    // Arrange a two-arg function info and type.
1667
130
    const CGFunctionInfo &FnInfo =
1668
130
        CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
1669
1670
130
    auto Callee = CGCallee::forDirect(OutlinedFinally);
1671
130
    CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
1672
130
  }
1673
};
1674
} // end anonymous namespace
1675
1676
namespace {
1677
/// Find all local variable captures in the statement.
1678
struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1679
  CodeGenFunction &ParentCGF;
1680
  const VarDecl *ParentThis;
1681
  llvm::SmallSetVector<const VarDecl *, 4> Captures;
1682
  Address SEHCodeSlot = Address::invalid();
1683
  CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1684
107
      : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1685
1686
  // Return true if we need to do any capturing work.
1687
107
  bool foundCaptures() {
1688
107
    return !Captures.empty() || 
SEHCodeSlot.isValid()77
;
1689
107
  }
1690
1691
498
  void Visit(const Stmt *S) {
1692
    // See if this is a capture, then recurse.
1693
498
    ConstStmtVisitor<CaptureFinder>::Visit(S);
1694
498
    for (const Stmt *Child : S->children())
1695
391
      if (Child)
1696
391
        Visit(Child);
1697
498
  }
1698
1699
99
  void VisitDeclRefExpr(const DeclRefExpr *E) {
1700
    // If this is already a capture, just make sure we capture 'this'.
1701
99
    if (E->refersToEnclosingVariableOrCapture()) {
1702
0
      Captures.insert(ParentThis);
1703
0
      return;
1704
0
    }
1705
1706
99
    const auto *D = dyn_cast<VarDecl>(E->getDecl());
1707
99
    if (D && 
D->isLocalVarDeclOrParm()48
&&
D->hasLocalStorage()43
)
1708
42
      Captures.insert(D);
1709
99
  }
1710
1711
0
  void VisitCXXThisExpr(const CXXThisExpr *E) {
1712
0
    Captures.insert(ParentThis);
1713
0
  }
1714
1715
51
  void VisitCallExpr(const CallExpr *E) {
1716
    // We only need to add parent frame allocations for these builtins in x86.
1717
51
    if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1718
39
      return;
1719
1720
12
    unsigned ID = E->getBuiltinCallee();
1721
12
    switch (ID) {
1722
4
    case Builtin::BI__exception_code:
1723
4
    case Builtin::BI_exception_code:
1724
      // This is the simple case where we are the outermost finally. All we
1725
      // have to do here is make sure we escape this and recover it in the
1726
      // outlined handler.
1727
4
      if (!SEHCodeSlot.isValid())
1728
4
        SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1729
4
      break;
1730
12
    }
1731
12
  }
1732
};
1733
} // end anonymous namespace
1734
1735
Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
1736
                                                   Address ParentVar,
1737
47
                                                   llvm::Value *ParentFP) {
1738
47
  llvm::CallInst *RecoverCall = nullptr;
1739
47
  CGBuilderTy Builder(*this, AllocaInsertPt);
1740
47
  if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
1741
    // Mark the variable escaped if nobody else referenced it and compute the
1742
    // localescape index.
1743
43
    auto InsertPair = ParentCGF.EscapedLocals.insert(
1744
43
        std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1745
43
    int FrameEscapeIdx = InsertPair.first->second;
1746
    // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
1747
43
    llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1748
43
        &CGM.getModule(), llvm::Intrinsic::localrecover);
1749
43
    llvm::Constant *ParentI8Fn =
1750
43
        llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1751
43
    RecoverCall = Builder.CreateCall(
1752
43
        FrameRecoverFn, {ParentI8Fn, ParentFP,
1753
43
                         llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1754
1755
4
  } else {
1756
    // If the parent didn't have an alloca, we're doing some nested outlining.
1757
    // Just clone the existing localrecover call, but tweak the FP argument to
1758
    // use our FP value. All other arguments are constants.
1759
4
    auto *ParentRecover =
1760
4
        cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
1761
4
    assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1762
4
           "expected alloca or localrecover in parent LocalDeclMap");
1763
4
    RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1764
4
    RecoverCall->setArgOperand(1, ParentFP);
1765
4
    RecoverCall->insertBefore(AllocaInsertPt);
1766
4
  }
1767
1768
  // Bitcast the variable, rename it, and insert it in the local decl map.
1769
47
  llvm::Value *ChildVar =
1770
47
      Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1771
47
  ChildVar->setName(ParentVar.getName());
1772
47
  return Address(ChildVar, ParentVar.getAlignment());
1773
47
}
1774
1775
void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
1776
                                         const Stmt *OutlinedStmt,
1777
107
                                         bool IsFilter) {
1778
  // Find all captures in the Stmt.
1779
107
  CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1780
107
  Finder.Visit(OutlinedStmt);
1781
1782
  // We can exit early on x86_64 when there are no captures. We just have to
1783
  // save the exception code in filters so that __exception_code() works.
1784
107
  if (!Finder.foundCaptures() &&
1785
73
      CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1786
51
    if (IsFilter)
1787
10
      EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
1788
51
    return;
1789
51
  }
1790
1791
56
  llvm::Value *EntryFP = nullptr;
1792
56
  CGBuilderTy Builder(CGM, AllocaInsertPt);
1793
56
  if (IsFilter && 
CGM.getTarget().getTriple().getArch() == llvm::Triple::x8620
) {
1794
    // 32-bit SEH filters need to be careful about FP recovery.  The end of the
1795
    // EH registration is passed in as the EBP physical register.  We can
1796
    // recover that with llvm.frameaddress(1).
1797
12
    EntryFP = Builder.CreateCall(
1798
12
        CGM.getIntrinsic(llvm::Intrinsic::frameaddress, AllocaInt8PtrTy),
1799
12
        {Builder.getInt32(1)});
1800
44
  } else {
1801
    // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1802
    // second parameter.
1803
44
    auto AI = CurFn->arg_begin();
1804
44
    ++AI;
1805
44
    EntryFP = &*AI;
1806
44
  }
1807
1808
56
  llvm::Value *ParentFP = EntryFP;
1809
56
  if (IsFilter) {
1810
    // Given whatever FP the runtime provided us in EntryFP, recover the true
1811
    // frame pointer of the parent function. We only need to do this in filters,
1812
    // since finally funclets recover the parent FP for us.
1813
20
    llvm::Function *RecoverFPIntrin =
1814
20
        CGM.getIntrinsic(llvm::Intrinsic::eh_recoverfp);
1815
20
    llvm::Constant *ParentI8Fn =
1816
20
        llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1817
20
    ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
1818
1819
    // if the parent is a _finally, the passed-in ParentFP is the FP
1820
    // of parent _finally, not Establisher's FP (FP of outermost function).
1821
    // Establkisher FP is 2nd paramenter passed into parent _finally.
1822
    // Fortunately, it's always saved in parent's frame. The following
1823
    // code retrieves it, and escapes it so that spill instruction won't be
1824
    // optimized away.
1825
20
    if (ParentCGF.ParentCGF != nullptr) {
1826
      // Locate and escape Parent's frame_pointer.addr alloca
1827
      // Depending on target, should be 1st/2nd one in LocalDeclMap.
1828
      // Let's just scan for ImplicitParamDecl with VoidPtrTy.
1829
1
      llvm::AllocaInst *FramePtrAddrAlloca = nullptr;
1830
3
      for (auto &I : ParentCGF.LocalDeclMap) {
1831
3
        const VarDecl *D = cast<VarDecl>(I.first);
1832
3
        if (isa<ImplicitParamDecl>(D) &&
1833
2
            D->getType() == getContext().VoidPtrTy) {
1834
1
          assert(D->getName().startswith("frame_pointer"));
1835
1
          FramePtrAddrAlloca = cast<llvm::AllocaInst>(I.second.getPointer());
1836
1
          break;
1837
1
        }
1838
3
      }
1839
1
      assert(FramePtrAddrAlloca);
1840
1
      auto InsertPair = ParentCGF.EscapedLocals.insert(
1841
1
          std::make_pair(FramePtrAddrAlloca, ParentCGF.EscapedLocals.size()));
1842
1
      int FrameEscapeIdx = InsertPair.first->second;
1843
1844
      // an example of a filter's prolog::
1845
      // %0 = call i8* @llvm.eh.recoverfp(bitcast(@"?fin$0@0@main@@"),..)
1846
      // %1 = call i8* @llvm.localrecover(bitcast(@"?fin$0@0@main@@"),..)
1847
      // %2 = bitcast i8* %1 to i8**
1848
      // %3 = load i8*, i8* *%2, align 8
1849
      //   ==> %3 is the frame-pointer of outermost host function
1850
1
      llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1851
1
          &CGM.getModule(), llvm::Intrinsic::localrecover);
1852
1
      llvm::Constant *ParentI8Fn =
1853
1
          llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1854
1
      ParentFP = Builder.CreateCall(
1855
1
          FrameRecoverFn, {ParentI8Fn, ParentFP,
1856
1
                           llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1857
1
      ParentFP = Builder.CreateBitCast(ParentFP, CGM.VoidPtrPtrTy);
1858
1
      ParentFP = Builder.CreateLoad(Address(ParentFP, getPointerAlign()));
1859
1
    }
1860
20
  }
1861
1862
  // Create llvm.localrecover calls for all captures.
1863
31
  for (const VarDecl *VD : Finder.Captures) {
1864
31
    if (isa<ImplicitParamDecl>(VD)) {
1865
0
      CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1866
0
      CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1867
0
      continue;
1868
0
    }
1869
31
    if (VD->getType()->isVariablyModifiedType()) {
1870
0
      CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1871
0
      continue;
1872
0
    }
1873
31
    assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1874
31
           "captured non-local variable");
1875
1876
    // If this decl hasn't been declared yet, it will be declared in the
1877
    // OutlinedStmt.
1878
31
    auto I = ParentCGF.LocalDeclMap.find(VD);
1879
31
    if (I == ParentCGF.LocalDeclMap.end())
1880
0
      continue;
1881
1882
31
    Address ParentVar = I->second;
1883
31
    setAddrOfLocalVar(
1884
31
        VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
1885
31
  }
1886
1887
56
  if (Finder.SEHCodeSlot.isValid()) {
1888
4
    SEHCodeSlotStack.push_back(
1889
4
        recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1890
4
  }
1891
1892
56
  if (IsFilter)
1893
20
    EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
1894
56
}
1895
1896
/// Arrange a function prototype that can be called by Windows exception
1897
/// handling personalities. On Win64, the prototype looks like:
1898
/// RetTy func(void *EHPtrs, void *ParentFP);
1899
void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
1900
                                             bool IsFilter,
1901
107
                                             const Stmt *OutlinedStmt) {
1902
107
  SourceLocation StartLoc = OutlinedStmt->getBeginLoc();
1903
1904
  // Get the mangled function name.
1905
107
  SmallString<128> Name;
1906
107
  {
1907
107
    llvm::raw_svector_ostream OS(Name);
1908
107
    const NamedDecl *ParentSEHFn = ParentCGF.CurSEHParent;
1909
107
    assert(ParentSEHFn && "No CurSEHParent!");
1910
107
    MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1911
107
    if (IsFilter)
1912
30
      Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
1913
77
    else
1914
77
      Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
1915
107
  }
1916
1917
107
  FunctionArgList Args;
1918
107
  if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || 
!IsFilter34
) {
1919
    // All SEH finally functions take two parameters. Win64 filters take two
1920
    // parameters. Win32 filters take no parameters.
1921
95
    if (IsFilter) {
1922
18
      Args.push_back(ImplicitParamDecl::Create(
1923
18
          getContext(), /*DC=*/nullptr, StartLoc,
1924
18
          &getContext().Idents.get("exception_pointers"),
1925
18
          getContext().VoidPtrTy, ImplicitParamDecl::Other));
1926
77
    } else {
1927
77
      Args.push_back(ImplicitParamDecl::Create(
1928
77
          getContext(), /*DC=*/nullptr, StartLoc,
1929
77
          &getContext().Idents.get("abnormal_termination"),
1930
77
          getContext().UnsignedCharTy, ImplicitParamDecl::Other));
1931
77
    }
1932
95
    Args.push_back(ImplicitParamDecl::Create(
1933
95
        getContext(), /*DC=*/nullptr, StartLoc,
1934
95
        &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
1935
95
        ImplicitParamDecl::Other));
1936
95
  }
1937
1938
77
  QualType RetTy = IsFilter ? 
getContext().LongTy30
: getContext().VoidTy;
1939
1940
107
  const CGFunctionInfo &FnInfo =
1941
107
    CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
1942
1943
107
  llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1944
107
  llvm::Function *Fn = llvm::Function::Create(
1945
107
      FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
1946
1947
107
  IsOutlinedSEHHelper = true;
1948
1949
107
  StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1950
107
                OutlinedStmt->getBeginLoc(), OutlinedStmt->getBeginLoc());
1951
107
  CurSEHParent = ParentCGF.CurSEHParent;
1952
1953
107
  CGM.SetInternalFunctionAttributes(GlobalDecl(), CurFn, FnInfo);
1954
107
  EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
1955
107
}
1956
1957
/// Create a stub filter function that will ultimately hold the code of the
1958
/// filter expression. The EH preparation passes in LLVM will outline the code
1959
/// from the main function body into this stub.
1960
llvm::Function *
1961
CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1962
30
                                           const SEHExceptStmt &Except) {
1963
30
  const Expr *FilterExpr = Except.getFilterExpr();
1964
30
  startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
1965
1966
  // Emit the original filter expression, convert to i32, and return.
1967
30
  llvm::Value *R = EmitScalarExpr(FilterExpr);
1968
30
  R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
1969
30
                            FilterExpr->getType()->isSignedIntegerType());
1970
30
  Builder.CreateStore(R, ReturnValue);
1971
1972
30
  FinishFunction(FilterExpr->getEndLoc());
1973
1974
30
  return CurFn;
1975
30
}
1976
1977
llvm::Function *
1978
CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1979
77
                                            const SEHFinallyStmt &Finally) {
1980
77
  const Stmt *FinallyBlock = Finally.getBlock();
1981
77
  startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
1982
1983
  // Emit the original filter expression, convert to i32, and return.
1984
77
  EmitStmt(FinallyBlock);
1985
1986
77
  FinishFunction(FinallyBlock->getEndLoc());
1987
1988
77
  return CurFn;
1989
77
}
1990
1991
void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
1992
                                               llvm::Value *ParentFP,
1993
30
                                               llvm::Value *EntryFP) {
1994
  // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1995
  // __exception_info intrinsic.
1996
30
  if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1997
    // On Win64, the info is passed as the first parameter to the filter.
1998
18
    SEHInfo = &*CurFn->arg_begin();
1999
18
    SEHCodeSlotStack.push_back(
2000
18
        CreateMemTemp(getContext().IntTy, "__exception_code"));
2001
12
  } else {
2002
    // On Win32, the EBP on entry to the filter points to the end of an
2003
    // exception registration object. It contains 6 32-bit fields, and the info
2004
    // pointer is stored in the second field. So, GEP 20 bytes backwards and
2005
    // load the pointer.
2006
12
    SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
2007
12
    SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
2008
12
    SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
2009
12
    SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
2010
12
        ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
2011
12
  }
2012
2013
  // Save the exception code in the exception slot to unify exception access in
2014
  // the filter function and the landing pad.
2015
  // struct EXCEPTION_POINTERS {
2016
  //   EXCEPTION_RECORD *ExceptionRecord;
2017
  //   CONTEXT *ContextRecord;
2018
  // };
2019
  // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
2020
30
  llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
2021
30
  llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
2022
30
  llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
2023
30
  llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
2024
30
  Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
2025
30
  llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
2026
30
  assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
2027
30
  Builder.CreateStore(Code, SEHCodeSlotStack.back());
2028
30
}
2029
2030
0
llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
2031
  // Sema should diagnose calling this builtin outside of a filter context, but
2032
  // don't crash if we screw up.
2033
0
  if (!SEHInfo)
2034
0
    return llvm::UndefValue::get(Int8PtrTy);
2035
0
  assert(SEHInfo->getType() == Int8PtrTy);
2036
0
  return SEHInfo;
2037
0
}
2038
2039
18
llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
2040
18
  assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
2041
18
  return Builder.CreateLoad(SEHCodeSlotStack.back());
2042
18
}
2043
2044
3
llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
2045
  // Abnormal termination is just the first parameter to the outlined finally
2046
  // helper.
2047
3
  auto AI = CurFn->arg_begin();
2048
3
  return Builder.CreateZExt(&*AI, Int32Ty);
2049
3
}
2050
2051
void CodeGenFunction::pushSEHCleanup(CleanupKind Kind,
2052
0
                                     llvm::Function *FinallyFunc) {
2053
0
  EHStack.pushCleanup<PerformSEHFinally>(Kind, FinallyFunc);
2054
0
}
2055
2056
128
void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
2057
128
  CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
2058
128
  HelperCGF.ParentCGF = this;
2059
128
  if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
2060
    // Outline the finally block.
2061
77
    llvm::Function *FinallyFunc =
2062
77
        HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
2063
2064
    // Push a cleanup for __finally blocks.
2065
77
    EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
2066
77
    return;
2067
77
  }
2068
2069
  // Otherwise, we must have an __except block.
2070
51
  const SEHExceptStmt *Except = S.getExceptHandler();
2071
51
  assert(Except);
2072
51
  EHCatchScope *CatchScope = EHStack.pushCatch(1);
2073
51
  SEHCodeSlotStack.push_back(
2074
51
      CreateMemTemp(getContext().IntTy, "__exception_code"));
2075
2076
  // If the filter is known to evaluate to 1, then we can use the clause
2077
  // "catch i8* null". We can't do this on x86 because the filter has to save
2078
  // the exception code.
2079
51
  llvm::Constant *C =
2080
51
    ConstantEmitter(*this).tryEmitAbstract(Except->getFilterExpr(),
2081
51
                                           getContext().IntTy);
2082
51
  if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && 
C39
&&
2083
21
      C->isOneValue()) {
2084
21
    CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
2085
21
    return;
2086
21
  }
2087
2088
  // In general, we have to emit an outlined filter function. Use the function
2089
  // in place of the RTTI typeinfo global that C++ EH uses.
2090
30
  llvm::Function *FilterFunc =
2091
30
      HelperCGF.GenerateSEHFilterFunction(*this, *Except);
2092
30
  llvm::Constant *OpaqueFunc =
2093
30
      llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
2094
30
  CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
2095
30
}
2096
2097
128
void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
2098
  // Just pop the cleanup if it's a __finally block.
2099
128
  if (S.getFinallyHandler()) {
2100
77
    PopCleanupBlock();
2101
77
    return;
2102
77
  }
2103
2104
  // Otherwise, we must have an __except block.
2105
51
  const SEHExceptStmt *Except = S.getExceptHandler();
2106
51
  assert(Except && "__try must have __finally xor __except");
2107
51
  EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
2108
2109
  // Don't emit the __except block if the __try block lacked invokes.
2110
  // TODO: Model unwind edges from instructions, either with iload / istore or
2111
  // a try body function.
2112
51
  if (!CatchScope.hasEHBranches()) {
2113
4
    CatchScope.clearHandlerBlocks();
2114
4
    EHStack.popCatch();
2115
4
    SEHCodeSlotStack.pop_back();
2116
4
    return;
2117
4
  }
2118
2119
  // The fall-through block.
2120
47
  llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
2121
2122
  // We just emitted the body of the __try; jump to the continue block.
2123
47
  if (HaveInsertPoint())
2124
42
    Builder.CreateBr(ContBB);
2125
2126
  // Check if our filter function returned true.
2127
47
  emitCatchDispatchBlock(*this, CatchScope);
2128
2129
  // Grab the block before we pop the handler.
2130
47
  llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
2131
47
  EHStack.popCatch();
2132
2133
47
  EmitBlockAfterUses(CatchPadBB);
2134
2135
  // __except blocks don't get outlined into funclets, so immediately do a
2136
  // catchret.
2137
47
  llvm::CatchPadInst *CPI =
2138
47
      cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
2139
47
  llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
2140
47
  Builder.CreateCatchRet(CPI, ExceptBB);
2141
47
  EmitBlock(ExceptBB);
2142
2143
  // On Win64, the exception code is returned in EAX. Copy it into the slot.
2144
47
  if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
2145
35
    llvm::Function *SEHCodeIntrin =
2146
35
        CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
2147
35
    llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
2148
35
    Builder.CreateStore(Code, SEHCodeSlotStack.back());
2149
35
  }
2150
2151
  // Emit the __except body.
2152
47
  EmitStmt(Except->getBlock());
2153
2154
  // End the lifetime of the exception code.
2155
47
  SEHCodeSlotStack.pop_back();
2156
2157
47
  if (HaveInsertPoint())
2158
34
    Builder.CreateBr(ContBB);
2159
2160
47
  EmitBlock(ContBB);
2161
47
}
2162
2163
10
void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
2164
  // If this code is reachable then emit a stop point (if generating
2165
  // debug info). We have to do this ourselves because we are on the
2166
  // "simple" statement path.
2167
10
  if (HaveInsertPoint())
2168
10
    EmitStopPoint(&S);
2169
2170
  // This must be a __leave from a __finally block, which we warn on and is UB.
2171
  // Just emit unreachable.
2172
10
  if (!isSEHTryScope()) {
2173
2
    Builder.CreateUnreachable();
2174
2
    Builder.ClearInsertionPoint();
2175
2
    return;
2176
2
  }
2177
2178
8
  EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
2179
8
}