Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/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/TypeLoc.h"
19
#include "clang/Basic/Diagnostic.h"
20
#include "clang/Basic/SourceManager.h"
21
#include "llvm/ADT/SmallPtrSet.h"
22
#include "llvm/ADT/SmallString.h"
23
24
namespace clang {
25
26
static const FunctionProtoType *GetUnderlyingFunction(QualType T)
27
6.52M
{
28
6.52M
  if (const PointerType *PtrTy = T->getAs<PointerType>())
29
1.14M
    T = PtrTy->getPointeeType();
30
5.37M
  else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
31
23.0k
    T = RefTy->getPointeeType();
32
5.35M
  else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
33
3.80k
    T = MPTy->getPointeeType();
34
6.52M
  return T->getAs<FunctionProtoType>();
35
6.52M
}
36
37
/// HACK: libstdc++ has a bug where it shadows std::swap with a member
38
/// swap function then tries to call std::swap unqualified from the exception
39
/// specification of that function. This function detects whether we're in
40
/// such a case and turns off delay-parsing of exception specifications.
41
1.63M
bool Sema::isLibstdcxxEagerExceptionSpecHack(const Declarator &D) {
42
1.63M
  auto *RD = dyn_cast<CXXRecordDecl>(CurContext);
43
1.63M
44
1.63M
  // All the problem cases are member functions named "swap" within class
45
1.63M
  // templates declared directly within namespace std or std::__debug or
46
1.63M
  // std::__profile.
47
1.63M
  if (!RD || 
!RD->getIdentifier()1.63M
||
!RD->getDescribedClassTemplate()1.63M
||
48
1.63M
      
!D.getIdentifier()803k
||
!D.getIdentifier()->isStr("swap")534k
)
49
1.63M
    return false;
50
7.96k
51
7.96k
  auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext());
52
7.96k
  if (!ND)
53
86
    return false;
54
7.87k
55
7.87k
  bool IsInStd = ND->isStdNamespace();
56
7.87k
  if (!IsInStd) {
57
1.33k
    // This isn't a direct member of namespace std, but it might still be
58
1.33k
    // libstdc++'s std::__debug::array or std::__profile::array.
59
1.33k
    IdentifierInfo *II = ND->getIdentifier();
60
1.33k
    if (!II || !(II->isStr("__debug") || 
II->isStr("__profile")1.33k
) ||
61
1.33k
        
!ND->isInStdNamespace()2
)
62
1.33k
      return false;
63
6.53k
  }
64
6.53k
65
6.53k
  // Only apply this hack within a system header.
66
6.53k
  if (!Context.getSourceManager().isInSystemHeader(D.getBeginLoc()))
67
0
    return false;
68
6.53k
69
6.53k
  return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
70
6.53k
      .Case("array", true)
71
6.53k
      .Case("pair", IsInStd)
72
6.53k
      .Case("priority_queue", IsInStd)
73
6.53k
      .Case("stack", IsInStd)
74
6.53k
      .Case("queue", IsInStd)
75
6.53k
      .Default(false);
76
6.53k
}
77
78
ExprResult Sema::ActOnNoexceptSpec(SourceLocation NoexceptLoc,
79
                                   Expr *NoexceptExpr,
80
60.7k
                                   ExceptionSpecificationType &EST) {
81
60.7k
  // FIXME: This is bogus, a noexcept expression is not a condition.
82
60.7k
  ExprResult Converted = CheckBooleanCondition(NoexceptLoc, NoexceptExpr);
83
60.7k
  if (Converted.isInvalid())
84
5
    return Converted;
85
60.7k
86
60.7k
  if (Converted.get()->isValueDependent()) {
87
51.8k
    EST = EST_DependentNoexcept;
88
51.8k
    return Converted;
89
51.8k
  }
90
8.89k
91
8.89k
  llvm::APSInt Result;
92
8.89k
  Converted = VerifyIntegerConstantExpression(
93
8.89k
      Converted.get(), &Result,
94
8.89k
      diag::err_noexcept_needs_constant_expression,
95
8.89k
      /*AllowFold*/ false);
96
8.89k
  if (!Converted.isInvalid())
97
8.88k
    EST = !Result ? 
EST_NoexceptFalse705
:
EST_NoexceptTrue8.18k
;
98
8.89k
  return Converted;
99
8.89k
}
100
101
/// CheckSpecifiedExceptionType - Check if the given type is valid in an
102
/// exception specification. Incomplete types, or pointers to incomplete types
103
/// other than void are not allowed.
104
///
105
/// \param[in,out] T  The exception type. This will be decayed to a pointer type
106
///                   when the input is an array or a function type.
107
1.04k
bool Sema::CheckSpecifiedExceptionType(QualType &T, SourceRange Range) {
108
1.04k
  // C++11 [except.spec]p2:
109
1.04k
  //   A type cv T, "array of T", or "function returning T" denoted
110
1.04k
  //   in an exception-specification is adjusted to type T, "pointer to T", or
111
1.04k
  //   "pointer to function returning T", respectively.
112
1.04k
  //
113
1.04k
  // We also apply this rule in C++98.
114
1.04k
  if (T->isArrayType())
115
14
    T = Context.getArrayDecayedType(T);
116
1.03k
  else if (T->isFunctionType())
117
4
    T = Context.getPointerType(T);
118
1.04k
119
1.04k
  int Kind = 0;
120
1.04k
  QualType PointeeT = T;
121
1.04k
  if (const PointerType *PT = T->getAs<PointerType>()) {
122
94
    PointeeT = PT->getPointeeType();
123
94
    Kind = 1;
124
94
125
94
    // cv void* is explicitly permitted, despite being a pointer to an
126
94
    // incomplete type.
127
94
    if (PointeeT->isVoidType())
128
5
      return false;
129
952
  } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
130
54
    PointeeT = RT->getPointeeType();
131
54
    Kind = 2;
132
54
133
54
    if (RT->isRValueReferenceType()) {
134
3
      // C++11 [except.spec]p2:
135
3
      //   A type denoted in an exception-specification shall not denote [...]
136
3
      //   an rvalue reference type.
137
3
      Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
138
3
        << T << Range;
139
3
      return true;
140
3
    }
141
1.03k
  }
142
1.03k
143
1.03k
  // C++11 [except.spec]p2:
144
1.03k
  //   A type denoted in an exception-specification shall not denote an
145
1.03k
  //   incomplete type other than a class currently being defined [...].
146
1.03k
  //   A type denoted in an exception-specification shall not denote a
147
1.03k
  //   pointer or reference to an incomplete type, other than (cv) void* or a
148
1.03k
  //   pointer or reference to a class currently being defined.
149
1.03k
  // In Microsoft mode, downgrade this to a warning.
150
1.03k
  unsigned DiagID = diag::err_incomplete_in_exception_spec;
151
1.03k
  bool ReturnValueOnError = true;
152
1.03k
  if (getLangOpts().MicrosoftExt) {
153
15
    DiagID = diag::ext_incomplete_in_exception_spec;
154
15
    ReturnValueOnError = false;
155
15
  }
156
1.03k
  if (!(PointeeT->isRecordType() &&
157
1.03k
        
PointeeT->getAs<RecordType>()->isBeingDefined()544
) &&
158
1.03k
      
RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range)1.03k
)
159
16
    return ReturnValueOnError;
160
1.02k
161
1.02k
  return false;
162
1.02k
}
163
164
/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
165
/// to member to a function with an exception specification. This means that
166
/// it is invalid to add another level of indirection.
167
4.23M
bool Sema::CheckDistantExceptionSpec(QualType T) {
168
4.23M
  // C++17 removes this rule in favor of putting exception specifications into
169
4.23M
  // the type system.
170
4.23M
  if (getLangOpts().CPlusPlus17)
171
16.3k
    return false;
172
4.21M
173
4.21M
  if (const PointerType *PT = T->getAs<PointerType>())
174
116k
    T = PT->getPointeeType();
175
4.10M
  else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
176
197
    T = PT->getPointeeType();
177
4.10M
  else
178
4.10M
    return false;
179
116k
180
116k
  const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
181
116k
  if (!FnT)
182
116k
    return false;
183
441
184
441
  return FnT->hasExceptionSpec();
185
441
}
186
187
const FunctionProtoType *
188
7.91M
Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
189
7.91M
  if (FPT->getExceptionSpecType() == EST_Unparsed) {
190
1
    Diag(Loc, diag::err_exception_spec_not_parsed);
191
1
    return nullptr;
192
1
  }
193
7.91M
194
7.91M
  if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
195
7.66M
    return FPT;
196
252k
197
252k
  FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
198
252k
  const FunctionProtoType *SourceFPT =
199
252k
      SourceDecl->getType()->castAs<FunctionProtoType>();
200
252k
201
252k
  // If the exception specification has already been resolved, just return it.
202
252k
  if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
203
4
    return SourceFPT;
204
252k
205
252k
  // Compute or instantiate the exception specification now.
206
252k
  if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
207
244k
    EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
208
8.47k
  else
209
8.47k
    InstantiateExceptionSpec(Loc, SourceDecl);
210
252k
211
252k
  const FunctionProtoType *Proto =
212
252k
    SourceDecl->getType()->castAs<FunctionProtoType>();
213
252k
  if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
214
2
    Diag(Loc, diag::err_exception_spec_not_parsed);
215
2
    Proto = nullptr;
216
2
  }
217
252k
  return Proto;
218
252k
}
219
220
void
221
Sema::UpdateExceptionSpec(FunctionDecl *FD,
222
666k
                          const FunctionProtoType::ExceptionSpecInfo &ESI) {
223
666k
  // If we've fully resolved the exception specification, notify listeners.
224
666k
  if (!isUnresolvedExceptionSpec(ESI.Type))
225
666k
    if (auto *Listener = getASTMutationListener())
226
3.05k
      Listener->ResolvedExceptionSpec(FD);
227
666k
228
666k
  for (FunctionDecl *Redecl : FD->redecls())
229
666k
    Context.adjustExceptionSpec(Redecl, ESI);
230
666k
}
231
232
591k
static bool exceptionSpecNotKnownYet(const FunctionDecl *FD) {
233
591k
  auto *MD = dyn_cast<CXXMethodDecl>(FD);
234
591k
  if (!MD)
235
88.4k
    return false;
236
503k
237
503k
  auto EST = MD->getType()->castAs<FunctionProtoType>()->getExceptionSpecType();
238
503k
  return EST == EST_Unparsed ||
239
503k
         
(503k
EST == EST_Unevaluated503k
&&
MD->getParent()->isBeingDefined()58.8k
);
240
503k
}
241
242
static bool CheckEquivalentExceptionSpecImpl(
243
    Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
244
    const FunctionProtoType *Old, SourceLocation OldLoc,
245
    const FunctionProtoType *New, SourceLocation NewLoc,
246
    bool *MissingExceptionSpecification = nullptr,
247
    bool *MissingEmptyExceptionSpecification = nullptr,
248
    bool AllowNoexceptAllMatchWithNoSpec = false, bool IsOperatorNew = false);
249
250
/// Determine whether a function has an implicitly-generated exception
251
/// specification.
252
342k
static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
253
342k
  if (!isa<CXXDestructorDecl>(Decl) &&
254
342k
      
Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete336k
&&
255
342k
      
Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete336k
)
256
335k
    return false;
257
7.13k
258
7.13k
  // For a function that the user didn't declare:
259
7.13k
  //  - if this is a destructor, its exception specification is implicit.
260
7.13k
  //  - if this is 'operator delete' or 'operator delete[]', the exception
261
7.13k
  //    specification is as-if an explicit exception specification was given
262
7.13k
  //    (per [basic.stc.dynamic]p2).
263
7.13k
  if (!Decl->getTypeSourceInfo())
264
421
    return isa<CXXDestructorDecl>(Decl);
265
6.71k
266
6.71k
  const FunctionProtoType *Ty =
267
6.71k
    Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
268
6.71k
  return !Ty->hasExceptionSpec();
269
6.71k
}
270
271
310k
bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
272
310k
  // Just completely ignore this under -fno-exceptions prior to C++17.
273
310k
  // In C++17 onwards, the exception specification is part of the type and
274
310k
  // we will diagnose mismatches anyway, so it's better to check for them here.
275
310k
  if (!getLangOpts().CXXExceptions && 
!getLangOpts().CPlusPlus17132k
)
276
132k
    return false;
277
178k
278
178k
  OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
279
178k
  bool IsOperatorNew = OO == OO_New || 
OO == OO_Array_New178k
;
280
178k
  bool MissingExceptionSpecification = false;
281
178k
  bool MissingEmptyExceptionSpecification = false;
282
178k
283
178k
  unsigned DiagID = diag::err_mismatched_exception_spec;
284
178k
  bool ReturnValueOnError = true;
285
178k
  if (getLangOpts().MicrosoftExt) {
286
200
    DiagID = diag::ext_mismatched_exception_spec;
287
200
    ReturnValueOnError = false;
288
200
  }
289
178k
290
178k
  // If we're befriending a member function of a class that's currently being
291
178k
  // defined, we might not be able to work out its exception specification yet.
292
178k
  // If not, defer the check until later.
293
178k
  if (exceptionSpecNotKnownYet(Old) || 
exceptionSpecNotKnownYet(New)178k
) {
294
13
    DelayedEquivalentExceptionSpecChecks.push_back({New, Old});
295
13
    return false;
296
13
  }
297
178k
298
178k
  // Check the types as written: they must match before any exception
299
178k
  // specification adjustment is applied.
300
178k
  if (!CheckEquivalentExceptionSpecImpl(
301
178k
        *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
302
178k
        Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
303
178k
        New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
304
178k
        &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
305
178k
        /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
306
178k
    // C++11 [except.spec]p4 [DR1492]:
307
178k
    //   If a declaration of a function has an implicit
308
178k
    //   exception-specification, other declarations of the function shall
309
178k
    //   not specify an exception-specification.
310
178k
    if (getLangOpts().CPlusPlus11 && 
getLangOpts().CXXExceptions172k
&&
311
178k
        
hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)171k
) {
312
16
      Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
313
16
        << hasImplicitExceptionSpec(Old);
314
16
      if (Old->getLocation().isValid())
315
11
        Diag(Old->getLocation(), diag::note_previous_declaration);
316
16
    }
317
178k
    return false;
318
178k
  }
319
66
320
66
  // The failure was something other than an missing exception
321
66
  // specification; return an error, except in MS mode where this is a warning.
322
66
  if (!MissingExceptionSpecification)
323
31
    return ReturnValueOnError;
324
35
325
35
  const FunctionProtoType *NewProto =
326
35
    New->getType()->castAs<FunctionProtoType>();
327
35
328
35
  // The new function declaration is only missing an empty exception
329
35
  // specification "throw()". If the throw() specification came from a
330
35
  // function in a system header that has C linkage, just add an empty
331
35
  // exception specification to the "new" declaration. Note that C library
332
35
  // implementations are permitted to add these nothrow exception
333
35
  // specifications.
334
35
  //
335
35
  // Likewise if the old function is a builtin.
336
35
  if (MissingEmptyExceptionSpecification && 
NewProto30
&&
337
35
      
(30
Old->getLocation().isInvalid()30
||
338
30
       Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
339
30
       
Old->getBuiltinID()22
) &&
340
35
      
Old->isExternC()11
) {
341
11
    New->setType(Context.getFunctionType(
342
11
        NewProto->getReturnType(), NewProto->getParamTypes(),
343
11
        NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
344
11
    return false;
345
11
  }
346
24
347
24
  const FunctionProtoType *OldProto =
348
24
    Old->getType()->castAs<FunctionProtoType>();
349
24
350
24
  FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
351
24
  if (ESI.Type == EST_Dynamic) {
352
4
    // FIXME: What if the exceptions are described in terms of the old
353
4
    // prototype's parameters?
354
4
    ESI.Exceptions = OldProto->exceptions();
355
4
  }
356
24
357
24
  if (ESI.Type == EST_NoexceptFalse)
358
0
    ESI.Type = EST_None;
359
24
  if (ESI.Type == EST_NoexceptTrue)
360
1
    ESI.Type = EST_BasicNoexcept;
361
24
362
24
  // For dependent noexcept, we can't just take the expression from the old
363
24
  // prototype. It likely contains references to the old prototype's parameters.
364
24
  if (ESI.Type == EST_DependentNoexcept) {
365
1
    New->setInvalidDecl();
366
23
  } else {
367
23
    // Update the type of the function with the appropriate exception
368
23
    // specification.
369
23
    New->setType(Context.getFunctionType(
370
23
        NewProto->getReturnType(), NewProto->getParamTypes(),
371
23
        NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
372
23
  }
373
24
374
24
  if (getLangOpts().MicrosoftExt && 
ESI.Type != EST_DependentNoexcept6
) {
375
6
    // Allow missing exception specifications in redeclarations as an extension.
376
6
    DiagID = diag::ext_ms_missing_exception_specification;
377
6
    ReturnValueOnError = false;
378
18
  } else if (New->isReplaceableGlobalAllocationFunction() &&
379
18
             
ESI.Type != EST_DependentNoexcept3
) {
380
3
    // Allow missing exception specifications in redeclarations as an extension,
381
3
    // when declaring a replaceable global allocation function.
382
3
    DiagID = diag::ext_missing_exception_specification;
383
3
    ReturnValueOnError = false;
384
15
  } else if (ESI.Type == EST_NoThrow) {
385
2
    // Allow missing attribute 'nothrow' in redeclarations, since this is a very
386
2
    // common omission.
387
2
    DiagID = diag::ext_missing_exception_specification;
388
2
    ReturnValueOnError = false;
389
13
  } else {
390
13
    DiagID = diag::err_missing_exception_specification;
391
13
    ReturnValueOnError = true;
392
13
  }
393
24
394
24
  // Warn about the lack of exception specification.
395
24
  SmallString<128> ExceptionSpecString;
396
24
  llvm::raw_svector_ostream OS(ExceptionSpecString);
397
24
  switch (OldProto->getExceptionSpecType()) {
398
24
  case EST_DynamicNone:
399
9
    OS << "throw()";
400
9
    break;
401
24
402
24
  case EST_Dynamic: {
403
4
    OS << "throw(";
404
4
    bool OnFirstException = true;
405
4
    for (const auto &E : OldProto->exceptions()) {
406
4
      if (OnFirstException)
407
4
        OnFirstException = false;
408
0
      else
409
0
        OS << ", ";
410
4
411
4
      OS << E.getAsString(getPrintingPolicy());
412
4
    }
413
4
    OS << ")";
414
4
    break;
415
24
  }
416
24
417
24
  case EST_BasicNoexcept:
418
4
    OS << "noexcept";
419
4
    break;
420
24
421
24
  case EST_DependentNoexcept:
422
2
  case EST_NoexceptFalse:
423
2
  case EST_NoexceptTrue:
424
2
    OS << "noexcept(";
425
2
    assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
426
2
    OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
427
2
    OS << ")";
428
2
    break;
429
5
  case EST_NoThrow:
430
5
    OS <<"__attribute__((nothrow))";
431
5
    break;
432
2
  case EST_None:
433
0
  case EST_MSAny:
434
0
  case EST_Unevaluated:
435
0
  case EST_Uninstantiated:
436
0
  case EST_Unparsed:
437
0
    llvm_unreachable("This spec type is compatible with none.");
438
24
  }
439
24
440
24
  SourceLocation FixItLoc;
441
24
  if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
442
24
    TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
443
24
    // FIXME: Preserve enough information so that we can produce a correct fixit
444
24
    // location when there is a trailing return type.
445
24
    if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
446
24
      if (!FTLoc.getTypePtr()->hasTrailingReturn())
447
24
        FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
448
24
  }
449
24
450
24
  if (FixItLoc.isInvalid())
451
0
    Diag(New->getLocation(), DiagID)
452
0
      << New << OS.str();
453
24
  else {
454
24
    Diag(New->getLocation(), DiagID)
455
24
      << New << OS.str()
456
24
      << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
457
24
  }
458
24
459
24
  if (Old->getLocation().isValid())
460
23
    Diag(Old->getLocation(), diag::note_previous_declaration);
461
24
462
24
  return ReturnValueOnError;
463
24
}
464
465
/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
466
/// exception specifications. Exception specifications are equivalent if
467
/// they allow exactly the same set of exception types. It does not matter how
468
/// that is achieved. See C++ [except.spec]p2.
469
bool Sema::CheckEquivalentExceptionSpec(
470
    const FunctionProtoType *Old, SourceLocation OldLoc,
471
205
    const FunctionProtoType *New, SourceLocation NewLoc) {
472
205
  if (!getLangOpts().CXXExceptions)
473
152
    return false;
474
53
475
53
  unsigned DiagID = diag::err_mismatched_exception_spec;
476
53
  if (getLangOpts().MicrosoftExt)
477
0
    DiagID = diag::ext_mismatched_exception_spec;
478
53
  bool Result = CheckEquivalentExceptionSpecImpl(
479
53
      *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
480
53
      Old, OldLoc, New, NewLoc);
481
53
482
53
  // In Microsoft mode, mismatching exception specifications just cause a warning.
483
53
  if (getLangOpts().MicrosoftExt)
484
0
    return false;
485
53
  return Result;
486
53
}
487
488
/// CheckEquivalentExceptionSpec - Check if the two types have compatible
489
/// exception specifications. See C++ [except.spec]p3.
490
///
491
/// \return \c false if the exception specifications match, \c true if there is
492
/// a problem. If \c true is returned, either a diagnostic has already been
493
/// produced or \c *MissingExceptionSpecification is set to \c true.
494
static bool CheckEquivalentExceptionSpecImpl(
495
    Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
496
    const FunctionProtoType *Old, SourceLocation OldLoc,
497
    const FunctionProtoType *New, SourceLocation NewLoc,
498
    bool *MissingExceptionSpecification,
499
    bool *MissingEmptyExceptionSpecification,
500
178k
    bool AllowNoexceptAllMatchWithNoSpec, bool IsOperatorNew) {
501
178k
  if (MissingExceptionSpecification)
502
178k
    *MissingExceptionSpecification = false;
503
178k
504
178k
  if (MissingEmptyExceptionSpecification)
505
178k
    *MissingEmptyExceptionSpecification = false;
506
178k
507
178k
  Old = S.ResolveExceptionSpec(NewLoc, Old);
508
178k
  if (!Old)
509
0
    return false;
510
178k
  New = S.ResolveExceptionSpec(NewLoc, New);
511
178k
  if (!New)
512
0
    return false;
513
178k
514
178k
  // C++0x [except.spec]p3: Two exception-specifications are compatible if:
515
178k
  //   - both are non-throwing, regardless of their form,
516
178k
  //   - both have the form noexcept(constant-expression) and the constant-
517
178k
  //     expressions are equivalent,
518
178k
  //   - both are dynamic-exception-specifications that have the same set of
519
178k
  //     adjusted types.
520
178k
  //
521
178k
  // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
522
178k
  //   of the form throw(), noexcept, or noexcept(constant-expression) where the
523
178k
  //   constant-expression yields true.
524
178k
  //
525
178k
  // C++0x [except.spec]p4: If any declaration of a function has an exception-
526
178k
  //   specifier that is not a noexcept-specification allowing all exceptions,
527
178k
  //   all declarations [...] of that function shall have a compatible
528
178k
  //   exception-specification.
529
178k
  //
530
178k
  // That last point basically means that noexcept(false) matches no spec.
531
178k
  // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
532
178k
533
178k
  ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
534
178k
  ExceptionSpecificationType NewEST = New->getExceptionSpecType();
535
178k
536
178k
  assert(!isUnresolvedExceptionSpec(OldEST) &&
537
178k
         !isUnresolvedExceptionSpec(NewEST) &&
538
178k
         "Shouldn't see unknown exception specifications here");
539
178k
540
178k
  CanThrowResult OldCanThrow = Old->canThrow();
541
178k
  CanThrowResult NewCanThrow = New->canThrow();
542
178k
543
178k
  // Any non-throwing specifications are compatible.
544
178k
  if (OldCanThrow == CT_Cannot && 
NewCanThrow == CT_Cannot35.0k
)
545
35.0k
    return false;
546
143k
547
143k
  // Any throws-anything specifications are usually compatible.
548
143k
  if (OldCanThrow == CT_Can && 
OldEST != EST_Dynamic139k
&&
549
143k
      
NewCanThrow == CT_Can139k
&&
NewEST != EST_Dynamic139k
) {
550
139k
    // The exception is that the absence of an exception specification only
551
139k
    // matches noexcept(false) for functions, as described above.
552
139k
    if (!AllowNoexceptAllMatchWithNoSpec &&
553
139k
        
(36
(36
OldEST == EST_None36
&&
NewEST == EST_NoexceptFalse34
) ||
554
36
         
(35
OldEST == EST_NoexceptFalse35
&&
NewEST == EST_None2
))) {
555
1
      // This is the disallowed case.
556
139k
    } else {
557
139k
      return false;
558
139k
    }
559
4.47k
  }
560
4.47k
561
4.47k
  // C++14 [except.spec]p3:
562
4.47k
  //   Two exception-specifications are compatible if [...] both have the form
563
4.47k
  //   noexcept(constant-expression) and the constant-expressions are equivalent
564
4.47k
  if (OldEST == EST_DependentNoexcept && 
NewEST == EST_DependentNoexcept4.21k
) {
565
4.20k
    llvm::FoldingSetNodeID OldFSN, NewFSN;
566
4.20k
    Old->getNoexceptExpr()->Profile(OldFSN, S.Context, true);
567
4.20k
    New->getNoexceptExpr()->Profile(NewFSN, S.Context, true);
568
4.20k
    if (OldFSN == NewFSN)
569
4.20k
      return false;
570
273
  }
571
273
572
273
  // Dynamic exception specifications with the same set of adjusted types
573
273
  // are compatible.
574
273
  if (OldEST == EST_Dynamic && 
NewEST == EST_Dynamic203
) {
575
187
    bool Success = true;
576
187
    // Both have a dynamic exception spec. Collect the first set, then compare
577
187
    // to the second.
578
187
    llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
579
187
    for (const auto &I : Old->exceptions())
580
192
      OldTypes.insert(S.Context.getCanonicalType(I).getUnqualifiedType());
581
187
582
194
    for (const auto &I : New->exceptions()) {
583
194
      CanQualType TypePtr = S.Context.getCanonicalType(I).getUnqualifiedType();
584
194
      if (OldTypes.count(TypePtr))
585
184
        NewTypes.insert(TypePtr);
586
10
      else {
587
10
        Success = false;
588
10
        break;
589
10
      }
590
194
    }
591
187
592
187
    if (Success && 
OldTypes.size() == NewTypes.size()177
)
593
177
      return false;
594
96
  }
595
96
596
96
  // As a special compatibility feature, under C++0x we accept no spec and
597
96
  // throw(std::bad_alloc) as equivalent for operator new and operator new[].
598
96
  // This is because the implicit declaration changed, but old code would break.
599
96
  if (S.getLangOpts().CPlusPlus11 && 
IsOperatorNew86
) {
600
12
    const FunctionProtoType *WithExceptions = nullptr;
601
12
    if (OldEST == EST_None && 
NewEST == EST_Dynamic9
)
602
6
      WithExceptions = New;
603
6
    else if (OldEST == EST_Dynamic && 
NewEST == EST_None3
)
604
3
      WithExceptions = Old;
605
12
    if (WithExceptions && 
WithExceptions->getNumExceptions() == 19
) {
606
9
      // One has no spec, the other throw(something). If that something is
607
9
      // std::bad_alloc, all conditions are met.
608
9
      QualType Exception = *WithExceptions->exception_begin();
609
9
      if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
610
9
        IdentifierInfo* Name = ExRecord->getIdentifier();
611
9
        if (Name && Name->getName() == "bad_alloc") {
612
9
          // It's called bad_alloc, but is it in std?
613
9
          if (ExRecord->isInStdNamespace()) {
614
9
            return false;
615
9
          }
616
87
        }
617
9
      }
618
9
    }
619
12
  }
620
87
621
87
  // If the caller wants to handle the case that the new function is
622
87
  // incompatible due to a missing exception specification, let it.
623
87
  if (MissingExceptionSpecification && 
OldEST != EST_None66
&&
624
87
      
NewEST == EST_None54
) {
625
35
    // The old type has an exception specification of some sort, but
626
35
    // the new type does not.
627
35
    *MissingExceptionSpecification = true;
628
35
629
35
    if (MissingEmptyExceptionSpecification && OldCanThrow == CT_Cannot) {
630
30
      // The old type has a throw() or noexcept(true) exception specification
631
30
      // and the new type has no exception specification, and the caller asked
632
30
      // to handle this itself.
633
30
      *MissingEmptyExceptionSpecification = true;
634
30
    }
635
35
636
35
    return true;
637
35
  }
638
52
639
52
  S.Diag(NewLoc, DiagID);
640
52
  if (NoteID.getDiagID() != 0 && 
OldLoc.isValid()48
)
641
45
    S.Diag(OldLoc, NoteID);
642
52
  return true;
643
52
}
644
645
bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
646
                                        const PartialDiagnostic &NoteID,
647
                                        const FunctionProtoType *Old,
648
                                        SourceLocation OldLoc,
649
                                        const FunctionProtoType *New,
650
14
                                        SourceLocation NewLoc) {
651
14
  if (!getLangOpts().CXXExceptions)
652
0
    return false;
653
14
  return CheckEquivalentExceptionSpecImpl(*this, DiagID, NoteID, Old, OldLoc,
654
14
                                          New, NewLoc);
655
14
}
656
657
226
bool Sema::handlerCanCatch(QualType HandlerType, QualType ExceptionType) {
658
226
  // [except.handle]p3:
659
226
  //   A handler is a match for an exception object of type E if:
660
226
661
226
  // HandlerType must be ExceptionType or derived from it, or pointer or
662
226
  // reference to such types.
663
226
  const ReferenceType *RefTy = HandlerType->getAs<ReferenceType>();
664
226
  if (RefTy)
665
45
    HandlerType = RefTy->getPointeeType();
666
226
667
226
  //   -- the handler is of type cv T or cv T& and E and T are the same type
668
226
  if (Context.hasSameUnqualifiedType(ExceptionType, HandlerType))
669
89
    return true;
670
137
671
137
  // FIXME: ObjC pointer types?
672
137
  if (HandlerType->isPointerType() || 
HandlerType->isMemberPointerType()77
) {
673
62
    if (RefTy && 
(16
!HandlerType.isConstQualified()16
||
674
16
                  
HandlerType.isVolatileQualified()12
))
675
6
      return false;
676
56
677
56
    // -- the handler is of type cv T or const T& where T is a pointer or
678
56
    //    pointer to member type and E is std::nullptr_t
679
56
    if (ExceptionType->isNullPtrType())
680
8
      return true;
681
48
682
48
    // -- the handler is of type cv T or const T& where T is a pointer or
683
48
    //    pointer to member type and E is a pointer or pointer to member type
684
48
    //    that can be converted to T by one or more of
685
48
    //    -- a qualification conversion
686
48
    //    -- a function pointer conversion
687
48
    bool LifetimeConv;
688
48
    QualType Result;
689
48
    // FIXME: Should we treat the exception as catchable if a lifetime
690
48
    // conversion is required?
691
48
    if (IsQualificationConversion(ExceptionType, HandlerType, false,
692
48
                                  LifetimeConv) ||
693
48
        
IsFunctionConversion(ExceptionType, HandlerType, Result)43
)
694
7
      return true;
695
41
696
41
    //    -- a standard pointer conversion [...]
697
41
    if (!ExceptionType->isPointerType() || 
!HandlerType->isPointerType()37
)
698
4
      return false;
699
37
700
37
    // Handle the "qualification conversion" portion.
701
37
    Qualifiers EQuals, HQuals;
702
37
    ExceptionType = Context.getUnqualifiedArrayType(
703
37
        ExceptionType->getPointeeType(), EQuals);
704
37
    HandlerType = Context.getUnqualifiedArrayType(
705
37
        HandlerType->getPointeeType(), HQuals);
706
37
    if (!HQuals.compatiblyIncludes(EQuals))
707
3
      return false;
708
34
709
34
    if (HandlerType->isVoidType() && 
ExceptionType->isObjectType()5
)
710
5
      return true;
711
104
712
104
    // The only remaining case is a derived-to-base conversion.
713
104
  }
714
104
715
104
  //   -- the handler is of type cg T or cv T& and T is an unambiguous public
716
104
  //      base class of E
717
104
  if (!ExceptionType->isRecordType() || 
!HandlerType->isRecordType()71
)
718
36
    return false;
719
68
  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
720
68
                     /*DetectVirtual=*/false);
721
68
  if (!IsDerivedFrom(SourceLocation(), ExceptionType, HandlerType, Paths) ||
722
68
      
Paths.isAmbiguous(Context.getCanonicalType(HandlerType))56
)
723
22
    return false;
724
46
725
46
  // Do this check from a context without privileges.
726
46
  switch (CheckBaseClassAccess(SourceLocation(), HandlerType, ExceptionType,
727
46
                               Paths.front(),
728
46
                               /*Diagnostic*/ 0,
729
46
                               /*ForceCheck*/ true,
730
46
                               /*ForceUnprivileged*/ true)) {
731
46
  
case AR_accessible: return true31
;
732
46
  
case AR_inaccessible: return false15
;
733
46
  case AR_dependent:
734
0
    llvm_unreachable("access check dependent for unprivileged context");
735
46
  case AR_delayed:
736
0
    llvm_unreachable("access check delayed in non-declaration");
737
0
  }
738
0
  llvm_unreachable("unexpected access check result");
739
0
}
740
741
/// CheckExceptionSpecSubset - Check whether the second function type's
742
/// exception specification is a subset (or equivalent) of the first function
743
/// type. This is used by override and pointer assignment checks.
744
bool Sema::CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
745
                                    const PartialDiagnostic &NestedDiagID,
746
                                    const PartialDiagnostic &NoteID,
747
                                    const PartialDiagnostic &NoThrowDiagID,
748
                                    const FunctionProtoType *Superset,
749
                                    SourceLocation SuperLoc,
750
                                    const FunctionProtoType *Subset,
751
104k
                                    SourceLocation SubLoc) {
752
104k
753
104k
  // Just auto-succeed under -fno-exceptions.
754
104k
  if (!getLangOpts().CXXExceptions)
755
26.6k
    return false;
756
77.8k
757
77.8k
  // FIXME: As usual, we could be more specific in our error messages, but
758
77.8k
  // that better waits until we've got types with source locations.
759
77.8k
760
77.8k
  if (!SubLoc.isValid())
761
6.18k
    SubLoc = SuperLoc;
762
77.8k
763
77.8k
  // Resolve the exception specifications, if needed.
764
77.8k
  Superset = ResolveExceptionSpec(SuperLoc, Superset);
765
77.8k
  if (!Superset)
766
0
    return false;
767
77.8k
  Subset = ResolveExceptionSpec(SubLoc, Subset);
768
77.8k
  if (!Subset)
769
0
    return false;
770
77.8k
771
77.8k
  ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
772
77.8k
  ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
773
77.8k
  assert(!isUnresolvedExceptionSpec(SuperEST) &&
774
77.8k
         !isUnresolvedExceptionSpec(SubEST) &&
775
77.8k
         "Shouldn't see unknown exception specifications here");
776
77.8k
777
77.8k
  // If there are dependent noexcept specs, assume everything is fine. Unlike
778
77.8k
  // with the equivalency check, this is safe in this case, because we don't
779
77.8k
  // want to merge declarations. Checks after instantiation will catch any
780
77.8k
  // omissions we make here.
781
77.8k
  if (SuperEST == EST_DependentNoexcept || SubEST == EST_DependentNoexcept)
782
1
    return false;
783
77.8k
784
77.8k
  CanThrowResult SuperCanThrow = Superset->canThrow();
785
77.8k
  CanThrowResult SubCanThrow = Subset->canThrow();
786
77.8k
787
77.8k
  // If the superset contains everything or the subset contains nothing, we're
788
77.8k
  // done.
789
77.8k
  if ((SuperCanThrow == CT_Can && 
SuperEST != EST_Dynamic50.1k
) ||
790
77.8k
      
SubCanThrow == CT_Cannot27.8k
)
791
77.6k
    return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
792
77.6k
                                   Subset, SubLoc);
793
197
794
197
  // Allow __declspec(nothrow) to be missing on redeclaration as an extension in
795
197
  // some cases.
796
197
  if (NoThrowDiagID.getDiagID() != 0 && 
SubCanThrow == CT_Can99
&&
797
197
      
SuperCanThrow == CT_Cannot99
&&
SuperEST == EST_NoThrow12
) {
798
2
    Diag(SubLoc, NoThrowDiagID);
799
2
    if (NoteID.getDiagID() != 0)
800
2
      Diag(SuperLoc, NoteID);
801
2
    return true;
802
2
  }
803
195
804
195
  // If the subset contains everything or the superset contains nothing, we've
805
195
  // failed.
806
195
  if ((SubCanThrow == CT_Can && SubEST != EST_Dynamic) ||
807
195
      
SuperCanThrow == CT_Cannot177
) {
808
53
    Diag(SubLoc, DiagID);
809
53
    if (NoteID.getDiagID() != 0)
810
12
      Diag(SuperLoc, NoteID);
811
53
    return true;
812
53
  }
813
142
814
142
  assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
815
142
         "Exception spec subset: non-dynamic case slipped through.");
816
142
817
142
  // Neither contains everything or nothing. Do a proper comparison.
818
163
  for (QualType SubI : Subset->exceptions()) {
819
163
    if (const ReferenceType *RefTy = SubI->getAs<ReferenceType>())
820
23
      SubI = RefTy->getPointeeType();
821
163
822
163
    // Make sure it's in the superset.
823
163
    bool Contained = false;
824
176
    for (QualType SuperI : Superset->exceptions()) {
825
176
      // [except.spec]p5:
826
176
      //   the target entity shall allow at least the exceptions allowed by the
827
176
      //   source
828
176
      //
829
176
      // We interpret this as meaning that a handler for some target type would
830
176
      // catch an exception of each source type.
831
176
      if (handlerCanCatch(SuperI, SubI)) {
832
112
        Contained = true;
833
112
        break;
834
112
      }
835
176
    }
836
163
    if (!Contained) {
837
51
      Diag(SubLoc, DiagID);
838
51
      if (NoteID.getDiagID() != 0)
839
33
        Diag(SuperLoc, NoteID);
840
51
      return true;
841
51
    }
842
163
  }
843
142
  // We've run half the gauntlet.
844
142
  return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
845
91
                                 Subset, SubLoc);
846
142
}
847
848
static bool
849
CheckSpecForTypesEquivalent(Sema &S, const PartialDiagnostic &DiagID,
850
                            const PartialDiagnostic &NoteID, QualType Target,
851
                            SourceLocation TargetLoc, QualType Source,
852
127k
                            SourceLocation SourceLoc) {
853
127k
  const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
854
127k
  if (!TFunc)
855
127k
    return false;
856
6
  const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
857
6
  if (!SFunc)
858
0
    return false;
859
6
860
6
  return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
861
6
                                        SFunc, SourceLoc);
862
6
}
863
864
/// CheckParamExceptionSpec - Check if the parameter and return types of the
865
/// two functions have equivalent exception specs. This is part of the
866
/// assignment and override compatibility check. We do not check the parameters
867
/// of parameter function pointers recursively, as no sane programmer would
868
/// even be able to write such a function type.
869
bool Sema::CheckParamExceptionSpec(const PartialDiagnostic &DiagID,
870
                                   const PartialDiagnostic &NoteID,
871
                                   const FunctionProtoType *Target,
872
                                   SourceLocation TargetLoc,
873
                                   const FunctionProtoType *Source,
874
77.7k
                                   SourceLocation SourceLoc) {
875
77.7k
  auto RetDiag = DiagID;
876
77.7k
  RetDiag << 0;
877
77.7k
  if (CheckSpecForTypesEquivalent(
878
77.7k
          *this, RetDiag, PDiag(),
879
77.7k
          Target->getReturnType(), TargetLoc, Source->getReturnType(),
880
77.7k
          SourceLoc))
881
2
    return true;
882
77.7k
883
77.7k
  // We shouldn't even be testing this unless the arguments are otherwise
884
77.7k
  // compatible.
885
77.7k
  assert(Target->getNumParams() == Source->getNumParams() &&
886
77.7k
         "Functions have different argument counts.");
887
127k
  for (unsigned i = 0, E = Target->getNumParams(); i != E; 
++i50.1k
) {
888
50.1k
    auto ParamDiag = DiagID;
889
50.1k
    ParamDiag << 1;
890
50.1k
    if (CheckSpecForTypesEquivalent(
891
50.1k
            *this, ParamDiag, PDiag(),
892
50.1k
            Target->getParamType(i), TargetLoc, Source->getParamType(i),
893
50.1k
            SourceLoc))
894
2
      return true;
895
50.1k
  }
896
77.7k
  
return false77.7k
;
897
77.7k
}
898
899
6.37M
bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {
900
6.37M
  // First we check for applicability.
901
6.37M
  // Target type must be a function, function pointer or function reference.
902
6.37M
  const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
903
6.37M
  if (!ToFunc || 
ToFunc->hasDependentExceptionSpec()13.8k
)
904
6.36M
    return false;
905
13.8k
906
13.8k
  // SourceType must be a function or function pointer.
907
13.8k
  const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
908
13.8k
  if (!FromFunc || 
FromFunc->hasDependentExceptionSpec()13.5k
)
909
314
    return false;
910
13.5k
911
13.5k
  unsigned DiagID = diag::err_incompatible_exception_specs;
912
13.5k
  unsigned NestedDiagID = diag::err_deep_exception_specs_differ;
913
13.5k
  // This is not an error in C++17 onwards, unless the noexceptness doesn't
914
13.5k
  // match, but in that case we have a full-on type mismatch, not just a
915
13.5k
  // type sugar mismatch.
916
13.5k
  if (getLangOpts().CPlusPlus17) {
917
475
    DiagID = diag::warn_incompatible_exception_specs;
918
475
    NestedDiagID = diag::warn_deep_exception_specs_differ;
919
475
  }
920
13.5k
921
13.5k
  // Now we've got the correct types on both sides, check their compatibility.
922
13.5k
  // This means that the source of the conversion can only throw a subset of
923
13.5k
  // the exceptions of the target, and any exception specs on arguments or
924
13.5k
  // return types must be equivalent.
925
13.5k
  //
926
13.5k
  // FIXME: If there is a nested dependent exception specification, we should
927
13.5k
  // not be checking it here. This is fine:
928
13.5k
  //   template<typename T> void f() {
929
13.5k
  //     void (*p)(void (*) throw(T));
930
13.5k
  //     void (*q)(void (*) throw(int)) = p;
931
13.5k
  //   }
932
13.5k
  // ... because it might be instantiated with T=int.
933
13.5k
  return CheckExceptionSpecSubset(
934
13.5k
             PDiag(DiagID), PDiag(NestedDiagID), PDiag(), PDiag(), ToFunc,
935
13.5k
             From->getSourceRange().getBegin(), FromFunc, SourceLocation()) &&
936
13.5k
         
!getLangOpts().CPlusPlus1763
;
937
13.5k
}
938
939
bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
940
120k
                                                const CXXMethodDecl *Old) {
941
120k
  // If the new exception specification hasn't been parsed yet, skip the check.
942
120k
  // We'll get called again once it's been parsed.
943
120k
  if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
944
120k
      EST_Unparsed)
945
895
    return false;
946
119k
947
119k
  // Don't check uninstantiated template destructors at all. We can only
948
119k
  // synthesize correct specs after the template is instantiated.
949
119k
  if (isa<CXXDestructorDecl>(New) && 
New->getParent()->isDependentType()60.6k
)
950
2.24k
    return false;
951
117k
952
117k
  // If the old exception specification hasn't been parsed yet, or the new
953
117k
  // exception specification can't be computed yet, remember that we need to
954
117k
  // perform this check when we get to the end of the outermost
955
117k
  // lexically-surrounding class.
956
117k
  if (exceptionSpecNotKnownYet(Old) || 
exceptionSpecNotKnownYet(New)117k
) {
957
26.2k
    DelayedOverridingExceptionSpecChecks.push_back({New, Old});
958
26.2k
    return false;
959
26.2k
  }
960
90.9k
961
90.9k
  unsigned DiagID = diag::err_override_exception_spec;
962
90.9k
  if (getLangOpts().MicrosoftExt)
963
256
    DiagID = diag::ext_override_exception_spec;
964
90.9k
  return CheckExceptionSpecSubset(PDiag(DiagID),
965
90.9k
                                  PDiag(diag::err_deep_exception_specs_differ),
966
90.9k
                                  PDiag(diag::note_overridden_virtual_function),
967
90.9k
                                  PDiag(diag::ext_override_exception_spec),
968
90.9k
                                  Old->getType()->getAs<FunctionProtoType>(),
969
90.9k
                                  Old->getLocation(),
970
90.9k
                                  New->getType()->getAs<FunctionProtoType>(),
971
90.9k
                                  New->getLocation());
972
90.9k
}
973
974
66.8k
static CanThrowResult canSubExprsThrow(Sema &S, const Expr *E) {
975
66.8k
  CanThrowResult R = CT_Cannot;
976
104k
  for (const Stmt *SubStmt : E->children()) {
977
104k
    R = mergeCanThrow(R, S.canThrow(cast<Expr>(SubStmt)));
978
104k
    if (R == CT_Can)
979
370
      break;
980
104k
  }
981
66.8k
  return R;
982
66.8k
}
983
984
7.76k
static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
985
7.76k
  // As an extension, we assume that __attribute__((nothrow)) functions don't
986
7.76k
  // throw.
987
7.76k
  if (D && 
isa<FunctionDecl>(D)7.73k
&&
D->hasAttr<NoThrowAttr>()7.70k
)
988
3
    return CT_Cannot;
989
7.75k
990
7.75k
  QualType T;
991
7.75k
992
7.75k
  // In C++1z, just look at the function type of the callee.
993
7.75k
  if (S.getLangOpts().CPlusPlus17 && 
isa<CallExpr>(E)89
) {
994
56
    E = cast<CallExpr>(E)->getCallee();
995
56
    T = E->getType();
996
56
    if (T->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
997
13
      // Sadly we don't preserve the actual type as part of the "bound member"
998
13
      // placeholder, so we need to reconstruct it.
999
13
      E = E->IgnoreParenImpCasts();
1000
13
1001
13
      // Could be a call to a pointer-to-member or a plain member access.
1002
13
      if (auto *Op = dyn_cast<BinaryOperator>(E)) {
1003
0
        assert(Op->getOpcode() == BO_PtrMemD || Op->getOpcode() == BO_PtrMemI);
1004
0
        T = Op->getRHS()->getType()
1005
0
              ->castAs<MemberPointerType>()->getPointeeType();
1006
13
      } else {
1007
13
        T = cast<MemberExpr>(E)->getMemberDecl()->getType();
1008
13
      }
1009
13
    }
1010
7.70k
  } else if (const ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D))
1011
7.67k
    T = VD->getType();
1012
29
  else
1013
29
    // If we have no clue what we're calling, assume the worst.
1014
29
    return CT_Can;
1015
7.72k
1016
7.72k
  const FunctionProtoType *FT;
1017
7.72k
  if ((FT = T->getAs<FunctionProtoType>())) {
1018
7.66k
  } else 
if (const PointerType *61
PT61
= T->getAs<PointerType>())
1019
56
    FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1020
5
  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1021
1
    FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1022
4
  else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1023
4
    FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1024
0
  else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1025
0
    FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1026
7.72k
1027
7.72k
  if (!FT)
1028
0
    return CT_Can;
1029
7.72k
1030
7.72k
  FT = S.ResolveExceptionSpec(E->getBeginLoc(), FT);
1031
7.72k
  if (!FT)
1032
0
    return CT_Can;
1033
7.72k
1034
7.72k
  return FT->canThrow();
1035
7.72k
}
1036
1037
8
static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
1038
8
  if (DC->isTypeDependent())
1039
0
    return CT_Dependent;
1040
8
1041
8
  if (!DC->getTypeAsWritten()->isReferenceType())
1042
4
    return CT_Cannot;
1043
4
1044
4
  if (DC->getSubExpr()->isTypeDependent())
1045
1
    return CT_Dependent;
1046
3
1047
3
  return DC->getCastKind() == clang::CK_Dynamic? 
CT_Can1
:
CT_Cannot2
;
1048
3
}
1049
1050
11
static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
1051
11
  if (DC->isTypeOperand())
1052
1
    return CT_Cannot;
1053
10
1054
10
  Expr *Op = DC->getExprOperand();
1055
10
  if (Op->isTypeDependent())
1056
1
    return CT_Dependent;
1057
9
1058
9
  const RecordType *RT = Op->getType()->getAs<RecordType>();
1059
9
  if (!RT)
1060
2
    return CT_Cannot;
1061
7
1062
7
  if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
1063
3
    return CT_Cannot;
1064
4
1065
4
  if (Op->Classify(S.Context).isPRValue())
1066
0
    return CT_Cannot;
1067
4
1068
4
  return CT_Can;
1069
4
}
1070
1071
133k
CanThrowResult Sema::canThrow(const Expr *E) {
1072
133k
  // C++ [expr.unary.noexcept]p3:
1073
133k
  //   [Can throw] if in a potentially-evaluated context the expression would
1074
133k
  //   contain:
1075
133k
  switch (E->getStmtClass()) {
1076
133k
  case Expr::ConstantExprClass:
1077
0
    return canThrow(cast<ConstantExpr>(E)->getSubExpr());
1078
133k
1079
133k
  case Expr::CXXThrowExprClass:
1080
7
    //   - a potentially evaluated throw-expression
1081
7
    return CT_Can;
1082
133k
1083
133k
  case Expr::CXXDynamicCastExprClass: {
1084
8
    //   - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1085
8
    //     where T is a reference type, that requires a run-time check
1086
8
    CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
1087
8
    if (CT == CT_Can)
1088
1
      return CT;
1089
7
    return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1090
7
  }
1091
7
1092
11
  case Expr::CXXTypeidExprClass:
1093
11
    //   - a potentially evaluated typeid expression applied to a glvalue
1094
11
    //     expression whose type is a polymorphic class type
1095
11
    return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
1096
7
1097
7
    //   - a potentially evaluated call to a function, member function, function
1098
7
    //     pointer, or member function pointer that does not have a non-throwing
1099
7
    //     exception-specification
1100
33.9k
  case Expr::CallExprClass:
1101
33.9k
  case Expr::CXXMemberCallExprClass:
1102
33.9k
  case Expr::CXXOperatorCallExprClass:
1103
33.9k
  case Expr::UserDefinedLiteralClass: {
1104
33.9k
    const CallExpr *CE = cast<CallExpr>(E);
1105
33.9k
    CanThrowResult CT;
1106
33.9k
    if (E->isTypeDependent())
1107
32.5k
      CT = CT_Dependent;
1108
1.39k
    else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
1109
1
      CT = CT_Cannot;
1110
1.39k
    else
1111
1.39k
      CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
1112
33.9k
    if (CT == CT_Can)
1113
375
      return CT;
1114
33.5k
    return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1115
33.5k
  }
1116
33.5k
1117
33.5k
  case Expr::CXXConstructExprClass:
1118
5.54k
  case Expr::CXXTemporaryObjectExprClass: {
1119
5.54k
    CanThrowResult CT = canCalleeThrow(*this, E,
1120
5.54k
        cast<CXXConstructExpr>(E)->getConstructor());
1121
5.54k
    if (CT == CT_Can)
1122
291
      return CT;
1123
5.25k
    return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1124
5.25k
  }
1125
5.25k
1126
5.25k
  case Expr::CXXInheritedCtorInitExprClass:
1127
0
    return canCalleeThrow(*this, E,
1128
0
                          cast<CXXInheritedCtorInitExpr>(E)->getConstructor());
1129
5.25k
1130
5.25k
  case Expr::LambdaExprClass: {
1131
6
    const LambdaExpr *Lambda = cast<LambdaExpr>(E);
1132
6
    CanThrowResult CT = CT_Cannot;
1133
6
    for (LambdaExpr::const_capture_init_iterator
1134
6
             Cap = Lambda->capture_init_begin(),
1135
6
             CapEnd = Lambda->capture_init_end();
1136
6
         Cap != CapEnd; 
++Cap0
)
1137
0
      CT = mergeCanThrow(CT, canThrow(*Cap));
1138
6
    return CT;
1139
5.25k
  }
1140
5.25k
1141
5.25k
  case Expr::CXXNewExprClass: {
1142
26
    CanThrowResult CT;
1143
26
    if (E->isTypeDependent())
1144
4
      CT = CT_Dependent;
1145
22
    else
1146
22
      CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
1147
26
    if (CT == CT_Can)
1148
1
      return CT;
1149
25
    return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1150
25
  }
1151
25
1152
25
  case Expr::CXXDeleteExprClass: {
1153
16
    CanThrowResult CT;
1154
16
    QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
1155
16
    if (DTy.isNull() || 
DTy->isDependentType()15
) {
1156
2
      CT = CT_Dependent;
1157
14
    } else {
1158
14
      CT = canCalleeThrow(*this, E,
1159
14
                          cast<CXXDeleteExpr>(E)->getOperatorDelete());
1160
14
      if (const RecordType *RT = DTy->getAs<RecordType>()) {
1161
12
        const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1162
12
        const CXXDestructorDecl *DD = RD->getDestructor();
1163
12
        if (DD)
1164
11
          CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
1165
12
      }
1166
14
      if (CT == CT_Can)
1167
6
        return CT;
1168
10
    }
1169
10
    return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1170
10
  }
1171
10
1172
781
  case Expr::CXXBindTemporaryExprClass: {
1173
781
    // The bound temporary has to be destroyed again, which might throw.
1174
781
    CanThrowResult CT = canCalleeThrow(*this, E,
1175
781
      cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
1176
781
    if (CT == CT_Can)
1177
11
      return CT;
1178
770
    return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1179
770
  }
1180
770
1181
770
    // ObjC message sends are like function calls, but never have exception
1182
770
    // specs.
1183
770
  case Expr::ObjCMessageExprClass:
1184
1
  case Expr::ObjCPropertyRefExprClass:
1185
1
  case Expr::ObjCSubscriptRefExprClass:
1186
1
    return CT_Can;
1187
1
1188
1
    // All the ObjC literals that are implemented as calls are
1189
1
    // potentially throwing unless we decide to close off that
1190
1
    // possibility.
1191
1
  case Expr::ObjCArrayLiteralClass:
1192
0
  case Expr::ObjCDictionaryLiteralClass:
1193
0
  case Expr::ObjCBoxedExprClass:
1194
0
    return CT_Can;
1195
0
1196
0
    // Many other things have subexpressions, so we have to test those.
1197
0
    // Some are simple:
1198
7.43k
  case Expr::CoawaitExprClass:
1199
7.43k
  case Expr::ConditionalOperatorClass:
1200
7.43k
  case Expr::CompoundLiteralExprClass:
1201
7.43k
  case Expr::CoyieldExprClass:
1202
7.43k
  case Expr::CXXConstCastExprClass:
1203
7.43k
  case Expr::CXXReinterpretCastExprClass:
1204
7.43k
  case Expr::BuiltinBitCastExprClass:
1205
7.43k
  case Expr::CXXStdInitializerListExprClass:
1206
7.43k
  case Expr::DesignatedInitExprClass:
1207
7.43k
  case Expr::DesignatedInitUpdateExprClass:
1208
7.43k
  case Expr::ExprWithCleanupsClass:
1209
7.43k
  case Expr::ExtVectorElementExprClass:
1210
7.43k
  case Expr::InitListExprClass:
1211
7.43k
  case Expr::ArrayInitLoopExprClass:
1212
7.43k
  case Expr::MemberExprClass:
1213
7.43k
  case Expr::ObjCIsaExprClass:
1214
7.43k
  case Expr::ObjCIvarRefExprClass:
1215
7.43k
  case Expr::ParenExprClass:
1216
7.43k
  case Expr::ParenListExprClass:
1217
7.43k
  case Expr::ShuffleVectorExprClass:
1218
7.43k
  case Expr::ConvertVectorExprClass:
1219
7.43k
  case Expr::VAArgExprClass:
1220
7.43k
    return canSubExprsThrow(*this, E);
1221
7.43k
1222
7.43k
    // Some might be dependent for other reasons.
1223
19.7k
  case Expr::ArraySubscriptExprClass:
1224
19.7k
  case Expr::OMPArraySectionExprClass:
1225
19.7k
  case Expr::BinaryOperatorClass:
1226
19.7k
  case Expr::DependentCoawaitExprClass:
1227
19.7k
  case Expr::CompoundAssignOperatorClass:
1228
19.7k
  case Expr::CStyleCastExprClass:
1229
19.7k
  case Expr::CXXStaticCastExprClass:
1230
19.7k
  case Expr::CXXFunctionalCastExprClass:
1231
19.7k
  case Expr::ImplicitCastExprClass:
1232
19.7k
  case Expr::MaterializeTemporaryExprClass:
1233
19.7k
  case Expr::UnaryOperatorClass: {
1234
19.7k
    CanThrowResult CT = E->isTypeDependent() ? 
CT_Dependent13.4k
:
CT_Cannot6.35k
;
1235
19.7k
    return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1236
19.7k
  }
1237
19.7k
1238
19.7k
    // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1239
19.7k
  case Expr::StmtExprClass:
1240
0
    return CT_Can;
1241
19.7k
1242
19.7k
  case Expr::CXXDefaultArgExprClass:
1243
23
    return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
1244
19.7k
1245
19.7k
  case Expr::CXXDefaultInitExprClass:
1246
77
    return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
1247
19.7k
1248
19.7k
  case Expr::ChooseExprClass:
1249
0
    if (E->isTypeDependent() || E->isValueDependent())
1250
0
      return CT_Dependent;
1251
0
    return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
1252
0
1253
0
  case Expr::GenericSelectionExprClass:
1254
0
    if (cast<GenericSelectionExpr>(E)->isResultDependent())
1255
0
      return CT_Dependent;
1256
0
    return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1257
0
1258
0
    // Some expressions are always dependent.
1259
4.59k
  case Expr::CXXDependentScopeMemberExprClass:
1260
4.59k
  case Expr::CXXUnresolvedConstructExprClass:
1261
4.59k
  case Expr::DependentScopeDeclRefExprClass:
1262
4.59k
  case Expr::CXXFoldExprClass:
1263
4.59k
    return CT_Dependent;
1264
4.59k
1265
50.7k
  case Expr::AsTypeExprClass:
1266
50.7k
  case Expr::BinaryConditionalOperatorClass:
1267
50.7k
  case Expr::BlockExprClass:
1268
50.7k
  case Expr::CUDAKernelCallExprClass:
1269
50.7k
  case Expr::DeclRefExprClass:
1270
50.7k
  case Expr::ObjCBridgedCastExprClass:
1271
50.7k
  case Expr::ObjCIndirectCopyRestoreExprClass:
1272
50.7k
  case Expr::ObjCProtocolExprClass:
1273
50.7k
  case Expr::ObjCSelectorExprClass:
1274
50.7k
  case Expr::ObjCAvailabilityCheckExprClass:
1275
50.7k
  case Expr::OffsetOfExprClass:
1276
50.7k
  case Expr::PackExpansionExprClass:
1277
50.7k
  case Expr::PseudoObjectExprClass:
1278
50.7k
  case Expr::SubstNonTypeTemplateParmExprClass:
1279
50.7k
  case Expr::SubstNonTypeTemplateParmPackExprClass:
1280
50.7k
  case Expr::FunctionParmPackExprClass:
1281
50.7k
  case Expr::UnaryExprOrTypeTraitExprClass:
1282
50.7k
  case Expr::UnresolvedLookupExprClass:
1283
50.7k
  case Expr::UnresolvedMemberExprClass:
1284
50.7k
  case Expr::TypoExprClass:
1285
50.7k
    // FIXME: Can any of the above throw?  If so, when?
1286
50.7k
    return CT_Cannot;
1287
50.7k
1288
50.7k
  case Expr::AddrLabelExprClass:
1289
10.0k
  case Expr::ArrayTypeTraitExprClass:
1290
10.0k
  case Expr::AtomicExprClass:
1291
10.0k
  case Expr::TypeTraitExprClass:
1292
10.0k
  case Expr::CXXBoolLiteralExprClass:
1293
10.0k
  case Expr::CXXNoexceptExprClass:
1294
10.0k
  case Expr::CXXNullPtrLiteralExprClass:
1295
10.0k
  case Expr::CXXPseudoDestructorExprClass:
1296
10.0k
  case Expr::CXXScalarValueInitExprClass:
1297
10.0k
  case Expr::CXXThisExprClass:
1298
10.0k
  case Expr::CXXUuidofExprClass:
1299
10.0k
  case Expr::CharacterLiteralClass:
1300
10.0k
  case Expr::ExpressionTraitExprClass:
1301
10.0k
  case Expr::FloatingLiteralClass:
1302
10.0k
  case Expr::GNUNullExprClass:
1303
10.0k
  case Expr::ImaginaryLiteralClass:
1304
10.0k
  case Expr::ImplicitValueInitExprClass:
1305
10.0k
  case Expr::IntegerLiteralClass:
1306
10.0k
  case Expr::FixedPointLiteralClass:
1307
10.0k
  case Expr::ArrayInitIndexExprClass:
1308
10.0k
  case Expr::NoInitExprClass:
1309
10.0k
  case Expr::ObjCEncodeExprClass:
1310
10.0k
  case Expr::ObjCStringLiteralClass:
1311
10.0k
  case Expr::ObjCBoolLiteralExprClass:
1312
10.0k
  case Expr::OpaqueValueExprClass:
1313
10.0k
  case Expr::PredefinedExprClass:
1314
10.0k
  case Expr::SizeOfPackExprClass:
1315
10.0k
  case Expr::StringLiteralClass:
1316
10.0k
  case Expr::SourceLocExprClass:
1317
10.0k
    // These expressions can never throw.
1318
10.0k
    return CT_Cannot;
1319
10.0k
1320
10.0k
  case Expr::MSPropertyRefExprClass:
1321
0
  case Expr::MSPropertySubscriptExprClass:
1322
0
    llvm_unreachable("Invalid class for expression");
1323
0
1324
0
#define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1325
0
#define STMT_RANGE(Base, First, Last)
1326
0
#define LAST_STMT_RANGE(BASE, FIRST, LAST)
1327
0
#define EXPR(CLASS, PARENT)
1328
0
#define ABSTRACT_STMT(STMT)
1329
0
#include "clang/AST/StmtNodes.inc"
1330
0
  case Expr::NoStmtClass:
1331
0
    llvm_unreachable("Invalid class for expression");
1332
0
  }
1333
0
  llvm_unreachable("Bogus StmtClass");
1334
0
}
1335
1336
} // end namespace clang