clang  5.0.0
Sema.cpp
Go to the documentation of this file.
1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
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 implements the actions class which performs semantic analysis and
11 // builds an AST out of a parse stream.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclFriend.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/StmtCXX.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/HeaderSearch.h"
27 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/ScopeInfo.h"
40 #include "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/SmallSet.h"
42 using namespace clang;
43 using namespace sema;
44 
46  return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
47 }
48 
49 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
50 
52  const Preprocessor &PP) {
53  PrintingPolicy Policy = Context.getPrintingPolicy();
54  // Our printing policy is copied over the ASTContext printing policy whenever
55  // a diagnostic is emitted, so recompute it.
56  Policy.Bool = Context.getLangOpts().Bool;
57  if (!Policy.Bool) {
58  if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
59  Policy.Bool = BoolMacro->isObjectLike() &&
60  BoolMacro->getNumTokens() == 1 &&
61  BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
62  }
63  }
64 
65  return Policy;
66 }
67 
69  TUScope = S;
70  PushDeclContext(S, Context.getTranslationUnitDecl());
71 }
72 
73 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
74  TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
75  : ExternalSource(nullptr), isMultiplexExternalSource(false),
76  FPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
77  Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
78  SourceMgr(PP.getSourceManager()), CollectStats(false),
79  CodeCompleter(CodeCompleter), CurContext(nullptr),
80  OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
81  MSPointerToMemberRepresentationMethod(
82  LangOpts.getMSPointerToMemberRepresentationMethod()),
83  VtorDispStack(MSVtorDispAttr::Mode(LangOpts.VtorDispMode)), PackStack(0),
84  DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
85  CodeSegStack(nullptr), CurInitSeg(nullptr), VisContext(nullptr),
86  PragmaAttributeCurrentTargetDecl(nullptr),
87  IsBuildingRecoveryCallExpr(false), Cleanup{}, LateTemplateParser(nullptr),
88  LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
89  StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
90  CXXTypeInfoDecl(nullptr), MSVCGuidDecl(nullptr), NSNumberDecl(nullptr),
91  NSValueDecl(nullptr), NSStringDecl(nullptr),
92  StringWithUTF8StringMethod(nullptr),
93  ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
94  ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
95  DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
96  TUKind(TUKind), NumSFINAEErrors(0), AccessCheckingSFINAE(false),
97  InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
98  ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
99  DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
100  ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
101  CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
102  TUScope = nullptr;
103 
104  LoadedExternalKnownNamespaces = false;
105  for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
106  NSNumberLiteralMethods[I] = nullptr;
107 
108  if (getLangOpts().ObjC1)
109  NSAPIObj.reset(new NSAPI(Context));
110 
111  if (getLangOpts().CPlusPlus)
112  FieldCollector.reset(new CXXFieldCollector());
113 
114  // Tell diagnostics how to render things from the AST library.
115  Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
116 
117  ExprEvalContexts.emplace_back(
118  ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
119  nullptr, false);
120 
121  FunctionScopes.push_back(new FunctionScopeInfo(Diags));
122 
123  // Initilization of data sharing attributes stack for OpenMP
124  InitDataSharingAttributesStack();
125 }
126 
128  DeclarationName DN = &Context.Idents.get(Name);
129  if (IdResolver.begin(DN) == IdResolver.end())
131 }
132 
134  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
135  SC->InitializeSema(*this);
136 
137  // Tell the external Sema source about this Sema object.
138  if (ExternalSemaSource *ExternalSema
139  = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
140  ExternalSema->InitializeSema(*this);
141 
142  // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
143  // will not be able to merge any duplicate __va_list_tag decls correctly.
144  VAListTagName = PP.getIdentifierInfo("__va_list_tag");
145 
146  if (!TUScope)
147  return;
148 
149  // Initialize predefined 128-bit integer types, if needed.
151  // If either of the 128-bit integer types are unavailable to name lookup,
152  // define them now.
153  DeclarationName Int128 = &Context.Idents.get("__int128_t");
154  if (IdResolver.begin(Int128) == IdResolver.end())
156 
157  DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
158  if (IdResolver.begin(UInt128) == IdResolver.end())
160  }
161 
162 
163  // Initialize predefined Objective-C types:
164  if (getLangOpts().ObjC1) {
165  // If 'SEL' does not yet refer to any declarations, make it refer to the
166  // predefined 'SEL'.
167  DeclarationName SEL = &Context.Idents.get("SEL");
168  if (IdResolver.begin(SEL) == IdResolver.end())
170 
171  // If 'id' does not yet refer to any declarations, make it refer to the
172  // predefined 'id'.
173  DeclarationName Id = &Context.Idents.get("id");
174  if (IdResolver.begin(Id) == IdResolver.end())
176 
177  // Create the built-in typedef for 'Class'.
178  DeclarationName Class = &Context.Idents.get("Class");
179  if (IdResolver.begin(Class) == IdResolver.end())
181 
182  // Create the built-in forward declaratino for 'Protocol'.
183  DeclarationName Protocol = &Context.Idents.get("Protocol");
184  if (IdResolver.begin(Protocol) == IdResolver.end())
186  }
187 
188  // Create the internal type for the *StringMakeConstantString builtins.
189  DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
190  if (IdResolver.begin(ConstantString) == IdResolver.end())
192 
193  // Initialize Microsoft "predefined C++ types".
194  if (getLangOpts().MSVCCompat) {
195  if (getLangOpts().CPlusPlus &&
196  IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
198  TUScope);
199 
201  }
202 
203  // Initialize predefined OpenCL types and supported extensions and (optional)
204  // core features.
205  if (getLangOpts().OpenCL) {
210  if (getLangOpts().OpenCLVersion >= 200) {
211  addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
213  addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
215  addImplicitTypedef("atomic_uint",
217  auto AtomicLongT = Context.getAtomicType(Context.LongTy);
218  addImplicitTypedef("atomic_long", AtomicLongT);
219  auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
220  addImplicitTypedef("atomic_ulong", AtomicULongT);
221  addImplicitTypedef("atomic_float",
223  auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
224  addImplicitTypedef("atomic_double", AtomicDoubleT);
225  // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
226  // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
228  auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
229  addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
230  auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
231  addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
232  auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
233  addImplicitTypedef("atomic_size_t", AtomicSizeT);
234  auto AtomicPtrDiffT = Context.getAtomicType(Context.getPointerDiffType());
235  addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
236 
237  // OpenCL v2.0 s6.13.11.6:
238  // - The atomic_long and atomic_ulong types are supported if the
239  // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
240  // extensions are supported.
241  // - The atomic_double type is only supported if double precision
242  // is supported and the cl_khr_int64_base_atomics and
243  // cl_khr_int64_extended_atomics extensions are supported.
244  // - If the device address space is 64-bits, the data types
245  // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
246  // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
247  // cl_khr_int64_extended_atomics extensions are supported.
248  std::vector<QualType> Atomic64BitTypes;
249  Atomic64BitTypes.push_back(AtomicLongT);
250  Atomic64BitTypes.push_back(AtomicULongT);
251  Atomic64BitTypes.push_back(AtomicDoubleT);
252  if (Context.getTypeSize(AtomicSizeT) == 64) {
253  Atomic64BitTypes.push_back(AtomicSizeT);
254  Atomic64BitTypes.push_back(AtomicIntPtrT);
255  Atomic64BitTypes.push_back(AtomicUIntPtrT);
256  Atomic64BitTypes.push_back(AtomicPtrDiffT);
257  }
258  for (auto &I : Atomic64BitTypes)
260  "cl_khr_int64_base_atomics cl_khr_int64_extended_atomics");
261 
262  setOpenCLExtensionForType(AtomicDoubleT, "cl_khr_fp64");
263  }
264 
266 
267 #define GENERIC_IMAGE_TYPE_EXT(Type, Id, Ext) \
268  setOpenCLExtensionForType(Context.Id, Ext);
269 #include "clang/Basic/OpenCLImageTypes.def"
270  };
271 
273  DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
274  if (IdResolver.begin(MSVaList) == IdResolver.end())
276  }
277 
278  DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
279  if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
281 }
282 
284  if (VisContext) FreeVisContext();
285  // Kill all the active scopes.
286  for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
287  delete FunctionScopes[I];
288  if (FunctionScopes.size() == 1)
289  delete FunctionScopes[0];
290 
291  // Tell the SemaConsumer to forget about us; we're going out of scope.
292  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
293  SC->ForgetSema();
294 
295  // Detach from the external Sema source.
296  if (ExternalSemaSource *ExternalSema
297  = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
298  ExternalSema->ForgetSema();
299 
300  // If Sema's ExternalSource is the multiplexer - we own it.
301  if (isMultiplexExternalSource)
302  delete ExternalSource;
303 
305 
306  // Destroys data sharing attributes stack for OpenMP
307  DestroyDataSharingAttributesStack();
308 
309  assert(DelayedTypos.empty() && "Uncorrected typos!");
310 }
311 
312 /// makeUnavailableInSystemHeader - There is an error in the current
313 /// context. If we're still in a system header, and we can plausibly
314 /// make the relevant declaration unavailable instead of erroring, do
315 /// so and return true.
317  UnavailableAttr::ImplicitReason reason) {
318  // If we're not in a function, it's an error.
319  FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
320  if (!fn) return false;
321 
322  // If we're in template instantiation, it's an error.
324  return false;
325 
326  // If that function's not in a system header, it's an error.
328  return false;
329 
330  // If the function is already unavailable, it's not an error.
331  if (fn->hasAttr<UnavailableAttr>()) return true;
332 
333  fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
334  return true;
335 }
336 
339 }
340 
341 ///\brief Registers an external source. If an external source already exists,
342 /// creates a multiplex external source and appends to it.
343 ///
344 ///\param[in] E - A non-null external sema source.
345 ///
347  assert(E && "Cannot use with NULL ptr");
348 
349  if (!ExternalSource) {
350  ExternalSource = E;
351  return;
352  }
353 
354  if (isMultiplexExternalSource)
355  static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
356  else {
357  ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
358  isMultiplexExternalSource = true;
359  }
360 }
361 
362 /// \brief Print out statistics about the semantic analysis.
363 void Sema::PrintStats() const {
364  llvm::errs() << "\n*** Semantic Analysis Stats:\n";
365  llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
366 
367  BumpAlloc.PrintStats();
369 }
370 
372  QualType SrcType,
373  SourceLocation Loc) {
374  Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
375  if (!ExprNullability || *ExprNullability != NullabilityKind::Nullable)
376  return;
377 
378  Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
379  if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
380  return;
381 
382  Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
383 }
384 
386  if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
387  return;
388  if (E->getType()->isNullPtrType())
389  return;
390  // nullptr only exists from C++11 on, so don't warn on its absence earlier.
391  if (!getLangOpts().CPlusPlus11)
392  return;
393 
394  Diag(E->getLocStart(), diag::warn_zero_as_null_pointer_constant)
395  << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
396 }
397 
398 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
399 /// If there is already an implicit cast, merge into the existing one.
400 /// The result is of the given category.
403  const CXXCastPath *BasePath,
404  CheckedConversionKind CCK) {
405 #ifndef NDEBUG
406  if (VK == VK_RValue && !E->isRValue()) {
407  switch (Kind) {
408  default:
409  llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
410  "kind");
411  case CK_LValueToRValue:
412  case CK_ArrayToPointerDecay:
413  case CK_FunctionToPointerDecay:
414  case CK_ToVoid:
415  break;
416  }
417  }
418  assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
419 #endif
420 
423 
424  QualType ExprTy = Context.getCanonicalType(E->getType());
426 
427  if (ExprTy == TypeTy)
428  return E;
429 
430  // C++1z [conv.array]: The temporary materialization conversion is applied.
431  // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
432  if (Kind == CK_ArrayToPointerDecay && getLangOpts().CPlusPlus &&
433  E->getValueKind() == VK_RValue) {
434  // The temporary is an lvalue in C++98 and an xvalue otherwise.
436  E->getType(), E, !getLangOpts().CPlusPlus11);
437  if (Materialized.isInvalid())
438  return ExprError();
439  E = Materialized.get();
440  }
441 
442  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
443  if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
444  ImpCast->setType(Ty);
445  ImpCast->setValueKind(VK);
446  return E;
447  }
448  }
449 
450  return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
451 }
452 
453 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
454 /// to the conversion from scalar type ScalarTy to the Boolean type.
456  switch (ScalarTy->getScalarTypeKind()) {
457  case Type::STK_Bool: return CK_NoOp;
458  case Type::STK_CPointer: return CK_PointerToBoolean;
459  case Type::STK_BlockPointer: return CK_PointerToBoolean;
460  case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
461  case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
462  case Type::STK_Integral: return CK_IntegralToBoolean;
463  case Type::STK_Floating: return CK_FloatingToBoolean;
464  case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
465  case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
466  }
467  return CK_Invalid;
468 }
469 
470 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
471 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
472  if (D->getMostRecentDecl()->isUsed())
473  return true;
474 
475  if (D->isExternallyVisible())
476  return true;
477 
478  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
479  // If this is a function template and none of its specializations is used,
480  // we should warn.
481  if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
482  for (const auto *Spec : Template->specializations())
483  if (ShouldRemoveFromUnused(SemaRef, Spec))
484  return true;
485 
486  // UnusedFileScopedDecls stores the first declaration.
487  // The declaration may have become definition so check again.
488  const FunctionDecl *DeclToCheck;
489  if (FD->hasBody(DeclToCheck))
490  return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
491 
492  // Later redecls may add new information resulting in not having to warn,
493  // so check again.
494  DeclToCheck = FD->getMostRecentDecl();
495  if (DeclToCheck != FD)
496  return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
497  }
498 
499  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
500  // If a variable usable in constant expressions is referenced,
501  // don't warn if it isn't used: if the value of a variable is required
502  // for the computation of a constant expression, it doesn't make sense to
503  // warn even if the variable isn't odr-used. (isReferenced doesn't
504  // precisely reflect that, but it's a decent approximation.)
505  if (VD->isReferenced() &&
506  VD->isUsableInConstantExpressions(SemaRef->Context))
507  return true;
508 
509  if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
510  // If this is a variable template and none of its specializations is used,
511  // we should warn.
512  for (const auto *Spec : Template->specializations())
513  if (ShouldRemoveFromUnused(SemaRef, Spec))
514  return true;
515 
516  // UnusedFileScopedDecls stores the first declaration.
517  // The declaration may have become definition so check again.
518  const VarDecl *DeclToCheck = VD->getDefinition();
519  if (DeclToCheck)
520  return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
521 
522  // Later redecls may add new information resulting in not having to warn,
523  // so check again.
524  DeclToCheck = VD->getMostRecentDecl();
525  if (DeclToCheck != VD)
526  return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
527  }
528 
529  return false;
530 }
531 
532 /// Obtains a sorted list of functions and variables that are undefined but
533 /// ODR-used.
535  SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
536  for (const auto &UndefinedUse : UndefinedButUsed) {
537  NamedDecl *ND = UndefinedUse.first;
538 
539  // Ignore attributes that have become invalid.
540  if (ND->isInvalidDecl()) continue;
541 
542  // __attribute__((weakref)) is basically a definition.
543  if (ND->hasAttr<WeakRefAttr>()) continue;
544 
545  if (isa<CXXDeductionGuideDecl>(ND))
546  continue;
547 
548  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
549  if (FD->isDefined())
550  continue;
551  if (FD->isExternallyVisible() &&
552  !FD->getMostRecentDecl()->isInlined())
553  continue;
554  } else {
555  auto *VD = cast<VarDecl>(ND);
556  if (VD->hasDefinition() != VarDecl::DeclarationOnly)
557  continue;
558  if (VD->isExternallyVisible() && !VD->getMostRecentDecl()->isInline())
559  continue;
560  }
561 
562  Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
563  }
564 }
565 
566 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
567 /// or that are inline.
568 static void checkUndefinedButUsed(Sema &S) {
569  if (S.UndefinedButUsed.empty()) return;
570 
571  // Collect all the still-undefined entities with internal linkage.
573  S.getUndefinedButUsed(Undefined);
574  if (Undefined.empty()) return;
575 
576  for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
577  I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
578  NamedDecl *ND = I->first;
579 
580  if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
581  // An exported function will always be emitted when defined, so even if
582  // the function is inline, it doesn't have to be emitted in this TU. An
583  // imported function implies that it has been exported somewhere else.
584  continue;
585  }
586 
587  if (!ND->isExternallyVisible()) {
588  S.Diag(ND->getLocation(), diag::warn_undefined_internal)
589  << isa<VarDecl>(ND) << ND;
590  } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
591  (void)FD;
592  assert(FD->getMostRecentDecl()->isInlined() &&
593  "used object requires definition but isn't inline or internal?");
594  // FIXME: This is ill-formed; we should reject.
595  S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND;
596  } else {
597  assert(cast<VarDecl>(ND)->getMostRecentDecl()->isInline() &&
598  "used var requires definition but isn't inline or internal?");
599  S.Diag(ND->getLocation(), diag::err_undefined_inline_var) << ND;
600  }
601  if (I->second.isValid())
602  S.Diag(I->second, diag::note_used_here);
603  }
604 
605  S.UndefinedButUsed.clear();
606 }
607 
609  if (!ExternalSource)
610  return;
611 
613  ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
614  for (auto &WeakID : WeakIDs)
615  WeakUndeclaredIdentifiers.insert(WeakID);
616 }
617 
618 
619 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
620 
621 /// \brief Returns true, if all methods and nested classes of the given
622 /// CXXRecordDecl are defined in this translation unit.
623 ///
624 /// Should only be called from ActOnEndOfTranslationUnit so that all
625 /// definitions are actually read.
627  RecordCompleteMap &MNCComplete) {
628  RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
629  if (Cache != MNCComplete.end())
630  return Cache->second;
631  if (!RD->isCompleteDefinition())
632  return false;
633  bool Complete = true;
635  E = RD->decls_end();
636  I != E && Complete; ++I) {
637  if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
638  Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M));
639  else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
640  // If the template function is marked as late template parsed at this
641  // point, it has not been instantiated and therefore we have not
642  // performed semantic analysis on it yet, so we cannot know if the type
643  // can be considered complete.
644  Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
645  F->getTemplatedDecl()->isDefined();
646  else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
647  if (R->isInjectedClassName())
648  continue;
649  if (R->hasDefinition())
650  Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
651  MNCComplete);
652  else
653  Complete = false;
654  }
655  }
656  MNCComplete[RD] = Complete;
657  return Complete;
658 }
659 
660 /// \brief Returns true, if the given CXXRecordDecl is fully defined in this
661 /// translation unit, i.e. all methods are defined or pure virtual and all
662 /// friends, friend functions and nested classes are fully defined in this
663 /// translation unit.
664 ///
665 /// Should only be called from ActOnEndOfTranslationUnit so that all
666 /// definitions are actually read.
667 static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
668  RecordCompleteMap &RecordsComplete,
669  RecordCompleteMap &MNCComplete) {
670  RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
671  if (Cache != RecordsComplete.end())
672  return Cache->second;
673  bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
675  E = RD->friend_end();
676  I != E && Complete; ++I) {
677  // Check if friend classes and methods are complete.
678  if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
679  // Friend classes are available as the TypeSourceInfo of the FriendDecl.
680  if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
681  Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
682  else
683  Complete = false;
684  } else {
685  // Friend functions are available through the NamedDecl of FriendDecl.
686  if (const FunctionDecl *FD =
687  dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
688  Complete = FD->isDefined();
689  else
690  // This is a template friend, give up.
691  Complete = false;
692  }
693  }
694  RecordsComplete[RD] = Complete;
695  return Complete;
696 }
697 
699  if (ExternalSource)
700  ExternalSource->ReadUnusedLocalTypedefNameCandidates(
703  if (TD->isReferenced())
704  continue;
705  Diag(TD->getLocation(), diag::warn_unused_local_typedef)
706  << isa<TypeAliasDecl>(TD) << TD->getDeclName();
707  }
708  UnusedLocalTypedefNameCandidates.clear();
709 }
710 
711 /// This is called before the very first declaration in the translation unit
712 /// is parsed. Note that the ASTContext may have already injected some
713 /// declarations.
715  if (getLangOpts().ModulesTS) {
716  // We start in the global module; all those declarations are implicitly
717  // module-private (though they do not have module linkage).
720  }
721 }
722 
723 /// ActOnEndOfTranslationUnit - This is called at the very end of the
724 /// translation unit when EOF is reached and all but the top-level scope is
725 /// popped.
727  assert(DelayedDiagnostics.getCurrentPool() == nullptr
728  && "reached end of translation unit with a pool attached?");
729 
730  // If code completion is enabled, don't perform any end-of-translation-unit
731  // work.
733  return;
734 
735  // Complete translation units and modules define vtables and perform implicit
736  // instantiations. PCH files do not.
737  if (TUKind != TU_Prefix) {
739 
740  // If DefinedUsedVTables ends up marking any virtual member functions it
741  // might lead to more pending template instantiations, which we then need
742  // to instantiate.
744 
745  // C++: Perform implicit template instantiations.
746  //
747  // FIXME: When we perform these implicit instantiations, we do not
748  // carefully keep track of the point of instantiation (C++ [temp.point]).
749  // This means that name lookup that occurs within the template
750  // instantiation will always happen at the end of the translation unit,
751  // so it will find some names that are not required to be found. This is
752  // valid, but we could do better by diagnosing if an instantiation uses a
753  // name that was not visible at its first point of instantiation.
754  if (ExternalSource) {
755  // Load pending instantiations from the external source.
757  ExternalSource->ReadPendingInstantiations(Pending);
758  for (auto PII : Pending)
759  if (auto Func = dyn_cast<FunctionDecl>(PII.first))
760  Func->setInstantiationIsPending(true);
762  Pending.begin(), Pending.end());
763  }
765 
768 
770  }
771 
773 
774  // All delayed member exception specs should be checked or we end up accepting
775  // incompatible declarations.
776  // FIXME: This is wrong for TUKind == TU_Prefix. In that case, we need to
777  // write out the lists to the AST file (if any).
778  assert(DelayedDefaultedMemberExceptionSpecs.empty());
779  assert(DelayedExceptionSpecChecks.empty());
780 
781  // All dllexport classes should have been processed already.
782  assert(DelayedDllExportClasses.empty());
783 
784  // Remove file scoped decls that turned out to be used.
786  std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
788  [this](const DeclaratorDecl *DD) {
789  return ShouldRemoveFromUnused(this, DD);
790  }),
792 
793  if (TUKind == TU_Prefix) {
794  // Translation unit prefixes don't need any of the checking below.
796  TUScope = nullptr;
797  return;
798  }
799 
800  // Check for #pragma weak identifiers that were never declared
802  for (auto WeakID : WeakUndeclaredIdentifiers) {
803  if (WeakID.second.getUsed())
804  continue;
805 
806  Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(),
808  if (PrevDecl != nullptr &&
809  !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
810  Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type)
811  << "'weak'" << ExpectedVariableOrFunction;
812  else
813  Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
814  << WeakID.first;
815  }
816 
817  if (LangOpts.CPlusPlus11 &&
818  !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
820 
821  if (!Diags.hasErrorOccurred()) {
822  if (ExternalSource)
823  ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
824  checkUndefinedButUsed(*this);
825  }
826 
827  if (TUKind == TU_Module) {
828  // If we are building a module, resolve all of the exported declarations
829  // now.
830  if (Module *CurrentModule = PP.getCurrentModule()) {
832 
834  Stack.push_back(CurrentModule);
835  while (!Stack.empty()) {
836  Module *Mod = Stack.pop_back_val();
837 
838  // Resolve the exported declarations and conflicts.
839  // FIXME: Actually complain, once we figure out how to teach the
840  // diagnostic client to deal with complaints in the module map at this
841  // point.
842  ModMap.resolveExports(Mod, /*Complain=*/false);
843  ModMap.resolveUses(Mod, /*Complain=*/false);
844  ModMap.resolveConflicts(Mod, /*Complain=*/false);
845 
846  // Queue the submodules, so their exports will also be resolved.
847  Stack.append(Mod->submodule_begin(), Mod->submodule_end());
848  }
849  }
850 
851  // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
852  // modules when they are built, not every time they are used.
854 
855  // Modules don't need any of the checking below.
857  TUScope = nullptr;
858  return;
859  }
860 
861  // C99 6.9.2p2:
862  // A declaration of an identifier for an object that has file
863  // scope without an initializer, and without a storage-class
864  // specifier or with the storage-class specifier static,
865  // constitutes a tentative definition. If a translation unit
866  // contains one or more tentative definitions for an identifier,
867  // and the translation unit contains no external definition for
868  // that identifier, then the behavior is exactly as if the
869  // translation unit contains a file scope declaration of that
870  // identifier, with the composite type as of the end of the
871  // translation unit, with an initializer equal to 0.
872  llvm::SmallSet<VarDecl *, 32> Seen;
873  for (TentativeDefinitionsType::iterator
874  T = TentativeDefinitions.begin(ExternalSource),
875  TEnd = TentativeDefinitions.end();
876  T != TEnd; ++T)
877  {
878  VarDecl *VD = (*T)->getActingDefinition();
879 
880  // If the tentative definition was completed, getActingDefinition() returns
881  // null. If we've already seen this variable before, insert()'s second
882  // return value is false.
883  if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
884  continue;
885 
886  if (const IncompleteArrayType *ArrayT
888  // Set the length of the array to 1 (C99 6.9.2p5).
889  Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
890  llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
891  QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
892  One, ArrayType::Normal, 0);
893  VD->setType(T);
894  } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
895  diag::err_tentative_def_incomplete_type))
896  VD->setInvalidDecl();
897 
898  // No initialization is performed for a tentative definition.
900 
901  // Notify the consumer that we've completed a tentative definition.
902  if (!VD->isInvalidDecl())
904 
905  }
906 
907  // If there were errors, disable 'unused' warnings since they will mostly be
908  // noise.
909  if (!Diags.hasErrorOccurred()) {
910  // Output warning for unused file scoped decls.
911  for (UnusedFileScopedDeclsType::iterator
912  I = UnusedFileScopedDecls.begin(ExternalSource),
913  E = UnusedFileScopedDecls.end(); I != E; ++I) {
914  if (ShouldRemoveFromUnused(this, *I))
915  continue;
916 
917  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
918  const FunctionDecl *DiagD;
919  if (!FD->hasBody(DiagD))
920  DiagD = FD;
921  if (DiagD->isDeleted())
922  continue; // Deleted functions are supposed to be unused.
923  if (DiagD->isReferenced()) {
924  if (isa<CXXMethodDecl>(DiagD))
925  Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
926  << DiagD->getDeclName();
927  else {
928  if (FD->getStorageClass() == SC_Static &&
929  !FD->isInlineSpecified() &&
931  SourceMgr.getExpansionLoc(FD->getLocation())))
932  Diag(DiagD->getLocation(),
933  diag::warn_unneeded_static_internal_decl)
934  << DiagD->getDeclName();
935  else
936  Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
937  << /*function*/0 << DiagD->getDeclName();
938  }
939  } else {
940  if (FD->getDescribedFunctionTemplate())
941  Diag(DiagD->getLocation(), diag::warn_unused_template)
942  << /*function*/0 << DiagD->getDeclName();
943  else
944  Diag(DiagD->getLocation(),
945  isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
946  : diag::warn_unused_function)
947  << DiagD->getDeclName();
948  }
949  } else {
950  const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
951  if (!DiagD)
952  DiagD = cast<VarDecl>(*I);
953  if (DiagD->isReferenced()) {
954  Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
955  << /*variable*/1 << DiagD->getDeclName();
956  } else if (DiagD->getType().isConstQualified()) {
957  const SourceManager &SM = SourceMgr;
958  if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
960  Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
961  << DiagD->getDeclName();
962  } else {
963  if (DiagD->getDescribedVarTemplate())
964  Diag(DiagD->getLocation(), diag::warn_unused_template)
965  << /*variable*/1 << DiagD->getDeclName();
966  else
967  Diag(DiagD->getLocation(), diag::warn_unused_variable)
968  << DiagD->getDeclName();
969  }
970  }
971  }
972 
974  }
975 
976  if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
977  RecordCompleteMap RecordsComplete;
978  RecordCompleteMap MNCComplete;
979  for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
980  E = UnusedPrivateFields.end(); I != E; ++I) {
981  const NamedDecl *D = *I;
982  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
983  if (RD && !RD->isUnion() &&
984  IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
985  Diag(D->getLocation(), diag::warn_unused_private_field)
986  << D->getDeclName();
987  }
988  }
989  }
990 
991  if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
992  if (ExternalSource)
994  for (const auto &DeletedFieldInfo : DeleteExprs) {
995  for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
996  AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
997  DeleteExprLoc.second);
998  }
999  }
1000  }
1001 
1002  // Check we've noticed that we're no longer parsing the initializer for every
1003  // variable. If we miss cases, then at best we have a performance issue and
1004  // at worst a rejects-valid bug.
1005  assert(ParsingInitForAutoVars.empty() &&
1006  "Didn't unmark var as having its initializer parsed");
1007 
1009  TUScope = nullptr;
1010 }
1011 
1012 
1013 //===----------------------------------------------------------------------===//
1014 // Helper functions.
1015 //===----------------------------------------------------------------------===//
1016 
1018  DeclContext *DC = CurContext;
1019 
1020  while (true) {
1021  if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
1022  DC = DC->getParent();
1023  } else if (isa<CXXMethodDecl>(DC) &&
1024  cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
1025  cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
1026  DC = DC->getParent()->getParent();
1027  }
1028  else break;
1029  }
1030 
1031  return DC;
1032 }
1033 
1034 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1035 /// to the function decl for the function being parsed. If we're currently
1036 /// in a 'block', this returns the containing context.
1039  return dyn_cast<FunctionDecl>(DC);
1040 }
1041 
1044  while (isa<RecordDecl>(DC))
1045  DC = DC->getParent();
1046  return dyn_cast<ObjCMethodDecl>(DC);
1047 }
1048 
1051  if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
1052  return cast<NamedDecl>(DC);
1053  return nullptr;
1054 }
1055 
1056 void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
1057  // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1058  // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1059  // been made more painfully obvious by the refactor that introduced this
1060  // function, but it is possible that the incoming argument can be
1061  // eliminated. If it truly cannot be (for example, there is some reentrancy
1062  // issue I am not seeing yet), then there should at least be a clarifying
1063  // comment somewhere.
1066  Diags.getCurrentDiagID())) {
1068  // We'll report the diagnostic below.
1069  break;
1070 
1072  // Count this failure so that we know that template argument deduction
1073  // has failed.
1074  ++NumSFINAEErrors;
1075 
1076  // Make a copy of this suppressed diagnostic and store it with the
1077  // template-deduction information.
1078  if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1079  Diagnostic DiagInfo(&Diags);
1080  (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1082  }
1083 
1085  Diags.Clear();
1086  return;
1087 
1089  // Per C++ Core Issue 1170, access control is part of SFINAE.
1090  // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1091  // make access control a part of SFINAE for the purposes of checking
1092  // type traits.
1094  break;
1095 
1097 
1098  // Suppress this diagnostic.
1099  ++NumSFINAEErrors;
1100 
1101  // Make a copy of this suppressed diagnostic and store it with the
1102  // template-deduction information.
1103  if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1104  Diagnostic DiagInfo(&Diags);
1105  (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1107  }
1108 
1110  Diags.Clear();
1111 
1112  // Now the diagnostic state is clear, produce a C++98 compatibility
1113  // warning.
1114  Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1115 
1116  // The last diagnostic which Sema produced was ignored. Suppress any
1117  // notes attached to it.
1119  return;
1120  }
1121 
1123  // Make a copy of this suppressed diagnostic and store it with the
1124  // template-deduction information;
1125  if (*Info) {
1126  Diagnostic DiagInfo(&Diags);
1127  (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1129  }
1130 
1131  // Suppress this diagnostic.
1133  Diags.Clear();
1134  return;
1135  }
1136  }
1137 
1138  // Set up the context's printing policy based on our current state.
1140 
1141  // Emit the diagnostic.
1143  return;
1144 
1145  // If this is not a note, and we're in a template instantiation
1146  // that is different from the last template instantiation where
1147  // we emitted an error, print a template instantiation
1148  // backtrace.
1149  if (!DiagnosticIDs::isBuiltinNote(DiagID))
1151 }
1152 
1156  PD.Emit(Builder);
1157 
1158  return Builder;
1159 }
1160 
1161 /// \brief Looks through the macro-expansion chain for the given
1162 /// location, looking for a macro expansion with the given name.
1163 /// If one is found, returns true and sets the location to that
1164 /// expansion loc.
1165 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
1166  SourceLocation loc = locref;
1167  if (!loc.isMacroID()) return false;
1168 
1169  // There's no good way right now to look at the intermediate
1170  // expansions, so just jump to the expansion location.
1171  loc = getSourceManager().getExpansionLoc(loc);
1172 
1173  // If that's written with the name, stop here.
1174  SmallVector<char, 16> buffer;
1175  if (getPreprocessor().getSpelling(loc, buffer) == name) {
1176  locref = loc;
1177  return true;
1178  }
1179  return false;
1180 }
1181 
1182 /// \brief Determines the active Scope associated with the given declaration
1183 /// context.
1184 ///
1185 /// This routine maps a declaration context to the active Scope object that
1186 /// represents that declaration context in the parser. It is typically used
1187 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1188 /// declarations) that injects a name for name-lookup purposes and, therefore,
1189 /// must update the Scope.
1190 ///
1191 /// \returns The scope corresponding to the given declaraion context, or NULL
1192 /// if no such scope is open.
1194 
1195  if (!Ctx)
1196  return nullptr;
1197 
1198  Ctx = Ctx->getPrimaryContext();
1199  for (Scope *S = getCurScope(); S; S = S->getParent()) {
1200  // Ignore scopes that cannot have declarations. This is important for
1201  // out-of-line definitions of static class members.
1202  if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
1203  if (DeclContext *Entity = S->getEntity())
1204  if (Ctx == Entity->getPrimaryContext())
1205  return S;
1206  }
1207 
1208  return nullptr;
1209 }
1210 
1211 /// \brief Enter a new function scope
1213  if (FunctionScopes.size() == 1) {
1214  // Use the "top" function scope rather than having to allocate
1215  // memory for a new scope.
1216  FunctionScopes.back()->Clear();
1217  FunctionScopes.push_back(FunctionScopes.back());
1218  if (LangOpts.OpenMP)
1219  pushOpenMPFunctionRegion();
1220  return;
1221  }
1222 
1224  if (LangOpts.OpenMP)
1225  pushOpenMPFunctionRegion();
1226 }
1227 
1228 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
1230  BlockScope, Block));
1231 }
1232 
1234  LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
1235  FunctionScopes.push_back(LSI);
1236  return LSI;
1237 }
1238 
1240  if (LambdaScopeInfo *const LSI = getCurLambda()) {
1241  LSI->AutoTemplateParameterDepth = Depth;
1242  return;
1243  }
1244  llvm_unreachable(
1245  "Remove assertion if intentionally called in a non-lambda context.");
1246 }
1247 
1249  const Decl *D, const BlockExpr *blkExpr) {
1250  FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
1251  assert(!FunctionScopes.empty() && "mismatched push/pop!");
1252 
1253  if (LangOpts.OpenMP)
1254  popOpenMPFunctionRegion(Scope);
1255 
1256  // Issue any analysis-based warnings.
1257  if (WP && D)
1258  AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
1259  else
1260  for (const auto &PUD : Scope->PossiblyUnreachableDiags)
1261  Diag(PUD.Loc, PUD.PD);
1262 
1263  if (FunctionScopes.back() != Scope)
1264  delete Scope;
1265 }
1266 
1269 }
1270 
1272  FunctionScopeInfo *CurFunction = getCurFunction();
1273  assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
1274 
1275  CurFunction->CompoundScopes.pop_back();
1276 }
1277 
1278 /// \brief Determine whether any errors occurred within this function/method/
1279 /// block.
1282 }
1283 
1285  if (FunctionScopes.empty())
1286  return nullptr;
1287 
1288  auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
1289  if (CurBSI && CurBSI->TheDecl &&
1290  !CurBSI->TheDecl->Encloses(CurContext)) {
1291  // We have switched contexts due to template instantiation.
1292  assert(!CodeSynthesisContexts.empty());
1293  return nullptr;
1294  }
1295 
1296  return CurBSI;
1297 }
1298 
1299 LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
1300  if (FunctionScopes.empty())
1301  return nullptr;
1302 
1303  auto I = FunctionScopes.rbegin();
1304  if (IgnoreNonLambdaCapturingScope) {
1305  auto E = FunctionScopes.rend();
1306  while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
1307  ++I;
1308  if (I == E)
1309  return nullptr;
1310  }
1311  auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
1312  if (CurLSI && CurLSI->Lambda &&
1313  !CurLSI->Lambda->Encloses(CurContext)) {
1314  // We have switched contexts due to template instantiation.
1315  assert(!CodeSynthesisContexts.empty());
1316  return nullptr;
1317  }
1318 
1319  return CurLSI;
1320 }
1321 // We have a generic lambda if we parsed auto parameters, or we have
1322 // an associated template parameter list.
1324  if (LambdaScopeInfo *LSI = getCurLambda()) {
1325  return (LSI->AutoTemplateParams.size() ||
1326  LSI->GLTemplateParameterList) ? LSI : nullptr;
1327  }
1328  return nullptr;
1329 }
1330 
1331 
1333  if (!LangOpts.RetainCommentsFromSystemHeaders &&
1334  SourceMgr.isInSystemHeader(Comment.getBegin()))
1335  return;
1336  RawComment RC(SourceMgr, Comment, false,
1338  if (RC.isAlmostTrailingComment()) {
1339  SourceRange MagicMarkerRange(Comment.getBegin(),
1340  Comment.getBegin().getLocWithOffset(3));
1341  StringRef MagicMarkerText;
1342  switch (RC.getKind()) {
1344  MagicMarkerText = "///<";
1345  break;
1347  MagicMarkerText = "/**<";
1348  break;
1349  default:
1350  llvm_unreachable("if this is an almost Doxygen comment, "
1351  "it should be ordinary");
1352  }
1353  Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
1354  FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
1355  }
1356  Context.addComment(RC);
1357 }
1358 
1359 // Pin this vtable to this file.
1361 
1364 
1366  SmallVectorImpl<NamespaceDecl *> &Namespaces) {
1367 }
1368 
1370  llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
1371 
1373  FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
1374 
1375 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
1376  SourceLocation Loc = this->Loc;
1377  if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
1378  if (Loc.isValid()) {
1379  Loc.print(OS, S.getSourceManager());
1380  OS << ": ";
1381  }
1382  OS << Message;
1383 
1384  if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
1385  OS << " '";
1386  ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(), true);
1387  OS << "'";
1388  }
1389 
1390  OS << '\n';
1391 }
1392 
1393 /// \brief Figure out if an expression could be turned into a call.
1394 ///
1395 /// Use this when trying to recover from an error where the programmer may have
1396 /// written just the name of a function instead of actually calling it.
1397 ///
1398 /// \param E - The expression to examine.
1399 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1400 /// with no arguments, this parameter is set to the type returned by such a
1401 /// call; otherwise, it is set to an empty QualType.
1402 /// \param OverloadSet - If the expression is an overloaded function
1403 /// name, this parameter is populated with the decls of the various overloads.
1404 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1405  UnresolvedSetImpl &OverloadSet) {
1406  ZeroArgCallReturnTy = QualType();
1407  OverloadSet.clear();
1408 
1409  const OverloadExpr *Overloads = nullptr;
1410  bool IsMemExpr = false;
1411  if (E.getType() == Context.OverloadTy) {
1412  OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
1413 
1414  // Ignore overloads that are pointer-to-member constants.
1415  if (FR.HasFormOfMemberPointer)
1416  return false;
1417 
1418  Overloads = FR.Expression;
1419  } else if (E.getType() == Context.BoundMemberTy) {
1420  Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
1421  IsMemExpr = true;
1422  }
1423 
1424  bool Ambiguous = false;
1425 
1426  if (Overloads) {
1427  for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
1428  DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
1429  OverloadSet.addDecl(*it);
1430 
1431  // Check whether the function is a non-template, non-member which takes no
1432  // arguments.
1433  if (IsMemExpr)
1434  continue;
1435  if (const FunctionDecl *OverloadDecl
1436  = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
1437  if (OverloadDecl->getMinRequiredArguments() == 0) {
1438  if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) {
1439  ZeroArgCallReturnTy = QualType();
1440  Ambiguous = true;
1441  } else
1442  ZeroArgCallReturnTy = OverloadDecl->getReturnType();
1443  }
1444  }
1445  }
1446 
1447  // If it's not a member, use better machinery to try to resolve the call
1448  if (!IsMemExpr)
1449  return !ZeroArgCallReturnTy.isNull();
1450  }
1451 
1452  // Attempt to call the member with no arguments - this will correctly handle
1453  // member templates with defaults/deduction of template arguments, overloads
1454  // with default arguments, etc.
1455  if (IsMemExpr && !E.isTypeDependent()) {
1456  bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
1459  None, SourceLocation());
1461  if (R.isUsable()) {
1462  ZeroArgCallReturnTy = R.get()->getType();
1463  return true;
1464  }
1465  return false;
1466  }
1467 
1468  if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
1469  if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
1470  if (Fun->getMinRequiredArguments() == 0)
1471  ZeroArgCallReturnTy = Fun->getReturnType();
1472  return true;
1473  }
1474  }
1475 
1476  // We don't have an expression that's convenient to get a FunctionDecl from,
1477  // but we can at least check if the type is "function of 0 arguments".
1478  QualType ExprTy = E.getType();
1479  const FunctionType *FunTy = nullptr;
1480  QualType PointeeTy = ExprTy->getPointeeType();
1481  if (!PointeeTy.isNull())
1482  FunTy = PointeeTy->getAs<FunctionType>();
1483  if (!FunTy)
1484  FunTy = ExprTy->getAs<FunctionType>();
1485 
1486  if (const FunctionProtoType *FPT =
1487  dyn_cast_or_null<FunctionProtoType>(FunTy)) {
1488  if (FPT->getNumParams() == 0)
1489  ZeroArgCallReturnTy = FunTy->getReturnType();
1490  return true;
1491  }
1492  return false;
1493 }
1494 
1495 /// \brief Give notes for a set of overloads.
1496 ///
1497 /// A companion to tryExprAsCall. In cases when the name that the programmer
1498 /// wrote was an overloaded function, we may be able to make some guesses about
1499 /// plausible overloads based on their return types; such guesses can be handed
1500 /// off to this method to be emitted as notes.
1501 ///
1502 /// \param Overloads - The overloads to note.
1503 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
1504 /// -fshow-overloads=best, this is the location to attach to the note about too
1505 /// many candidates. Typically this will be the location of the original
1506 /// ill-formed expression.
1507 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
1508  const SourceLocation FinalNoteLoc) {
1509  int ShownOverloads = 0;
1510  int SuppressedOverloads = 0;
1511  for (UnresolvedSetImpl::iterator It = Overloads.begin(),
1512  DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1513  // FIXME: Magic number for max shown overloads stolen from
1514  // OverloadCandidateSet::NoteCandidates.
1515  if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
1516  ++SuppressedOverloads;
1517  continue;
1518  }
1519 
1520  NamedDecl *Fn = (*It)->getUnderlyingDecl();
1521  S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
1522  ++ShownOverloads;
1523  }
1524 
1525  if (SuppressedOverloads)
1526  S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
1527  << SuppressedOverloads;
1528 }
1529 
1531  const UnresolvedSetImpl &Overloads,
1532  bool (*IsPlausibleResult)(QualType)) {
1533  if (!IsPlausibleResult)
1534  return noteOverloads(S, Overloads, Loc);
1535 
1536  UnresolvedSet<2> PlausibleOverloads;
1537  for (OverloadExpr::decls_iterator It = Overloads.begin(),
1538  DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1539  const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
1540  QualType OverloadResultTy = OverloadDecl->getReturnType();
1541  if (IsPlausibleResult(OverloadResultTy))
1542  PlausibleOverloads.addDecl(It.getDecl());
1543  }
1544  noteOverloads(S, PlausibleOverloads, Loc);
1545 }
1546 
1547 /// Determine whether the given expression can be called by just
1548 /// putting parentheses after it. Notably, expressions with unary
1549 /// operators can't be because the unary operator will start parsing
1550 /// outside the call.
1551 static bool IsCallableWithAppend(Expr *E) {
1552  E = E->IgnoreImplicit();
1553  return (!isa<CStyleCastExpr>(E) &&
1554  !isa<UnaryOperator>(E) &&
1555  !isa<BinaryOperator>(E) &&
1556  !isa<CXXOperatorCallExpr>(E));
1557 }
1558 
1560  bool ForceComplain,
1561  bool (*IsPlausibleResult)(QualType)) {
1562  SourceLocation Loc = E.get()->getExprLoc();
1563  SourceRange Range = E.get()->getSourceRange();
1564 
1565  QualType ZeroArgCallTy;
1566  UnresolvedSet<4> Overloads;
1567  if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
1568  !ZeroArgCallTy.isNull() &&
1569  (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
1570  // At this point, we know E is potentially callable with 0
1571  // arguments and that it returns something of a reasonable type,
1572  // so we can emit a fixit and carry on pretending that E was
1573  // actually a CallExpr.
1574  SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
1575  Diag(Loc, PD)
1576  << /*zero-arg*/ 1 << Range
1577  << (IsCallableWithAppend(E.get())
1578  ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
1579  : FixItHint());
1580  notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1581 
1582  // FIXME: Try this before emitting the fixit, and suppress diagnostics
1583  // while doing so.
1584  E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None,
1585  Range.getEnd().getLocWithOffset(1));
1586  return true;
1587  }
1588 
1589  if (!ForceComplain) return false;
1590 
1591  Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
1592  notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1593  E = ExprError();
1594  return true;
1595 }
1596 
1598  if (!Ident_super)
1599  Ident_super = &Context.Idents.get("super");
1600  return Ident_super;
1601 }
1602 
1604  if (!Ident___float128)
1605  Ident___float128 = &Context.Idents.get("__float128");
1606  return Ident___float128;
1607 }
1608 
1610  CapturedRegionKind K) {
1612  getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
1613  (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0);
1614  CSI->ReturnType = Context.VoidTy;
1615  FunctionScopes.push_back(CSI);
1616 }
1617 
1619  if (FunctionScopes.empty())
1620  return nullptr;
1621 
1622  return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
1623 }
1624 
1625 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
1627  return DeleteExprs;
1628 }
1629 
1630 void Sema::setOpenCLExtensionForType(QualType T, llvm::StringRef ExtStr) {
1631  if (ExtStr.empty())
1632  return;
1634  ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
1635  auto CanT = T.getCanonicalType().getTypePtr();
1636  for (auto &I : Exts)
1637  OpenCLTypeExtMap[CanT].insert(I.str());
1638 }
1639 
1640 void Sema::setOpenCLExtensionForDecl(Decl *FD, StringRef ExtStr) {
1642  ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
1643  if (Exts.empty())
1644  return;
1645  for (auto &I : Exts)
1646  OpenCLDeclExtMap[FD].insert(I.str());
1647 }
1648 
1650  if (CurrOpenCLExtension.empty())
1651  return;
1652  setOpenCLExtensionForType(T, CurrOpenCLExtension);
1653 }
1654 
1656  if (CurrOpenCLExtension.empty())
1657  return;
1658  setOpenCLExtensionForDecl(D, CurrOpenCLExtension);
1659 }
1660 
1662  auto Loc = OpenCLDeclExtMap.find(FD);
1663  if (Loc == OpenCLDeclExtMap.end())
1664  return false;
1665  for (auto &I : Loc->second) {
1666  if (!getOpenCLOptions().isEnabled(I))
1667  return true;
1668  }
1669  return false;
1670 }
1671 
1672 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
1673 bool Sema::checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc,
1674  DiagInfoT DiagInfo, MapT &Map,
1675  unsigned Selector,
1676  SourceRange SrcRange) {
1677  auto Loc = Map.find(D);
1678  if (Loc == Map.end())
1679  return false;
1680  bool Disabled = false;
1681  for (auto &I : Loc->second) {
1682  if (I != CurrOpenCLExtension && !getOpenCLOptions().isEnabled(I)) {
1683  Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo
1684  << I << SrcRange;
1685  Disabled = true;
1686  }
1687  }
1688  return Disabled;
1689 }
1690 
1692  // Check extensions for declared types.
1693  Decl *Decl = nullptr;
1694  if (auto TypedefT = dyn_cast<TypedefType>(QT.getTypePtr()))
1695  Decl = TypedefT->getDecl();
1696  if (auto TagT = dyn_cast<TagType>(QT.getCanonicalType().getTypePtr()))
1697  Decl = TagT->getDecl();
1698  auto Loc = DS.getTypeSpecTypeLoc();
1699  if (checkOpenCLDisabledTypeOrDecl(Decl, Loc, QT, OpenCLDeclExtMap))
1700  return true;
1701 
1702  // Check extensions for builtin types.
1703  return checkOpenCLDisabledTypeOrDecl(QT.getCanonicalType().getTypePtr(), Loc,
1704  QT, OpenCLTypeExtMap);
1705 }
1706 
1708  IdentifierInfo *FnName = D.getIdentifier();
1709  return checkOpenCLDisabledTypeOrDecl(&D, E.getLocStart(), FnName,
1710  OpenCLDeclExtMap, 1, D.getSourceRange());
1711 }
Defines the clang::ASTContext interface.
SourceLocation getEnd() const
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used...
Definition: Sema.h:575
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1618
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:537
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:10411
bool isNullPtrType() const
Definition: Type.h:5919
IdentifierInfo * getSuperIdentifier() const
Definition: Sema.cpp:1597
CanQualType OCLQueueTy
Definition: ASTContext.h:988
Smart pointer class that efficiently represents Objective-C method names.
A (possibly-)qualified type.
Definition: Type.h:616
ASTConsumer & Consumer
Definition: Sema.h:306
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1519
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
bool isInvalid() const
Definition: Ownership.h:159
bool isMacroID() const
void Initialize()
Perform initialization that occurs after the parser has been initialized but before it parses anythin...
Definition: Sema.cpp:133
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs...
Definition: ASTConsumer.h:34
DeclContext * getFunctionLevelDeclContext()
Definition: Sema.cpp:1017
static const CastKind CK_Invalid
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=TTK_Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:2954
A class which encapsulates the logic for delaying diagnostics during parsing and other processing...
Definition: Sema.h:632
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:232
This declaration has an owning module, but is only visible to lookups that occur within that module...
const LangOptions & getLangOpts() const
Definition: Sema.h:1166
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:11004
void getUndefinedButUsed(SmallVectorImpl< std::pair< NamedDecl *, SourceLocation > > &Undefined)
Obtain a sorted list of functions that are undefined but ODR-used.
Definition: Sema.cpp:534
submodule_iterator submodule_begin()
Definition: Module.h:514
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2923
CXXFieldCollector - Used to keep track of CXXFieldDecls during parsing of C++ classes.
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:608
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
Definition: Preprocessor.h:974
static void notePlausibleOverloads(Sema &S, SourceLocation Loc, const UnresolvedSetImpl &Overloads, bool(*IsPlausibleResult)(QualType))
Definition: Sema.cpp:1530
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1243
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:81
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToMemberFunction - Build a call to a member function.
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2069
void setType(QualType t)
Definition: Expr.h:128
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed...
Definition: Sema.h:7452
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:784
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:242
bool hasErrorOccurred() const
Definition: Diagnostic.h:660
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:7102
PtrTy get() const
Definition: Ownership.h:163
virtual void updateOutOfDateSelector(Selector Sel)
Load the contents of the global method pool for a given selector if necessary.
Definition: Sema.cpp:1363
virtual void ReadMethodPool(Selector Sel)
Load the contents of the global method pool for a given selector.
Definition: Sema.cpp:1362
CanQualType LongTy
Definition: ASTContext.h:971
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2241
Any normal BCPL comments.
Declaration of a variable template.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:45
A container of type source information.
Definition: Decl.h:62
IdentifierInfo * getFloat128Identifier() const
Definition: Sema.cpp:1603
The diagnostic should not be reported, but it should cause template argument deduction to fail...
void LoadExternalWeakUndeclaredIdentifiers()
Load weak undeclared identifiers from the external source.
Definition: Sema.cpp:608
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Definition: ModuleMap.cpp:1143
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:82
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
Definition: Sema.cpp:49
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:758
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type...
DiagnosticsEngine & Diags
Definition: Sema.h:307
virtual void ReadWeakUndeclaredIdentifiers(SmallVectorImpl< std::pair< IdentifierInfo *, WeakInfo > > &WI)
Read the set of weak, undeclared identifiers known to the external Sema source.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1924
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:113
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:377
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:10446
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:1076
Expr * IgnoreImplicit() LLVM_READONLY
IgnoreImplicit - Skip past any implicit AST nodes which might surround this expression.
Definition: Expr.h:731
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:624
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:38
decl_iterator decls_end() const
Definition: DeclBase.h:1539
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:1167
Defines the clang::Expr interface and subclasses for C++ expressions.
iterator begin(Source *source, bool LocalOnly=false)
iterator begin(DeclarationName Name)
begin - Returns an iterator for decls with the name 'Name'.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:5110
void threadSafetyCleanup(BeforeSet *Cache)
CanQualType OCLSamplerTy
Definition: ASTContext.h:987
void CheckDelayedMemberExceptionSpecs()
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3354
void FreeVisContext()
FreeVisContext - Deallocate and null out VisContext.
Definition: SemaAttr.cpp:665
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class...
An iterator over the friend declarations of a class.
Definition: DeclFriend.h:175
One of these records is kept for each identifier that is lexed.
virtual void ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector< const TypedefNameDecl *, 4 > &Decls)
Read the set of potentially unused typedefs known to the source.
void enableSupportedCore(unsigned CLVer)
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:1280
sema::DelayedDiagnosticPool * getCurrentPool() const
Returns the current delayed-diagnostics pool.
Definition: Sema.h:647
bool hasAttr() const
Definition: DeclBase.h:521
bool resolveConflicts(Module *Mod, bool Complain)
Resolve all of the unresolved conflicts in the given module.
Definition: ModuleMap.cpp:1156
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition: Sema.cpp:1323
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:128
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:1284
void setCurrentOpenCLExtensionForType(QualType T)
Set current OpenCL extensions for a type which can only be used when these OpenCL extensions are enab...
Definition: Sema.cpp:1649
QualType getReturnType() const
Definition: Decl.h:2106
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
Definition: Decl.h:2366
void erase(iterator From, iterator To)
bool isCompleteDefinition() const
isCompleteDefinition - Return true if this decl has its body fully specified.
Definition: Decl.h:2960
threadSafety::BeforeSet * ThreadSafetyDeclCache
Definition: Sema.h:7438
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:392
void ActOnEndOfTranslationUnit()
ActOnEndOfTranslationUnit - This is called at the very end of the translation unit when EOF is reache...
Definition: Sema.cpp:726
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
Definition: Preprocessor.h:895
CanQualType OCLEventTy
Definition: ASTContext.h:987
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:27
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:725
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:397
Represents a C++ member access expression for which lookup produced a set of overloaded functions...
Definition: ExprCXX.h:3350
void setPrintingPolicy(const clang::PrintingPolicy &Policy)
Definition: ASTContext.h:612
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:511
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
bool isOpenCLDisabledDecl(Decl *FD)
Definition: Sema.cpp:1661
CanQualType OCLReserveIDTy
Definition: ASTContext.h:988
Describes a module or submodule.
Definition: Module.h:57
llvm::BumpPtrAllocator BumpAlloc
Definition: Sema.h:1053
IdentifierTable & Idents
Definition: ASTContext.h:513
static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, const SourceLocation FinalNoteLoc)
Give notes for a set of overloads.
Definition: Sema.cpp:1507
bool AccessCheckingSFINAE
When true, access checking violations are treated as SFINAE failures rather than hard errors...
Definition: Sema.h:5929
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:106
Values of this type can be null.
iterator end()
end - Returns an iterator that has 'finished'.
DiagnosticErrorTrap ErrorTrap
Used to determine if errors occurred in this function or block.
Definition: ScopeInfo.h:161
An abstract interface that should be implemented by clients that read ASTs and then require further s...
Definition: SemaConsumer.h:26
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2052
static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD, RecordCompleteMap &MNCComplete)
Returns true, if all methods and nested classes of the given CXXRecordDecl are defined in this transl...
Definition: Sema.cpp:626
friend_iterator friend_end() const
Definition: DeclFriend.h:229
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred since this object instance was created...
Definition: Diagnostic.h:926
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition: Sema.cpp:1165
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:643
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:659
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1042
const SourceLocation & getLocation() const
Definition: Diagnostic.h:1236
unsigned getDiagID() const
uint32_t Offset
Definition: CacheTokens.cpp:43
bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T)
Check if type T corresponding to declaration specifier DS is disabled due to required OpenCL extensio...
Definition: Sema.cpp:1691
QualType getReturnType() const
Definition: Type.h:3065
std::pair< SourceLocation, bool > DeleteExprLoc
Delete-expressions to be analyzed at the end of translation unit.
Definition: Sema.h:544
HeaderSearch & getHeaderSearchInfo() const
Definition: Preprocessor.h:731
void PerformPendingInstantiations(bool LocalOnly=false)
Performs template instantiation for all implicit template instantiations we have seen until this poin...
A set of unresolved declarations.
Definition: UnresolvedSet.h:56
void IssueWarnings(Policy P, FunctionScopeInfo *fscope, const Decl *D, const BlockExpr *blkExpr)
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
void CheckDelegatingCtorCycles()
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:9122
~ExternalSemaSource() override
Definition: Sema.cpp:1360
Values of this type can never be null.
void addExternalSource(ExternalSemaSource *E)
Registers an external source.
Definition: Sema.cpp:346
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
static const unsigned NumNSNumberLiteralMethods
Definition: NSAPI.h:187
submodule_iterator submodule_end()
Definition: Module.h:516
void emitAndClearUnusedLocalTypedefWarnings()
Definition: Sema.cpp:698
virtual ASTMutationListener * GetASTMutationListener()
If the consumer is interested in entities getting modified after their initial creation, it should return a pointer to an ASTMutationListener here.
Definition: ASTConsumer.h:124
Preprocessor & PP
Definition: Sema.h:304
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:7437
This represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:3726
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1306
detail::InMemoryDirectory::const_iterator I
void PushCompoundScope()
Definition: Sema.cpp:1267
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type...
QualType getType() const
Definition: Decl.h:589
const LangOptions & LangOpts
Definition: Sema.h:303
bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E)
Check if declaration D used by expression E is disabled due to required OpenCL extensions being disab...
Definition: Sema.cpp:1707
Contains information about the compound statement currently being parsed.
Definition: ScopeInfo.h:55
bool EmitCurrentDiagnostic(bool Force=false)
Emit the current diagnostic and clear the diagnostic state.
Definition: Diagnostic.cpp:399
void Emit(const DiagnosticBuilder &DB) const
static bool IsCallableWithAppend(Expr *E)
Determine whether the given expression can be called by just putting parentheses after it...
Definition: Sema.cpp:1551
bool isUnion() const
Definition: Decl.h:3028
void setLastDiagnosticIgnored()
Pretend that the last diagnostic issued was ignored, so any subsequent notes will be suppressed...
Definition: Diagnostic.h:581
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:269
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3129
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:567
const llvm::MapVector< FieldDecl *, DeleteLocs > & getMismatchingDeleteExpressions() const
Retrieves list of suspicious delete-expressions that will be checked at the end of translation unit...
Definition: Sema.cpp:1626
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
Retains information about a captured region.
Definition: ScopeInfo.h:696
unsigned getCurrentDiagID() const
Definition: Diagnostic.h:896
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:636
CastKind
CastKind - The kind of operation required for a conversion.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1698
void PopCompoundScope()
Definition: Sema.cpp:1271
virtual void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 >> &)
Definition: Sema.cpp:1372
ASTContext * Context
std::vector< bool > & Stack
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:414
virtual void ReadKnownNamespaces(SmallVectorImpl< NamespaceDecl * > &Namespaces)
Load the set of namespaces that are known to the external source, which will be used during typo corr...
Definition: Sema.cpp:1365
int * Depth
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:139
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:669
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:1979
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2383
Any normal C comment.
An abstract interface that should be implemented by external AST sources that also provide informatio...
BlockDecl - This represents a block literal declaration, which is like an unnamed FunctionDecl...
Definition: Decl.h:3557
static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D)
Used to prune the decls of Sema's UnusedFileScopedDecls vector.
Definition: Sema.cpp:471
Expr - This represents one expression.
Definition: Expr.h:105
void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts)
Set OpenCL extensions for a declaration which can only be used when these OpenCL extensions are enabl...
Definition: Sema.cpp:1640
Show just the "best" overload candidates.
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition: Lexer.cpp:762
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:103
bool isAlmostTrailingComment() const LLVM_READONLY
Returns true if it is a probable typo:
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:557
decls_iterator decls_end() const
Definition: ExprCXX.h:2557
friend_iterator friend_begin() const
Definition: DeclFriend.h:225
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:2529
void addImplicitTypedef(StringRef Name, QualType T)
Definition: Sema.cpp:127
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:4820
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:111
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:956
Defines the clang::Preprocessor interface.
llvm::MapVector< IdentifierInfo *, WeakInfo > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition: Sema.h:760
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
DeclContext * getDeclContext()
Definition: DeclBase.h:416
void PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, const BlockExpr *blkExpr=nullptr)
Definition: Sema.cpp:1248
bool resolveExports(Module *Mod, bool Complain)
Resolve all of the unresolved exports in the given module.
Definition: ModuleMap.cpp:1130
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
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:7107
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:337
void Clear()
Clear out the current diagnostic.
Definition: Diagnostic.h:792
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:516
PartialDiagnostic::StorageAllocator & getDiagAllocator()
Definition: ASTContext.h:639
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1294
bool isExternallyVisible() const
Definition: Decl.h:338
unsigned Map[FirstTargetAddressSpace]
The type of a lookup table which maps from language-specific address spaces to target-specific ones...
Definition: AddressSpaces.h:53
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:258
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1170
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1344
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:1233
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
const SourceManager & SM
Definition: Format.cpp:1293
unsigned NumSFINAEErrors
The number of SFINAE diagnostics that have been trapped.
Definition: Sema.h:1056
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:608
llvm::DenseMap< const CXXRecordDecl *, bool > RecordCompleteMap
Definition: Sema.cpp:619
An abstract interface that should be implemented by external AST sources that also provide informatio...
decls_iterator decls_begin() const
Definition: ExprCXX.h:2556
void addAttr(Attr *A)
Definition: DeclBase.h:472
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
unsigned Bool
Whether we can use 'bool' rather than '_Bool' (even if the language doesn't actually have 'bool'...
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:1228
CanQualType OverloadTy
Definition: ASTContext.h:979
#define false
Definition: stdbool.h:33
Kind
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr...
Definition: ExprCXX.h:2467
void print(raw_ostream &OS, const SourceManager &SM) const
Encodes a location in the source.
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
void setCurrentOpenCLExtensionForDecl(Decl *FD)
Set current OpenCL extensions for a declaration which can only be used when these OpenCL extensions a...
Definition: Sema.cpp:1655
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
Definition: ASTContext.h:1014
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5489
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:762
bool isValid() const
Return true if this is a valid SourceLocation object.
bool getSuppressAllDiagnostics() const
Definition: Diagnostic.h:551
bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason)
makeUnavailableInSystemHeader - There is an error in the current context.
Definition: Sema.cpp:316
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1903
void DiagnoseUseOfUnimplementedSelectors()
CanQualType FloatTy
Definition: ASTContext.h:974
ASTConsumer & getASTConsumer() const
Definition: Sema.h:1174
CanQualType VoidTy
Definition: ASTContext.h:963
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:83
virtual void ReadUndefinedButUsed(llvm::MapVector< NamedDecl *, SourceLocation > &Undefined)
Load the set of used but not defined functions or variables with internal linkage, or used but not defined internal functions.
Definition: Sema.cpp:1369
void EmitCurrentDiagnostic(unsigned DiagID)
Cause the active diagnostic on the DiagosticsEngine to be emitted.
Definition: Sema.cpp:1056
This declaration is only a declaration.
Definition: Decl.h:1076
void addSupport(const OpenCLOptions &Opts)
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
Definition: TargetInfo.h:604
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2804
bool isRValue() const
Definition: Expr.h:249
The diagnostic should be suppressed entirely.
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:166
static bool IsRecordFullyDefined(const CXXRecordDecl *RD, RecordCompleteMap &RecordsComplete, RecordCompleteMap &MNCComplete)
Returns true, if the given CXXRecordDecl is fully defined in this translation unit, i.e.
Definition: Sema.cpp:667
FileID getMainFileID() const
Returns the FileID of the main source file.
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1293
sema::CapturedRegionScopeInfo * getCurCapturedRegion()
Retrieve the current captured region, if any.
Definition: Sema.cpp:1618
static bool isBuiltinNote(unsigned DiagID)
Determine whether the given built-in diagnostic ID is a Note.
void ActOnStartOfTranslationUnit()
This is called before the very first declaration in the translation unit is parsed.
Definition: Sema.cpp:714
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:732
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts)
Set OpenCL extensions for a type which can only be used when these OpenCL extensions are enabled...
Definition: Sema.cpp:1630
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:1496
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2682
Abstract interface for a consumer of code-completion information.
QualType getType() const
Definition: Expr.h:127
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T-> getSizeExpr()))
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
bool isEnabled(llvm::StringRef Ext) const
Definition: OpenCLOptions.h:39
LateTemplateParserCleanupCB * LateTemplateParserCleanup
Definition: Sema.h:610
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1215
StringRef Name
Definition: USRFinder.cpp:123
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:401
bool isInvalidDecl() const
Definition: DeclBase.h:532
void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E)
Warn when implicitly casting 0 to nullptr.
Definition: Sema.cpp:385
void RecordParsingTemplateParameterDepth(unsigned Depth)
This is used to inform Sema what the current TemplateParameterDepth is during Parsing.
Definition: Sema.cpp:1239
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:76
DeclarationName - The name of a declaration.
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain=false, bool(*IsPlausibleResult)(QualType)=nullptr)
Try to recover by turning the given expression into a call.
Definition: Sema.cpp:1559
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required...
Definition: DeclBase.cpp:367
A set of unresolved declarations.
detail::InMemoryDirectory::const_iterator E
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:7328
IdentifierResolver IdResolver
Definition: Sema.h:779
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i...
Definition: LangOptions.h:154
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:358
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2087
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:455
Abstract interface for a module loader.
Definition: ModuleLoader.h:69
NamedDecl * getCurFunctionOrMethodDecl()
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in...
Definition: Sema.cpp:1049
SourceMgr(SourceMgr)
llvm::MapVector< FieldDecl *, DeleteLocs > DeleteExprs
Definition: Sema.h:546
void DiagnoseUnterminatedPragmaAttribute()
Definition: SemaAttr.cpp:608
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:34
DeclarationName VAListTagName
VAListTagName - The declaration name corresponding to __va_list_tag.
Definition: Sema.h:325
void FormatASTNodeDiagnosticArgument(DiagnosticsEngine::ArgumentKind Kind, intptr_t Val, StringRef Modifier, StringRef Argument, ArrayRef< DiagnosticsEngine::ArgumentValue > PrevArgs, SmallVectorImpl< char > &Output, void *Cookie, ArrayRef< intptr_t > QualTypeVals)
DiagnosticsEngine argument formatting function for diagnostics that involve AST nodes.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
SourceManager & getSourceManager() const
Definition: Sema.h:1171
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:6042
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy.
Definition: Sema.h:2100
QualType getCanonicalType() const
Definition: Type.h:5528
CanQualType UnsignedLongTy
Definition: ASTContext.h:972
FunctionDecl * getCurFunctionDecl()
getCurFunctionDecl - If inside of a function body, this returns a pointer to the function decl for th...
Definition: Sema.cpp:1037
void * OpaqueParser
Definition: Sema.h:611
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:6398
void print(raw_ostream &OS) const override
Definition: Sema.cpp:1375
CanQualType BoundMemberTy
Definition: ASTContext.h:979
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
void addComment(const RawComment &RC)
Definition: ASTContext.h:755
ImplicitParamDecl * getContextParam() const
Retrieve the parameter containing captured variables.
Definition: Decl.h:3785
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:90
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
The "class" keyword.
Definition: Type.h:4496
bool isUsable() const
Definition: Ownership.h:160
This is a scope that can contain a declaration.
Definition: Scope.h:58
SourceManager & getSourceManager()
Definition: ASTContext.h:616
The type-property cache.
Definition: Type.cpp:3286
void ActOnTranslationUnitScope(Scope *S)
Definition: Sema.cpp:68
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:1193
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
void setSuppressAllDiagnostics(bool Val=true)
Suppress all diagnostics, to silence the front end when we know that we don't want any more diagnosti...
Definition: Diagnostic.h:548
void * VisContext
VisContext - Manages the stack for #pragma GCC visibility.
Definition: Sema.h:467
SmallVector< PossiblyUnreachableDiag, 4 > PossiblyUnreachableDiags
A list of PartialDiagnostics created but delayed within the current function scope.
Definition: ScopeInfo.h:185
Captures information about "declaration specifiers".
Definition: DeclSpec.h:228
static SFINAEResponse getDiagnosticSFINAEResponse(unsigned DiagID)
Determines whether the given built-in diagnostic ID is for an error that is suppressed if it occurs d...
Represents a C++ struct/union/class.
Definition: DeclCXX.h:267
BoundNodesTreeBuilder *const Builder
CommentKind getKind() const LLVM_READONLY
Represents a C array with an unspecified size.
Definition: Type.h:2603
Optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
OverloadsShown getShowOverloads() const
Definition: Diagnostic.h:575
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:317
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:237
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:127
TypedefDecl * getCFConstantStringDecl() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:245
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition: Sema.cpp:1404
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1225
TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:1051
Defines the clang::TargetInfo interface.
ExprResult ExprError()
Definition: Ownership.h:268
The diagnostic should be reported.
CanQualType IntTy
Definition: ASTContext.h:971
void PrintStats() const
Print out statistics about the semantic analysis.
Definition: Sema.cpp:363
void ActOnComment(SourceRange Comment)
Definition: Sema.cpp:1332
virtual void ReadPendingInstantiations(SmallVectorImpl< std::pair< ValueDecl *, SourceLocation > > &Pending)
Read the set of pending instantiations known to the external Sema source.
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:219
The diagnostic is an access-control diagnostic, which will be substitution failures in some contexts ...
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:953
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:402
NamedDecl * getMostRecentDecl()
Definition: Decl.h:391
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1090
SourceManager & SourceMgr
Definition: Sema.h:308
CapturedRegionKind
The different kinds of captured statement.
Definition: CapturedStmt.h:17
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:64
SourceLocation getCurrentDiagLoc() const
Definition: Diagnostic.h:898
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type...
SmallVector< CompoundScopeInfo, 4 > CompoundScopes
The stack of currently active compound stamement scopes in the function.
Definition: ScopeInfo.h:180
virtual void CompleteTentativeDefinition(VarDecl *D)
CompleteTentativeDefinition - Callback invoked at the end of a translation unit to notify the consume...
Definition: ASTConsumer.h:104
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
Definition: DeclBase.h:407
ASTContext & Context
Definition: Sema.h:305
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one. ...
Definition: Sema.cpp:371
NamedDecl - This represents a decl with a name.
Definition: Decl.h:213
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K)
Definition: Sema.cpp:1609
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID...
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:1299
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5548
CanQualType DoubleTy
Definition: ASTContext.h:974
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:589
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:683
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:257
void setType(QualType newType)
Definition: Decl.h:590
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3526
static void checkUndefinedButUsed(Sema &S)
checkUndefinedButUsed - Check for undefined objects with internal linkage or that are inline...
Definition: Sema.cpp:568
SmallVector< std::pair< CXXMethodDecl *, const FunctionProtoType * >, 2 > DelayedDefaultedMemberExceptionSpecs
All the members seen during a class definition which were both explicitly defaulted and had explicitl...
Definition: Sema.h:599
This class handles loading and caching of source files into memory.
Preprocessor & getPreprocessor() const
Definition: Sema.h:1172
void PrintContextStack()
Definition: Sema.h:7332
OpenCLOptions & getSupportedOpenCLOpts()
Get supported OpenCL extensions and optional core features.
Definition: TargetInfo.h:1045
Declaration of a template function.
Definition: DeclTemplate.h:939
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:1212
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:533
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:1867
CanQualType OCLClkEventTy
Definition: ASTContext.h:987
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1196
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2368
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:98
CanQualType UnsignedIntTy
Definition: ASTContext.h:972
bool ParseAllComments
Treat ordinary comments as documentation comments.
IdentifierInfo * getBoolName() const
Retrieve the identifier 'bool'.
Definition: ASTContext.h:1585
The translation unit is a module.
Definition: LangOptions.h:244