clang  7.0.0svn
SemaExceptionSpec.cpp
Go to the documentation of this file.
1 //===--- SemaExceptionSpec.cpp - C++ Exception Specifications ---*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ exception specification testing.
11 //
12 //===----------------------------------------------------------------------===//
13 
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/Basic/Diagnostic.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallString.h"
24 
25 namespace clang {
26 
28 {
29  if (const PointerType *PtrTy = T->getAs<PointerType>())
30  T = PtrTy->getPointeeType();
31  else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
32  T = RefTy->getPointeeType();
33  else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
34  T = MPTy->getPointeeType();
35  return T->getAs<FunctionProtoType>();
36 }
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.
43  auto *RD = dyn_cast<CXXRecordDecl>(CurContext);
44 
45  // All the problem cases are member functions named "swap" within class
46  // templates declared directly within namespace std or std::__debug or
47  // std::__profile.
48  if (!RD || !RD->getIdentifier() || !RD->getDescribedClassTemplate() ||
49  !D.getIdentifier() || !D.getIdentifier()->isStr("swap"))
50  return false;
51 
52  auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext());
53  if (!ND)
54  return false;
55 
56  bool IsInStd = ND->isStdNamespace();
57  if (!IsInStd) {
58  // This isn't a direct member of namespace std, but it might still be
59  // libstdc++'s std::__debug::array or std::__profile::array.
60  IdentifierInfo *II = ND->getIdentifier();
61  if (!II || !(II->isStr("__debug") || II->isStr("__profile")) ||
62  !ND->isInStdNamespace())
63  return false;
64  }
65 
66  // Only apply this hack within a system header.
68  return false;
69 
70  return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
71  .Case("array", true)
72  .Case("pair", IsInStd)
73  .Case("priority_queue", IsInStd)
74  .Case("stack", IsInStd)
75  .Case("queue", IsInStd)
76  .Default(false);
77 }
78 
80  Expr *NoexceptExpr,
82  // FIXME: This is bogus, a noexcept expression is not a condition.
83  ExprResult Converted = CheckBooleanCondition(NoexceptLoc, NoexceptExpr);
84  if (Converted.isInvalid())
85  return Converted;
86 
87  if (Converted.get()->isValueDependent()) {
89  return Converted;
90  }
91 
92  llvm::APSInt Result;
94  Converted.get(), &Result,
95  diag::err_noexcept_needs_constant_expression,
96  /*AllowFold*/ false);
97  if (!Converted.isInvalid())
98  EST = !Result ? EST_NoexceptFalse : EST_NoexceptTrue;
99  return Converted;
100 }
101 
102 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
103 /// exception specification. Incomplete types, or pointers to incomplete types
104 /// other than void are not allowed.
105 ///
106 /// \param[in,out] T The exception type. This will be decayed to a pointer type
107 /// when the input is an array or a function type.
109  // C++11 [except.spec]p2:
110  // A type cv T, "array of T", or "function returning T" denoted
111  // in an exception-specification is adjusted to type T, "pointer to T", or
112  // "pointer to function returning T", respectively.
113  //
114  // We also apply this rule in C++98.
115  if (T->isArrayType())
117  else if (T->isFunctionType())
118  T = Context.getPointerType(T);
119 
120  int Kind = 0;
121  QualType PointeeT = T;
122  if (const PointerType *PT = T->getAs<PointerType>()) {
123  PointeeT = PT->getPointeeType();
124  Kind = 1;
125 
126  // cv void* is explicitly permitted, despite being a pointer to an
127  // incomplete type.
128  if (PointeeT->isVoidType())
129  return false;
130  } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
131  PointeeT = RT->getPointeeType();
132  Kind = 2;
133 
134  if (RT->isRValueReferenceType()) {
135  // C++11 [except.spec]p2:
136  // A type denoted in an exception-specification shall not denote [...]
137  // an rvalue reference type.
138  Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
139  << T << Range;
140  return true;
141  }
142  }
143 
144  // C++11 [except.spec]p2:
145  // A type denoted in an exception-specification shall not denote an
146  // incomplete type other than a class currently being defined [...].
147  // A type denoted in an exception-specification shall not denote a
148  // pointer or reference to an incomplete type, other than (cv) void* or a
149  // pointer or reference to a class currently being defined.
150  // In Microsoft mode, downgrade this to a warning.
151  unsigned DiagID = diag::err_incomplete_in_exception_spec;
152  bool ReturnValueOnError = true;
153  if (getLangOpts().MicrosoftExt) {
154  DiagID = diag::ext_incomplete_in_exception_spec;
155  ReturnValueOnError = false;
156  }
157  if (!(PointeeT->isRecordType() &&
158  PointeeT->getAs<RecordType>()->isBeingDefined()) &&
159  RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range))
160  return ReturnValueOnError;
161 
162  return false;
163 }
164 
165 /// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
166 /// to member to a function with an exception specification. This means that
167 /// it is invalid to add another level of indirection.
169  // C++17 removes this rule in favor of putting exception specifications into
170  // the type system.
171  if (getLangOpts().CPlusPlus17)
172  return false;
173 
174  if (const PointerType *PT = T->getAs<PointerType>())
175  T = PT->getPointeeType();
176  else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
177  T = PT->getPointeeType();
178  else
179  return false;
180 
181  const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
182  if (!FnT)
183  return false;
184 
185  return FnT->hasExceptionSpec();
186 }
187 
188 const FunctionProtoType *
190  if (FPT->getExceptionSpecType() == EST_Unparsed) {
191  Diag(Loc, diag::err_exception_spec_not_parsed);
192  return nullptr;
193  }
194 
196  return FPT;
197 
198  FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
199  const FunctionProtoType *SourceFPT =
200  SourceDecl->getType()->castAs<FunctionProtoType>();
201 
202  // If the exception specification has already been resolved, just return it.
204  return SourceFPT;
205 
206  // Compute or instantiate the exception specification now.
207  if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
208  EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
209  else
210  InstantiateExceptionSpec(Loc, SourceDecl);
211 
212  const FunctionProtoType *Proto =
213  SourceDecl->getType()->castAs<FunctionProtoType>();
214  if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
215  Diag(Loc, diag::err_exception_spec_not_parsed);
216  Proto = nullptr;
217  }
218  return Proto;
219 }
220 
221 void
224  // If we've fully resolved the exception specification, notify listeners.
226  if (auto *Listener = getASTMutationListener())
227  Listener->ResolvedExceptionSpec(FD);
228 
229  for (FunctionDecl *Redecl : FD->redecls())
230  Context.adjustExceptionSpec(Redecl, ESI);
231 }
232 
234  Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
235  const FunctionProtoType *Old, SourceLocation OldLoc,
236  const FunctionProtoType *New, SourceLocation NewLoc,
237  bool *MissingExceptionSpecification = nullptr,
238  bool *MissingEmptyExceptionSpecification = nullptr,
239  bool AllowNoexceptAllMatchWithNoSpec = false, bool IsOperatorNew = false);
240 
241 /// Determine whether a function has an implicitly-generated exception
242 /// specification.
244  if (!isa<CXXDestructorDecl>(Decl) &&
245  Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
246  Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
247  return false;
248 
249  // For a function that the user didn't declare:
250  // - if this is a destructor, its exception specification is implicit.
251  // - if this is 'operator delete' or 'operator delete[]', the exception
252  // specification is as-if an explicit exception specification was given
253  // (per [basic.stc.dynamic]p2).
254  if (!Decl->getTypeSourceInfo())
255  return isa<CXXDestructorDecl>(Decl);
256 
257  const FunctionProtoType *Ty =
259  return !Ty->hasExceptionSpec();
260 }
261 
263  // Just completely ignore this under -fno-exceptions prior to C++17.
264  // In C++17 onwards, the exception specification is part of the type and
265  // we will diagnose mismatches anyway, so it's better to check for them here.
266  if (!getLangOpts().CXXExceptions && !getLangOpts().CPlusPlus17)
267  return false;
268 
270  bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
271  bool MissingExceptionSpecification = false;
272  bool MissingEmptyExceptionSpecification = false;
273 
274  unsigned DiagID = diag::err_mismatched_exception_spec;
275  bool ReturnValueOnError = true;
276  if (getLangOpts().MicrosoftExt) {
277  DiagID = diag::ext_mismatched_exception_spec;
278  ReturnValueOnError = false;
279  }
280 
281  // Check the types as written: they must match before any exception
282  // specification adjustment is applied.
284  *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
285  Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
286  New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
287  &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
288  /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
289  // C++11 [except.spec]p4 [DR1492]:
290  // If a declaration of a function has an implicit
291  // exception-specification, other declarations of the function shall
292  // not specify an exception-specification.
293  if (getLangOpts().CPlusPlus11 && getLangOpts().CXXExceptions &&
295  Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
296  << hasImplicitExceptionSpec(Old);
297  if (Old->getLocation().isValid())
298  Diag(Old->getLocation(), diag::note_previous_declaration);
299  }
300  return false;
301  }
302 
303  // The failure was something other than an missing exception
304  // specification; return an error, except in MS mode where this is a warning.
305  if (!MissingExceptionSpecification)
306  return ReturnValueOnError;
307 
308  const FunctionProtoType *NewProto =
309  New->getType()->castAs<FunctionProtoType>();
310 
311  // The new function declaration is only missing an empty exception
312  // specification "throw()". If the throw() specification came from a
313  // function in a system header that has C linkage, just add an empty
314  // exception specification to the "new" declaration. Note that C library
315  // implementations are permitted to add these nothrow exception
316  // specifications.
317  //
318  // Likewise if the old function is a builtin.
319  if (MissingEmptyExceptionSpecification && NewProto &&
320  (Old->getLocation().isInvalid() ||
322  Old->getBuiltinID()) &&
323  Old->isExternC()) {
325  NewProto->getReturnType(), NewProto->getParamTypes(),
327  return false;
328  }
329 
330  const FunctionProtoType *OldProto =
331  Old->getType()->castAs<FunctionProtoType>();
332 
334  if (ESI.Type == EST_Dynamic) {
335  // FIXME: What if the exceptions are described in terms of the old
336  // prototype's parameters?
337  ESI.Exceptions = OldProto->exceptions();
338  }
339 
340  if (ESI.Type == EST_NoexceptFalse)
341  ESI.Type = EST_None;
342  if (ESI.Type == EST_NoexceptTrue)
343  ESI.Type = EST_BasicNoexcept;
344 
345  // For dependent noexcept, we can't just take the expression from the old
346  // prototype. It likely contains references to the old prototype's parameters.
347  if (ESI.Type == EST_DependentNoexcept) {
348  New->setInvalidDecl();
349  } else {
350  // Update the type of the function with the appropriate exception
351  // specification.
353  NewProto->getReturnType(), NewProto->getParamTypes(),
354  NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
355  }
356 
357  if (getLangOpts().MicrosoftExt && ESI.Type != EST_DependentNoexcept) {
358  // Allow missing exception specifications in redeclarations as an extension.
359  DiagID = diag::ext_ms_missing_exception_specification;
360  ReturnValueOnError = false;
361  } else if (New->isReplaceableGlobalAllocationFunction() &&
362  ESI.Type != EST_DependentNoexcept) {
363  // Allow missing exception specifications in redeclarations as an extension,
364  // when declaring a replaceable global allocation function.
365  DiagID = diag::ext_missing_exception_specification;
366  ReturnValueOnError = false;
367  } else {
368  DiagID = diag::err_missing_exception_specification;
369  ReturnValueOnError = true;
370  }
371 
372  // Warn about the lack of exception specification.
373  SmallString<128> ExceptionSpecString;
374  llvm::raw_svector_ostream OS(ExceptionSpecString);
375  switch (OldProto->getExceptionSpecType()) {
376  case EST_DynamicNone:
377  OS << "throw()";
378  break;
379 
380  case EST_Dynamic: {
381  OS << "throw(";
382  bool OnFirstException = true;
383  for (const auto &E : OldProto->exceptions()) {
384  if (OnFirstException)
385  OnFirstException = false;
386  else
387  OS << ", ";
388 
389  OS << E.getAsString(getPrintingPolicy());
390  }
391  OS << ")";
392  break;
393  }
394 
395  case EST_BasicNoexcept:
396  OS << "noexcept";
397  break;
398 
400  case EST_NoexceptFalse:
401  case EST_NoexceptTrue:
402  OS << "noexcept(";
403  assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
404  OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
405  OS << ")";
406  break;
407 
408  default:
409  llvm_unreachable("This spec type is compatible with none.");
410  }
411 
412  SourceLocation FixItLoc;
413  if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
414  TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
415  // FIXME: Preserve enough information so that we can produce a correct fixit
416  // location when there is a trailing return type.
417  if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
418  if (!FTLoc.getTypePtr()->hasTrailingReturn())
419  FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
420  }
421 
422  if (FixItLoc.isInvalid())
423  Diag(New->getLocation(), DiagID)
424  << New << OS.str();
425  else {
426  Diag(New->getLocation(), DiagID)
427  << New << OS.str()
428  << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
429  }
430 
431  if (Old->getLocation().isValid())
432  Diag(Old->getLocation(), diag::note_previous_declaration);
433 
434  return ReturnValueOnError;
435 }
436 
437 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
438 /// exception specifications. Exception specifications are equivalent if
439 /// they allow exactly the same set of exception types. It does not matter how
440 /// that is achieved. See C++ [except.spec]p2.
442  const FunctionProtoType *Old, SourceLocation OldLoc,
443  const FunctionProtoType *New, SourceLocation NewLoc) {
444  if (!getLangOpts().CXXExceptions)
445  return false;
446 
447  unsigned DiagID = diag::err_mismatched_exception_spec;
448  if (getLangOpts().MicrosoftExt)
449  DiagID = diag::ext_mismatched_exception_spec;
451  *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
452  Old, OldLoc, New, NewLoc);
453 
454  // In Microsoft mode, mismatching exception specifications just cause a warning.
455  if (getLangOpts().MicrosoftExt)
456  return false;
457  return Result;
458 }
459 
460 /// CheckEquivalentExceptionSpec - Check if the two types have compatible
461 /// exception specifications. See C++ [except.spec]p3.
462 ///
463 /// \return \c false if the exception specifications match, \c true if there is
464 /// a problem. If \c true is returned, either a diagnostic has already been
465 /// produced or \c *MissingExceptionSpecification is set to \c true.
467  Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
468  const FunctionProtoType *Old, SourceLocation OldLoc,
469  const FunctionProtoType *New, SourceLocation NewLoc,
470  bool *MissingExceptionSpecification,
471  bool *MissingEmptyExceptionSpecification,
472  bool AllowNoexceptAllMatchWithNoSpec, bool IsOperatorNew) {
473  if (MissingExceptionSpecification)
474  *MissingExceptionSpecification = false;
475 
476  if (MissingEmptyExceptionSpecification)
477  *MissingEmptyExceptionSpecification = false;
478 
479  Old = S.ResolveExceptionSpec(NewLoc, Old);
480  if (!Old)
481  return false;
482  New = S.ResolveExceptionSpec(NewLoc, New);
483  if (!New)
484  return false;
485 
486  // C++0x [except.spec]p3: Two exception-specifications are compatible if:
487  // - both are non-throwing, regardless of their form,
488  // - both have the form noexcept(constant-expression) and the constant-
489  // expressions are equivalent,
490  // - both are dynamic-exception-specifications that have the same set of
491  // adjusted types.
492  //
493  // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
494  // of the form throw(), noexcept, or noexcept(constant-expression) where the
495  // constant-expression yields true.
496  //
497  // C++0x [except.spec]p4: If any declaration of a function has an exception-
498  // specifier that is not a noexcept-specification allowing all exceptions,
499  // all declarations [...] of that function shall have a compatible
500  // exception-specification.
501  //
502  // That last point basically means that noexcept(false) matches no spec.
503  // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
504 
507 
508  assert(!isUnresolvedExceptionSpec(OldEST) &&
509  !isUnresolvedExceptionSpec(NewEST) &&
510  "Shouldn't see unknown exception specifications here");
511 
512  CanThrowResult OldCanThrow = Old->canThrow();
513  CanThrowResult NewCanThrow = New->canThrow();
514 
515  // Any non-throwing specifications are compatible.
516  if (OldCanThrow == CT_Cannot && NewCanThrow == CT_Cannot)
517  return false;
518 
519  // Any throws-anything specifications are usually compatible.
520  if (OldCanThrow == CT_Can && OldEST != EST_Dynamic &&
521  NewCanThrow == CT_Can && NewEST != EST_Dynamic) {
522  // The exception is that the absence of an exception specification only
523  // matches noexcept(false) for functions, as described above.
524  if (!AllowNoexceptAllMatchWithNoSpec &&
525  ((OldEST == EST_None && NewEST == EST_NoexceptFalse) ||
526  (OldEST == EST_NoexceptFalse && NewEST == EST_None))) {
527  // This is the disallowed case.
528  } else {
529  return false;
530  }
531  }
532 
533  // FIXME: We treat dependent noexcept specifications as compatible even if
534  // their expressions are not equivalent.
535  if (OldEST == EST_DependentNoexcept && NewEST == EST_DependentNoexcept)
536  return false;
537 
538  // Dynamic exception specifications with the same set of adjusted types
539  // are compatible.
540  if (OldEST == EST_Dynamic && NewEST == EST_Dynamic) {
541  bool Success = true;
542  // Both have a dynamic exception spec. Collect the first set, then compare
543  // to the second.
544  llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
545  for (const auto &I : Old->exceptions())
546  OldTypes.insert(S.Context.getCanonicalType(I).getUnqualifiedType());
547 
548  for (const auto &I : New->exceptions()) {
550  if (OldTypes.count(TypePtr))
551  NewTypes.insert(TypePtr);
552  else {
553  Success = false;
554  break;
555  }
556  }
557 
558  if (Success && OldTypes.size() == NewTypes.size())
559  return false;
560  }
561 
562  // As a special compatibility feature, under C++0x we accept no spec and
563  // throw(std::bad_alloc) as equivalent for operator new and operator new[].
564  // This is because the implicit declaration changed, but old code would break.
565  if (S.getLangOpts().CPlusPlus11 && IsOperatorNew) {
566  const FunctionProtoType *WithExceptions = nullptr;
567  if (OldEST == EST_None && NewEST == EST_Dynamic)
568  WithExceptions = New;
569  else if (OldEST == EST_Dynamic && NewEST == EST_None)
570  WithExceptions = Old;
571  if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
572  // One has no spec, the other throw(something). If that something is
573  // std::bad_alloc, all conditions are met.
574  QualType Exception = *WithExceptions->exception_begin();
575  if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
576  IdentifierInfo* Name = ExRecord->getIdentifier();
577  if (Name && Name->getName() == "bad_alloc") {
578  // It's called bad_alloc, but is it in std?
579  if (ExRecord->isInStdNamespace()) {
580  return false;
581  }
582  }
583  }
584  }
585  }
586 
587  // If the caller wants to handle the case that the new function is
588  // incompatible due to a missing exception specification, let it.
589  if (MissingExceptionSpecification && OldEST != EST_None &&
590  NewEST == EST_None) {
591  // The old type has an exception specification of some sort, but
592  // the new type does not.
593  *MissingExceptionSpecification = true;
594 
595  if (MissingEmptyExceptionSpecification && OldCanThrow == CT_Cannot) {
596  // The old type has a throw() or noexcept(true) exception specification
597  // and the new type has no exception specification, and the caller asked
598  // to handle this itself.
599  *MissingEmptyExceptionSpecification = true;
600  }
601 
602  return true;
603  }
604 
605  S.Diag(NewLoc, DiagID);
606  if (NoteID.getDiagID() != 0 && OldLoc.isValid())
607  S.Diag(OldLoc, NoteID);
608  return true;
609 }
610 
612  const PartialDiagnostic &NoteID,
613  const FunctionProtoType *Old,
614  SourceLocation OldLoc,
615  const FunctionProtoType *New,
616  SourceLocation NewLoc) {
617  if (!getLangOpts().CXXExceptions)
618  return false;
619  return CheckEquivalentExceptionSpecImpl(*this, DiagID, NoteID, Old, OldLoc,
620  New, NewLoc);
621 }
622 
623 bool Sema::handlerCanCatch(QualType HandlerType, QualType ExceptionType) {
624  // [except.handle]p3:
625  // A handler is a match for an exception object of type E if:
626 
627  // HandlerType must be ExceptionType or derived from it, or pointer or
628  // reference to such types.
629  const ReferenceType *RefTy = HandlerType->getAs<ReferenceType>();
630  if (RefTy)
631  HandlerType = RefTy->getPointeeType();
632 
633  // -- the handler is of type cv T or cv T& and E and T are the same type
634  if (Context.hasSameUnqualifiedType(ExceptionType, HandlerType))
635  return true;
636 
637  // FIXME: ObjC pointer types?
638  if (HandlerType->isPointerType() || HandlerType->isMemberPointerType()) {
639  if (RefTy && (!HandlerType.isConstQualified() ||
640  HandlerType.isVolatileQualified()))
641  return false;
642 
643  // -- the handler is of type cv T or const T& where T is a pointer or
644  // pointer to member type and E is std::nullptr_t
645  if (ExceptionType->isNullPtrType())
646  return true;
647 
648  // -- the handler is of type cv T or const T& where T is a pointer or
649  // pointer to member type and E is a pointer or pointer to member type
650  // that can be converted to T by one or more of
651  // -- a qualification conversion
652  // -- a function pointer conversion
653  bool LifetimeConv;
655  // FIXME: Should we treat the exception as catchable if a lifetime
656  // conversion is required?
657  if (IsQualificationConversion(ExceptionType, HandlerType, false,
658  LifetimeConv) ||
659  IsFunctionConversion(ExceptionType, HandlerType, Result))
660  return true;
661 
662  // -- a standard pointer conversion [...]
663  if (!ExceptionType->isPointerType() || !HandlerType->isPointerType())
664  return false;
665 
666  // Handle the "qualification conversion" portion.
667  Qualifiers EQuals, HQuals;
668  ExceptionType = Context.getUnqualifiedArrayType(
669  ExceptionType->getPointeeType(), EQuals);
670  HandlerType = Context.getUnqualifiedArrayType(
671  HandlerType->getPointeeType(), HQuals);
672  if (!HQuals.compatiblyIncludes(EQuals))
673  return false;
674 
675  if (HandlerType->isVoidType() && ExceptionType->isObjectType())
676  return true;
677 
678  // The only remaining case is a derived-to-base conversion.
679  }
680 
681  // -- the handler is of type cg T or cv T& and T is an unambiguous public
682  // base class of E
683  if (!ExceptionType->isRecordType() || !HandlerType->isRecordType())
684  return false;
685  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
686  /*DetectVirtual=*/false);
687  if (!IsDerivedFrom(SourceLocation(), ExceptionType, HandlerType, Paths) ||
688  Paths.isAmbiguous(Context.getCanonicalType(HandlerType)))
689  return false;
690 
691  // Do this check from a context without privileges.
692  switch (CheckBaseClassAccess(SourceLocation(), HandlerType, ExceptionType,
693  Paths.front(),
694  /*Diagnostic*/ 0,
695  /*ForceCheck*/ true,
696  /*ForceUnprivileged*/ true)) {
697  case AR_accessible: return true;
698  case AR_inaccessible: return false;
699  case AR_dependent:
700  llvm_unreachable("access check dependent for unprivileged context");
701  case AR_delayed:
702  llvm_unreachable("access check delayed in non-declaration");
703  }
704  llvm_unreachable("unexpected access check result");
705 }
706 
707 /// CheckExceptionSpecSubset - Check whether the second function type's
708 /// exception specification is a subset (or equivalent) of the first function
709 /// type. This is used by override and pointer assignment checks.
711  const PartialDiagnostic &NestedDiagID,
712  const PartialDiagnostic &NoteID,
713  const FunctionProtoType *Superset,
714  SourceLocation SuperLoc,
715  const FunctionProtoType *Subset,
716  SourceLocation SubLoc) {
717 
718  // Just auto-succeed under -fno-exceptions.
719  if (!getLangOpts().CXXExceptions)
720  return false;
721 
722  // FIXME: As usual, we could be more specific in our error messages, but
723  // that better waits until we've got types with source locations.
724 
725  if (!SubLoc.isValid())
726  SubLoc = SuperLoc;
727 
728  // Resolve the exception specifications, if needed.
729  Superset = ResolveExceptionSpec(SuperLoc, Superset);
730  if (!Superset)
731  return false;
732  Subset = ResolveExceptionSpec(SubLoc, Subset);
733  if (!Subset)
734  return false;
735 
736  ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
738  assert(!isUnresolvedExceptionSpec(SuperEST) &&
739  !isUnresolvedExceptionSpec(SubEST) &&
740  "Shouldn't see unknown exception specifications here");
741 
742  // If there are dependent noexcept specs, assume everything is fine. Unlike
743  // with the equivalency check, this is safe in this case, because we don't
744  // want to merge declarations. Checks after instantiation will catch any
745  // omissions we make here.
746  if (SuperEST == EST_DependentNoexcept || SubEST == EST_DependentNoexcept)
747  return false;
748 
749  CanThrowResult SuperCanThrow = Superset->canThrow();
750  CanThrowResult SubCanThrow = Subset->canThrow();
751 
752  // If the superset contains everything or the subset contains nothing, we're
753  // done.
754  if ((SuperCanThrow == CT_Can && SuperEST != EST_Dynamic) ||
755  SubCanThrow == CT_Cannot)
756  return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
757  Subset, SubLoc);
758 
759  // If the subset contains everything or the superset contains nothing, we've
760  // failed.
761  if ((SubCanThrow == CT_Can && SubEST != EST_Dynamic) ||
762  SuperCanThrow == CT_Cannot) {
763  Diag(SubLoc, DiagID);
764  if (NoteID.getDiagID() != 0)
765  Diag(SuperLoc, NoteID);
766  return true;
767  }
768 
769  assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
770  "Exception spec subset: non-dynamic case slipped through.");
771 
772  // Neither contains everything or nothing. Do a proper comparison.
773  for (QualType SubI : Subset->exceptions()) {
774  if (const ReferenceType *RefTy = SubI->getAs<ReferenceType>())
775  SubI = RefTy->getPointeeType();
776 
777  // Make sure it's in the superset.
778  bool Contained = false;
779  for (QualType SuperI : Superset->exceptions()) {
780  // [except.spec]p5:
781  // the target entity shall allow at least the exceptions allowed by the
782  // source
783  //
784  // We interpret this as meaning that a handler for some target type would
785  // catch an exception of each source type.
786  if (handlerCanCatch(SuperI, SubI)) {
787  Contained = true;
788  break;
789  }
790  }
791  if (!Contained) {
792  Diag(SubLoc, DiagID);
793  if (NoteID.getDiagID() != 0)
794  Diag(SuperLoc, NoteID);
795  return true;
796  }
797  }
798  // We've run half the gauntlet.
799  return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
800  Subset, SubLoc);
801 }
802 
803 static bool
805  const PartialDiagnostic &NoteID, QualType Target,
806  SourceLocation TargetLoc, QualType Source,
807  SourceLocation SourceLoc) {
808  const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
809  if (!TFunc)
810  return false;
811  const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
812  if (!SFunc)
813  return false;
814 
815  return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
816  SFunc, SourceLoc);
817 }
818 
819 /// CheckParamExceptionSpec - Check if the parameter and return types of the
820 /// two functions have equivalent exception specs. This is part of the
821 /// assignment and override compatibility check. We do not check the parameters
822 /// of parameter function pointers recursively, as no sane programmer would
823 /// even be able to write such a function type.
825  const PartialDiagnostic &NoteID,
826  const FunctionProtoType *Target,
827  SourceLocation TargetLoc,
828  const FunctionProtoType *Source,
829  SourceLocation SourceLoc) {
830  auto RetDiag = DiagID;
831  RetDiag << 0;
833  *this, RetDiag, PDiag(),
834  Target->getReturnType(), TargetLoc, Source->getReturnType(),
835  SourceLoc))
836  return true;
837 
838  // We shouldn't even be testing this unless the arguments are otherwise
839  // compatible.
840  assert(Target->getNumParams() == Source->getNumParams() &&
841  "Functions have different argument counts.");
842  for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
843  auto ParamDiag = DiagID;
844  ParamDiag << 1;
846  *this, ParamDiag, PDiag(),
847  Target->getParamType(i), TargetLoc, Source->getParamType(i),
848  SourceLoc))
849  return true;
850  }
851  return false;
852 }
853 
855  // First we check for applicability.
856  // Target type must be a function, function pointer or function reference.
857  const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
858  if (!ToFunc || ToFunc->hasDependentExceptionSpec())
859  return false;
860 
861  // SourceType must be a function or function pointer.
862  const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
863  if (!FromFunc || FromFunc->hasDependentExceptionSpec())
864  return false;
865 
866  unsigned DiagID = diag::err_incompatible_exception_specs;
867  unsigned NestedDiagID = diag::err_deep_exception_specs_differ;
868  // This is not an error in C++17 onwards, unless the noexceptness doesn't
869  // match, but in that case we have a full-on type mismatch, not just a
870  // type sugar mismatch.
871  if (getLangOpts().CPlusPlus17) {
872  DiagID = diag::warn_incompatible_exception_specs;
873  NestedDiagID = diag::warn_deep_exception_specs_differ;
874  }
875 
876  // Now we've got the correct types on both sides, check their compatibility.
877  // This means that the source of the conversion can only throw a subset of
878  // the exceptions of the target, and any exception specs on arguments or
879  // return types must be equivalent.
880  //
881  // FIXME: If there is a nested dependent exception specification, we should
882  // not be checking it here. This is fine:
883  // template<typename T> void f() {
884  // void (*p)(void (*) throw(T));
885  // void (*q)(void (*) throw(int)) = p;
886  // }
887  // ... because it might be instantiated with T=int.
888  return CheckExceptionSpecSubset(PDiag(DiagID), PDiag(NestedDiagID), PDiag(),
889  ToFunc, From->getSourceRange().getBegin(),
890  FromFunc, SourceLocation()) &&
891  !getLangOpts().CPlusPlus17;
892 }
893 
895  const CXXMethodDecl *Old) {
896  // If the new exception specification hasn't been parsed yet, skip the check.
897  // We'll get called again once it's been parsed.
898  if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
899  EST_Unparsed)
900  return false;
901  if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
902  // Don't check uninstantiated template destructors at all. We can only
903  // synthesize correct specs after the template is instantiated.
904  if (New->getParent()->isDependentType())
905  return false;
906  if (New->getParent()->isBeingDefined()) {
907  // The destructor might be updated once the definition is finished. So
908  // remember it and check later.
909  DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
910  return false;
911  }
912  }
913  // If the old exception specification hasn't been parsed yet, remember that
914  // we need to perform this check when we get to the end of the outermost
915  // lexically-surrounding class.
916  if (Old->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
917  EST_Unparsed) {
918  DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
919  return false;
920  }
921  unsigned DiagID = diag::err_override_exception_spec;
922  if (getLangOpts().MicrosoftExt)
923  DiagID = diag::ext_override_exception_spec;
924  return CheckExceptionSpecSubset(PDiag(DiagID),
925  PDiag(diag::err_deep_exception_specs_differ),
926  PDiag(diag::note_overridden_virtual_function),
927  Old->getType()->getAs<FunctionProtoType>(),
928  Old->getLocation(),
929  New->getType()->getAs<FunctionProtoType>(),
930  New->getLocation());
931 }
932 
933 static CanThrowResult canSubExprsThrow(Sema &S, const Expr *E) {
935  for (const Stmt *SubStmt : E->children()) {
936  R = mergeCanThrow(R, S.canThrow(cast<Expr>(SubStmt)));
937  if (R == CT_Can)
938  break;
939  }
940  return R;
941 }
942 
943 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
944  // As an extension, we assume that __attribute__((nothrow)) functions don't
945  // throw.
946  if (D && isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
947  return CT_Cannot;
948 
949  QualType T;
950 
951  // In C++1z, just look at the function type of the callee.
952  if (S.getLangOpts().CPlusPlus17 && isa<CallExpr>(E)) {
953  E = cast<CallExpr>(E)->getCallee();
954  T = E->getType();
955  if (T->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
956  // Sadly we don't preserve the actual type as part of the "bound member"
957  // placeholder, so we need to reconstruct it.
958  E = E->IgnoreParenImpCasts();
959 
960  // Could be a call to a pointer-to-member or a plain member access.
961  if (auto *Op = dyn_cast<BinaryOperator>(E)) {
962  assert(Op->getOpcode() == BO_PtrMemD || Op->getOpcode() == BO_PtrMemI);
963  T = Op->getRHS()->getType()
964  ->castAs<MemberPointerType>()->getPointeeType();
965  } else {
966  T = cast<MemberExpr>(E)->getMemberDecl()->getType();
967  }
968  }
969  } else if (const ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D))
970  T = VD->getType();
971  else
972  // If we have no clue what we're calling, assume the worst.
973  return CT_Can;
974 
975  const FunctionProtoType *FT;
976  if ((FT = T->getAs<FunctionProtoType>())) {
977  } else if (const PointerType *PT = T->getAs<PointerType>())
978  FT = PT->getPointeeType()->getAs<FunctionProtoType>();
979  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
980  FT = RT->getPointeeType()->getAs<FunctionProtoType>();
981  else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
982  FT = MT->getPointeeType()->getAs<FunctionProtoType>();
983  else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
984  FT = BT->getPointeeType()->getAs<FunctionProtoType>();
985 
986  if (!FT)
987  return CT_Can;
988 
989  FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
990  if (!FT)
991  return CT_Can;
992 
993  return FT->canThrow();
994 }
995 
997  if (DC->isTypeDependent())
998  return CT_Dependent;
999 
1000  if (!DC->getTypeAsWritten()->isReferenceType())
1001  return CT_Cannot;
1002 
1003  if (DC->getSubExpr()->isTypeDependent())
1004  return CT_Dependent;
1005 
1006  return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
1007 }
1008 
1010  if (DC->isTypeOperand())
1011  return CT_Cannot;
1012 
1013  Expr *Op = DC->getExprOperand();
1014  if (Op->isTypeDependent())
1015  return CT_Dependent;
1016 
1017  const RecordType *RT = Op->getType()->getAs<RecordType>();
1018  if (!RT)
1019  return CT_Cannot;
1020 
1021  if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
1022  return CT_Cannot;
1023 
1024  if (Op->Classify(S.Context).isPRValue())
1025  return CT_Cannot;
1026 
1027  return CT_Can;
1028 }
1029 
1031  // C++ [expr.unary.noexcept]p3:
1032  // [Can throw] if in a potentially-evaluated context the expression would
1033  // contain:
1034  switch (E->getStmtClass()) {
1035  case Expr::CXXThrowExprClass:
1036  // - a potentially evaluated throw-expression
1037  return CT_Can;
1038 
1039  case Expr::CXXDynamicCastExprClass: {
1040  // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1041  // where T is a reference type, that requires a run-time check
1042  CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
1043  if (CT == CT_Can)
1044  return CT;
1045  return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1046  }
1047 
1048  case Expr::CXXTypeidExprClass:
1049  // - a potentially evaluated typeid expression applied to a glvalue
1050  // expression whose type is a polymorphic class type
1051  return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
1052 
1053  // - a potentially evaluated call to a function, member function, function
1054  // pointer, or member function pointer that does not have a non-throwing
1055  // exception-specification
1056  case Expr::CallExprClass:
1057  case Expr::CXXMemberCallExprClass:
1058  case Expr::CXXOperatorCallExprClass:
1059  case Expr::UserDefinedLiteralClass: {
1060  const CallExpr *CE = cast<CallExpr>(E);
1061  CanThrowResult CT;
1062  if (E->isTypeDependent())
1063  CT = CT_Dependent;
1064  else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
1065  CT = CT_Cannot;
1066  else
1067  CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
1068  if (CT == CT_Can)
1069  return CT;
1070  return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1071  }
1072 
1073  case Expr::CXXConstructExprClass:
1074  case Expr::CXXTemporaryObjectExprClass: {
1075  CanThrowResult CT = canCalleeThrow(*this, E,
1076  cast<CXXConstructExpr>(E)->getConstructor());
1077  if (CT == CT_Can)
1078  return CT;
1079  return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1080  }
1081 
1082  case Expr::CXXInheritedCtorInitExprClass:
1083  return canCalleeThrow(*this, E,
1084  cast<CXXInheritedCtorInitExpr>(E)->getConstructor());
1085 
1086  case Expr::LambdaExprClass: {
1087  const LambdaExpr *Lambda = cast<LambdaExpr>(E);
1090  Cap = Lambda->capture_init_begin(),
1091  CapEnd = Lambda->capture_init_end();
1092  Cap != CapEnd; ++Cap)
1093  CT = mergeCanThrow(CT, canThrow(*Cap));
1094  return CT;
1095  }
1096 
1097  case Expr::CXXNewExprClass: {
1098  CanThrowResult CT;
1099  if (E->isTypeDependent())
1100  CT = CT_Dependent;
1101  else
1102  CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
1103  if (CT == CT_Can)
1104  return CT;
1105  return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1106  }
1107 
1108  case Expr::CXXDeleteExprClass: {
1109  CanThrowResult CT;
1110  QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
1111  if (DTy.isNull() || DTy->isDependentType()) {
1112  CT = CT_Dependent;
1113  } else {
1114  CT = canCalleeThrow(*this, E,
1115  cast<CXXDeleteExpr>(E)->getOperatorDelete());
1116  if (const RecordType *RT = DTy->getAs<RecordType>()) {
1117  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1118  const CXXDestructorDecl *DD = RD->getDestructor();
1119  if (DD)
1120  CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
1121  }
1122  if (CT == CT_Can)
1123  return CT;
1124  }
1125  return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1126  }
1127 
1128  case Expr::CXXBindTemporaryExprClass: {
1129  // The bound temporary has to be destroyed again, which might throw.
1130  CanThrowResult CT = canCalleeThrow(*this, E,
1131  cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
1132  if (CT == CT_Can)
1133  return CT;
1134  return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1135  }
1136 
1137  // ObjC message sends are like function calls, but never have exception
1138  // specs.
1139  case Expr::ObjCMessageExprClass:
1140  case Expr::ObjCPropertyRefExprClass:
1141  case Expr::ObjCSubscriptRefExprClass:
1142  return CT_Can;
1143 
1144  // All the ObjC literals that are implemented as calls are
1145  // potentially throwing unless we decide to close off that
1146  // possibility.
1147  case Expr::ObjCArrayLiteralClass:
1148  case Expr::ObjCDictionaryLiteralClass:
1149  case Expr::ObjCBoxedExprClass:
1150  return CT_Can;
1151 
1152  // Many other things have subexpressions, so we have to test those.
1153  // Some are simple:
1154  case Expr::CoawaitExprClass:
1155  case Expr::ConditionalOperatorClass:
1156  case Expr::CompoundLiteralExprClass:
1157  case Expr::CoyieldExprClass:
1158  case Expr::CXXConstCastExprClass:
1159  case Expr::CXXReinterpretCastExprClass:
1160  case Expr::CXXStdInitializerListExprClass:
1161  case Expr::DesignatedInitExprClass:
1162  case Expr::DesignatedInitUpdateExprClass:
1163  case Expr::ExprWithCleanupsClass:
1164  case Expr::ExtVectorElementExprClass:
1165  case Expr::InitListExprClass:
1166  case Expr::ArrayInitLoopExprClass:
1167  case Expr::MemberExprClass:
1168  case Expr::ObjCIsaExprClass:
1169  case Expr::ObjCIvarRefExprClass:
1170  case Expr::ParenExprClass:
1171  case Expr::ParenListExprClass:
1172  case Expr::ShuffleVectorExprClass:
1173  case Expr::ConvertVectorExprClass:
1174  case Expr::VAArgExprClass:
1175  return canSubExprsThrow(*this, E);
1176 
1177  // Some might be dependent for other reasons.
1178  case Expr::ArraySubscriptExprClass:
1179  case Expr::OMPArraySectionExprClass:
1180  case Expr::BinaryOperatorClass:
1181  case Expr::DependentCoawaitExprClass:
1182  case Expr::CompoundAssignOperatorClass:
1183  case Expr::CStyleCastExprClass:
1184  case Expr::CXXStaticCastExprClass:
1185  case Expr::CXXFunctionalCastExprClass:
1186  case Expr::ImplicitCastExprClass:
1187  case Expr::MaterializeTemporaryExprClass:
1188  case Expr::UnaryOperatorClass: {
1190  return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1191  }
1192 
1193  // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1194  case Expr::StmtExprClass:
1195  return CT_Can;
1196 
1197  case Expr::CXXDefaultArgExprClass:
1198  return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
1199 
1200  case Expr::CXXDefaultInitExprClass:
1201  return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
1202 
1203  case Expr::ChooseExprClass:
1204  if (E->isTypeDependent() || E->isValueDependent())
1205  return CT_Dependent;
1206  return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
1207 
1208  case Expr::GenericSelectionExprClass:
1209  if (cast<GenericSelectionExpr>(E)->isResultDependent())
1210  return CT_Dependent;
1211  return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1212 
1213  // Some expressions are always dependent.
1214  case Expr::CXXDependentScopeMemberExprClass:
1215  case Expr::CXXUnresolvedConstructExprClass:
1216  case Expr::DependentScopeDeclRefExprClass:
1217  case Expr::CXXFoldExprClass:
1218  return CT_Dependent;
1219 
1220  case Expr::AsTypeExprClass:
1221  case Expr::BinaryConditionalOperatorClass:
1222  case Expr::BlockExprClass:
1223  case Expr::CUDAKernelCallExprClass:
1224  case Expr::DeclRefExprClass:
1225  case Expr::ObjCBridgedCastExprClass:
1226  case Expr::ObjCIndirectCopyRestoreExprClass:
1227  case Expr::ObjCProtocolExprClass:
1228  case Expr::ObjCSelectorExprClass:
1229  case Expr::ObjCAvailabilityCheckExprClass:
1230  case Expr::OffsetOfExprClass:
1231  case Expr::PackExpansionExprClass:
1232  case Expr::PseudoObjectExprClass:
1233  case Expr::SubstNonTypeTemplateParmExprClass:
1234  case Expr::SubstNonTypeTemplateParmPackExprClass:
1235  case Expr::FunctionParmPackExprClass:
1236  case Expr::UnaryExprOrTypeTraitExprClass:
1237  case Expr::UnresolvedLookupExprClass:
1238  case Expr::UnresolvedMemberExprClass:
1239  case Expr::TypoExprClass:
1240  // FIXME: Can any of the above throw? If so, when?
1241  return CT_Cannot;
1242 
1243  case Expr::AddrLabelExprClass:
1244  case Expr::ArrayTypeTraitExprClass:
1245  case Expr::AtomicExprClass:
1246  case Expr::TypeTraitExprClass:
1247  case Expr::CXXBoolLiteralExprClass:
1248  case Expr::CXXNoexceptExprClass:
1249  case Expr::CXXNullPtrLiteralExprClass:
1250  case Expr::CXXPseudoDestructorExprClass:
1251  case Expr::CXXScalarValueInitExprClass:
1252  case Expr::CXXThisExprClass:
1253  case Expr::CXXUuidofExprClass:
1254  case Expr::CharacterLiteralClass:
1255  case Expr::ExpressionTraitExprClass:
1256  case Expr::FloatingLiteralClass:
1257  case Expr::GNUNullExprClass:
1258  case Expr::ImaginaryLiteralClass:
1259  case Expr::ImplicitValueInitExprClass:
1260  case Expr::IntegerLiteralClass:
1261  case Expr::FixedPointLiteralClass:
1262  case Expr::ArrayInitIndexExprClass:
1263  case Expr::NoInitExprClass:
1264  case Expr::ObjCEncodeExprClass:
1265  case Expr::ObjCStringLiteralClass:
1266  case Expr::ObjCBoolLiteralExprClass:
1267  case Expr::OpaqueValueExprClass:
1268  case Expr::PredefinedExprClass:
1269  case Expr::SizeOfPackExprClass:
1270  case Expr::StringLiteralClass:
1271  // These expressions can never throw.
1272  return CT_Cannot;
1273 
1274  case Expr::MSPropertyRefExprClass:
1275  case Expr::MSPropertySubscriptExprClass:
1276  llvm_unreachable("Invalid class for expression");
1277 
1278 #define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1279 #define STMT_RANGE(Base, First, Last)
1280 #define LAST_STMT_RANGE(BASE, FIRST, LAST)
1281 #define EXPR(CLASS, PARENT)
1282 #define ABSTRACT_STMT(STMT)
1283 #include "clang/AST/StmtNodes.inc"
1284  case Expr::NoStmtClass:
1285  llvm_unreachable("Invalid class for expression");
1286  }
1287  llvm_unreachable("Bogus StmtClass");
1288 }
1289 
1290 } // end namespace clang
CanThrowResult canThrow(const Expr *E)
Represents a function declaration or definition.
Definition: Decl.h:1714
no exception specification
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2375
A (possibly-)qualified type.
Definition: Type.h:655
bool isArrayType() const
Definition: Type.h:6098
bool isMemberPointerType() const
Definition: Type.h:6080
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
unsigned getNumExceptions() const
Definition: Type.h:3666
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:2833
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function)
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
Stmt - This represents one statement.
Definition: Stmt.h:66
ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, ExceptionSpecificationType &EST)
Check the given noexcept-specifier, convert its expression, and compute the appropriate ExceptionSpec...
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:460
Defines the SourceManager interface.
bool isRecordType() const
Definition: Type.h:6122
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:6263
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1270
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Target, SourceLocation TargetLoc, const FunctionProtoType *Source, SourceLocation SourceLoc)
CheckParamExceptionSpec - Check if the parameter and return types of the two functions have equivalen...
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:377
void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD)
Evaluate the implicit exception specification for a defaulted special member function.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Represent a C++ namespace.
Definition: Decl.h:514
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:46
A container of type source information.
Definition: Decl.h:86
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:25
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1764
unsigned getNumParams() const
Definition: Type.h:3605
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6456
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:2118
Expr * getExprOperand() const
Definition: ExprCXX.h:695
Defines the clang::Expr interface and subclasses for C++ expressions.
noexcept(expression), value-dependent
The collection of all-type qualifiers we support.
Definition: Type.h:154
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:56
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:297
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3612
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isReferenceType() const
Definition: Type.h:6061
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:1889
Expr * getSubExpr()
Definition: Expr.h:2841
bool isReplaceableGlobalAllocationFunction(bool *IsAligned=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:2749
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:638
PtrTy get() const
Definition: Ownership.h:174
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec...
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition: ExprCXX.h:1728
child_range children()
Definition: Stmt.cpp:227
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:5895
static bool CheckSpecForTypesEquivalent(Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID, QualType Target, SourceLocation TargetLoc, QualType Source, SourceLocation SourceLoc)
Defines the Diagnostic-related interfaces.
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, const ASTContext *Context=nullptr) const
static bool CheckEquivalentExceptionSpecImpl(Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc, bool *MissingExceptionSpecification=nullptr, bool *MissingEmptyExceptionSpecification=nullptr, bool AllowNoexceptAllMatchWithNoSpec=false, bool IsOperatorNew=false)
CheckEquivalentExceptionSpec - Check if the two types have compatible exception specifications.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1583
const LangOptions & getLangOpts() const
Definition: Sema.h:1193
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:167
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1663
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2126
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:2991
bool hasAttr() const
Definition: DeclBase.h:536
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:276
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1590
FunctionDecl * getExceptionSpecDecl() const
If this function type has an exception specification which hasn&#39;t been determined yet (either because...
Definition: Type.h:3682
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3369
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:499
CanThrowResult mergeCanThrow(CanThrowResult CT1, CanThrowResult CT2)
OverloadedOperatorKind getCXXOverloadedOperator() const
getCXXOverloadedOperator - If this name is the name of an overloadable operator in C++ (e...
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:3187
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:636
Expr - This represents one expression.
Definition: Expr.h:106
QualType getPointeeType() const
Definition: Type.h:2532
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
const FunctionProtoType * T
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6519
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:86
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2686
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
const Expr * getCallee() const
Definition: Expr.h:2323
bool isNullPtrType() const
Definition: Type.h:6295
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold=true)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:13899
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &O)
Definition: Type.h:3503
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:7518
Defines the clang::TypeLoc interface and its subclasses.
QualType getType() const
Definition: Expr.h:128
bool handlerCanCatch(QualType HandlerType, QualType ExceptionType)
bool isInvalid() const
Definition: Ownership.h:170
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1353
The result type of a method or function.
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:720
static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC)
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5884
RecordDecl * getDecl() const
Definition: Type.h:4082
noexcept(expression), evals to &#39;false&#39;
CanThrowResult
Possible results from evaluation of a noexcept expression.
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition: ExprCXX.h:338
Kind
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:157
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:3466
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1196
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3616
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:299
Encodes a location in the source.
QualType getReturnType() const
Definition: Type.h:3302
bool CheckDistantExceptionSpec(QualType T)
CheckDistantExceptionSpec - Check if the given type is a pointer or pointer to member to a function w...
CastKind getCastKind() const
Definition: Expr.h:2835
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2031
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:3645
static bool hasImplicitExceptionSpec(FunctionDecl *Decl)
Determine whether a function has an implicitly-generated exception specification. ...
bool isStdNamespace() const
Definition: DeclBase.cpp:1024
static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC)
Expr * getNoexceptExpr() const
Definition: Type.h:3671
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:149
bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D)
Determine if we&#39;re in a case where we need to (incorrectly) eagerly parse an exception specification ...
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2247
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:3640
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
exception_iterator exception_begin() const
Definition: Type.h:3751
StringRef getName() const
Return the actual identifier string.
bool isTypeOperand() const
Definition: ExprCXX.h:678
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
not evaluated yet, for special member function
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:22
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:394
bool hasDependentExceptionSpec() const
Return whether this function has a dependent exception spec.
Definition: Type.cpp:2902
StmtClass getStmtClass() const
Definition: Stmt.h:389
ArrayRef< QualType > exceptions() const
Definition: Type.h:3747
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2151
bool isAmbiguous(CanQualType BaseType)
Determine whether the path from the most-derived type to the given base type is ambiguous (i...
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2594
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2587
Decl * getCalleeDecl()
Definition: Expr.cpp:1251
Pointer to a block type.
Definition: Type.h:2477
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4072
CanThrowResult canThrow() const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.cpp:2923
bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Superset, SourceLocation SuperLoc, const FunctionProtoType *Subset, SourceLocation SubLoc)
CheckExceptionSpecSubset - Check whether the second function type&#39;s exception specification is a subs...
bool isFunctionType() const
Definition: Type.h:6045
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:715
CXXBasePath & front()
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2511
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:92
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:1738
SourceManager & getSourceManager()
Definition: ASTContext.h:644
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2207
QualType getParamType(unsigned i) const
Definition: Type.h:3607
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
bool isVoidType() const
Definition: Type.h:6276
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:2902
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range)
CheckSpecifiedExceptionType - Check if the given type is valid in an exception specification.
bool isPRValue() const
Definition: Expr.h:355
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:330
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:266
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2283
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated, or computed.
static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D)
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1930
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression...
Definition: ExprCXX.h:1740
Expr *const * const_capture_init_iterator
Const iterator that walks over the capture initialization arguments.
Definition: ExprCXX.h:1714
bool isPointerType() const
Definition: Type.h:6049
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
QualType getType() const
Definition: Decl.h:647
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:318
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
Definition: SemaExpr.cpp:15711
static CanThrowResult canSubExprsThrow(Sema &S, const Expr *E)
SmallVector< std::pair< const CXXMethodDecl *, const CXXMethodDecl * >, 2 > DelayedExceptionSpecChecks
All the overriding functions seen during a class definition that had their exception spec checks dela...
Definition: Sema.h:610
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:278
void setType(QualType newType)
Definition: Decl.h:648
SourceLocation getBegin() const
static const FunctionProtoType * GetUnderlyingFunction(QualType T)
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals...
SourceLocation getLocation() const
Definition: DeclBase.h:417
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:97
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3168
noexcept(expression), evals to &#39;true&#39;
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2469