clang  3.8.0
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.
47  if (!RD || RD->getEnclosingNamespaceContext() != getStdNamespace() ||
48  !RD->getIdentifier() || !RD->getDescribedClassTemplate() ||
49  !D.getIdentifier() || !D.getIdentifier()->isStr("swap"))
50  return false;
51 
52  // Only apply this hack within a system header.
54  return false;
55 
56  return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
57  .Case("array", true)
58  .Case("pair", true)
59  .Case("priority_queue", true)
60  .Case("stack", true)
61  .Case("queue", true)
62  .Default(false);
63 }
64 
65 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
66 /// exception specification. Incomplete types, or pointers to incomplete types
67 /// other than void are not allowed.
68 ///
69 /// \param[in,out] T The exception type. This will be decayed to a pointer type
70 /// when the input is an array or a function type.
72  // C++11 [except.spec]p2:
73  // A type cv T, "array of T", or "function returning T" denoted
74  // in an exception-specification is adjusted to type T, "pointer to T", or
75  // "pointer to function returning T", respectively.
76  //
77  // We also apply this rule in C++98.
78  if (T->isArrayType())
80  else if (T->isFunctionType())
81  T = Context.getPointerType(T);
82 
83  int Kind = 0;
84  QualType PointeeT = T;
85  if (const PointerType *PT = T->getAs<PointerType>()) {
86  PointeeT = PT->getPointeeType();
87  Kind = 1;
88 
89  // cv void* is explicitly permitted, despite being a pointer to an
90  // incomplete type.
91  if (PointeeT->isVoidType())
92  return false;
93  } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
94  PointeeT = RT->getPointeeType();
95  Kind = 2;
96 
97  if (RT->isRValueReferenceType()) {
98  // C++11 [except.spec]p2:
99  // A type denoted in an exception-specification shall not denote [...]
100  // an rvalue reference type.
101  Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
102  << T << Range;
103  return true;
104  }
105  }
106 
107  // C++11 [except.spec]p2:
108  // A type denoted in an exception-specification shall not denote an
109  // incomplete type other than a class currently being defined [...].
110  // A type denoted in an exception-specification shall not denote a
111  // pointer or reference to an incomplete type, other than (cv) void* or a
112  // pointer or reference to a class currently being defined.
113  if (!(PointeeT->isRecordType() &&
114  PointeeT->getAs<RecordType>()->isBeingDefined()) &&
115  RequireCompleteType(Range.getBegin(), PointeeT,
116  diag::err_incomplete_in_exception_spec, Kind, Range))
117  return true;
118 
119  return false;
120 }
121 
122 /// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
123 /// to member to a function with an exception specification. This means that
124 /// it is invalid to add another level of indirection.
126  if (const PointerType *PT = T->getAs<PointerType>())
127  T = PT->getPointeeType();
128  else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
129  T = PT->getPointeeType();
130  else
131  return false;
132 
133  const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
134  if (!FnT)
135  return false;
136 
137  return FnT->hasExceptionSpec();
138 }
139 
140 const FunctionProtoType *
142  if (FPT->getExceptionSpecType() == EST_Unparsed) {
143  Diag(Loc, diag::err_exception_spec_not_parsed);
144  return nullptr;
145  }
146 
148  return FPT;
149 
150  FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
151  const FunctionProtoType *SourceFPT =
152  SourceDecl->getType()->castAs<FunctionProtoType>();
153 
154  // If the exception specification has already been resolved, just return it.
156  return SourceFPT;
157 
158  // Compute or instantiate the exception specification now.
159  if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
160  EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
161  else
162  InstantiateExceptionSpec(Loc, SourceDecl);
163 
164  const FunctionProtoType *Proto =
165  SourceDecl->getType()->castAs<FunctionProtoType>();
166  if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
167  Diag(Loc, diag::err_exception_spec_not_parsed);
168  Proto = nullptr;
169  }
170  return Proto;
171 }
172 
173 void
176  // If we've fully resolved the exception specification, notify listeners.
178  if (auto *Listener = getASTMutationListener())
179  Listener->ResolvedExceptionSpec(FD);
180 
181  for (auto *Redecl : FD->redecls())
182  Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
183 }
184 
185 /// Determine whether a function has an implicitly-generated exception
186 /// specification.
188  if (!isa<CXXDestructorDecl>(Decl) &&
189  Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
190  Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
191  return false;
192 
193  // For a function that the user didn't declare:
194  // - if this is a destructor, its exception specification is implicit.
195  // - if this is 'operator delete' or 'operator delete[]', the exception
196  // specification is as-if an explicit exception specification was given
197  // (per [basic.stc.dynamic]p2).
198  if (!Decl->getTypeSourceInfo())
199  return isa<CXXDestructorDecl>(Decl);
200 
201  const FunctionProtoType *Ty =
203  return !Ty->hasExceptionSpec();
204 }
205 
208  bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
209  bool MissingExceptionSpecification = false;
210  bool MissingEmptyExceptionSpecification = false;
211 
212  unsigned DiagID = diag::err_mismatched_exception_spec;
213  bool ReturnValueOnError = true;
214  if (getLangOpts().MicrosoftExt) {
215  DiagID = diag::ext_mismatched_exception_spec;
216  ReturnValueOnError = false;
217  }
218 
219  // Check the types as written: they must match before any exception
220  // specification adjustment is applied.
222  PDiag(DiagID), PDiag(diag::note_previous_declaration),
223  Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
224  New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
225  &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
226  /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
227  // C++11 [except.spec]p4 [DR1492]:
228  // If a declaration of a function has an implicit
229  // exception-specification, other declarations of the function shall
230  // not specify an exception-specification.
231  if (getLangOpts().CPlusPlus11 &&
233  Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
234  << hasImplicitExceptionSpec(Old);
235  if (Old->getLocation().isValid())
236  Diag(Old->getLocation(), diag::note_previous_declaration);
237  }
238  return false;
239  }
240 
241  // The failure was something other than an missing exception
242  // specification; return an error, except in MS mode where this is a warning.
243  if (!MissingExceptionSpecification)
244  return ReturnValueOnError;
245 
246  const FunctionProtoType *NewProto =
247  New->getType()->castAs<FunctionProtoType>();
248 
249  // The new function declaration is only missing an empty exception
250  // specification "throw()". If the throw() specification came from a
251  // function in a system header that has C linkage, just add an empty
252  // exception specification to the "new" declaration. This is an
253  // egregious workaround for glibc, which adds throw() specifications
254  // to many libc functions as an optimization. Unfortunately, that
255  // optimization isn't permitted by the C++ standard, so we're forced
256  // to work around it here.
257  if (MissingEmptyExceptionSpecification && NewProto &&
258  (Old->getLocation().isInvalid() ||
260  Old->isExternC()) {
262  NewProto->getReturnType(), NewProto->getParamTypes(),
264  return false;
265  }
266 
267  const FunctionProtoType *OldProto =
268  Old->getType()->castAs<FunctionProtoType>();
269 
271  if (ESI.Type == EST_Dynamic) {
272  ESI.Exceptions = OldProto->exceptions();
273  }
274 
275  if (ESI.Type == EST_ComputedNoexcept) {
276  // For computed noexcept, we can't just take the expression from the old
277  // prototype. It likely contains references to the old prototype's
278  // parameters.
279  New->setInvalidDecl();
280  } else {
281  // Update the type of the function with the appropriate exception
282  // specification.
284  NewProto->getReturnType(), NewProto->getParamTypes(),
285  NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
286  }
287 
288  if (getLangOpts().MicrosoftExt && ESI.Type != EST_ComputedNoexcept) {
289  // Allow missing exception specifications in redeclarations as an extension.
290  DiagID = diag::ext_ms_missing_exception_specification;
291  ReturnValueOnError = false;
292  } else if (New->isReplaceableGlobalAllocationFunction() &&
293  ESI.Type != EST_ComputedNoexcept) {
294  // Allow missing exception specifications in redeclarations as an extension,
295  // when declaring a replaceable global allocation function.
296  DiagID = diag::ext_missing_exception_specification;
297  ReturnValueOnError = false;
298  } else {
299  DiagID = diag::err_missing_exception_specification;
300  ReturnValueOnError = true;
301  }
302 
303  // Warn about the lack of exception specification.
304  SmallString<128> ExceptionSpecString;
305  llvm::raw_svector_ostream OS(ExceptionSpecString);
306  switch (OldProto->getExceptionSpecType()) {
307  case EST_DynamicNone:
308  OS << "throw()";
309  break;
310 
311  case EST_Dynamic: {
312  OS << "throw(";
313  bool OnFirstException = true;
314  for (const auto &E : OldProto->exceptions()) {
315  if (OnFirstException)
316  OnFirstException = false;
317  else
318  OS << ", ";
319 
320  OS << E.getAsString(getPrintingPolicy());
321  }
322  OS << ")";
323  break;
324  }
325 
326  case EST_BasicNoexcept:
327  OS << "noexcept";
328  break;
329 
331  OS << "noexcept(";
332  assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
333  OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
334  OS << ")";
335  break;
336 
337  default:
338  llvm_unreachable("This spec type is compatible with none.");
339  }
340 
341  SourceLocation FixItLoc;
342  if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
343  TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
344  // FIXME: Preserve enough information so that we can produce a correct fixit
345  // location when there is a trailing return type.
346  if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
347  if (!FTLoc.getTypePtr()->hasTrailingReturn())
348  FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
349  }
350 
351  if (FixItLoc.isInvalid())
352  Diag(New->getLocation(), DiagID)
353  << New << OS.str();
354  else {
355  Diag(New->getLocation(), DiagID)
356  << New << OS.str()
357  << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
358  }
359 
360  if (Old->getLocation().isValid())
361  Diag(Old->getLocation(), diag::note_previous_declaration);
362 
363  return ReturnValueOnError;
364 }
365 
366 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
367 /// exception specifications. Exception specifications are equivalent if
368 /// they allow exactly the same set of exception types. It does not matter how
369 /// that is achieved. See C++ [except.spec]p2.
371  const FunctionProtoType *Old, SourceLocation OldLoc,
372  const FunctionProtoType *New, SourceLocation NewLoc) {
373  unsigned DiagID = diag::err_mismatched_exception_spec;
374  if (getLangOpts().MicrosoftExt)
375  DiagID = diag::ext_mismatched_exception_spec;
377  PDiag(diag::note_previous_declaration), Old, OldLoc, New, NewLoc);
378 
379  // In Microsoft mode, mismatching exception specifications just cause a warning.
380  if (getLangOpts().MicrosoftExt)
381  return false;
382  return Result;
383 }
384 
385 /// CheckEquivalentExceptionSpec - Check if the two types have compatible
386 /// exception specifications. See C++ [except.spec]p3.
387 ///
388 /// \return \c false if the exception specifications match, \c true if there is
389 /// a problem. If \c true is returned, either a diagnostic has already been
390 /// produced or \c *MissingExceptionSpecification is set to \c true.
392  const PartialDiagnostic & NoteID,
393  const FunctionProtoType *Old,
394  SourceLocation OldLoc,
395  const FunctionProtoType *New,
396  SourceLocation NewLoc,
397  bool *MissingExceptionSpecification,
398  bool*MissingEmptyExceptionSpecification,
399  bool AllowNoexceptAllMatchWithNoSpec,
400  bool IsOperatorNew) {
401  // Just completely ignore this under -fno-exceptions.
402  if (!getLangOpts().CXXExceptions)
403  return false;
404 
405  if (MissingExceptionSpecification)
406  *MissingExceptionSpecification = false;
407 
408  if (MissingEmptyExceptionSpecification)
409  *MissingEmptyExceptionSpecification = false;
410 
411  Old = ResolveExceptionSpec(NewLoc, Old);
412  if (!Old)
413  return false;
414  New = ResolveExceptionSpec(NewLoc, New);
415  if (!New)
416  return false;
417 
418  // C++0x [except.spec]p3: Two exception-specifications are compatible if:
419  // - both are non-throwing, regardless of their form,
420  // - both have the form noexcept(constant-expression) and the constant-
421  // expressions are equivalent,
422  // - both are dynamic-exception-specifications that have the same set of
423  // adjusted types.
424  //
425  // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
426  // of the form throw(), noexcept, or noexcept(constant-expression) where the
427  // constant-expression yields true.
428  //
429  // C++0x [except.spec]p4: If any declaration of a function has an exception-
430  // specifier that is not a noexcept-specification allowing all exceptions,
431  // all declarations [...] of that function shall have a compatible
432  // exception-specification.
433  //
434  // That last point basically means that noexcept(false) matches no spec.
435  // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
436 
439 
440  assert(!isUnresolvedExceptionSpec(OldEST) &&
441  !isUnresolvedExceptionSpec(NewEST) &&
442  "Shouldn't see unknown exception specifications here");
443 
444  // Shortcut the case where both have no spec.
445  if (OldEST == EST_None && NewEST == EST_None)
446  return false;
447 
450  if (OldNR == FunctionProtoType::NR_BadNoexcept ||
452  return false;
453 
454  // Dependent noexcept specifiers are compatible with each other, but nothing
455  // else.
456  // One noexcept is compatible with another if the argument is the same
457  if (OldNR == NewNR &&
460  return false;
461  if (OldNR != NewNR &&
464  Diag(NewLoc, DiagID);
465  if (NoteID.getDiagID() != 0 && OldLoc.isValid())
466  Diag(OldLoc, NoteID);
467  return true;
468  }
469 
470  // The MS extension throw(...) is compatible with itself.
471  if (OldEST == EST_MSAny && NewEST == EST_MSAny)
472  return false;
473 
474  // It's also compatible with no spec.
475  if ((OldEST == EST_None && NewEST == EST_MSAny) ||
476  (OldEST == EST_MSAny && NewEST == EST_None))
477  return false;
478 
479  // It's also compatible with noexcept(false).
480  if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
481  return false;
482  if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
483  return false;
484 
485  // As described above, noexcept(false) matches no spec only for functions.
486  if (AllowNoexceptAllMatchWithNoSpec) {
487  if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
488  return false;
489  if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
490  return false;
491  }
492 
493  // Any non-throwing specifications are compatible.
494  bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
495  OldEST == EST_DynamicNone;
496  bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
497  NewEST == EST_DynamicNone;
498  if (OldNonThrowing && NewNonThrowing)
499  return false;
500 
501  // As a special compatibility feature, under C++0x we accept no spec and
502  // throw(std::bad_alloc) as equivalent for operator new and operator new[].
503  // This is because the implicit declaration changed, but old code would break.
504  if (getLangOpts().CPlusPlus11 && IsOperatorNew) {
505  const FunctionProtoType *WithExceptions = nullptr;
506  if (OldEST == EST_None && NewEST == EST_Dynamic)
507  WithExceptions = New;
508  else if (OldEST == EST_Dynamic && NewEST == EST_None)
509  WithExceptions = Old;
510  if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
511  // One has no spec, the other throw(something). If that something is
512  // std::bad_alloc, all conditions are met.
513  QualType Exception = *WithExceptions->exception_begin();
514  if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
515  IdentifierInfo* Name = ExRecord->getIdentifier();
516  if (Name && Name->getName() == "bad_alloc") {
517  // It's called bad_alloc, but is it in std?
518  if (ExRecord->isInStdNamespace()) {
519  return false;
520  }
521  }
522  }
523  }
524  }
525 
526  // At this point, the only remaining valid case is two matching dynamic
527  // specifications. We return here unless both specifications are dynamic.
528  if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
529  if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
530  !New->hasExceptionSpec()) {
531  // The old type has an exception specification of some sort, but
532  // the new type does not.
533  *MissingExceptionSpecification = true;
534 
535  if (MissingEmptyExceptionSpecification && OldNonThrowing) {
536  // The old type has a throw() or noexcept(true) exception specification
537  // and the new type has no exception specification, and the caller asked
538  // to handle this itself.
539  *MissingEmptyExceptionSpecification = true;
540  }
541 
542  return true;
543  }
544 
545  Diag(NewLoc, DiagID);
546  if (NoteID.getDiagID() != 0 && OldLoc.isValid())
547  Diag(OldLoc, NoteID);
548  return true;
549  }
550 
551  assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
552  "Exception compatibility logic error: non-dynamic spec slipped through.");
553 
554  bool Success = true;
555  // Both have a dynamic exception spec. Collect the first set, then compare
556  // to the second.
557  llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
558  for (const auto &I : Old->exceptions())
559  OldTypes.insert(Context.getCanonicalType(I).getUnqualifiedType());
560 
561  for (const auto &I : New->exceptions()) {
563  if(OldTypes.count(TypePtr))
564  NewTypes.insert(TypePtr);
565  else
566  Success = false;
567  }
568 
569  Success = Success && OldTypes.size() == NewTypes.size();
570 
571  if (Success) {
572  return false;
573  }
574  Diag(NewLoc, DiagID);
575  if (NoteID.getDiagID() != 0 && OldLoc.isValid())
576  Diag(OldLoc, NoteID);
577  return true;
578 }
579 
580 /// CheckExceptionSpecSubset - Check whether the second function type's
581 /// exception specification is a subset (or equivalent) of the first function
582 /// type. This is used by override and pointer assignment checks.
584  const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
585  const FunctionProtoType *Superset, SourceLocation SuperLoc,
586  const FunctionProtoType *Subset, SourceLocation SubLoc) {
587 
588  // Just auto-succeed under -fno-exceptions.
589  if (!getLangOpts().CXXExceptions)
590  return false;
591 
592  // FIXME: As usual, we could be more specific in our error messages, but
593  // that better waits until we've got types with source locations.
594 
595  if (!SubLoc.isValid())
596  SubLoc = SuperLoc;
597 
598  // Resolve the exception specifications, if needed.
599  Superset = ResolveExceptionSpec(SuperLoc, Superset);
600  if (!Superset)
601  return false;
602  Subset = ResolveExceptionSpec(SubLoc, Subset);
603  if (!Subset)
604  return false;
605 
606  ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
607 
608  // If superset contains everything, we're done.
609  if (SuperEST == EST_None || SuperEST == EST_MSAny)
610  return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
611 
612  // If there are dependent noexcept specs, assume everything is fine. Unlike
613  // with the equivalency check, this is safe in this case, because we don't
614  // want to merge declarations. Checks after instantiation will catch any
615  // omissions we make here.
616  // We also shortcut checking if a noexcept expression was bad.
617 
619  if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
621  return false;
622 
623  // Another case of the superset containing everything.
624  if (SuperNR == FunctionProtoType::NR_Throw)
625  return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
626 
628 
629  assert(!isUnresolvedExceptionSpec(SuperEST) &&
630  !isUnresolvedExceptionSpec(SubEST) &&
631  "Shouldn't see unknown exception specifications here");
632 
633  // It does not. If the subset contains everything, we've failed.
634  if (SubEST == EST_None || SubEST == EST_MSAny) {
635  Diag(SubLoc, DiagID);
636  if (NoteID.getDiagID() != 0)
637  Diag(SuperLoc, NoteID);
638  return true;
639  }
640 
642  if (SubNR == FunctionProtoType::NR_BadNoexcept ||
644  return false;
645 
646  // Another case of the subset containing everything.
647  if (SubNR == FunctionProtoType::NR_Throw) {
648  Diag(SubLoc, DiagID);
649  if (NoteID.getDiagID() != 0)
650  Diag(SuperLoc, NoteID);
651  return true;
652  }
653 
654  // If the subset contains nothing, we're done.
655  if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
656  return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
657 
658  // Otherwise, if the superset contains nothing, we've failed.
659  if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
660  Diag(SubLoc, DiagID);
661  if (NoteID.getDiagID() != 0)
662  Diag(SuperLoc, NoteID);
663  return true;
664  }
665 
666  assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
667  "Exception spec subset: non-dynamic case slipped through.");
668 
669  // Neither contains everything or nothing. Do a proper comparison.
670  for (const auto &SubI : Subset->exceptions()) {
671  // Take one type from the subset.
672  QualType CanonicalSubT = Context.getCanonicalType(SubI);
673  // Unwrap pointers and references so that we can do checks within a class
674  // hierarchy. Don't unwrap member pointers; they don't have hierarchy
675  // conversions on the pointee.
676  bool SubIsPointer = false;
677  if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
678  CanonicalSubT = RefTy->getPointeeType();
679  if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
680  CanonicalSubT = PtrTy->getPointeeType();
681  SubIsPointer = true;
682  }
683  bool SubIsClass = CanonicalSubT->isRecordType();
684  CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
685 
686  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
687  /*DetectVirtual=*/false);
688 
689  bool Contained = false;
690  // Make sure it's in the superset.
691  for (const auto &SuperI : Superset->exceptions()) {
692  QualType CanonicalSuperT = Context.getCanonicalType(SuperI);
693  // SubT must be SuperT or derived from it, or pointer or reference to
694  // such types.
695  if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
696  CanonicalSuperT = RefTy->getPointeeType();
697  if (SubIsPointer) {
698  if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
699  CanonicalSuperT = PtrTy->getPointeeType();
700  else {
701  continue;
702  }
703  }
704  CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
705  // If the types are the same, move on to the next type in the subset.
706  if (CanonicalSubT == CanonicalSuperT) {
707  Contained = true;
708  break;
709  }
710 
711  // Otherwise we need to check the inheritance.
712  if (!SubIsClass || !CanonicalSuperT->isRecordType())
713  continue;
714 
715  Paths.clear();
716  if (!IsDerivedFrom(SubLoc, CanonicalSubT, CanonicalSuperT, Paths))
717  continue;
718 
719  if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
720  continue;
721 
722  // Do this check from a context without privileges.
724  CanonicalSuperT, CanonicalSubT,
725  Paths.front(),
726  /*Diagnostic*/ 0,
727  /*ForceCheck*/ true,
728  /*ForceUnprivileged*/ true)) {
729  case AR_accessible: break;
730  case AR_inaccessible: continue;
731  case AR_dependent:
732  llvm_unreachable("access check dependent for unprivileged context");
733  case AR_delayed:
734  llvm_unreachable("access check delayed in non-declaration");
735  }
736 
737  Contained = true;
738  break;
739  }
740  if (!Contained) {
741  Diag(SubLoc, DiagID);
742  if (NoteID.getDiagID() != 0)
743  Diag(SuperLoc, NoteID);
744  return true;
745  }
746  }
747  // We've run half the gauntlet.
748  return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
749 }
750 
752  const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
753  QualType Target, SourceLocation TargetLoc,
754  QualType Source, SourceLocation SourceLoc)
755 {
756  const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
757  if (!TFunc)
758  return false;
759  const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
760  if (!SFunc)
761  return false;
762 
763  return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
764  SFunc, SourceLoc);
765 }
766 
767 /// CheckParamExceptionSpec - Check if the parameter and return types of the
768 /// two functions have equivalent exception specs. This is part of the
769 /// assignment and override compatibility check. We do not check the parameters
770 /// of parameter function pointers recursively, as no sane programmer would
771 /// even be able to write such a function type.
773  const FunctionProtoType *Target,
774  SourceLocation TargetLoc,
775  const FunctionProtoType *Source,
776  SourceLocation SourceLoc) {
778  *this, PDiag(diag::err_deep_exception_specs_differ) << 0, PDiag(),
779  Target->getReturnType(), TargetLoc, Source->getReturnType(),
780  SourceLoc))
781  return true;
782 
783  // We shouldn't even be testing this unless the arguments are otherwise
784  // compatible.
785  assert(Target->getNumParams() == Source->getNumParams() &&
786  "Functions have different argument counts.");
787  for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
789  *this, PDiag(diag::err_deep_exception_specs_differ) << 1, PDiag(),
790  Target->getParamType(i), TargetLoc, Source->getParamType(i),
791  SourceLoc))
792  return true;
793  }
794  return false;
795 }
796 
798  // First we check for applicability.
799  // Target type must be a function, function pointer or function reference.
800  const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
801  if (!ToFunc || ToFunc->hasDependentExceptionSpec())
802  return false;
803 
804  // SourceType must be a function or function pointer.
805  const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
806  if (!FromFunc || FromFunc->hasDependentExceptionSpec())
807  return false;
808 
809  // Now we've got the correct types on both sides, check their compatibility.
810  // This means that the source of the conversion can only throw a subset of
811  // the exceptions of the target, and any exception specs on arguments or
812  // return types must be equivalent.
813  //
814  // FIXME: If there is a nested dependent exception specification, we should
815  // not be checking it here. This is fine:
816  // template<typename T> void f() {
817  // void (*p)(void (*) throw(T));
818  // void (*q)(void (*) throw(int)) = p;
819  // }
820  // ... because it might be instantiated with T=int.
821  return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
822  PDiag(), ToFunc,
823  From->getSourceRange().getBegin(),
824  FromFunc, SourceLocation());
825 }
826 
828  const CXXMethodDecl *Old) {
829  // If the new exception specification hasn't been parsed yet, skip the check.
830  // We'll get called again once it's been parsed.
831  if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
832  EST_Unparsed)
833  return false;
834  if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
835  // Don't check uninstantiated template destructors at all. We can only
836  // synthesize correct specs after the template is instantiated.
837  if (New->getParent()->isDependentType())
838  return false;
839  if (New->getParent()->isBeingDefined()) {
840  // The destructor might be updated once the definition is finished. So
841  // remember it and check later.
842  DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
843  return false;
844  }
845  }
846  // If the old exception specification hasn't been parsed yet, remember that
847  // we need to perform this check when we get to the end of the outermost
848  // lexically-surrounding class.
849  if (Old->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
850  EST_Unparsed) {
851  DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
852  return false;
853  }
854  unsigned DiagID = diag::err_override_exception_spec;
855  if (getLangOpts().MicrosoftExt)
856  DiagID = diag::ext_override_exception_spec;
857  return CheckExceptionSpecSubset(PDiag(DiagID),
858  PDiag(diag::note_overridden_virtual_function),
859  Old->getType()->getAs<FunctionProtoType>(),
860  Old->getLocation(),
861  New->getType()->getAs<FunctionProtoType>(),
862  New->getLocation());
863 }
864 
867  for (const Stmt *SubStmt : E->children()) {
868  R = mergeCanThrow(R, S.canThrow(cast<Expr>(SubStmt)));
869  if (R == CT_Can)
870  break;
871  }
872  return R;
873 }
874 
875 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
876  assert(D && "Expected decl");
877 
878  // See if we can get a function type from the decl somehow.
879  const ValueDecl *VD = dyn_cast<ValueDecl>(D);
880  if (!VD) // If we have no clue what we're calling, assume the worst.
881  return CT_Can;
882 
883  // As an extension, we assume that __attribute__((nothrow)) functions don't
884  // throw.
885  if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
886  return CT_Cannot;
887 
888  QualType T = VD->getType();
889  const FunctionProtoType *FT;
890  if ((FT = T->getAs<FunctionProtoType>())) {
891  } else if (const PointerType *PT = T->getAs<PointerType>())
892  FT = PT->getPointeeType()->getAs<FunctionProtoType>();
893  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
894  FT = RT->getPointeeType()->getAs<FunctionProtoType>();
895  else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
896  FT = MT->getPointeeType()->getAs<FunctionProtoType>();
897  else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
898  FT = BT->getPointeeType()->getAs<FunctionProtoType>();
899 
900  if (!FT)
901  return CT_Can;
902 
903  FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
904  if (!FT)
905  return CT_Can;
906 
907  return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
908 }
909 
911  if (DC->isTypeDependent())
912  return CT_Dependent;
913 
914  if (!DC->getTypeAsWritten()->isReferenceType())
915  return CT_Cannot;
916 
917  if (DC->getSubExpr()->isTypeDependent())
918  return CT_Dependent;
919 
920  return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
921 }
922 
924  if (DC->isTypeOperand())
925  return CT_Cannot;
926 
927  Expr *Op = DC->getExprOperand();
928  if (Op->isTypeDependent())
929  return CT_Dependent;
930 
931  const RecordType *RT = Op->getType()->getAs<RecordType>();
932  if (!RT)
933  return CT_Cannot;
934 
935  if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
936  return CT_Cannot;
937 
938  if (Op->Classify(S.Context).isPRValue())
939  return CT_Cannot;
940 
941  return CT_Can;
942 }
943 
945  // C++ [expr.unary.noexcept]p3:
946  // [Can throw] if in a potentially-evaluated context the expression would
947  // contain:
948  switch (E->getStmtClass()) {
949  case Expr::CXXThrowExprClass:
950  // - a potentially evaluated throw-expression
951  return CT_Can;
952 
953  case Expr::CXXDynamicCastExprClass: {
954  // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
955  // where T is a reference type, that requires a run-time check
956  CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
957  if (CT == CT_Can)
958  return CT;
959  return mergeCanThrow(CT, canSubExprsThrow(*this, E));
960  }
961 
962  case Expr::CXXTypeidExprClass:
963  // - a potentially evaluated typeid expression applied to a glvalue
964  // expression whose type is a polymorphic class type
965  return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
966 
967  // - a potentially evaluated call to a function, member function, function
968  // pointer, or member function pointer that does not have a non-throwing
969  // exception-specification
970  case Expr::CallExprClass:
971  case Expr::CXXMemberCallExprClass:
972  case Expr::CXXOperatorCallExprClass:
973  case Expr::UserDefinedLiteralClass: {
974  const CallExpr *CE = cast<CallExpr>(E);
975  CanThrowResult CT;
976  if (E->isTypeDependent())
977  CT = CT_Dependent;
978  else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
979  CT = CT_Cannot;
980  else if (CE->getCalleeDecl())
981  CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
982  else
983  CT = CT_Can;
984  if (CT == CT_Can)
985  return CT;
986  return mergeCanThrow(CT, canSubExprsThrow(*this, E));
987  }
988 
989  case Expr::CXXConstructExprClass:
990  case Expr::CXXTemporaryObjectExprClass: {
991  CanThrowResult CT = canCalleeThrow(*this, E,
992  cast<CXXConstructExpr>(E)->getConstructor());
993  if (CT == CT_Can)
994  return CT;
995  return mergeCanThrow(CT, canSubExprsThrow(*this, E));
996  }
997 
998  case Expr::LambdaExprClass: {
999  const LambdaExpr *Lambda = cast<LambdaExpr>(E);
1002  Cap = Lambda->capture_init_begin(),
1003  CapEnd = Lambda->capture_init_end();
1004  Cap != CapEnd; ++Cap)
1005  CT = mergeCanThrow(CT, canThrow(*Cap));
1006  return CT;
1007  }
1008 
1009  case Expr::CXXNewExprClass: {
1010  CanThrowResult CT;
1011  if (E->isTypeDependent())
1012  CT = CT_Dependent;
1013  else
1014  CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
1015  if (CT == CT_Can)
1016  return CT;
1017  return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1018  }
1019 
1020  case Expr::CXXDeleteExprClass: {
1021  CanThrowResult CT;
1022  QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
1023  if (DTy.isNull() || DTy->isDependentType()) {
1024  CT = CT_Dependent;
1025  } else {
1026  CT = canCalleeThrow(*this, E,
1027  cast<CXXDeleteExpr>(E)->getOperatorDelete());
1028  if (const RecordType *RT = DTy->getAs<RecordType>()) {
1029  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1030  const CXXDestructorDecl *DD = RD->getDestructor();
1031  if (DD)
1032  CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
1033  }
1034  if (CT == CT_Can)
1035  return CT;
1036  }
1037  return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1038  }
1039 
1040  case Expr::CXXBindTemporaryExprClass: {
1041  // The bound temporary has to be destroyed again, which might throw.
1042  CanThrowResult CT = canCalleeThrow(*this, E,
1043  cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
1044  if (CT == CT_Can)
1045  return CT;
1046  return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1047  }
1048 
1049  // ObjC message sends are like function calls, but never have exception
1050  // specs.
1051  case Expr::ObjCMessageExprClass:
1052  case Expr::ObjCPropertyRefExprClass:
1053  case Expr::ObjCSubscriptRefExprClass:
1054  return CT_Can;
1055 
1056  // All the ObjC literals that are implemented as calls are
1057  // potentially throwing unless we decide to close off that
1058  // possibility.
1059  case Expr::ObjCArrayLiteralClass:
1060  case Expr::ObjCDictionaryLiteralClass:
1061  case Expr::ObjCBoxedExprClass:
1062  return CT_Can;
1063 
1064  // Many other things have subexpressions, so we have to test those.
1065  // Some are simple:
1066  case Expr::CoawaitExprClass:
1067  case Expr::ConditionalOperatorClass:
1068  case Expr::CompoundLiteralExprClass:
1069  case Expr::CoyieldExprClass:
1070  case Expr::CXXConstCastExprClass:
1071  case Expr::CXXReinterpretCastExprClass:
1072  case Expr::CXXStdInitializerListExprClass:
1073  case Expr::DesignatedInitExprClass:
1074  case Expr::DesignatedInitUpdateExprClass:
1075  case Expr::ExprWithCleanupsClass:
1076  case Expr::ExtVectorElementExprClass:
1077  case Expr::InitListExprClass:
1078  case Expr::MemberExprClass:
1079  case Expr::ObjCIsaExprClass:
1080  case Expr::ObjCIvarRefExprClass:
1081  case Expr::ParenExprClass:
1082  case Expr::ParenListExprClass:
1083  case Expr::ShuffleVectorExprClass:
1084  case Expr::ConvertVectorExprClass:
1085  case Expr::VAArgExprClass:
1086  return canSubExprsThrow(*this, E);
1087 
1088  // Some might be dependent for other reasons.
1089  case Expr::ArraySubscriptExprClass:
1090  case Expr::OMPArraySectionExprClass:
1091  case Expr::BinaryOperatorClass:
1092  case Expr::CompoundAssignOperatorClass:
1093  case Expr::CStyleCastExprClass:
1094  case Expr::CXXStaticCastExprClass:
1095  case Expr::CXXFunctionalCastExprClass:
1096  case Expr::ImplicitCastExprClass:
1097  case Expr::MaterializeTemporaryExprClass:
1098  case Expr::UnaryOperatorClass: {
1100  return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1101  }
1102 
1103  // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1104  case Expr::StmtExprClass:
1105  return CT_Can;
1106 
1107  case Expr::CXXDefaultArgExprClass:
1108  return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
1109 
1110  case Expr::CXXDefaultInitExprClass:
1111  return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
1112 
1113  case Expr::ChooseExprClass:
1114  if (E->isTypeDependent() || E->isValueDependent())
1115  return CT_Dependent;
1116  return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
1117 
1118  case Expr::GenericSelectionExprClass:
1119  if (cast<GenericSelectionExpr>(E)->isResultDependent())
1120  return CT_Dependent;
1121  return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1122 
1123  // Some expressions are always dependent.
1124  case Expr::CXXDependentScopeMemberExprClass:
1125  case Expr::CXXUnresolvedConstructExprClass:
1126  case Expr::DependentScopeDeclRefExprClass:
1127  case Expr::CXXFoldExprClass:
1128  return CT_Dependent;
1129 
1130  case Expr::AsTypeExprClass:
1131  case Expr::BinaryConditionalOperatorClass:
1132  case Expr::BlockExprClass:
1133  case Expr::CUDAKernelCallExprClass:
1134  case Expr::DeclRefExprClass:
1135  case Expr::ObjCBridgedCastExprClass:
1136  case Expr::ObjCIndirectCopyRestoreExprClass:
1137  case Expr::ObjCProtocolExprClass:
1138  case Expr::ObjCSelectorExprClass:
1139  case Expr::OffsetOfExprClass:
1140  case Expr::PackExpansionExprClass:
1141  case Expr::PseudoObjectExprClass:
1142  case Expr::SubstNonTypeTemplateParmExprClass:
1143  case Expr::SubstNonTypeTemplateParmPackExprClass:
1144  case Expr::FunctionParmPackExprClass:
1145  case Expr::UnaryExprOrTypeTraitExprClass:
1146  case Expr::UnresolvedLookupExprClass:
1147  case Expr::UnresolvedMemberExprClass:
1148  case Expr::TypoExprClass:
1149  // FIXME: Can any of the above throw? If so, when?
1150  return CT_Cannot;
1151 
1152  case Expr::AddrLabelExprClass:
1153  case Expr::ArrayTypeTraitExprClass:
1154  case Expr::AtomicExprClass:
1155  case Expr::TypeTraitExprClass:
1156  case Expr::CXXBoolLiteralExprClass:
1157  case Expr::CXXNoexceptExprClass:
1158  case Expr::CXXNullPtrLiteralExprClass:
1159  case Expr::CXXPseudoDestructorExprClass:
1160  case Expr::CXXScalarValueInitExprClass:
1161  case Expr::CXXThisExprClass:
1162  case Expr::CXXUuidofExprClass:
1163  case Expr::CharacterLiteralClass:
1164  case Expr::ExpressionTraitExprClass:
1165  case Expr::FloatingLiteralClass:
1166  case Expr::GNUNullExprClass:
1167  case Expr::ImaginaryLiteralClass:
1168  case Expr::ImplicitValueInitExprClass:
1169  case Expr::IntegerLiteralClass:
1170  case Expr::NoInitExprClass:
1171  case Expr::ObjCEncodeExprClass:
1172  case Expr::ObjCStringLiteralClass:
1173  case Expr::ObjCBoolLiteralExprClass:
1174  case Expr::OpaqueValueExprClass:
1175  case Expr::PredefinedExprClass:
1176  case Expr::SizeOfPackExprClass:
1177  case Expr::StringLiteralClass:
1178  // These expressions can never throw.
1179  return CT_Cannot;
1180 
1181  case Expr::MSPropertyRefExprClass:
1182  case Expr::MSPropertySubscriptExprClass:
1183  llvm_unreachable("Invalid class for expression");
1184 
1185 #define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1186 #define STMT_RANGE(Base, First, Last)
1187 #define LAST_STMT_RANGE(BASE, FIRST, LAST)
1188 #define EXPR(CLASS, PARENT)
1189 #define ABSTRACT_STMT(STMT)
1190 #include "clang/AST/StmtNodes.inc"
1191  case Expr::NoStmtClass:
1192  llvm_unreachable("Invalid class for expression");
1193  }
1194  llvm_unreachable("Bogus StmtClass");
1195 }
1196 
1197 } // end namespace clang
CanThrowResult canThrow(const Expr *E)
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:64
CastKind getCastKind() const
Definition: Expr.h:2658
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1483
no exception specification
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2147
A (possibly-)qualified type.
Definition: Type.h:575
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
bool isReplaceableGlobalAllocationFunction() const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:2584
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function)
FunctionDecl * getExceptionSpecDecl() const
If this function type has an exception specification which hasn't been determined yet (either because...
Definition: Type.h:3235
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:164
const LangOptions & getLangOpts() const
Definition: Sema.h:1041
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Defines the SourceManager interface.
bool isRecordType() const
Definition: Type.h:5362
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1118
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:77
void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD)
Evaluate the implicit exception specification for a defaulted special member function.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:46
A container of type source information.
Definition: Decl.h:61
Expr *const * const_capture_init_iterator
Const iterator that walks over the capture initialization arguments.
Definition: ExprCXX.h:1581
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:25
The noexcept specifier has a bad expression.
Definition: Type.h:3213
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1608
const Expr * getCallee() const
Definition: Expr.h:2170
void clear()
Clear the base-paths results.
CK_Dynamic - A C++ dynamic_cast.
Defines the clang::Expr interface and subclasses for C++ expressions.
bool isVoidType() const
Definition: Type.h:5546
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:40
unsigned getNumParams() const
Definition: Type.h:3160
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:2629
One of these records is kept for each identifier that is lexed.
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4381
bool hasAttr() const
Definition: DeclBase.h:498
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3165
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:5314
NoexceptResult
Result type of getNoexceptSpec().
Definition: Type.h:3211
bool isPRValue() const
Definition: Expr.h:350
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:1744
Expr * getSubExpr()
Definition: Expr.h:2662
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:559
Microsoft throw(...) extension.
unsigned getDiagID() const
QualType getReturnType() const
Definition: Type.h:2977
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:1801
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:1595
Expr * getExprOperand() const
Definition: ExprCXX.h:614
Expr * getNoexceptExpr() const
Definition: Type.h:3225
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:146
RecordDecl * getDecl() const
Definition: Type.h:3553
static bool CheckSpecForTypesEquivalent(Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID, QualType Target, SourceLocation TargetLoc, QualType Source, SourceLocation SourceLoc)
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:2801
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1422
detail::InMemoryDirectory::const_iterator I
QualType getType() const
Definition: Decl.h:530
bool isInvalid() const
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:259
QualType getParamType(unsigned i) const
Definition: Type.h:3161
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3041
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:3193
CanThrowResult mergeCanThrow(CanThrowResult CT1, CanThrowResult CT2)
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:415
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:521
Expr - This represents one expression.
Definition: Expr.h:104
StringRef getName() const
Return the actual identifier string.
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2345
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:111
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3169
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &O)
Definition: Type.h:3076
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:372
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:6518
Defines the clang::TypeLoc interface and its subclasses.
There is no noexcept specifier.
Definition: Type.h:3212
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:318
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1751
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:190
The result type of a method or function.
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:602
static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC)
bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.cpp:2783
CanThrowResult
Possible results from evaluation of a noexcept expression.
exception_iterator exception_begin() const
Definition: Type.h:3293
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition: ExprCXX.h:274
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:236
Kind
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:3053
Encodes a location in the source.
bool CheckDistantExceptionSpec(QualType T)
CheckDistantExceptionSpec - Check if the given type is a pointer or pointer to member to a function w...
bool isValid() const
Return true if this is a valid SourceLocation object.
OverloadedOperatorKind getCXXOverloadedOperator() const
getCXXOverloadedOperator - If this name is the name of an overloadable operator in C++ (e...
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1701
static bool hasImplicitExceptionSpec(FunctionDecl *Decl)
Determine whether a function has an implicitly-generated exception specification. ...
The noexcept specifier evaluates to true.
Definition: Type.h:3216
static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC)
bool hasDependentExceptionSpec() const
Return whether this function has a dependent exception spec.
Definition: Type.cpp:2747
SourceLocation getBegin() const
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:164
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:5706
NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const
Get the meaning of the noexcept spec on this function, if any.
Definition: Type.cpp:2760
bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D)
Determine if we're in a case where we need to (incorrectly) eagerly parse an exception specification ...
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:2818
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:69
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
QualType getType() const
Definition: Expr.h:125
not evaluated yet, for special member function
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:22
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1308
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1056
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
detail::InMemoryDirectory::const_iterator E
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:2369
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:1946
Defines the Diagnostic-related interfaces.
Decl * getCalleeDecl()
Definition: Expr.cpp:1186
Pointer to a block type.
Definition: Type.h:2254
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:808
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3544
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:5675
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy.
Definition: Sema.h:1853
bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Superset, SourceLocation SuperLoc, const FunctionProtoType *Subset, SourceLocation SubLoc)
CheckExceptionSpecSubset - Check whether the second function type's exception specification is a subs...
bool isFunctionType() const
Definition: Type.h:5302
CXXBasePath & front()
The noexcept specifier evaluates to false.
Definition: Type.h:3215
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2287
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1522
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:78
SourceManager & getSourceManager()
Definition: ASTContext.h:553
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:1951
bool CheckParamExceptionSpec(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...
Represents a C++ struct/union/class.
Definition: DeclCXX.h:285
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range)
CheckSpecifiedExceptionType - Check if the given type is valid in an exception specification.
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:307
bool isArrayType() const
Definition: Type.h:5344
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2134
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)
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression...
Definition: ExprCXX.h:1607
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:3197
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
Definition: DeclBase.h:384
ASTContext & Context
Definition: Sema.h:295
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:507
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:642
bool isTypeOperand() const
Definition: ExprCXX.h:597
The noexcept specifier is dependent.
Definition: Type.h:3214
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
NamespaceDecl * getStdNamespace() const
void setType(QualType newType)
Definition: Decl.h:531
ArrayRef< QualType > exceptions() const
Definition: Type.h:3290
bool isBeingDefined() const
isBeingDefined - Return true if this decl is currently being defined.
Definition: Decl.h:2799
static const FunctionProtoType * GetUnderlyingFunction(QualType T)
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2433
unsigned getNumExceptions() const
Definition: Type.h:3220