Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaExceptionSpec.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaExceptionSpec.cpp - C++ Exception Specifications ---*- 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 file provides Sema routines for C++ exception specification testing.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Sema/SemaInternal.h"
14
#include "clang/AST/ASTMutationListener.h"
15
#include "clang/AST/CXXInheritance.h"
16
#include "clang/AST/Expr.h"
17
#include "clang/AST/ExprCXX.h"
18
#include "clang/AST/StmtObjC.h"
19
#include "clang/AST/TypeLoc.h"
20
#include "clang/Basic/Diagnostic.h"
21
#include "clang/Basic/SourceManager.h"
22
#include "llvm/ADT/SmallPtrSet.h"
23
#include "llvm/ADT/SmallString.h"
24
25
namespace clang {
26
27
static const FunctionProtoType *GetUnderlyingFunction(QualType T)
28
3.75M
{
29
3.75M
  if (const PointerType *PtrTy = T->getAs<PointerType>())
30
476k
    T = PtrTy->getPointeeType();
31
3.28M
  else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
32
2.98k
    T = RefTy->getPointeeType();
33
3.27M
  else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
34
3.89k
    T = MPTy->getPointeeType();
35
3.75M
  return T->getAs<FunctionProtoType>();
36
3.75M
}
37
38
/// HACK: libstdc++ has a bug where it shadows std::swap with a member
39
/// swap function then tries to call std::swap unqualified from the exception
40
/// specification of that function. This function detects whether we're in
41
/// such a case and turns off delay-parsing of exception specifications.
42
919k
bool Sema::isLibstdcxxEagerExceptionSpecHack(const Declarator &D) {
43
919k
  auto *RD = dyn_cast<CXXRecordDecl>(CurContext);
44
919k
45
919k
  // All the problem cases are member functions named "swap" within class
46
919k
  // templates declared directly within namespace std or std::__debug or
47
919k
  // std::__profile.
48
919k
  if (!RD || 
!RD->getIdentifier()919k
||
!RD->getDescribedClassTemplate()919k
||
49
919k
      
!D.getIdentifier()480k
||
!D.getIdentifier()->isStr("swap")260k
)
50
914k
    return false;
51
5.24k
52
5.24k
  auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext());
53
5.24k
  if (!ND)
54
1
    return false;
55
5.24k
56
5.24k
  bool IsInStd = ND->isStdNamespace();
57
5.24k
  if (!IsInStd) {
58
23
    // This isn't a direct member of namespace std, but it might still be
59
23
    // libstdc++'s std::__debug::array or std::__profile::array.
60
23
    IdentifierInfo *II = ND->getIdentifier();
61
23
    if (!II || !(II->isStr("__debug") || 
II->isStr("__profile")22
) ||
62
23
        
!ND->isInStdNamespace()2
)
63
21
      return false;
64
5.22k
  }
65
5.22k
66
5.22k
  // Only apply this hack within a system header.
67
5.22k
  if (!Context.getSourceManager().isInSystemHeader(D.getBeginLoc()))
68
0
    return false;
69
5.22k
70
5.22k
  return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
71
5.22k
      .Case("array", true)
72
5.22k
      .Case("pair", IsInStd)
73
5.22k
      .Case("priority_queue", IsInStd)
74
5.22k
      .Case("stack", IsInStd)
75
5.22k
      .Case("queue", IsInStd)
76
5.22k
      .Default(false);
77
5.22k
}
78
79
ExprResult Sema::ActOnNoexceptSpec(SourceLocation NoexceptLoc,
80
                                   Expr *NoexceptExpr,
81
52.5k
                                   ExceptionSpecificationType &EST) {
82
52.5k
  // FIXME: This is bogus, a noexcept expression is not a condition.
83
52.5k
  ExprResult Converted = CheckBooleanCondition(NoexceptLoc, NoexceptExpr);
84
52.5k
  if (Converted.isInvalid()) {
85
10
    EST = EST_NoexceptFalse;
86
10
87
10
    // Fill in an expression of 'false' as a fixup.
88
10
    auto *BoolExpr = new (Context)
89
10
        CXXBoolLiteralExpr(false, Context.BoolTy, NoexceptExpr->getBeginLoc());
90
10
    llvm::APSInt Value{1};
91
10
    Value = 0;
92
10
    return ConstantExpr::Create(Context, BoolExpr, APValue{Value});
93
10
  }
94
52.5k
95
52.5k
  if (Converted.get()->isValueDependent()) {
96
46.2k
    EST = EST_DependentNoexcept;
97
46.2k
    return Converted;
98
46.2k
  }
99
6.27k
100
6.27k
  llvm::APSInt Result;
101
6.27k
  Converted = VerifyIntegerConstantExpression(
102
6.27k
      Converted.get(), &Result,
103
6.27k
      diag::err_noexcept_needs_constant_expression,
104
6.27k
      /*AllowFold*/ false);
105
6.27k
  if (!Converted.isInvalid())
106
6.27k
    EST = !Result ? 
EST_NoexceptFalse727
:
EST_NoexceptTrue5.54k
;
107
6.27k
  return Converted;
108
6.27k
}
109
110
/// CheckSpecifiedExceptionType - Check if the given type is valid in an
111
/// exception specification. Incomplete types, or pointers to incomplete types
112
/// other than void are not allowed.
113
///
114
/// \param[in,out] T  The exception type. This will be decayed to a pointer type
115
///                   when the input is an array or a function type.
116
729
bool Sema::CheckSpecifiedExceptionType(QualType &T, SourceRange Range) {
117
729
  // C++11 [except.spec]p2:
118
729
  //   A type cv T, "array of T", or "function returning T" denoted
119
729
  //   in an exception-specification is adjusted to type T, "pointer to T", or
120
729
  //   "pointer to function returning T", respectively.
121
729
  //
122
729
  // We also apply this rule in C++98.
123
729
  if (T->isArrayType())
124
14
    T = Context.getArrayDecayedType(T);
125
715
  else if (T->isFunctionType())
126
4
    T = Context.getPointerType(T);
127
729
128
729
  int Kind = 0;
129
729
  QualType PointeeT = T;
130
729
  if (const PointerType *PT = T->getAs<PointerType>()) {
131
94
    PointeeT = PT->getPointeeType();
132
94
    Kind = 1;
133
94
134
94
    // cv void* is explicitly permitted, despite being a pointer to an
135
94
    // incomplete type.
136
94
    if (PointeeT->isVoidType())
137
5
      return false;
138
635
  } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
139
54
    PointeeT = RT->getPointeeType();
140
54
    Kind = 2;
141
54
142
54
    if (RT->isRValueReferenceType()) {
143
3
      // C++11 [except.spec]p2:
144
3
      //   A type denoted in an exception-specification shall not denote [...]
145
3
      //   an rvalue reference type.
146
3
      Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
147
3
        << T << Range;
148
3
      return true;
149
3
    }
150
721
  }
151
721
152
721
  // C++11 [except.spec]p2:
153
721
  //   A type denoted in an exception-specification shall not denote an
154
721
  //   incomplete type other than a class currently being defined [...].
155
721
  //   A type denoted in an exception-specification shall not denote a
156
721
  //   pointer or reference to an incomplete type, other than (cv) void* or a
157
721
  //   pointer or reference to a class currently being defined.
158
721
  // In Microsoft mode, downgrade this to a warning.
159
721
  unsigned DiagID = diag::err_incomplete_in_exception_spec;
160
721
  bool ReturnValueOnError = true;
161
721
  if (getLangOpts().MSVCCompat) {
162
4
    DiagID = diag::ext_incomplete_in_exception_spec;
163
4
    ReturnValueOnError = false;
164
4
  }
165
721
  if (!(PointeeT->isRecordType() &&
166
721
        
PointeeT->castAs<RecordType>()->isBeingDefined()229
) &&
167
721
      
RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range)718
)
168
17
    return ReturnValueOnError;
169
704
170
704
  return false;
171
704
}
172
173
/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
174
/// to member to a function with an exception specification. This means that
175
/// it is invalid to add another level of indirection.
176
3.03M
bool Sema::CheckDistantExceptionSpec(QualType T) {
177
3.03M
  // C++17 removes this rule in favor of putting exception specifications into
178
3.03M
  // the type system.
179
3.03M
  if (getLangOpts().CPlusPlus17)
180
73.8k
    return false;
181
2.96M
182
2.96M
  if (const PointerType *PT = T->getAs<PointerType>())
183
82.4k
    T = PT->getPointeeType();
184
2.88M
  else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
185
181
    T = PT->getPointeeType();
186
2.88M
  else
187
2.88M
    return false;
188
82.5k
189
82.5k
  const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
190
82.5k
  if (!FnT)
191
82.0k
    return false;
192
571
193
571
  return FnT->hasExceptionSpec();
194
571
}
195
196
const FunctionProtoType *
197
3.65M
Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
198
3.65M
  if (FPT->getExceptionSpecType() == EST_Unparsed) {
199
1
    Diag(Loc, diag::err_exception_spec_not_parsed);
200
1
    return nullptr;
201
1
  }
202
3.65M
203
3.65M
  if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
204
3.47M
    return FPT;
205
182k
206
182k
  FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
207
182k
  const FunctionProtoType *SourceFPT =
208
182k
      SourceDecl->getType()->castAs<FunctionProtoType>();
209
182k
210
182k
  // If the exception specification has already been resolved, just return it.
211
182k
  if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
212
6.84k
    return SourceFPT;
213
175k
214
175k
  // Compute or instantiate the exception specification now.
215
175k
  if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
216
169k
    EvaluateImplicitExceptionSpec(Loc, SourceDecl);
217
5.87k
  else
218
5.87k
    InstantiateExceptionSpec(Loc, SourceDecl);
219
175k
220
175k
  const FunctionProtoType *Proto =
221
175k
    SourceDecl->getType()->castAs<FunctionProtoType>();
222
175k
  if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
223
2
    Diag(Loc, diag::err_exception_spec_not_parsed);
224
2
    Proto = nullptr;
225
2
  }
226
175k
  return Proto;
227
175k
}
228
229
void
230
Sema::UpdateExceptionSpec(FunctionDecl *FD,
231
519k
                          const FunctionProtoType::ExceptionSpecInfo &ESI) {
232
519k
  // If we've fully resolved the exception specification, notify listeners.
233
519k
  if (!isUnresolvedExceptionSpec(ESI.Type))
234
519k
    if (auto *Listener = getASTMutationListener())
235
54.3k
      Listener->ResolvedExceptionSpec(FD);
236
519k
237
519k
  for (FunctionDecl *Redecl : FD->redecls())
238
519k
    Context.adjustExceptionSpec(Redecl, ESI);
239
519k
}
240
241
494k
static bool exceptionSpecNotKnownYet(const FunctionDecl *FD) {
242
494k
  auto *MD = dyn_cast<CXXMethodDecl>(FD);
243
494k
  if (!MD)
244
127k
    return false;
245
367k
246
367k
  auto EST = MD->getType()->castAs<FunctionProtoType>()->getExceptionSpecType();
247
367k
  return EST == EST_Unparsed ||
248
367k
         
(367k
EST == EST_Unevaluated367k
&&
MD->getParent()->isBeingDefined()18.2k
);
249
367k
}
250
251
static bool CheckEquivalentExceptionSpecImpl(
252
    Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
253
    const FunctionProtoType *Old, SourceLocation OldLoc,
254
    const FunctionProtoType *New, SourceLocation NewLoc,
255
    bool *MissingExceptionSpecification = nullptr,
256
    bool *MissingEmptyExceptionSpecification = nullptr,
257
    bool AllowNoexceptAllMatchWithNoSpec = false, bool IsOperatorNew = false);
258
259
/// Determine whether a function has an implicitly-generated exception
260
/// specification.
261
409k
static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
262
409k
  if (!isa<CXXDestructorDecl>(Decl) &&
263
409k
      
Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete403k
&&
264
409k
      
Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete402k
)
265
401k
    return false;
266
8.30k
267
8.30k
  // For a function that the user didn't declare:
268
8.30k
  //  - if this is a destructor, its exception specification is implicit.
269
8.30k
  //  - if this is 'operator delete' or 'operator delete[]', the exception
270
8.30k
  //    specification is as-if an explicit exception specification was given
271
8.30k
  //    (per [basic.stc.dynamic]p2).
272
8.30k
  if (!Decl->getTypeSourceInfo())
273
769
    return isa<CXXDestructorDecl>(Decl);
274
7.53k
275
7.53k
  auto *Ty = Decl->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
276
7.53k
  return !Ty->hasExceptionSpec();
277
7.53k
}
278
279
225k
bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
280
225k
  // Just completely ignore this under -fno-exceptions prior to C++17.
281
225k
  // In C++17 onwards, the exception specification is part of the type and
282
225k
  // we will diagnose mismatches anyway, so it's better to check for them here.
283
225k
  if (!getLangOpts().CXXExceptions && 
!getLangOpts().CPlusPlus1719.8k
)
284
16.0k
    return false;
285
209k
286
209k
  OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
287
209k
  bool IsOperatorNew = OO == OO_New || 
OO == OO_Array_New209k
;
288
209k
  bool MissingExceptionSpecification = false;
289
209k
  bool MissingEmptyExceptionSpecification = false;
290
209k
291
209k
  unsigned DiagID = diag::err_mismatched_exception_spec;
292
209k
  bool ReturnValueOnError = true;
293
209k
  if (getLangOpts().MSVCCompat) {
294
173
    DiagID = diag::ext_mismatched_exception_spec;
295
173
    ReturnValueOnError = false;
296
173
  }
297
209k
298
209k
  // If we're befriending a member function of a class that's currently being
299
209k
  // defined, we might not be able to work out its exception specification yet.
300
209k
  // If not, defer the check until later.
301
209k
  if (exceptionSpecNotKnownYet(Old) || 
exceptionSpecNotKnownYet(New)209k
) {
302
7
    DelayedEquivalentExceptionSpecChecks.push_back({New, Old});
303
7
    return false;
304
7
  }
305
209k
306
209k
  // Check the types as written: they must match before any exception
307
209k
  // specification adjustment is applied.
308
209k
  if (!CheckEquivalentExceptionSpecImpl(
309
209k
        *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
310
209k
        Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
311
209k
        New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
312
209k
        &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
313
209k
        /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
314
209k
    // C++11 [except.spec]p4 [DR1492]:
315
209k
    //   If a declaration of a function has an implicit
316
209k
    //   exception-specification, other declarations of the function shall
317
209k
    //   not specify an exception-specification.
318
209k
    if (getLangOpts().CPlusPlus11 && 
getLangOpts().CXXExceptions208k
&&
319
209k
        
hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)204k
) {
320
16
      Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
321
16
        << hasImplicitExceptionSpec(Old);
322
16
      if (Old->getLocation().isValid())
323
11
        Diag(Old->getLocation(), diag::note_previous_declaration);
324
16
    }
325
209k
    return false;
326
209k
  }
327
301
328
301
  // The failure was something other than an missing exception
329
301
  // specification; return an error, except in MS mode where this is a warning.
330
301
  if (!MissingExceptionSpecification)
331
43
    return ReturnValueOnError;
332
258
333
258
  const FunctionProtoType *NewProto =
334
258
    New->getType()->castAs<FunctionProtoType>();
335
258
336
258
  // The new function declaration is only missing an empty exception
337
258
  // specification "throw()". If the throw() specification came from a
338
258
  // function in a system header that has C linkage, just add an empty
339
258
  // exception specification to the "new" declaration. Note that C library
340
258
  // implementations are permitted to add these nothrow exception
341
258
  // specifications.
342
258
  //
343
258
  // Likewise if the old function is a builtin.
344
258
  if (MissingEmptyExceptionSpecification && 
NewProto253
&&
345
258
      
(253
Old->getLocation().isInvalid()253
||
346
253
       Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
347
253
       
Old->getBuiltinID()21
) &&
348
258
      
Old->isExternC()235
) {
349
235
    New->setType(Context.getFunctionType(
350
235
        NewProto->getReturnType(), NewProto->getParamTypes(),
351
235
        NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
352
235
    return false;
353
235
  }
354
23
355
23
  const FunctionProtoType *OldProto =
356
23
    Old->getType()->castAs<FunctionProtoType>();
357
23
358
23
  FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
359
23
  if (ESI.Type == EST_Dynamic) {
360
4
    // FIXME: What if the exceptions are described in terms of the old
361
4
    // prototype's parameters?
362
4
    ESI.Exceptions = OldProto->exceptions();
363
4
  }
364
23
365
23
  if (ESI.Type == EST_NoexceptFalse)
366
0
    ESI.Type = EST_None;
367
23
  if (ESI.Type == EST_NoexceptTrue)
368
1
    ESI.Type = EST_BasicNoexcept;
369
23
370
23
  // For dependent noexcept, we can't just take the expression from the old
371
23
  // prototype. It likely contains references to the old prototype's parameters.
372
23
  if (ESI.Type == EST_DependentNoexcept) {
373
1
    New->setInvalidDecl();
374
22
  } else {
375
22
    // Update the type of the function with the appropriate exception
376
22
    // specification.
377
22
    New->setType(Context.getFunctionType(
378
22
        NewProto->getReturnType(), NewProto->getParamTypes(),
379
22
        NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
380
22
  }
381
23
382
23
  if (getLangOpts().MSVCCompat && 
ESI.Type != EST_DependentNoexcept2
) {
383
2
    // Allow missing exception specifications in redeclarations as an extension.
384
2
    DiagID = diag::ext_ms_missing_exception_specification;
385
2
    ReturnValueOnError = false;
386
21
  } else if (New->isReplaceableGlobalAllocationFunction() &&
387
21
             
ESI.Type != EST_DependentNoexcept3
) {
388
3
    // Allow missing exception specifications in redeclarations as an extension,
389
3
    // when declaring a replaceable global allocation function.
390
3
    DiagID = diag::ext_missing_exception_specification;
391
3
    ReturnValueOnError = false;
392
18
  } else if (ESI.Type == EST_NoThrow) {
393
5
    // Allow missing attribute 'nothrow' in redeclarations, since this is a very
394
5
    // common omission.
395
5
    DiagID = diag::ext_missing_exception_specification;
396
5
    ReturnValueOnError = false;
397
13
  } else {
398
13
    DiagID = diag::err_missing_exception_specification;
399
13
    ReturnValueOnError = true;
400
13
  }
401
23
402
23
  // Warn about the lack of exception specification.
403
23
  SmallString<128> ExceptionSpecString;
404
23
  llvm::raw_svector_ostream OS(ExceptionSpecString);
405
23
  switch (OldProto->getExceptionSpecType()) {
406
8
  case EST_DynamicNone:
407
8
    OS << "throw()";
408
8
    break;
409
0
410
4
  case EST_Dynamic: {
411
4
    OS << "throw(";
412
4
    bool OnFirstException = true;
413
4
    for (const auto &E : OldProto->exceptions()) {
414
4
      if (OnFirstException)
415
4
        OnFirstException = false;
416
0
      else
417
0
        OS << ", ";
418
4
419
4
      OS << E.getAsString(getPrintingPolicy());
420
4
    }
421
4
    OS << ")";
422
4
    break;
423
0
  }
424
0
425
4
  case EST_BasicNoexcept:
426
4
    OS << "noexcept";
427
4
    break;
428
0
429
2
  case EST_DependentNoexcept:
430
2
  case EST_NoexceptFalse:
431
2
  case EST_NoexceptTrue:
432
2
    OS << "noexcept(";
433
2
    assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
434
2
    OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
435
2
    OS << ")";
436
2
    break;
437
5
  case EST_NoThrow:
438
5
    OS <<"__attribute__((nothrow))";
439
5
    break;
440
2
  case EST_None:
441
0
  case EST_MSAny:
442
0
  case EST_Unevaluated:
443
0
  case EST_Uninstantiated:
444
0
  case EST_Unparsed:
445
0
    llvm_unreachable("This spec type is compatible with none.");
446
23
  }
447
23
448
23
  SourceLocation FixItLoc;
449
23
  if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
450
23
    TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
451
23
    // FIXME: Preserve enough information so that we can produce a correct fixit
452
23
    // location when there is a trailing return type.
453
23
    if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
454
23
      if (!FTLoc.getTypePtr()->hasTrailingReturn())
455
23
        FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
456
23
  }
457
23
458
23
  if (FixItLoc.isInvalid())
459
0
    Diag(New->getLocation(), DiagID)
460
0
      << New << OS.str();
461
23
  else {
462
23
    Diag(New->getLocation(), DiagID)
463
23
      << New << OS.str()
464
23
      << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
465
23
  }
466
23
467
23
  if (Old->getLocation().isValid())
468
22
    Diag(Old->getLocation(), diag::note_previous_declaration);
469
23
470
23
  return ReturnValueOnError;
471
23
}
472
473
/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
474
/// exception specifications. Exception specifications are equivalent if
475
/// they allow exactly the same set of exception types. It does not matter how
476
/// that is achieved. See C++ [except.spec]p2.
477
bool Sema::CheckEquivalentExceptionSpec(
478
    const FunctionProtoType *Old, SourceLocation OldLoc,
479
1.11k
    const FunctionProtoType *New, SourceLocation NewLoc) {
480
1.11k
  if (!getLangOpts().CXXExceptions)
481
613
    return false;
482
505
483
505
  unsigned DiagID = diag::err_mismatched_exception_spec;
484
505
  if (getLangOpts().MSVCCompat)
485
0
    DiagID = diag::ext_mismatched_exception_spec;
486
505
  bool Result = CheckEquivalentExceptionSpecImpl(
487
505
      *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
488
505
      Old, OldLoc, New, NewLoc);
489
505
490
505
  // In Microsoft mode, mismatching exception specifications just cause a warning.
491
505
  if (getLangOpts().MSVCCompat)
492
0
    return false;
493
505
  return Result;
494
505
}
495
496
/// CheckEquivalentExceptionSpec - Check if the two types have compatible
497
/// exception specifications. See C++ [except.spec]p3.
498
///
499
/// \return \c false if the exception specifications match, \c true if there is
500
/// a problem. If \c true is returned, either a diagnostic has already been
501
/// produced or \c *MissingExceptionSpecification is set to \c true.
502
static bool CheckEquivalentExceptionSpecImpl(
503
    Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
504
    const FunctionProtoType *Old, SourceLocation OldLoc,
505
    const FunctionProtoType *New, SourceLocation NewLoc,
506
    bool *MissingExceptionSpecification,
507
    bool *MissingEmptyExceptionSpecification,
508
210k
    bool AllowNoexceptAllMatchWithNoSpec, bool IsOperatorNew) {
509
210k
  if (MissingExceptionSpecification)
510
209k
    *MissingExceptionSpecification = false;
511
210k
512
210k
  if (MissingEmptyExceptionSpecification)
513
209k
    *MissingEmptyExceptionSpecification = false;
514
210k
515
210k
  Old = S.ResolveExceptionSpec(NewLoc, Old);
516
210k
  if (!Old)
517
0
    return false;
518
210k
  New = S.ResolveExceptionSpec(NewLoc, New);
519
210k
  if (!New)
520
0
    return false;
521
210k
522
210k
  // C++0x [except.spec]p3: Two exception-specifications are compatible if:
523
210k
  //   - both are non-throwing, regardless of their form,
524
210k
  //   - both have the form noexcept(constant-expression) and the constant-
525
210k
  //     expressions are equivalent,
526
210k
  //   - both are dynamic-exception-specifications that have the same set of
527
210k
  //     adjusted types.
528
210k
  //
529
210k
  // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
530
210k
  //   of the form throw(), noexcept, or noexcept(constant-expression) where the
531
210k
  //   constant-expression yields true.
532
210k
  //
533
210k
  // C++0x [except.spec]p4: If any declaration of a function has an exception-
534
210k
  //   specifier that is not a noexcept-specification allowing all exceptions,
535
210k
  //   all declarations [...] of that function shall have a compatible
536
210k
  //   exception-specification.
537
210k
  //
538
210k
  // That last point basically means that noexcept(false) matches no spec.
539
210k
  // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
540
210k
541
210k
  ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
542
210k
  ExceptionSpecificationType NewEST = New->getExceptionSpecType();
543
210k
544
210k
  assert(!isUnresolvedExceptionSpec(OldEST) &&
545
210k
         !isUnresolvedExceptionSpec(NewEST) &&
546
210k
         "Shouldn't see unknown exception specifications here");
547
210k
548
210k
  CanThrowResult OldCanThrow = Old->canThrow();
549
210k
  CanThrowResult NewCanThrow = New->canThrow();
550
210k
551
210k
  // Any non-throwing specifications are compatible.
552
210k
  if (OldCanThrow == CT_Cannot && 
NewCanThrow == CT_Cannot51.0k
)
553
50.8k
    return false;
554
159k
555
159k
  // Any throws-anything specifications are usually compatible.
556
159k
  if (OldCanThrow == CT_Can && 
OldEST != EST_Dynamic153k
&&
557
159k
      
NewCanThrow == CT_Can153k
&&
NewEST != EST_Dynamic153k
) {
558
153k
    // The exception is that the absence of an exception specification only
559
153k
    // matches noexcept(false) for functions, as described above.
560
153k
    if (!AllowNoexceptAllMatchWithNoSpec &&
561
153k
        
(487
(487
OldEST == EST_None487
&&
NewEST == EST_NoexceptFalse485
) ||
562
487
         
(486
OldEST == EST_NoexceptFalse486
&&
NewEST == EST_None2
))) {
563
1
      // This is the disallowed case.
564
153k
    } else {
565
153k
      return false;
566
153k
    }
567
6.14k
  }
568
6.14k
569
6.14k
  // C++14 [except.spec]p3:
570
6.14k
  //   Two exception-specifications are compatible if [...] both have the form
571
6.14k
  //   noexcept(constant-expression) and the constant-expressions are equivalent
572
6.14k
  if (OldEST == EST_DependentNoexcept && 
NewEST == EST_DependentNoexcept5.79k
) {
573
5.79k
    llvm::FoldingSetNodeID OldFSN, NewFSN;
574
5.79k
    Old->getNoexceptExpr()->Profile(OldFSN, S.Context, true);
575
5.79k
    New->getNoexceptExpr()->Profile(NewFSN, S.Context, true);
576
5.79k
    if (OldFSN == NewFSN)
577
5.79k
      return false;
578
354
  }
579
354
580
354
  // Dynamic exception specifications with the same set of adjusted types
581
354
  // are compatible.
582
354
  if (OldEST == EST_Dynamic && 
NewEST == EST_Dynamic46
) {
583
29
    bool Success = true;
584
29
    // Both have a dynamic exception spec. Collect the first set, then compare
585
29
    // to the second.
586
29
    llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
587
29
    for (const auto &I : Old->exceptions())
588
34
      OldTypes.insert(S.Context.getCanonicalType(I).getUnqualifiedType());
589
29
590
36
    for (const auto &I : New->exceptions()) {
591
36
      CanQualType TypePtr = S.Context.getCanonicalType(I).getUnqualifiedType();
592
36
      if (OldTypes.count(TypePtr))
593
26
        NewTypes.insert(TypePtr);
594
10
      else {
595
10
        Success = false;
596
10
        break;
597
10
      }
598
36
    }
599
29
600
29
    if (Success && 
OldTypes.size() == NewTypes.size()19
)
601
19
      return false;
602
335
  }
603
335
604
335
  // As a special compatibility feature, under C++0x we accept no spec and
605
335
  // throw(std::bad_alloc) as equivalent for operator new and operator new[].
606
335
  // This is because the implicit declaration changed, but old code would break.
607
335
  if (S.getLangOpts().CPlusPlus11 && 
IsOperatorNew328
) {
608
12
    const FunctionProtoType *WithExceptions = nullptr;
609
12
    if (OldEST == EST_None && 
NewEST == EST_Dynamic9
)
610
6
      WithExceptions = New;
611
6
    else if (OldEST == EST_Dynamic && 
NewEST == EST_None3
)
612
3
      WithExceptions = Old;
613
12
    if (WithExceptions && 
WithExceptions->getNumExceptions() == 19
) {
614
9
      // One has no spec, the other throw(something). If that something is
615
9
      // std::bad_alloc, all conditions are met.
616
9
      QualType Exception = *WithExceptions->exception_begin();
617
9
      if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
618
9
        IdentifierInfo* Name = ExRecord->getIdentifier();
619
9
        if (Name && Name->getName() == "bad_alloc") {
620
9
          // It's called bad_alloc, but is it in std?
621
9
          if (ExRecord->isInStdNamespace()) {
622
9
            return false;
623
9
          }
624
326
        }
625
9
      }
626
9
    }
627
12
  }
628
326
629
326
  // If the caller wants to handle the case that the new function is
630
326
  // incompatible due to a missing exception specification, let it.
631
326
  if (MissingExceptionSpecification && 
OldEST != EST_None301
&&
632
326
      
NewEST == EST_None289
) {
633
258
    // The old type has an exception specification of some sort, but
634
258
    // the new type does not.
635
258
    *MissingExceptionSpecification = true;
636
258
637
258
    if (MissingEmptyExceptionSpecification && OldCanThrow == CT_Cannot) {
638
253
      // The old type has a throw() or noexcept(true) exception specification
639
253
      // and the new type has no exception specification, and the caller asked
640
253
      // to handle this itself.
641
253
      *MissingEmptyExceptionSpecification = true;
642
253
    }
643
258
644
258
    return true;
645
258
  }
646
68
647
68
  S.Diag(NewLoc, DiagID);
648
68
  if (NoteID.getDiagID() != 0 && 
OldLoc.isValid()64
)
649
61
    S.Diag(OldLoc, NoteID);
650
68
  return true;
651
68
}
652
653
bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
654
                                        const PartialDiagnostic &NoteID,
655
                                        const FunctionProtoType *Old,
656
                                        SourceLocation OldLoc,
657
                                        const FunctionProtoType *New,
658
17
                                        SourceLocation NewLoc) {
659
17
  if (!getLangOpts().CXXExceptions)
660
0
    return false;
661
17
  return CheckEquivalentExceptionSpecImpl(*this, DiagID, NoteID, Old, OldLoc,
662
17
                                          New, NewLoc);
663
17
}
664
665
226
bool Sema::handlerCanCatch(QualType HandlerType, QualType ExceptionType) {
666
226
  // [except.handle]p3:
667
226
  //   A handler is a match for an exception object of type E if:
668
226
669
226
  // HandlerType must be ExceptionType or derived from it, or pointer or
670
226
  // reference to such types.
671
226
  const ReferenceType *RefTy = HandlerType->getAs<ReferenceType>();
672
226
  if (RefTy)
673
45
    HandlerType = RefTy->getPointeeType();
674
226
675
226
  //   -- the handler is of type cv T or cv T& and E and T are the same type
676
226
  if (Context.hasSameUnqualifiedType(ExceptionType, HandlerType))
677
89
    return true;
678
137
679
137
  // FIXME: ObjC pointer types?
680
137
  if (HandlerType->isPointerType() || 
HandlerType->isMemberPointerType()77
) {
681
62
    if (RefTy && 
(16
!HandlerType.isConstQualified()16
||
682
16
                  
HandlerType.isVolatileQualified()12
))
683
6
      return false;
684
56
685
56
    // -- the handler is of type cv T or const T& where T is a pointer or
686
56
    //    pointer to member type and E is std::nullptr_t
687
56
    if (ExceptionType->isNullPtrType())
688
8
      return true;
689
48
690
48
    // -- the handler is of type cv T or const T& where T is a pointer or
691
48
    //    pointer to member type and E is a pointer or pointer to member type
692
48
    //    that can be converted to T by one or more of
693
48
    //    -- a qualification conversion
694
48
    //    -- a function pointer conversion
695
48
    bool LifetimeConv;
696
48
    QualType Result;
697
48
    // FIXME: Should we treat the exception as catchable if a lifetime
698
48
    // conversion is required?
699
48
    if (IsQualificationConversion(ExceptionType, HandlerType, false,
700
48
                                  LifetimeConv) ||
701
48
        
IsFunctionConversion(ExceptionType, HandlerType, Result)43
)
702
7
      return true;
703
41
704
41
    //    -- a standard pointer conversion [...]
705
41
    if (!ExceptionType->isPointerType() || 
!HandlerType->isPointerType()37
)
706
4
      return false;
707
37
708
37
    // Handle the "qualification conversion" portion.
709
37
    Qualifiers EQuals, HQuals;
710
37
    ExceptionType = Context.getUnqualifiedArrayType(
711
37
        ExceptionType->getPointeeType(), EQuals);
712
37
    HandlerType = Context.getUnqualifiedArrayType(
713
37
        HandlerType->getPointeeType(), HQuals);
714
37
    if (!HQuals.compatiblyIncludes(EQuals))
715
3
      return false;
716
34
717
34
    if (HandlerType->isVoidType() && 
ExceptionType->isObjectType()5
)
718
5
      return true;
719
104
720
104
    // The only remaining case is a derived-to-base conversion.
721
104
  }
722
104
723
104
  //   -- the handler is of type cg T or cv T& and T is an unambiguous public
724
104
  //      base class of E
725
104
  if (!ExceptionType->isRecordType() || 
!HandlerType->isRecordType()71
)
726
36
    return false;
727
68
  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
728
68
                     /*DetectVirtual=*/false);
729
68
  if (!IsDerivedFrom(SourceLocation(), ExceptionType, HandlerType, Paths) ||
730
68
      
Paths.isAmbiguous(Context.getCanonicalType(HandlerType))56
)
731
22
    return false;
732
46
733
46
  // Do this check from a context without privileges.
734
46
  switch (CheckBaseClassAccess(SourceLocation(), HandlerType, ExceptionType,
735
46
                               Paths.front(),
736
46
                               /*Diagnostic*/ 0,
737
46
                               /*ForceCheck*/ true,
738
46
                               /*ForceUnprivileged*/ true)) {
739
31
  case AR_accessible: return true;
740
15
  case AR_inaccessible: return false;
741
0
  case AR_dependent:
742
0
    llvm_unreachable("access check dependent for unprivileged context");
743
0
  case AR_delayed:
744
0
    llvm_unreachable("access check delayed in non-declaration");
745
0
  }
746
0
  llvm_unreachable("unexpected access check result");
747
0
}
748
749
/// CheckExceptionSpecSubset - Check whether the second function type's
750
/// exception specification is a subset (or equivalent) of the first function
751
/// type. This is used by override and pointer assignment checks.
752
bool Sema::CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
753
                                    const PartialDiagnostic &NestedDiagID,
754
                                    const PartialDiagnostic &NoteID,
755
                                    const PartialDiagnostic &NoThrowDiagID,
756
                                    const FunctionProtoType *Superset,
757
                                    SourceLocation SuperLoc,
758
                                    const FunctionProtoType *Subset,
759
46.0k
                                    SourceLocation SubLoc) {
760
46.0k
761
46.0k
  // Just auto-succeed under -fno-exceptions.
762
46.0k
  if (!getLangOpts().CXXExceptions)
763
7.56k
    return false;
764
38.5k
765
38.5k
  // FIXME: As usual, we could be more specific in our error messages, but
766
38.5k
  // that better waits until we've got types with source locations.
767
38.5k
768
38.5k
  if (!SubLoc.isValid())
769
12.1k
    SubLoc = SuperLoc;
770
38.5k
771
38.5k
  // Resolve the exception specifications, if needed.
772
38.5k
  Superset = ResolveExceptionSpec(SuperLoc, Superset);
773
38.5k
  if (!Superset)
774
0
    return false;
775
38.5k
  Subset = ResolveExceptionSpec(SubLoc, Subset);
776
38.5k
  if (!Subset)
777
0
    return false;
778
38.5k
779
38.5k
  ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
780
38.5k
  ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
781
38.5k
  assert(!isUnresolvedExceptionSpec(SuperEST) &&
782
38.5k
         !isUnresolvedExceptionSpec(SubEST) &&
783
38.5k
         "Shouldn't see unknown exception specifications here");
784
38.5k
785
38.5k
  // If there are dependent noexcept specs, assume everything is fine. Unlike
786
38.5k
  // with the equivalency check, this is safe in this case, because we don't
787
38.5k
  // want to merge declarations. Checks after instantiation will catch any
788
38.5k
  // omissions we make here.
789
38.5k
  if (SuperEST == EST_DependentNoexcept || SubEST == EST_DependentNoexcept)
790
1
    return false;
791
38.5k
792
38.5k
  CanThrowResult SuperCanThrow = Superset->canThrow();
793
38.5k
  CanThrowResult SubCanThrow = Subset->canThrow();
794
38.5k
795
38.5k
  // If the superset contains everything or the subset contains nothing, we're
796
38.5k
  // done.
797
38.5k
  if ((SuperCanThrow == CT_Can && 
SuperEST != EST_Dynamic19.9k
) ||
798
38.5k
      
SubCanThrow == CT_Cannot18.7k
)
799
38.3k
    return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
800
38.3k
                                   Subset, SubLoc);
801
196
802
196
  // Allow __declspec(nothrow) to be missing on redeclaration as an extension in
803
196
  // some cases.
804
196
  if (NoThrowDiagID.getDiagID() != 0 && 
SubCanThrow == CT_Can98
&&
805
196
      
SuperCanThrow == CT_Cannot98
&&
SuperEST == EST_NoThrow11
) {
806
2
    Diag(SubLoc, NoThrowDiagID);
807
2
    if (NoteID.getDiagID() != 0)
808
2
      Diag(SuperLoc, NoteID);
809
2
    return true;
810
2
  }
811
194
812
194
  // If the subset contains everything or the superset contains nothing, we've
813
194
  // failed.
814
194
  if ((SubCanThrow == CT_Can && SubEST != EST_Dynamic) ||
815
194
      
SuperCanThrow == CT_Cannot177
) {
816
52
    Diag(SubLoc, DiagID);
817
52
    if (NoteID.getDiagID() != 0)
818
11
      Diag(SuperLoc, NoteID);
819
52
    return true;
820
52
  }
821
142
822
142
  assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
823
142
         "Exception spec subset: non-dynamic case slipped through.");
824
142
825
142
  // Neither contains everything or nothing. Do a proper comparison.
826
163
  for (QualType SubI : Subset->exceptions()) {
827
163
    if (const ReferenceType *RefTy = SubI->getAs<ReferenceType>())
828
23
      SubI = RefTy->getPointeeType();
829
163
830
163
    // Make sure it's in the superset.
831
163
    bool Contained = false;
832
176
    for (QualType SuperI : Superset->exceptions()) {
833
176
      // [except.spec]p5:
834
176
      //   the target entity shall allow at least the exceptions allowed by the
835
176
      //   source
836
176
      //
837
176
      // We interpret this as meaning that a handler for some target type would
838
176
      // catch an exception of each source type.
839
176
      if (handlerCanCatch(SuperI, SubI)) {
840
112
        Contained = true;
841
112
        break;
842
112
      }
843
176
    }
844
163
    if (!Contained) {
845
51
      Diag(SubLoc, DiagID);
846
51
      if (NoteID.getDiagID() != 0)
847
33
        Diag(SuperLoc, NoteID);
848
51
      return true;
849
51
    }
850
163
  }
851
142
  // We've run half the gauntlet.
852
142
  return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
853
91
                                 Subset, SubLoc);
854
142
}
855
856
static bool
857
CheckSpecForTypesEquivalent(Sema &S, const PartialDiagnostic &DiagID,
858
                            const PartialDiagnostic &NoteID, QualType Target,
859
                            SourceLocation TargetLoc, QualType Source,
860
61.0k
                            SourceLocation SourceLoc) {
861
61.0k
  const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
862
61.0k
  if (!TFunc)
863
61.0k
    return false;
864
9
  const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
865
9
  if (!SFunc)
866
0
    return false;
867
9
868
9
  return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
869
9
                                        SFunc, SourceLoc);
870
9
}
871
872
/// CheckParamExceptionSpec - Check if the parameter and return types of the
873
/// two functions have equivalent exception specs. This is part of the
874
/// assignment and override compatibility check. We do not check the parameters
875
/// of parameter function pointers recursively, as no sane programmer would
876
/// even be able to write such a function type.
877
bool Sema::CheckParamExceptionSpec(const PartialDiagnostic &DiagID,
878
                                   const PartialDiagnostic &NoteID,
879
                                   const FunctionProtoType *Target,
880
                                   SourceLocation TargetLoc,
881
                                   const FunctionProtoType *Source,
882
38.4k
                                   SourceLocation SourceLoc) {
883
38.4k
  auto RetDiag = DiagID;
884
38.4k
  RetDiag << 0;
885
38.4k
  if (CheckSpecForTypesEquivalent(
886
38.4k
          *this, RetDiag, PDiag(),
887
38.4k
          Target->getReturnType(), TargetLoc, Source->getReturnType(),
888
38.4k
          SourceLoc))
889
2
    return true;
890
38.4k
891
38.4k
  // We shouldn't even be testing this unless the arguments are otherwise
892
38.4k
  // compatible.
893
38.4k
  assert(Target->getNumParams() == Source->getNumParams() &&
894
38.4k
         "Functions have different argument counts.");
895
61.0k
  for (unsigned i = 0, E = Target->getNumParams(); i != E; 
++i22.6k
) {
896
22.6k
    auto ParamDiag = DiagID;
897
22.6k
    ParamDiag << 1;
898
22.6k
    if (CheckSpecForTypesEquivalent(
899
22.6k
            *this, ParamDiag, PDiag(),
900
22.6k
            Target->getParamType(i), TargetLoc, Source->getParamType(i),
901
22.6k
            SourceLoc))
902
2
      return true;
903
22.6k
  }
904
38.4k
  
return false38.4k
;
905
38.4k
}
906
907
3.68M
bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {
908
3.68M
  // First we check for applicability.
909
3.68M
  // Target type must be a function, function pointer or function reference.
910
3.68M
  const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
911
3.68M
  if (!ToFunc || 
ToFunc->hasDependentExceptionSpec()16.5k
)
912
3.66M
    return false;
913
16.5k
914
16.5k
  // SourceType must be a function or function pointer.
915
16.5k
  const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
916
16.5k
  if (!FromFunc || 
FromFunc->hasDependentExceptionSpec()16.4k
)
917
133
    return false;
918
16.4k
919
16.4k
  unsigned DiagID = diag::err_incompatible_exception_specs;
920
16.4k
  unsigned NestedDiagID = diag::err_deep_exception_specs_differ;
921
16.4k
  // This is not an error in C++17 onwards, unless the noexceptness doesn't
922
16.4k
  // match, but in that case we have a full-on type mismatch, not just a
923
16.4k
  // type sugar mismatch.
924
16.4k
  if (getLangOpts().CPlusPlus17) {
925
658
    DiagID = diag::warn_incompatible_exception_specs;
926
658
    NestedDiagID = diag::warn_deep_exception_specs_differ;
927
658
  }
928
16.4k
929
16.4k
  // Now we've got the correct types on both sides, check their compatibility.
930
16.4k
  // This means that the source of the conversion can only throw a subset of
931
16.4k
  // the exceptions of the target, and any exception specs on arguments or
932
16.4k
  // return types must be equivalent.
933
16.4k
  //
934
16.4k
  // FIXME: If there is a nested dependent exception specification, we should
935
16.4k
  // not be checking it here. This is fine:
936
16.4k
  //   template<typename T> void f() {
937
16.4k
  //     void (*p)(void (*) throw(T));
938
16.4k
  //     void (*q)(void (*) throw(int)) = p;
939
16.4k
  //   }
940
16.4k
  // ... because it might be instantiated with T=int.
941
16.4k
  return CheckExceptionSpecSubset(
942
16.4k
             PDiag(DiagID), PDiag(NestedDiagID), PDiag(), PDiag(), ToFunc,
943
16.4k
             From->getSourceRange().getBegin(), FromFunc, SourceLocation()) &&
944
16.4k
         
!getLangOpts().CPlusPlus1763
;
945
16.4k
}
946
947
bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
948
39.4k
                                                const CXXMethodDecl *Old) {
949
39.4k
  // If the new exception specification hasn't been parsed yet, skip the check.
950
39.4k
  // We'll get called again once it's been parsed.
951
39.4k
  if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
952
39.4k
      EST_Unparsed)
953
988
    return false;
954
38.4k
955
38.4k
  // Don't check uninstantiated template destructors at all. We can only
956
38.4k
  // synthesize correct specs after the template is instantiated.
957
38.4k
  if (isa<CXXDestructorDecl>(New) && 
New->getParent()->isDependentType()22.6k
)
958
862
    return false;
959
37.5k
960
37.5k
  // If the old exception specification hasn't been parsed yet, or the new
961
37.5k
  // exception specification can't be computed yet, remember that we need to
962
37.5k
  // perform this check when we get to the end of the outermost
963
37.5k
  // lexically-surrounding class.
964
37.5k
  if (exceptionSpecNotKnownYet(Old) || 
exceptionSpecNotKnownYet(New)37.5k
) {
965
7.88k
    DelayedOverridingExceptionSpecChecks.push_back({New, Old});
966
7.88k
    return false;
967
7.88k
  }
968
29.6k
969
29.6k
  unsigned DiagID = diag::err_override_exception_spec;
970
29.6k
  if (getLangOpts().MSVCCompat)
971
44
    DiagID = diag::ext_override_exception_spec;
972
29.6k
  return CheckExceptionSpecSubset(PDiag(DiagID),
973
29.6k
                                  PDiag(diag::err_deep_exception_specs_differ),
974
29.6k
                                  PDiag(diag::note_overridden_virtual_function),
975
29.6k
                                  PDiag(diag::ext_override_exception_spec),
976
29.6k
                                  Old->getType()->castAs<FunctionProtoType>(),
977
29.6k
                                  Old->getLocation(),
978
29.6k
                                  New->getType()->castAs<FunctionProtoType>(),
979
29.6k
                                  New->getLocation());
980
29.6k
}
981
982
54.3k
static CanThrowResult canSubStmtsThrow(Sema &Self, const Stmt *S) {
983
54.3k
  CanThrowResult R = CT_Cannot;
984
83.9k
  for (const Stmt *SubStmt : S->children()) {
985
83.9k
    if (!SubStmt)
986
5
      continue;
987
83.9k
    R = mergeCanThrow(R, Self.canThrow(SubStmt));
988
83.9k
    if (R == CT_Can)
989
632
      break;
990
83.9k
  }
991
54.3k
  return R;
992
54.3k
}
993
994
/// Determine whether the callee of a particular function call can throw.
995
/// E and D are both optional, but at least one of E and Loc must be specified.
996
static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
997
6.15k
                                     SourceLocation Loc = SourceLocation()) {
998
6.15k
  // As an extension, we assume that __attribute__((nothrow)) functions don't
999
6.15k
  // throw.
1000
6.15k
  if (D && 
isa<FunctionDecl>(D)5.98k
&&
D->hasAttr<NoThrowAttr>()5.95k
)
1001
3
    return CT_Cannot;
1002
6.15k
1003
6.15k
  QualType T;
1004
6.15k
1005
6.15k
  // In C++1z, just look at the function type of the callee.
1006
6.15k
  if (S.getLangOpts().CPlusPlus17 && 
E558
&&
isa<CallExpr>(E)558
) {
1007
287
    E = cast<CallExpr>(E)->getCallee();
1008
287
    T = E->getType();
1009
287
    if (T->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1010
58
      // Sadly we don't preserve the actual type as part of the "bound member"
1011
58
      // placeholder, so we need to reconstruct it.
1012
58
      E = E->IgnoreParenImpCasts();
1013
58
1014
58
      // Could be a call to a pointer-to-member or a plain member access.
1015
58
      if (auto *Op = dyn_cast<BinaryOperator>(E)) {
1016
0
        assert(Op->getOpcode() == BO_PtrMemD || Op->getOpcode() == BO_PtrMemI);
1017
0
        T = Op->getRHS()->getType()
1018
0
              ->castAs<MemberPointerType>()->getPointeeType();
1019
58
      } else {
1020
58
        T = cast<MemberExpr>(E)->getMemberDecl()->getType();
1021
58
      }
1022
58
    }
1023
5.86k
  } else if (const ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D))
1024
5.69k
    T = VD->getType();
1025
171
  else
1026
171
    // If we have no clue what we're calling, assume the worst.
1027
171
    return CT_Can;
1028
5.98k
1029
5.98k
  const FunctionProtoType *FT;
1030
5.98k
  if ((FT = T->getAs<FunctionProtoType>())) {
1031
5.73k
  } else 
if (const PointerType *251
PT251
= T->getAs<PointerType>())
1032
242
    FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1033
9
  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1034
5
    FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1035
4
  else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1036
4
    FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1037
0
  else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1038
0
    FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1039
5.98k
1040
5.98k
  if (!FT)
1041
4
    return CT_Can;
1042
5.97k
1043
5.97k
  FT = S.ResolveExceptionSpec(Loc.isInvalid() ? E->getBeginLoc() : 
Loc0
, FT);
1044
5.97k
  if (!FT)
1045
0
    return CT_Can;
1046
5.97k
1047
5.97k
  return FT->canThrow();
1048
5.97k
}
1049
1050
60
static CanThrowResult canVarDeclThrow(Sema &Self, const VarDecl *VD) {
1051
60
  CanThrowResult CT = CT_Cannot;
1052
60
1053
60
  // Initialization might throw.
1054
60
  if (!VD->isUsableInConstantExpressions(Self.Context))
1055
60
    if (const Expr *Init = VD->getInit())
1056
60
      CT = mergeCanThrow(CT, Self.canThrow(Init));
1057
60
1058
60
  // Destructor might throw.
1059
60
  if (VD->needsDestruction(Self.Context) == QualType::DK_cxx_destructor) {
1060
0
    if (auto *RD =
1061
0
            VD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
1062
0
      if (auto *Dtor = RD->getDestructor()) {
1063
0
        CT = mergeCanThrow(
1064
0
            CT, canCalleeThrow(Self, nullptr, Dtor, VD->getLocation()));
1065
0
      }
1066
0
    }
1067
0
  }
1068
60
1069
60
  // If this is a decomposition declaration, bindings might throw.
1070
60
  if (auto *DD = dyn_cast<DecompositionDecl>(VD))
1071
0
    for (auto *B : DD->bindings())
1072
0
      if (auto *HD = B->getHoldingVar())
1073
0
        CT = mergeCanThrow(CT, canVarDeclThrow(Self, HD));
1074
60
1075
60
  return CT;
1076
60
}
1077
1078
8
static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
1079
8
  if (DC->isTypeDependent())
1080
0
    return CT_Dependent;
1081
8
1082
8
  if (!DC->getTypeAsWritten()->isReferenceType())
1083
4
    return CT_Cannot;
1084
4
1085
4
  if (DC->getSubExpr()->isTypeDependent())
1086
1
    return CT_Dependent;
1087
3
1088
3
  return DC->getCastKind() == clang::CK_Dynamic? 
CT_Can1
:
CT_Cannot2
;
1089
3
}
1090
1091
11
static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
1092
11
  if (DC->isTypeOperand())
1093
1
    return CT_Cannot;
1094
10
1095
10
  Expr *Op = DC->getExprOperand();
1096
10
  if (Op->isTypeDependent())
1097
1
    return CT_Dependent;
1098
9
1099
9
  const RecordType *RT = Op->getType()->getAs<RecordType>();
1100
9
  if (!RT)
1101
2
    return CT_Cannot;
1102
7
1103
7
  if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
1104
3
    return CT_Cannot;
1105
4
1106
4
  if (Op->Classify(S.Context).isPRValue())
1107
0
    return CT_Cannot;
1108
4
1109
4
  return CT_Can;
1110
4
}
1111
1112
105k
CanThrowResult Sema::canThrow(const Stmt *S) {
1113
105k
  // C++ [expr.unary.noexcept]p3:
1114
105k
  //   [Can throw] if in a potentially-evaluated context the expression would
1115
105k
  //   contain:
1116
105k
  switch (S->getStmtClass()) {
1117
3
  case Expr::ConstantExprClass:
1118
3
    return canThrow(cast<ConstantExpr>(S)->getSubExpr());
1119
0
1120
12
  case Expr::CXXThrowExprClass:
1121
12
    //   - a potentially evaluated throw-expression
1122
12
    return CT_Can;
1123
0
1124
8
  case Expr::CXXDynamicCastExprClass: {
1125
8
    //   - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1126
8
    //     where T is a reference type, that requires a run-time check
1127
8
    auto *CE = cast<CXXDynamicCastExpr>(S);
1128
8
    // FIXME: Properly determine whether a variably-modified type can throw.
1129
8
    if (CE->getType()->isVariablyModifiedType())
1130
0
      return CT_Can;
1131
8
    CanThrowResult CT = canDynamicCastThrow(CE);
1132
8
    if (CT == CT_Can)
1133
1
      return CT;
1134
7
    return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));
1135
7
  }
1136
7
1137
11
  case Expr::CXXTypeidExprClass:
1138
11
    //   - a potentially evaluated typeid expression applied to a glvalue
1139
11
    //     expression whose type is a polymorphic class type
1140
11
    return canTypeidThrow(*this, cast<CXXTypeidExpr>(S));
1141
7
1142
7
    //   - a potentially evaluated call to a function, member function, function
1143
7
    //     pointer, or member function pointer that does not have a non-throwing
1144
7
    //     exception-specification
1145
26.1k
  case Expr::CallExprClass:
1146
26.1k
  case Expr::CXXMemberCallExprClass:
1147
26.1k
  case Expr::CXXOperatorCallExprClass:
1148
26.1k
  case Expr::UserDefinedLiteralClass: {
1149
26.1k
    const CallExpr *CE = cast<CallExpr>(S);
1150
26.1k
    CanThrowResult CT;
1151
26.1k
    if (CE->isTypeDependent())
1152
24.6k
      CT = CT_Dependent;
1153
1.47k
    else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
1154
1
      CT = CT_Cannot;
1155
1.47k
    else
1156
1.47k
      CT = canCalleeThrow(*this, CE, CE->getCalleeDecl());
1157
26.1k
    if (CT == CT_Can)
1158
660
      return CT;
1159
25.4k
    return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));
1160
25.4k
  }
1161
25.4k
1162
25.4k
  case Expr::CXXConstructExprClass:
1163
3.88k
  case Expr::CXXTemporaryObjectExprClass: {
1164
3.88k
    auto *CE = cast<CXXConstructExpr>(S);
1165
3.88k
    // FIXME: Properly determine whether a variably-modified type can throw.
1166
3.88k
    if (CE->getType()->isVariablyModifiedType())
1167
0
      return CT_Can;
1168
3.88k
    CanThrowResult CT = canCalleeThrow(*this, CE, CE->getConstructor());
1169
3.88k
    if (CT == CT_Can)
1170
164
      return CT;
1171
3.72k
    return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));
1172
3.72k
  }
1173
3.72k
1174
3.72k
  case Expr::CXXInheritedCtorInitExprClass: {
1175
0
    auto *ICIE = cast<CXXInheritedCtorInitExpr>(S);
1176
0
    return canCalleeThrow(*this, ICIE, ICIE->getConstructor());
1177
3.72k
  }
1178
3.72k
1179
3.72k
  case Expr::LambdaExprClass: {
1180
6
    const LambdaExpr *Lambda = cast<LambdaExpr>(S);
1181
6
    CanThrowResult CT = CT_Cannot;
1182
6
    for (LambdaExpr::const_capture_init_iterator
1183
6
             Cap = Lambda->capture_init_begin(),
1184
6
             CapEnd = Lambda->capture_init_end();
1185
6
         Cap != CapEnd; 
++Cap0
)
1186
0
      CT = mergeCanThrow(CT, canThrow(*Cap));
1187
6
    return CT;
1188
3.72k
  }
1189
3.72k
1190
3.72k
  case Expr::CXXNewExprClass: {
1191
27
    auto *NE = cast<CXXNewExpr>(S);
1192
27
    CanThrowResult CT;
1193
27
    if (NE->isTypeDependent())
1194
4
      CT = CT_Dependent;
1195
23
    else
1196
23
      CT = canCalleeThrow(*this, NE, NE->getOperatorNew());
1197
27
    if (CT == CT_Can)
1198
2
      return CT;
1199
25
    return mergeCanThrow(CT, canSubStmtsThrow(*this, NE));
1200
25
  }
1201
25
1202
25
  case Expr::CXXDeleteExprClass: {
1203
16
    auto *DE = cast<CXXDeleteExpr>(S);
1204
16
    CanThrowResult CT;
1205
16
    QualType DTy = DE->getDestroyedType();
1206
16
    if (DTy.isNull() || 
DTy->isDependentType()15
) {
1207
2
      CT = CT_Dependent;
1208
14
    } else {
1209
14
      CT = canCalleeThrow(*this, DE, DE->getOperatorDelete());
1210
14
      if (const RecordType *RT = DTy->getAs<RecordType>()) {
1211
12
        const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1212
12
        const CXXDestructorDecl *DD = RD->getDestructor();
1213
12
        if (DD)
1214
11
          CT = mergeCanThrow(CT, canCalleeThrow(*this, DE, DD));
1215
12
      }
1216
14
      if (CT == CT_Can)
1217
6
        return CT;
1218
10
    }
1219
10
    return mergeCanThrow(CT, canSubStmtsThrow(*this, DE));
1220
10
  }
1221
10
1222
747
  case Expr::CXXBindTemporaryExprClass: {
1223
747
    auto *BTE = cast<CXXBindTemporaryExpr>(S);
1224
747
    // The bound temporary has to be destroyed again, which might throw.
1225
747
    CanThrowResult CT =
1226
747
        canCalleeThrow(*this, BTE, BTE->getTemporary()->getDestructor());
1227
747
    if (CT == CT_Can)
1228
11
      return CT;
1229
736
    return mergeCanThrow(CT, canSubStmtsThrow(*this, BTE));
1230
736
  }
1231
736
1232
736
  case Expr::PseudoObjectExprClass: {
1233
13
    auto *POE = cast<PseudoObjectExpr>(S);
1234
13
    CanThrowResult CT = CT_Cannot;
1235
39
    for (const Expr *E : POE->semantics()) {
1236
39
      CT = mergeCanThrow(CT, canThrow(E));
1237
39
      if (CT == CT_Can)
1238
11
        break;
1239
39
    }
1240
13
    return CT;
1241
736
  }
1242
736
1243
736
    // ObjC message sends are like function calls, but never have exception
1244
736
    // specs.
1245
736
  case Expr::ObjCMessageExprClass:
1246
1
  case Expr::ObjCPropertyRefExprClass:
1247
1
  case Expr::ObjCSubscriptRefExprClass:
1248
1
    return CT_Can;
1249
1
1250
1
    // All the ObjC literals that are implemented as calls are
1251
1
    // potentially throwing unless we decide to close off that
1252
1
    // possibility.
1253
1
  case Expr::ObjCArrayLiteralClass:
1254
0
  case Expr::ObjCDictionaryLiteralClass:
1255
0
  case Expr::ObjCBoxedExprClass:
1256
0
    return CT_Can;
1257
0
1258
0
    // Many other things have subexpressions, so we have to test those.
1259
0
    // Some are simple:
1260
6.94k
  case Expr::CoawaitExprClass:
1261
6.94k
  case Expr::ConditionalOperatorClass:
1262
6.94k
  case Expr::CoyieldExprClass:
1263
6.94k
  case Expr::CXXRewrittenBinaryOperatorClass:
1264
6.94k
  case Expr::CXXStdInitializerListExprClass:
1265
6.94k
  case Expr::DesignatedInitExprClass:
1266
6.94k
  case Expr::DesignatedInitUpdateExprClass:
1267
6.94k
  case Expr::ExprWithCleanupsClass:
1268
6.94k
  case Expr::ExtVectorElementExprClass:
1269
6.94k
  case Expr::InitListExprClass:
1270
6.94k
  case Expr::ArrayInitLoopExprClass:
1271
6.94k
  case Expr::MemberExprClass:
1272
6.94k
  case Expr::ObjCIsaExprClass:
1273
6.94k
  case Expr::ObjCIvarRefExprClass:
1274
6.94k
  case Expr::ParenExprClass:
1275
6.94k
  case Expr::ParenListExprClass:
1276
6.94k
  case Expr::ShuffleVectorExprClass:
1277
6.94k
  case Expr::StmtExprClass:
1278
6.94k
  case Expr::ConvertVectorExprClass:
1279
6.94k
  case Expr::VAArgExprClass:
1280
6.94k
    return canSubStmtsThrow(*this, S);
1281
6.94k
1282
6.94k
  case Expr::CompoundLiteralExprClass:
1283
3
  case Expr::CXXConstCastExprClass:
1284
3
  case Expr::CXXReinterpretCastExprClass:
1285
3
  case Expr::BuiltinBitCastExprClass:
1286
3
      // FIXME: Properly determine whether a variably-modified type can throw.
1287
3
    if (cast<Expr>(S)->getType()->isVariablyModifiedType())
1288
2
      return CT_Can;
1289
1
    return canSubStmtsThrow(*this, S);
1290
1
1291
1
    // Some might be dependent for other reasons.
1292
17.0k
  case Expr::ArraySubscriptExprClass:
1293
17.0k
  case Expr::OMPArraySectionExprClass:
1294
17.0k
  case Expr::BinaryOperatorClass:
1295
17.0k
  case Expr::DependentCoawaitExprClass:
1296
17.0k
  case Expr::CompoundAssignOperatorClass:
1297
17.0k
  case Expr::CStyleCastExprClass:
1298
17.0k
  case Expr::CXXStaticCastExprClass:
1299
17.0k
  case Expr::CXXFunctionalCastExprClass:
1300
17.0k
  case Expr::ImplicitCastExprClass:
1301
17.0k
  case Expr::MaterializeTemporaryExprClass:
1302
17.0k
  case Expr::UnaryOperatorClass: {
1303
17.0k
    // FIXME: Properly determine whether a variably-modified type can throw.
1304
17.0k
    if (auto *CE = dyn_cast<CastExpr>(S))
1305
4.65k
      if (CE->getType()->isVariablyModifiedType())
1306
3
        return CT_Can;
1307
17.0k
    CanThrowResult CT =
1308
17.0k
        cast<Expr>(S)->isTypeDependent() ? 
CT_Dependent11.1k
:
CT_Cannot5.91k
;
1309
17.0k
    return mergeCanThrow(CT, canSubStmtsThrow(*this, S));
1310
17.0k
  }
1311
17.0k
1312
17.0k
  case Expr::CXXDefaultArgExprClass:
1313
23
    return canThrow(cast<CXXDefaultArgExpr>(S)->getExpr());
1314
17.0k
1315
17.0k
  case Expr::CXXDefaultInitExprClass:
1316
120
    return canThrow(cast<CXXDefaultInitExpr>(S)->getExpr());
1317
17.0k
1318
17.0k
  case Expr::ChooseExprClass: {
1319
0
    auto *CE = cast<ChooseExpr>(S);
1320
0
    if (CE->isTypeDependent() || CE->isValueDependent())
1321
0
      return CT_Dependent;
1322
0
    return canThrow(CE->getChosenSubExpr());
1323
0
  }
1324
0
1325
0
  case Expr::GenericSelectionExprClass:
1326
0
    if (cast<GenericSelectionExpr>(S)->isResultDependent())
1327
0
      return CT_Dependent;
1328
0
    return canThrow(cast<GenericSelectionExpr>(S)->getResultExpr());
1329
0
1330
0
    // Some expressions are always dependent.
1331
3.61k
  case Expr::CXXDependentScopeMemberExprClass:
1332
3.61k
  case Expr::CXXUnresolvedConstructExprClass:
1333
3.61k
  case Expr::DependentScopeDeclRefExprClass:
1334
3.61k
  case Expr::CXXFoldExprClass:
1335
3.61k
    return CT_Dependent;
1336
3.61k
1337
37.4k
  case Expr::AsTypeExprClass:
1338
37.4k
  case Expr::BinaryConditionalOperatorClass:
1339
37.4k
  case Expr::BlockExprClass:
1340
37.4k
  case Expr::CUDAKernelCallExprClass:
1341
37.4k
  case Expr::DeclRefExprClass:
1342
37.4k
  case Expr::ObjCBridgedCastExprClass:
1343
37.4k
  case Expr::ObjCIndirectCopyRestoreExprClass:
1344
37.4k
  case Expr::ObjCProtocolExprClass:
1345
37.4k
  case Expr::ObjCSelectorExprClass:
1346
37.4k
  case Expr::ObjCAvailabilityCheckExprClass:
1347
37.4k
  case Expr::OffsetOfExprClass:
1348
37.4k
  case Expr::PackExpansionExprClass:
1349
37.4k
  case Expr::SubstNonTypeTemplateParmExprClass:
1350
37.4k
  case Expr::SubstNonTypeTemplateParmPackExprClass:
1351
37.4k
  case Expr::FunctionParmPackExprClass:
1352
37.4k
  case Expr::UnaryExprOrTypeTraitExprClass:
1353
37.4k
  case Expr::UnresolvedLookupExprClass:
1354
37.4k
  case Expr::UnresolvedMemberExprClass:
1355
37.4k
  case Expr::TypoExprClass:
1356
37.4k
    // FIXME: Many of the above can throw.
1357
37.4k
    return CT_Cannot;
1358
37.4k
1359
37.4k
  case Expr::AddrLabelExprClass:
1360
9.11k
  case Expr::ArrayTypeTraitExprClass:
1361
9.11k
  case Expr::AtomicExprClass:
1362
9.11k
  case Expr::TypeTraitExprClass:
1363
9.11k
  case Expr::CXXBoolLiteralExprClass:
1364
9.11k
  case Expr::CXXNoexceptExprClass:
1365
9.11k
  case Expr::CXXNullPtrLiteralExprClass:
1366
9.11k
  case Expr::CXXPseudoDestructorExprClass:
1367
9.11k
  case Expr::CXXScalarValueInitExprClass:
1368
9.11k
  case Expr::CXXThisExprClass:
1369
9.11k
  case Expr::CXXUuidofExprClass:
1370
9.11k
  case Expr::CharacterLiteralClass:
1371
9.11k
  case Expr::ExpressionTraitExprClass:
1372
9.11k
  case Expr::FloatingLiteralClass:
1373
9.11k
  case Expr::GNUNullExprClass:
1374
9.11k
  case Expr::ImaginaryLiteralClass:
1375
9.11k
  case Expr::ImplicitValueInitExprClass:
1376
9.11k
  case Expr::IntegerLiteralClass:
1377
9.11k
  case Expr::FixedPointLiteralClass:
1378
9.11k
  case Expr::ArrayInitIndexExprClass:
1379
9.11k
  case Expr::NoInitExprClass:
1380
9.11k
  case Expr::ObjCEncodeExprClass:
1381
9.11k
  case Expr::ObjCStringLiteralClass:
1382
9.11k
  case Expr::ObjCBoolLiteralExprClass:
1383
9.11k
  case Expr::OpaqueValueExprClass:
1384
9.11k
  case Expr::PredefinedExprClass:
1385
9.11k
  case Expr::SizeOfPackExprClass:
1386
9.11k
  case Expr::StringLiteralClass:
1387
9.11k
  case Expr::SourceLocExprClass:
1388
9.11k
  case Expr::ConceptSpecializationExprClass:
1389
9.11k
  case Expr::RequiresExprClass:
1390
9.11k
    // These expressions can never throw.
1391
9.11k
    return CT_Cannot;
1392
9.11k
1393
9.11k
  case Expr::MSPropertyRefExprClass:
1394
0
  case Expr::MSPropertySubscriptExprClass:
1395
0
    llvm_unreachable("Invalid class for expression");
1396
0
1397
0
    // Most statements can throw if any substatement can throw.
1398
343
  case Stmt::AttributedStmtClass:
1399
343
  case Stmt::BreakStmtClass:
1400
343
  case Stmt::CapturedStmtClass:
1401
343
  case Stmt::CaseStmtClass:
1402
343
  case Stmt::CompoundStmtClass:
1403
343
  case Stmt::ContinueStmtClass:
1404
343
  case Stmt::CoreturnStmtClass:
1405
343
  case Stmt::CoroutineBodyStmtClass:
1406
343
  case Stmt::CXXCatchStmtClass:
1407
343
  case Stmt::CXXForRangeStmtClass:
1408
343
  case Stmt::DefaultStmtClass:
1409
343
  case Stmt::DoStmtClass:
1410
343
  case Stmt::ForStmtClass:
1411
343
  case Stmt::GCCAsmStmtClass:
1412
343
  case Stmt::GotoStmtClass:
1413
343
  case Stmt::IndirectGotoStmtClass:
1414
343
  case Stmt::LabelStmtClass:
1415
343
  case Stmt::MSAsmStmtClass:
1416
343
  case Stmt::MSDependentExistsStmtClass:
1417
343
  case Stmt::NullStmtClass:
1418
343
  case Stmt::ObjCAtCatchStmtClass:
1419
343
  case Stmt::ObjCAtFinallyStmtClass:
1420
343
  case Stmt::ObjCAtSynchronizedStmtClass:
1421
343
  case Stmt::ObjCAutoreleasePoolStmtClass:
1422
343
  case Stmt::ObjCForCollectionStmtClass:
1423
343
  case Stmt::OMPAtomicDirectiveClass:
1424
343
  case Stmt::OMPBarrierDirectiveClass:
1425
343
  case Stmt::OMPCancelDirectiveClass:
1426
343
  case Stmt::OMPCancellationPointDirectiveClass:
1427
343
  case Stmt::OMPCriticalDirectiveClass:
1428
343
  case Stmt::OMPDistributeDirectiveClass:
1429
343
  case Stmt::OMPDistributeParallelForDirectiveClass:
1430
343
  case Stmt::OMPDistributeParallelForSimdDirectiveClass:
1431
343
  case Stmt::OMPDistributeSimdDirectiveClass:
1432
343
  case Stmt::OMPFlushDirectiveClass:
1433
343
  case Stmt::OMPForDirectiveClass:
1434
343
  case Stmt::OMPForSimdDirectiveClass:
1435
343
  case Stmt::OMPMasterDirectiveClass:
1436
343
  case Stmt::OMPMasterTaskLoopDirectiveClass:
1437
343
  case Stmt::OMPMasterTaskLoopSimdDirectiveClass:
1438
343
  case Stmt::OMPOrderedDirectiveClass:
1439
343
  case Stmt::OMPParallelDirectiveClass:
1440
343
  case Stmt::OMPParallelForDirectiveClass:
1441
343
  case Stmt::OMPParallelForSimdDirectiveClass:
1442
343
  case Stmt::OMPParallelMasterDirectiveClass:
1443
343
  case Stmt::OMPParallelMasterTaskLoopDirectiveClass:
1444
343
  case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass:
1445
343
  case Stmt::OMPParallelSectionsDirectiveClass:
1446
343
  case Stmt::OMPSectionDirectiveClass:
1447
343
  case Stmt::OMPSectionsDirectiveClass:
1448
343
  case Stmt::OMPSimdDirectiveClass:
1449
343
  case Stmt::OMPSingleDirectiveClass:
1450
343
  case Stmt::OMPTargetDataDirectiveClass:
1451
343
  case Stmt::OMPTargetDirectiveClass:
1452
343
  case Stmt::OMPTargetEnterDataDirectiveClass:
1453
343
  case Stmt::OMPTargetExitDataDirectiveClass:
1454
343
  case Stmt::OMPTargetParallelDirectiveClass:
1455
343
  case Stmt::OMPTargetParallelForDirectiveClass:
1456
343
  case Stmt::OMPTargetParallelForSimdDirectiveClass:
1457
343
  case Stmt::OMPTargetSimdDirectiveClass:
1458
343
  case Stmt::OMPTargetTeamsDirectiveClass:
1459
343
  case Stmt::OMPTargetTeamsDistributeDirectiveClass:
1460
343
  case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
1461
343
  case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
1462
343
  case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
1463
343
  case Stmt::OMPTargetUpdateDirectiveClass:
1464
343
  case Stmt::OMPTaskDirectiveClass:
1465
343
  case Stmt::OMPTaskgroupDirectiveClass:
1466
343
  case Stmt::OMPTaskLoopDirectiveClass:
1467
343
  case Stmt::OMPTaskLoopSimdDirectiveClass:
1468
343
  case Stmt::OMPTaskwaitDirectiveClass:
1469
343
  case Stmt::OMPTaskyieldDirectiveClass:
1470
343
  case Stmt::OMPTeamsDirectiveClass:
1471
343
  case Stmt::OMPTeamsDistributeDirectiveClass:
1472
343
  case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
1473
343
  case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
1474
343
  case Stmt::OMPTeamsDistributeSimdDirectiveClass:
1475
343
  case Stmt::ReturnStmtClass:
1476
343
  case Stmt::SEHExceptStmtClass:
1477
343
  case Stmt::SEHFinallyStmtClass:
1478
343
  case Stmt::SEHLeaveStmtClass:
1479
343
  case Stmt::SEHTryStmtClass:
1480
343
  case Stmt::SwitchStmtClass:
1481
343
  case Stmt::WhileStmtClass:
1482
343
    return canSubStmtsThrow(*this, S);
1483
343
1484
343
  case Stmt::DeclStmtClass: {
1485
60
    CanThrowResult CT = CT_Cannot;
1486
60
    for (const Decl *D : cast<DeclStmt>(S)->decls()) {
1487
60
      if (auto *VD = dyn_cast<VarDecl>(D))
1488
60
        CT = mergeCanThrow(CT, canVarDeclThrow(*this, VD));
1489
60
1490
60
      // FIXME: Properly determine whether a variably-modified type can throw.
1491
60
      if (auto *TND = dyn_cast<TypedefNameDecl>(D))
1492
0
        if (TND->getUnderlyingType()->isVariablyModifiedType())
1493
0
          return CT_Can;
1494
60
      if (auto *VD = dyn_cast<ValueDecl>(D))
1495
60
        if (VD->getType()->isVariablyModifiedType())
1496
0
          return CT_Can;
1497
60
    }
1498
60
    return CT;
1499
60
  }
1500
60
1501
66
  case Stmt::IfStmtClass: {
1502
66
    auto *IS = cast<IfStmt>(S);
1503
66
    CanThrowResult CT = CT_Cannot;
1504
66
    if (const Stmt *Init = IS->getInit())
1505
55
      CT = mergeCanThrow(CT, canThrow(Init));
1506
66
    if (const Stmt *CondDS = IS->getConditionVariableDeclStmt())
1507
0
      CT = mergeCanThrow(CT, canThrow(CondDS));
1508
66
    CT = mergeCanThrow(CT, canThrow(IS->getCond()));
1509
66
1510
66
    // For 'if constexpr', consider only the non-discarded case.
1511
66
    // FIXME: We should add a DiscardedStmt marker to the AST.
1512
66
    if (Optional<const Stmt *> Case = IS->getNondiscardedCase(Context))
1513
3
      return *Case ? 
mergeCanThrow(CT, canThrow(*Case))2
:
CT1
;
1514
63
1515
63
    CanThrowResult Then = canThrow(IS->getThen());
1516
63
    CanThrowResult Else = IS->getElse() ? 
canThrow(IS->getElse())0
: CT_Cannot;
1517
63
    if (Then == Else)
1518
62
      return mergeCanThrow(CT, Then);
1519
1
1520
1
    // For a dependent 'if constexpr', the result is dependent if it depends on
1521
1
    // the value of the condition.
1522
1
    return mergeCanThrow(CT, IS->isConstexpr() ? 
CT_Dependent0
1523
1
                                               : mergeCanThrow(Then, Else));
1524
1
  }
1525
1
1526
3
  case Stmt::CXXTryStmtClass: {
1527
3
    auto *TS = cast<CXXTryStmt>(S);
1528
3
    // try /*...*/ catch (...) { H } can throw only if H can throw.
1529
3
    // Any other try-catch can throw if any substatement can throw.
1530
3
    const CXXCatchStmt *FinalHandler = TS->getHandler(TS->getNumHandlers() - 1);
1531
3
    if (!FinalHandler->getExceptionDecl())
1532
2
      return canThrow(FinalHandler->getHandlerBlock());
1533
1
    return canSubStmtsThrow(*this, S);
1534
1
  }
1535
1
1536
1
  case Stmt::ObjCAtThrowStmtClass:
1537
0
    return CT_Can;
1538
1
1539
1
  case Stmt::ObjCAtTryStmtClass: {
1540
0
    auto *TS = cast<ObjCAtTryStmt>(S);
1541
0
1542
0
    // @catch(...) need not be last in Objective-C. Walk backwards until we
1543
0
    // see one or hit the @try.
1544
0
    CanThrowResult CT = CT_Cannot;
1545
0
    if (const Stmt *Finally = TS->getFinallyStmt())
1546
0
      CT = mergeCanThrow(CT, canThrow(Finally));
1547
0
    for (unsigned I = TS->getNumCatchStmts(); I != 0; --I) {
1548
0
      const ObjCAtCatchStmt *Catch = TS->getCatchStmt(I - 1);
1549
0
      CT = mergeCanThrow(CT, canThrow(Catch));
1550
0
      // If we reach a @catch(...), no earlier exceptions can escape.
1551
0
      if (Catch->hasEllipsis())
1552
0
        return CT;
1553
0
    }
1554
0
1555
0
    // Didn't find an @catch(...). Exceptions from the @try body can escape.
1556
0
    return mergeCanThrow(CT, canThrow(TS->getTryBody()));
1557
0
  }
1558
0
1559
0
  case Stmt::NoStmtClass:
1560
0
    llvm_unreachable("Invalid class for statement");
1561
0
  }
1562
0
  llvm_unreachable("Bogus StmtClass");
1563
0
}
1564
1565
} // end namespace clang