xref: /llvm-project-15.0.7/clang/lib/Sema/Sema.cpp (revision 80bb52ae)
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"
16 #include "clang/AST/ASTDiagnostic.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"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/HeaderSearch.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Sema/CXXFieldCollector.h"
29 #include "clang/Sema/DelayedDiagnostic.h"
30 #include "clang/Sema/ExternalSemaSource.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/MultiplexExternalSemaSource.h"
33 #include "clang/Sema/ObjCMethodList.h"
34 #include "clang/Sema/PrettyDeclStackTrace.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/ScopeInfo.h"
37 #include "clang/Sema/SemaConsumer.h"
38 #include "clang/Sema/SemaInternal.h"
39 #include "clang/Sema/TemplateDeduction.h"
40 #include "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/SmallSet.h"
42 using namespace clang;
43 using namespace sema;
44 
45 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
46   return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
47 }
48 
49 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
50 
51 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
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 
68 void Sema::ActOnTranslationUnitScope(Scope *S) {
69   TUScope = S;
70   PushDeclContext(S, Context.getTranslationUnitDecl());
71 }
72 
73 namespace clang {
74 namespace sema {
75 
76 class SemaPPCallbacks : public PPCallbacks {
77   Sema *S = nullptr;
78   llvm::SmallVector<SourceLocation, 8> IncludeStack;
79 
80 public:
81   void set(Sema &S) { this->S = &S; }
82 
83   void reset() { S = nullptr; }
84 
85   virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
86                            SrcMgr::CharacteristicKind FileType,
87                            FileID PrevFID) override {
88     if (!S)
89       return;
90     switch (Reason) {
91     case EnterFile: {
92       SourceManager &SM = S->getSourceManager();
93       SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
94       if (IncludeLoc.isValid()) {
95         IncludeStack.push_back(IncludeLoc);
96         S->DiagnoseNonDefaultPragmaPack(
97             Sema::PragmaPackDiagnoseKind::NonDefaultStateAtInclude, IncludeLoc);
98       }
99       break;
100     }
101     case ExitFile:
102       if (!IncludeStack.empty())
103         S->DiagnoseNonDefaultPragmaPack(
104             Sema::PragmaPackDiagnoseKind::ChangedStateAtExit,
105             IncludeStack.pop_back_val());
106       break;
107     default:
108       break;
109     }
110   }
111 };
112 
113 } // end namespace sema
114 } // end namespace clang
115 
116 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
117            TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
118     : ExternalSource(nullptr), isMultiplexExternalSource(false),
119       FPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
120       Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
121       SourceMgr(PP.getSourceManager()), CollectStats(false),
122       CodeCompleter(CodeCompleter), CurContext(nullptr),
123       OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
124       MSPointerToMemberRepresentationMethod(
125           LangOpts.getMSPointerToMemberRepresentationMethod()),
126       VtorDispStack(MSVtorDispAttr::Mode(LangOpts.VtorDispMode)), PackStack(0),
127       DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
128       CodeSegStack(nullptr), CurInitSeg(nullptr), VisContext(nullptr),
129       PragmaAttributeCurrentTargetDecl(nullptr),
130       IsBuildingRecoveryCallExpr(false), Cleanup{}, LateTemplateParser(nullptr),
131       LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
132       StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
133       CXXTypeInfoDecl(nullptr), MSVCGuidDecl(nullptr), NSNumberDecl(nullptr),
134       NSValueDecl(nullptr), NSStringDecl(nullptr),
135       StringWithUTF8StringMethod(nullptr),
136       ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
137       ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
138       DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
139       TUKind(TUKind), NumSFINAEErrors(0), AccessCheckingSFINAE(false),
140       InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
141       ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
142       DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
143       ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
144       CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
145   TUScope = nullptr;
146 
147   LoadedExternalKnownNamespaces = false;
148   for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
149     NSNumberLiteralMethods[I] = nullptr;
150 
151   if (getLangOpts().ObjC1)
152     NSAPIObj.reset(new NSAPI(Context));
153 
154   if (getLangOpts().CPlusPlus)
155     FieldCollector.reset(new CXXFieldCollector());
156 
157   // Tell diagnostics how to render things from the AST library.
158   Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
159 
160   ExprEvalContexts.emplace_back(
161       ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
162       nullptr, false);
163 
164   FunctionScopes.push_back(new FunctionScopeInfo(Diags));
165 
166   // Initilization of data sharing attributes stack for OpenMP
167   InitDataSharingAttributesStack();
168 
169   std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
170       llvm::make_unique<sema::SemaPPCallbacks>();
171   SemaPPCallbackHandler = Callbacks.get();
172   PP.addPPCallbacks(std::move(Callbacks));
173   SemaPPCallbackHandler->set(*this);
174 }
175 
176 void Sema::addImplicitTypedef(StringRef Name, QualType T) {
177   DeclarationName DN = &Context.Idents.get(Name);
178   if (IdResolver.begin(DN) == IdResolver.end())
179     PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
180 }
181 
182 void Sema::Initialize() {
183   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
184     SC->InitializeSema(*this);
185 
186   // Tell the external Sema source about this Sema object.
187   if (ExternalSemaSource *ExternalSema
188       = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
189     ExternalSema->InitializeSema(*this);
190 
191   // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
192   // will not be able to merge any duplicate __va_list_tag decls correctly.
193   VAListTagName = PP.getIdentifierInfo("__va_list_tag");
194 
195   if (!TUScope)
196     return;
197 
198   // Initialize predefined 128-bit integer types, if needed.
199   if (Context.getTargetInfo().hasInt128Type()) {
200     // If either of the 128-bit integer types are unavailable to name lookup,
201     // define them now.
202     DeclarationName Int128 = &Context.Idents.get("__int128_t");
203     if (IdResolver.begin(Int128) == IdResolver.end())
204       PushOnScopeChains(Context.getInt128Decl(), TUScope);
205 
206     DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
207     if (IdResolver.begin(UInt128) == IdResolver.end())
208       PushOnScopeChains(Context.getUInt128Decl(), TUScope);
209   }
210 
211 
212   // Initialize predefined Objective-C types:
213   if (getLangOpts().ObjC1) {
214     // If 'SEL' does not yet refer to any declarations, make it refer to the
215     // predefined 'SEL'.
216     DeclarationName SEL = &Context.Idents.get("SEL");
217     if (IdResolver.begin(SEL) == IdResolver.end())
218       PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
219 
220     // If 'id' does not yet refer to any declarations, make it refer to the
221     // predefined 'id'.
222     DeclarationName Id = &Context.Idents.get("id");
223     if (IdResolver.begin(Id) == IdResolver.end())
224       PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
225 
226     // Create the built-in typedef for 'Class'.
227     DeclarationName Class = &Context.Idents.get("Class");
228     if (IdResolver.begin(Class) == IdResolver.end())
229       PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
230 
231     // Create the built-in forward declaratino for 'Protocol'.
232     DeclarationName Protocol = &Context.Idents.get("Protocol");
233     if (IdResolver.begin(Protocol) == IdResolver.end())
234       PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
235   }
236 
237   // Create the internal type for the *StringMakeConstantString builtins.
238   DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
239   if (IdResolver.begin(ConstantString) == IdResolver.end())
240     PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
241 
242   // Initialize Microsoft "predefined C++ types".
243   if (getLangOpts().MSVCCompat) {
244     if (getLangOpts().CPlusPlus &&
245         IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
246       PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
247                         TUScope);
248 
249     addImplicitTypedef("size_t", Context.getSizeType());
250   }
251 
252   // Initialize predefined OpenCL types and supported extensions and (optional)
253   // core features.
254   if (getLangOpts().OpenCL) {
255     getOpenCLOptions().addSupport(Context.getTargetInfo().getSupportedOpenCLOpts());
256     getOpenCLOptions().enableSupportedCore(getLangOpts().OpenCLVersion);
257     addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
258     addImplicitTypedef("event_t", Context.OCLEventTy);
259     if (getLangOpts().OpenCLVersion >= 200) {
260       addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
261       addImplicitTypedef("queue_t", Context.OCLQueueTy);
262       addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
263       addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
264       addImplicitTypedef("atomic_uint",
265                          Context.getAtomicType(Context.UnsignedIntTy));
266       auto AtomicLongT = Context.getAtomicType(Context.LongTy);
267       addImplicitTypedef("atomic_long", AtomicLongT);
268       auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
269       addImplicitTypedef("atomic_ulong", AtomicULongT);
270       addImplicitTypedef("atomic_float",
271                          Context.getAtomicType(Context.FloatTy));
272       auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
273       addImplicitTypedef("atomic_double", AtomicDoubleT);
274       // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
275       // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
276       addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
277       auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
278       addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
279       auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
280       addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
281       auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
282       addImplicitTypedef("atomic_size_t", AtomicSizeT);
283       auto AtomicPtrDiffT = Context.getAtomicType(Context.getPointerDiffType());
284       addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
285 
286       // OpenCL v2.0 s6.13.11.6:
287       // - The atomic_long and atomic_ulong types are supported if the
288       //   cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
289       //   extensions are supported.
290       // - The atomic_double type is only supported if double precision
291       //   is supported and the cl_khr_int64_base_atomics and
292       //   cl_khr_int64_extended_atomics extensions are supported.
293       // - If the device address space is 64-bits, the data types
294       //   atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
295       //   atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
296       //   cl_khr_int64_extended_atomics extensions are supported.
297       std::vector<QualType> Atomic64BitTypes;
298       Atomic64BitTypes.push_back(AtomicLongT);
299       Atomic64BitTypes.push_back(AtomicULongT);
300       Atomic64BitTypes.push_back(AtomicDoubleT);
301       if (Context.getTypeSize(AtomicSizeT) == 64) {
302         Atomic64BitTypes.push_back(AtomicSizeT);
303         Atomic64BitTypes.push_back(AtomicIntPtrT);
304         Atomic64BitTypes.push_back(AtomicUIntPtrT);
305         Atomic64BitTypes.push_back(AtomicPtrDiffT);
306       }
307       for (auto &I : Atomic64BitTypes)
308         setOpenCLExtensionForType(I,
309             "cl_khr_int64_base_atomics cl_khr_int64_extended_atomics");
310 
311       setOpenCLExtensionForType(AtomicDoubleT, "cl_khr_fp64");
312     }
313 
314     setOpenCLExtensionForType(Context.DoubleTy, "cl_khr_fp64");
315 
316 #define GENERIC_IMAGE_TYPE_EXT(Type, Id, Ext) \
317     setOpenCLExtensionForType(Context.Id, Ext);
318 #include "clang/Basic/OpenCLImageTypes.def"
319     };
320 
321   if (Context.getTargetInfo().hasBuiltinMSVaList()) {
322     DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
323     if (IdResolver.begin(MSVaList) == IdResolver.end())
324       PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
325   }
326 
327   DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
328   if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
329     PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
330 }
331 
332 Sema::~Sema() {
333   if (VisContext) FreeVisContext();
334   // Kill all the active scopes.
335   for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
336     delete FunctionScopes[I];
337   if (FunctionScopes.size() == 1)
338     delete FunctionScopes[0];
339 
340   // Tell the SemaConsumer to forget about us; we're going out of scope.
341   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
342     SC->ForgetSema();
343 
344   // Detach from the external Sema source.
345   if (ExternalSemaSource *ExternalSema
346         = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
347     ExternalSema->ForgetSema();
348 
349   // If Sema's ExternalSource is the multiplexer - we own it.
350   if (isMultiplexExternalSource)
351     delete ExternalSource;
352 
353   threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
354 
355   // Destroys data sharing attributes stack for OpenMP
356   DestroyDataSharingAttributesStack();
357 
358   // Detach from the PP callback handler which outlives Sema since it's owned
359   // by the preprocessor.
360   SemaPPCallbackHandler->reset();
361 
362   assert(DelayedTypos.empty() && "Uncorrected typos!");
363 }
364 
365 /// makeUnavailableInSystemHeader - There is an error in the current
366 /// context.  If we're still in a system header, and we can plausibly
367 /// make the relevant declaration unavailable instead of erroring, do
368 /// so and return true.
369 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
370                                       UnavailableAttr::ImplicitReason reason) {
371   // If we're not in a function, it's an error.
372   FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
373   if (!fn) return false;
374 
375   // If we're in template instantiation, it's an error.
376   if (inTemplateInstantiation())
377     return false;
378 
379   // If that function's not in a system header, it's an error.
380   if (!Context.getSourceManager().isInSystemHeader(loc))
381     return false;
382 
383   // If the function is already unavailable, it's not an error.
384   if (fn->hasAttr<UnavailableAttr>()) return true;
385 
386   fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
387   return true;
388 }
389 
390 ASTMutationListener *Sema::getASTMutationListener() const {
391   return getASTConsumer().GetASTMutationListener();
392 }
393 
394 ///\brief Registers an external source. If an external source already exists,
395 /// creates a multiplex external source and appends to it.
396 ///
397 ///\param[in] E - A non-null external sema source.
398 ///
399 void Sema::addExternalSource(ExternalSemaSource *E) {
400   assert(E && "Cannot use with NULL ptr");
401 
402   if (!ExternalSource) {
403     ExternalSource = E;
404     return;
405   }
406 
407   if (isMultiplexExternalSource)
408     static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
409   else {
410     ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
411     isMultiplexExternalSource = true;
412   }
413 }
414 
415 /// \brief Print out statistics about the semantic analysis.
416 void Sema::PrintStats() const {
417   llvm::errs() << "\n*** Semantic Analysis Stats:\n";
418   llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
419 
420   BumpAlloc.PrintStats();
421   AnalysisWarnings.PrintStats();
422 }
423 
424 void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
425                                                QualType SrcType,
426                                                SourceLocation Loc) {
427   Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
428   if (!ExprNullability || *ExprNullability != NullabilityKind::Nullable)
429     return;
430 
431   Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
432   if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
433     return;
434 
435   Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
436 }
437 
438 void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) {
439   if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
440     return;
441   if (E->getType()->isNullPtrType())
442     return;
443   // nullptr only exists from C++11 on, so don't warn on its absence earlier.
444   if (!getLangOpts().CPlusPlus11)
445     return;
446 
447   Diag(E->getLocStart(), diag::warn_zero_as_null_pointer_constant)
448       << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
449 }
450 
451 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
452 /// If there is already an implicit cast, merge into the existing one.
453 /// The result is of the given category.
454 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
455                                    CastKind Kind, ExprValueKind VK,
456                                    const CXXCastPath *BasePath,
457                                    CheckedConversionKind CCK) {
458 #ifndef NDEBUG
459   if (VK == VK_RValue && !E->isRValue()) {
460     switch (Kind) {
461     default:
462       llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
463                        "kind");
464     case CK_LValueToRValue:
465     case CK_ArrayToPointerDecay:
466     case CK_FunctionToPointerDecay:
467     case CK_ToVoid:
468       break;
469     }
470   }
471   assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
472 #endif
473 
474   diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getLocStart());
475   diagnoseZeroToNullptrConversion(Kind, E);
476 
477   QualType ExprTy = Context.getCanonicalType(E->getType());
478   QualType TypeTy = Context.getCanonicalType(Ty);
479 
480   if (ExprTy == TypeTy)
481     return E;
482 
483   // C++1z [conv.array]: The temporary materialization conversion is applied.
484   // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
485   if (Kind == CK_ArrayToPointerDecay && getLangOpts().CPlusPlus &&
486       E->getValueKind() == VK_RValue) {
487     // The temporary is an lvalue in C++98 and an xvalue otherwise.
488     ExprResult Materialized = CreateMaterializeTemporaryExpr(
489         E->getType(), E, !getLangOpts().CPlusPlus11);
490     if (Materialized.isInvalid())
491       return ExprError();
492     E = Materialized.get();
493   }
494 
495   if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
496     if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
497       ImpCast->setType(Ty);
498       ImpCast->setValueKind(VK);
499       return E;
500     }
501   }
502 
503   return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
504 }
505 
506 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
507 /// to the conversion from scalar type ScalarTy to the Boolean type.
508 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
509   switch (ScalarTy->getScalarTypeKind()) {
510   case Type::STK_Bool: return CK_NoOp;
511   case Type::STK_CPointer: return CK_PointerToBoolean;
512   case Type::STK_BlockPointer: return CK_PointerToBoolean;
513   case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
514   case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
515   case Type::STK_Integral: return CK_IntegralToBoolean;
516   case Type::STK_Floating: return CK_FloatingToBoolean;
517   case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
518   case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
519   }
520   return CK_Invalid;
521 }
522 
523 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
524 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
525   if (D->getMostRecentDecl()->isUsed())
526     return true;
527 
528   if (D->isExternallyVisible())
529     return true;
530 
531   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
532     // If this is a function template and none of its specializations is used,
533     // we should warn.
534     if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
535       for (const auto *Spec : Template->specializations())
536         if (ShouldRemoveFromUnused(SemaRef, Spec))
537           return true;
538 
539     // UnusedFileScopedDecls stores the first declaration.
540     // The declaration may have become definition so check again.
541     const FunctionDecl *DeclToCheck;
542     if (FD->hasBody(DeclToCheck))
543       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
544 
545     // Later redecls may add new information resulting in not having to warn,
546     // so check again.
547     DeclToCheck = FD->getMostRecentDecl();
548     if (DeclToCheck != FD)
549       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
550   }
551 
552   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
553     // If a variable usable in constant expressions is referenced,
554     // don't warn if it isn't used: if the value of a variable is required
555     // for the computation of a constant expression, it doesn't make sense to
556     // warn even if the variable isn't odr-used.  (isReferenced doesn't
557     // precisely reflect that, but it's a decent approximation.)
558     if (VD->isReferenced() &&
559         VD->isUsableInConstantExpressions(SemaRef->Context))
560       return true;
561 
562     if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
563       // If this is a variable template and none of its specializations is used,
564       // we should warn.
565       for (const auto *Spec : Template->specializations())
566         if (ShouldRemoveFromUnused(SemaRef, Spec))
567           return true;
568 
569     // UnusedFileScopedDecls stores the first declaration.
570     // The declaration may have become definition so check again.
571     const VarDecl *DeclToCheck = VD->getDefinition();
572     if (DeclToCheck)
573       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
574 
575     // Later redecls may add new information resulting in not having to warn,
576     // so check again.
577     DeclToCheck = VD->getMostRecentDecl();
578     if (DeclToCheck != VD)
579       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
580   }
581 
582   return false;
583 }
584 
585 static bool isFunctionOrVarDeclExternC(NamedDecl *ND) {
586   if (auto *FD = dyn_cast<FunctionDecl>(ND))
587     return FD->isExternC();
588   return cast<VarDecl>(ND)->isExternC();
589 }
590 
591 /// Determine whether ND is an external-linkage function or variable whose
592 /// type has no linkage.
593 bool Sema::isExternalWithNoLinkageType(ValueDecl *VD) {
594   // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
595   // because we also want to catch the case where its type has VisibleNoLinkage,
596   // which does not affect the linkage of VD.
597   return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
598          !isExternalFormalLinkage(VD->getType()->getLinkage()) &&
599          !isFunctionOrVarDeclExternC(VD);
600 }
601 
602 /// Obtains a sorted list of functions and variables that are undefined but
603 /// ODR-used.
604 void Sema::getUndefinedButUsed(
605     SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
606   for (const auto &UndefinedUse : UndefinedButUsed) {
607     NamedDecl *ND = UndefinedUse.first;
608 
609     // Ignore attributes that have become invalid.
610     if (ND->isInvalidDecl()) continue;
611 
612     // __attribute__((weakref)) is basically a definition.
613     if (ND->hasAttr<WeakRefAttr>()) continue;
614 
615     if (isa<CXXDeductionGuideDecl>(ND))
616       continue;
617 
618     if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
619       // An exported function will always be emitted when defined, so even if
620       // the function is inline, it doesn't have to be emitted in this TU. An
621       // imported function implies that it has been exported somewhere else.
622       continue;
623     }
624 
625     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
626       if (FD->isDefined())
627         continue;
628       if (FD->isExternallyVisible() &&
629           !isExternalWithNoLinkageType(FD) &&
630           !FD->getMostRecentDecl()->isInlined())
631         continue;
632     } else {
633       auto *VD = cast<VarDecl>(ND);
634       if (VD->hasDefinition() != VarDecl::DeclarationOnly)
635         continue;
636       if (VD->isExternallyVisible() &&
637           !isExternalWithNoLinkageType(VD) &&
638           !VD->getMostRecentDecl()->isInline())
639         continue;
640     }
641 
642     Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
643   }
644 }
645 
646 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
647 /// or that are inline.
648 static void checkUndefinedButUsed(Sema &S) {
649   if (S.UndefinedButUsed.empty()) return;
650 
651   // Collect all the still-undefined entities with internal linkage.
652   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
653   S.getUndefinedButUsed(Undefined);
654   if (Undefined.empty()) return;
655 
656   for (auto Undef : Undefined) {
657     ValueDecl *VD = cast<ValueDecl>(Undef.first);
658     SourceLocation UseLoc = Undef.second;
659 
660     if (S.isExternalWithNoLinkageType(VD)) {
661       // C++ [basic.link]p8:
662       //   A type without linkage shall not be used as the type of a variable
663       //   or function with external linkage unless
664       //    -- the entity has C language linkage
665       //    -- the entity is not odr-used or is defined in the same TU
666       //
667       // As an extension, accept this in cases where the type is externally
668       // visible, since the function or variable actually can be defined in
669       // another translation unit in that case.
670       S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())
671                                     ? diag::ext_undefined_internal_type
672                                     : diag::err_undefined_internal_type)
673         << isa<VarDecl>(VD) << VD;
674     } else if (!VD->isExternallyVisible()) {
675       // FIXME: We can promote this to an error. The function or variable can't
676       // be defined anywhere else, so the program must necessarily violate the
677       // one definition rule.
678       S.Diag(VD->getLocation(), diag::warn_undefined_internal)
679         << isa<VarDecl>(VD) << VD;
680     } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
681       (void)FD;
682       assert(FD->getMostRecentDecl()->isInlined() &&
683              "used object requires definition but isn't inline or internal?");
684       // FIXME: This is ill-formed; we should reject.
685       S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
686     } else {
687       assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
688              "used var requires definition but isn't inline or internal?");
689       S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
690     }
691     if (UseLoc.isValid())
692       S.Diag(UseLoc, diag::note_used_here);
693   }
694 
695   S.UndefinedButUsed.clear();
696 }
697 
698 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
699   if (!ExternalSource)
700     return;
701 
702   SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
703   ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
704   for (auto &WeakID : WeakIDs)
705     WeakUndeclaredIdentifiers.insert(WeakID);
706 }
707 
708 
709 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
710 
711 /// \brief Returns true, if all methods and nested classes of the given
712 /// CXXRecordDecl are defined in this translation unit.
713 ///
714 /// Should only be called from ActOnEndOfTranslationUnit so that all
715 /// definitions are actually read.
716 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
717                                             RecordCompleteMap &MNCComplete) {
718   RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
719   if (Cache != MNCComplete.end())
720     return Cache->second;
721   if (!RD->isCompleteDefinition())
722     return false;
723   bool Complete = true;
724   for (DeclContext::decl_iterator I = RD->decls_begin(),
725                                   E = RD->decls_end();
726        I != E && Complete; ++I) {
727     if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
728       Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M));
729     else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
730       // If the template function is marked as late template parsed at this
731       // point, it has not been instantiated and therefore we have not
732       // performed semantic analysis on it yet, so we cannot know if the type
733       // can be considered complete.
734       Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
735                   F->getTemplatedDecl()->isDefined();
736     else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
737       if (R->isInjectedClassName())
738         continue;
739       if (R->hasDefinition())
740         Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
741                                                    MNCComplete);
742       else
743         Complete = false;
744     }
745   }
746   MNCComplete[RD] = Complete;
747   return Complete;
748 }
749 
750 /// \brief Returns true, if the given CXXRecordDecl is fully defined in this
751 /// translation unit, i.e. all methods are defined or pure virtual and all
752 /// friends, friend functions and nested classes are fully defined in this
753 /// translation unit.
754 ///
755 /// Should only be called from ActOnEndOfTranslationUnit so that all
756 /// definitions are actually read.
757 static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
758                                  RecordCompleteMap &RecordsComplete,
759                                  RecordCompleteMap &MNCComplete) {
760   RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
761   if (Cache != RecordsComplete.end())
762     return Cache->second;
763   bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
764   for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
765                                       E = RD->friend_end();
766        I != E && Complete; ++I) {
767     // Check if friend classes and methods are complete.
768     if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
769       // Friend classes are available as the TypeSourceInfo of the FriendDecl.
770       if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
771         Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
772       else
773         Complete = false;
774     } else {
775       // Friend functions are available through the NamedDecl of FriendDecl.
776       if (const FunctionDecl *FD =
777           dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
778         Complete = FD->isDefined();
779       else
780         // This is a template friend, give up.
781         Complete = false;
782     }
783   }
784   RecordsComplete[RD] = Complete;
785   return Complete;
786 }
787 
788 void Sema::emitAndClearUnusedLocalTypedefWarnings() {
789   if (ExternalSource)
790     ExternalSource->ReadUnusedLocalTypedefNameCandidates(
791         UnusedLocalTypedefNameCandidates);
792   for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
793     if (TD->isReferenced())
794       continue;
795     Diag(TD->getLocation(), diag::warn_unused_local_typedef)
796         << isa<TypeAliasDecl>(TD) << TD->getDeclName();
797   }
798   UnusedLocalTypedefNameCandidates.clear();
799 }
800 
801 /// This is called before the very first declaration in the translation unit
802 /// is parsed. Note that the ASTContext may have already injected some
803 /// declarations.
804 void Sema::ActOnStartOfTranslationUnit() {
805   if (getLangOpts().ModulesTS) {
806     SourceLocation StartOfTU =
807         SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
808 
809     // We start in the global module; all those declarations are implicitly
810     // module-private (though they do not have module linkage).
811     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
812     auto *GlobalModule = Map.createGlobalModuleForInterfaceUnit(StartOfTU);
813     assert(GlobalModule && "module creation should not fail");
814 
815     // Enter the scope of the global module.
816     ModuleScopes.push_back({});
817     ModuleScopes.back().Module = GlobalModule;
818     VisibleModules.setVisible(GlobalModule, StartOfTU);
819 
820     // All declarations created from now on are owned by the global module.
821     auto *TU = Context.getTranslationUnitDecl();
822     TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
823     TU->setLocalOwningModule(GlobalModule);
824   }
825 }
826 
827 /// ActOnEndOfTranslationUnit - This is called at the very end of the
828 /// translation unit when EOF is reached and all but the top-level scope is
829 /// popped.
830 void Sema::ActOnEndOfTranslationUnit() {
831   assert(DelayedDiagnostics.getCurrentPool() == nullptr
832          && "reached end of translation unit with a pool attached?");
833 
834   // If code completion is enabled, don't perform any end-of-translation-unit
835   // work.
836   if (PP.isCodeCompletionEnabled())
837     return;
838 
839   // Complete translation units and modules define vtables and perform implicit
840   // instantiations. PCH files do not.
841   if (TUKind != TU_Prefix) {
842     DiagnoseUseOfUnimplementedSelectors();
843 
844     // If DefinedUsedVTables ends up marking any virtual member functions it
845     // might lead to more pending template instantiations, which we then need
846     // to instantiate.
847     DefineUsedVTables();
848 
849     // C++: Perform implicit template instantiations.
850     //
851     // FIXME: When we perform these implicit instantiations, we do not
852     // carefully keep track of the point of instantiation (C++ [temp.point]).
853     // This means that name lookup that occurs within the template
854     // instantiation will always happen at the end of the translation unit,
855     // so it will find some names that are not required to be found. This is
856     // valid, but we could do better by diagnosing if an instantiation uses a
857     // name that was not visible at its first point of instantiation.
858     if (ExternalSource) {
859       // Load pending instantiations from the external source.
860       SmallVector<PendingImplicitInstantiation, 4> Pending;
861       ExternalSource->ReadPendingInstantiations(Pending);
862       for (auto PII : Pending)
863         if (auto Func = dyn_cast<FunctionDecl>(PII.first))
864           Func->setInstantiationIsPending(true);
865       PendingInstantiations.insert(PendingInstantiations.begin(),
866                                    Pending.begin(), Pending.end());
867     }
868     PerformPendingInstantiations();
869 
870     if (LateTemplateParserCleanup)
871       LateTemplateParserCleanup(OpaqueParser);
872 
873     CheckDelayedMemberExceptionSpecs();
874   }
875 
876   DiagnoseUnterminatedPragmaPack();
877   DiagnoseUnterminatedPragmaAttribute();
878 
879   // All delayed member exception specs should be checked or we end up accepting
880   // incompatible declarations.
881   // FIXME: This is wrong for TUKind == TU_Prefix. In that case, we need to
882   // write out the lists to the AST file (if any).
883   assert(DelayedDefaultedMemberExceptionSpecs.empty());
884   assert(DelayedExceptionSpecChecks.empty());
885 
886   // All dllexport classes should have been processed already.
887   assert(DelayedDllExportClasses.empty());
888 
889   // Remove file scoped decls that turned out to be used.
890   UnusedFileScopedDecls.erase(
891       std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
892                      UnusedFileScopedDecls.end(),
893                      [this](const DeclaratorDecl *DD) {
894                        return ShouldRemoveFromUnused(this, DD);
895                      }),
896       UnusedFileScopedDecls.end());
897 
898   if (TUKind == TU_Prefix) {
899     // Translation unit prefixes don't need any of the checking below.
900     if (!PP.isIncrementalProcessingEnabled())
901       TUScope = nullptr;
902     return;
903   }
904 
905   // Check for #pragma weak identifiers that were never declared
906   LoadExternalWeakUndeclaredIdentifiers();
907   for (auto WeakID : WeakUndeclaredIdentifiers) {
908     if (WeakID.second.getUsed())
909       continue;
910 
911     Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(),
912                                       LookupOrdinaryName);
913     if (PrevDecl != nullptr &&
914         !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
915       Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type)
916           << "'weak'" << ExpectedVariableOrFunction;
917     else
918       Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
919           << WeakID.first;
920   }
921 
922   if (LangOpts.CPlusPlus11 &&
923       !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
924     CheckDelegatingCtorCycles();
925 
926   if (!Diags.hasErrorOccurred()) {
927     if (ExternalSource)
928       ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
929     checkUndefinedButUsed(*this);
930   }
931 
932   if (TUKind == TU_Module) {
933     // If we are building a module, resolve all of the exported declarations
934     // now.
935     if (Module *CurrentModule = PP.getCurrentModule()) {
936       ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
937 
938       SmallVector<Module *, 2> Stack;
939       Stack.push_back(CurrentModule);
940       while (!Stack.empty()) {
941         Module *Mod = Stack.pop_back_val();
942 
943         // Resolve the exported declarations and conflicts.
944         // FIXME: Actually complain, once we figure out how to teach the
945         // diagnostic client to deal with complaints in the module map at this
946         // point.
947         ModMap.resolveExports(Mod, /*Complain=*/false);
948         ModMap.resolveUses(Mod, /*Complain=*/false);
949         ModMap.resolveConflicts(Mod, /*Complain=*/false);
950 
951         // Queue the submodules, so their exports will also be resolved.
952         Stack.append(Mod->submodule_begin(), Mod->submodule_end());
953       }
954     }
955 
956     // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
957     // modules when they are built, not every time they are used.
958     emitAndClearUnusedLocalTypedefWarnings();
959 
960     // Modules don't need any of the checking below.
961     if (!PP.isIncrementalProcessingEnabled())
962       TUScope = nullptr;
963     return;
964   }
965 
966   // C99 6.9.2p2:
967   //   A declaration of an identifier for an object that has file
968   //   scope without an initializer, and without a storage-class
969   //   specifier or with the storage-class specifier static,
970   //   constitutes a tentative definition. If a translation unit
971   //   contains one or more tentative definitions for an identifier,
972   //   and the translation unit contains no external definition for
973   //   that identifier, then the behavior is exactly as if the
974   //   translation unit contains a file scope declaration of that
975   //   identifier, with the composite type as of the end of the
976   //   translation unit, with an initializer equal to 0.
977   llvm::SmallSet<VarDecl *, 32> Seen;
978   for (TentativeDefinitionsType::iterator
979             T = TentativeDefinitions.begin(ExternalSource),
980          TEnd = TentativeDefinitions.end();
981        T != TEnd; ++T)
982   {
983     VarDecl *VD = (*T)->getActingDefinition();
984 
985     // If the tentative definition was completed, getActingDefinition() returns
986     // null. If we've already seen this variable before, insert()'s second
987     // return value is false.
988     if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
989       continue;
990 
991     if (const IncompleteArrayType *ArrayT
992         = Context.getAsIncompleteArrayType(VD->getType())) {
993       // Set the length of the array to 1 (C99 6.9.2p5).
994       Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
995       llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
996       QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
997                                                 One, ArrayType::Normal, 0);
998       VD->setType(T);
999     } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
1000                                    diag::err_tentative_def_incomplete_type))
1001       VD->setInvalidDecl();
1002 
1003     // No initialization is performed for a tentative definition.
1004     CheckCompleteVariableDeclaration(VD);
1005 
1006     // Notify the consumer that we've completed a tentative definition.
1007     if (!VD->isInvalidDecl())
1008       Consumer.CompleteTentativeDefinition(VD);
1009 
1010   }
1011 
1012   // If there were errors, disable 'unused' warnings since they will mostly be
1013   // noise.
1014   if (!Diags.hasErrorOccurred()) {
1015     // Output warning for unused file scoped decls.
1016     for (UnusedFileScopedDeclsType::iterator
1017            I = UnusedFileScopedDecls.begin(ExternalSource),
1018            E = UnusedFileScopedDecls.end(); I != E; ++I) {
1019       if (ShouldRemoveFromUnused(this, *I))
1020         continue;
1021 
1022       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1023         const FunctionDecl *DiagD;
1024         if (!FD->hasBody(DiagD))
1025           DiagD = FD;
1026         if (DiagD->isDeleted())
1027           continue; // Deleted functions are supposed to be unused.
1028         if (DiagD->isReferenced()) {
1029           if (isa<CXXMethodDecl>(DiagD))
1030             Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
1031                   << DiagD->getDeclName();
1032           else {
1033             if (FD->getStorageClass() == SC_Static &&
1034                 !FD->isInlineSpecified() &&
1035                 !SourceMgr.isInMainFile(
1036                    SourceMgr.getExpansionLoc(FD->getLocation())))
1037               Diag(DiagD->getLocation(),
1038                    diag::warn_unneeded_static_internal_decl)
1039                   << DiagD->getDeclName();
1040             else
1041               Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1042                    << /*function*/0 << DiagD->getDeclName();
1043           }
1044         } else {
1045           if (FD->getDescribedFunctionTemplate())
1046             Diag(DiagD->getLocation(), diag::warn_unused_template)
1047               << /*function*/0 << DiagD->getDeclName();
1048           else
1049             Diag(DiagD->getLocation(),
1050                  isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
1051                                            : diag::warn_unused_function)
1052               << DiagD->getDeclName();
1053         }
1054       } else {
1055         const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
1056         if (!DiagD)
1057           DiagD = cast<VarDecl>(*I);
1058         if (DiagD->isReferenced()) {
1059           Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1060                 << /*variable*/1 << DiagD->getDeclName();
1061         } else if (DiagD->getType().isConstQualified()) {
1062           const SourceManager &SM = SourceMgr;
1063           if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
1064               !PP.getLangOpts().IsHeaderFile)
1065             Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
1066                 << DiagD->getDeclName();
1067         } else {
1068           if (DiagD->getDescribedVarTemplate())
1069             Diag(DiagD->getLocation(), diag::warn_unused_template)
1070               << /*variable*/1 << DiagD->getDeclName();
1071           else
1072             Diag(DiagD->getLocation(), diag::warn_unused_variable)
1073               << DiagD->getDeclName();
1074         }
1075       }
1076     }
1077 
1078     emitAndClearUnusedLocalTypedefWarnings();
1079   }
1080 
1081   if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
1082     RecordCompleteMap RecordsComplete;
1083     RecordCompleteMap MNCComplete;
1084     for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
1085          E = UnusedPrivateFields.end(); I != E; ++I) {
1086       const NamedDecl *D = *I;
1087       const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1088       if (RD && !RD->isUnion() &&
1089           IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
1090         Diag(D->getLocation(), diag::warn_unused_private_field)
1091               << D->getDeclName();
1092       }
1093     }
1094   }
1095 
1096   if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
1097     if (ExternalSource)
1098       ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
1099     for (const auto &DeletedFieldInfo : DeleteExprs) {
1100       for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
1101         AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
1102                                   DeleteExprLoc.second);
1103       }
1104     }
1105   }
1106 
1107   // Check we've noticed that we're no longer parsing the initializer for every
1108   // variable. If we miss cases, then at best we have a performance issue and
1109   // at worst a rejects-valid bug.
1110   assert(ParsingInitForAutoVars.empty() &&
1111          "Didn't unmark var as having its initializer parsed");
1112 
1113   if (!PP.isIncrementalProcessingEnabled())
1114     TUScope = nullptr;
1115 }
1116 
1117 
1118 //===----------------------------------------------------------------------===//
1119 // Helper functions.
1120 //===----------------------------------------------------------------------===//
1121 
1122 DeclContext *Sema::getFunctionLevelDeclContext() {
1123   DeclContext *DC = CurContext;
1124 
1125   while (true) {
1126     if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
1127       DC = DC->getParent();
1128     } else if (isa<CXXMethodDecl>(DC) &&
1129                cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
1130                cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
1131       DC = DC->getParent()->getParent();
1132     }
1133     else break;
1134   }
1135 
1136   return DC;
1137 }
1138 
1139 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1140 /// to the function decl for the function being parsed.  If we're currently
1141 /// in a 'block', this returns the containing context.
1142 FunctionDecl *Sema::getCurFunctionDecl() {
1143   DeclContext *DC = getFunctionLevelDeclContext();
1144   return dyn_cast<FunctionDecl>(DC);
1145 }
1146 
1147 ObjCMethodDecl *Sema::getCurMethodDecl() {
1148   DeclContext *DC = getFunctionLevelDeclContext();
1149   while (isa<RecordDecl>(DC))
1150     DC = DC->getParent();
1151   return dyn_cast<ObjCMethodDecl>(DC);
1152 }
1153 
1154 NamedDecl *Sema::getCurFunctionOrMethodDecl() {
1155   DeclContext *DC = getFunctionLevelDeclContext();
1156   if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
1157     return cast<NamedDecl>(DC);
1158   return nullptr;
1159 }
1160 
1161 void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
1162   // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1163   // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1164   // been made more painfully obvious by the refactor that introduced this
1165   // function, but it is possible that the incoming argument can be
1166   // eliminated. If it truly cannot be (for example, there is some reentrancy
1167   // issue I am not seeing yet), then there should at least be a clarifying
1168   // comment somewhere.
1169   if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
1170     switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
1171               Diags.getCurrentDiagID())) {
1172     case DiagnosticIDs::SFINAE_Report:
1173       // We'll report the diagnostic below.
1174       break;
1175 
1176     case DiagnosticIDs::SFINAE_SubstitutionFailure:
1177       // Count this failure so that we know that template argument deduction
1178       // has failed.
1179       ++NumSFINAEErrors;
1180 
1181       // Make a copy of this suppressed diagnostic and store it with the
1182       // template-deduction information.
1183       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1184         Diagnostic DiagInfo(&Diags);
1185         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1186                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1187       }
1188 
1189       Diags.setLastDiagnosticIgnored();
1190       Diags.Clear();
1191       return;
1192 
1193     case DiagnosticIDs::SFINAE_AccessControl: {
1194       // Per C++ Core Issue 1170, access control is part of SFINAE.
1195       // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1196       // make access control a part of SFINAE for the purposes of checking
1197       // type traits.
1198       if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
1199         break;
1200 
1201       SourceLocation Loc = Diags.getCurrentDiagLoc();
1202 
1203       // Suppress this diagnostic.
1204       ++NumSFINAEErrors;
1205 
1206       // Make a copy of this suppressed diagnostic and store it with the
1207       // template-deduction information.
1208       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1209         Diagnostic DiagInfo(&Diags);
1210         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1211                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1212       }
1213 
1214       Diags.setLastDiagnosticIgnored();
1215       Diags.Clear();
1216 
1217       // Now the diagnostic state is clear, produce a C++98 compatibility
1218       // warning.
1219       Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1220 
1221       // The last diagnostic which Sema produced was ignored. Suppress any
1222       // notes attached to it.
1223       Diags.setLastDiagnosticIgnored();
1224       return;
1225     }
1226 
1227     case DiagnosticIDs::SFINAE_Suppress:
1228       // Make a copy of this suppressed diagnostic and store it with the
1229       // template-deduction information;
1230       if (*Info) {
1231         Diagnostic DiagInfo(&Diags);
1232         (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1233                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1234       }
1235 
1236       // Suppress this diagnostic.
1237       Diags.setLastDiagnosticIgnored();
1238       Diags.Clear();
1239       return;
1240     }
1241   }
1242 
1243   // Set up the context's printing policy based on our current state.
1244   Context.setPrintingPolicy(getPrintingPolicy());
1245 
1246   // Emit the diagnostic.
1247   if (!Diags.EmitCurrentDiagnostic())
1248     return;
1249 
1250   // If this is not a note, and we're in a template instantiation
1251   // that is different from the last template instantiation where
1252   // we emitted an error, print a template instantiation
1253   // backtrace.
1254   if (!DiagnosticIDs::isBuiltinNote(DiagID))
1255     PrintContextStack();
1256 }
1257 
1258 Sema::SemaDiagnosticBuilder
1259 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
1260   SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
1261   PD.Emit(Builder);
1262 
1263   return Builder;
1264 }
1265 
1266 /// \brief Looks through the macro-expansion chain for the given
1267 /// location, looking for a macro expansion with the given name.
1268 /// If one is found, returns true and sets the location to that
1269 /// expansion loc.
1270 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
1271   SourceLocation loc = locref;
1272   if (!loc.isMacroID()) return false;
1273 
1274   // There's no good way right now to look at the intermediate
1275   // expansions, so just jump to the expansion location.
1276   loc = getSourceManager().getExpansionLoc(loc);
1277 
1278   // If that's written with the name, stop here.
1279   SmallVector<char, 16> buffer;
1280   if (getPreprocessor().getSpelling(loc, buffer) == name) {
1281     locref = loc;
1282     return true;
1283   }
1284   return false;
1285 }
1286 
1287 /// \brief Determines the active Scope associated with the given declaration
1288 /// context.
1289 ///
1290 /// This routine maps a declaration context to the active Scope object that
1291 /// represents that declaration context in the parser. It is typically used
1292 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1293 /// declarations) that injects a name for name-lookup purposes and, therefore,
1294 /// must update the Scope.
1295 ///
1296 /// \returns The scope corresponding to the given declaraion context, or NULL
1297 /// if no such scope is open.
1298 Scope *Sema::getScopeForContext(DeclContext *Ctx) {
1299 
1300   if (!Ctx)
1301     return nullptr;
1302 
1303   Ctx = Ctx->getPrimaryContext();
1304   for (Scope *S = getCurScope(); S; S = S->getParent()) {
1305     // Ignore scopes that cannot have declarations. This is important for
1306     // out-of-line definitions of static class members.
1307     if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
1308       if (DeclContext *Entity = S->getEntity())
1309         if (Ctx == Entity->getPrimaryContext())
1310           return S;
1311   }
1312 
1313   return nullptr;
1314 }
1315 
1316 /// \brief Enter a new function scope
1317 void Sema::PushFunctionScope() {
1318   if (FunctionScopes.size() == 1) {
1319     // Use the "top" function scope rather than having to allocate
1320     // memory for a new scope.
1321     FunctionScopes.back()->Clear();
1322     FunctionScopes.push_back(FunctionScopes.back());
1323     if (LangOpts.OpenMP)
1324       pushOpenMPFunctionRegion();
1325     return;
1326   }
1327 
1328   FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
1329   if (LangOpts.OpenMP)
1330     pushOpenMPFunctionRegion();
1331 }
1332 
1333 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
1334   FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
1335                                               BlockScope, Block));
1336 }
1337 
1338 LambdaScopeInfo *Sema::PushLambdaScope() {
1339   LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
1340   FunctionScopes.push_back(LSI);
1341   return LSI;
1342 }
1343 
1344 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
1345   if (LambdaScopeInfo *const LSI = getCurLambda()) {
1346     LSI->AutoTemplateParameterDepth = Depth;
1347     return;
1348   }
1349   llvm_unreachable(
1350       "Remove assertion if intentionally called in a non-lambda context.");
1351 }
1352 
1353 void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
1354                                 const Decl *D, const BlockExpr *blkExpr) {
1355   FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
1356   assert(!FunctionScopes.empty() && "mismatched push/pop!");
1357 
1358   if (LangOpts.OpenMP)
1359     popOpenMPFunctionRegion(Scope);
1360 
1361   // Issue any analysis-based warnings.
1362   if (WP && D)
1363     AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
1364   else
1365     for (const auto &PUD : Scope->PossiblyUnreachableDiags)
1366       Diag(PUD.Loc, PUD.PD);
1367 
1368   if (FunctionScopes.back() != Scope)
1369     delete Scope;
1370 }
1371 
1372 void Sema::PushCompoundScope() {
1373   getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo());
1374 }
1375 
1376 void Sema::PopCompoundScope() {
1377   FunctionScopeInfo *CurFunction = getCurFunction();
1378   assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
1379 
1380   CurFunction->CompoundScopes.pop_back();
1381 }
1382 
1383 /// \brief Determine whether any errors occurred within this function/method/
1384 /// block.
1385 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
1386   return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
1387 }
1388 
1389 BlockScopeInfo *Sema::getCurBlock() {
1390   if (FunctionScopes.empty())
1391     return nullptr;
1392 
1393   auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
1394   if (CurBSI && CurBSI->TheDecl &&
1395       !CurBSI->TheDecl->Encloses(CurContext)) {
1396     // We have switched contexts due to template instantiation.
1397     assert(!CodeSynthesisContexts.empty());
1398     return nullptr;
1399   }
1400 
1401   return CurBSI;
1402 }
1403 
1404 LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
1405   if (FunctionScopes.empty())
1406     return nullptr;
1407 
1408   auto I = FunctionScopes.rbegin();
1409   if (IgnoreNonLambdaCapturingScope) {
1410     auto E = FunctionScopes.rend();
1411     while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
1412       ++I;
1413     if (I == E)
1414       return nullptr;
1415   }
1416   auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
1417   if (CurLSI && CurLSI->Lambda &&
1418       !CurLSI->Lambda->Encloses(CurContext)) {
1419     // We have switched contexts due to template instantiation.
1420     assert(!CodeSynthesisContexts.empty());
1421     return nullptr;
1422   }
1423 
1424   return CurLSI;
1425 }
1426 // We have a generic lambda if we parsed auto parameters, or we have
1427 // an associated template parameter list.
1428 LambdaScopeInfo *Sema::getCurGenericLambda() {
1429   if (LambdaScopeInfo *LSI =  getCurLambda()) {
1430     return (LSI->AutoTemplateParams.size() ||
1431                     LSI->GLTemplateParameterList) ? LSI : nullptr;
1432   }
1433   return nullptr;
1434 }
1435 
1436 
1437 void Sema::ActOnComment(SourceRange Comment) {
1438   if (!LangOpts.RetainCommentsFromSystemHeaders &&
1439       SourceMgr.isInSystemHeader(Comment.getBegin()))
1440     return;
1441   RawComment RC(SourceMgr, Comment, false,
1442                 LangOpts.CommentOpts.ParseAllComments);
1443   if (RC.isAlmostTrailingComment()) {
1444     SourceRange MagicMarkerRange(Comment.getBegin(),
1445                                  Comment.getBegin().getLocWithOffset(3));
1446     StringRef MagicMarkerText;
1447     switch (RC.getKind()) {
1448     case RawComment::RCK_OrdinaryBCPL:
1449       MagicMarkerText = "///<";
1450       break;
1451     case RawComment::RCK_OrdinaryC:
1452       MagicMarkerText = "/**<";
1453       break;
1454     default:
1455       llvm_unreachable("if this is an almost Doxygen comment, "
1456                        "it should be ordinary");
1457     }
1458     Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
1459       FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
1460   }
1461   Context.addComment(RC);
1462 }
1463 
1464 // Pin this vtable to this file.
1465 ExternalSemaSource::~ExternalSemaSource() {}
1466 
1467 void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
1468 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
1469 
1470 void ExternalSemaSource::ReadKnownNamespaces(
1471                            SmallVectorImpl<NamespaceDecl *> &Namespaces) {
1472 }
1473 
1474 void ExternalSemaSource::ReadUndefinedButUsed(
1475     llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
1476 
1477 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
1478     FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
1479 
1480 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
1481   SourceLocation Loc = this->Loc;
1482   if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
1483   if (Loc.isValid()) {
1484     Loc.print(OS, S.getSourceManager());
1485     OS << ": ";
1486   }
1487   OS << Message;
1488 
1489   if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
1490     OS << " '";
1491     ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(), true);
1492     OS << "'";
1493   }
1494 
1495   OS << '\n';
1496 }
1497 
1498 /// \brief Figure out if an expression could be turned into a call.
1499 ///
1500 /// Use this when trying to recover from an error where the programmer may have
1501 /// written just the name of a function instead of actually calling it.
1502 ///
1503 /// \param E - The expression to examine.
1504 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1505 ///  with no arguments, this parameter is set to the type returned by such a
1506 ///  call; otherwise, it is set to an empty QualType.
1507 /// \param OverloadSet - If the expression is an overloaded function
1508 ///  name, this parameter is populated with the decls of the various overloads.
1509 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1510                          UnresolvedSetImpl &OverloadSet) {
1511   ZeroArgCallReturnTy = QualType();
1512   OverloadSet.clear();
1513 
1514   const OverloadExpr *Overloads = nullptr;
1515   bool IsMemExpr = false;
1516   if (E.getType() == Context.OverloadTy) {
1517     OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
1518 
1519     // Ignore overloads that are pointer-to-member constants.
1520     if (FR.HasFormOfMemberPointer)
1521       return false;
1522 
1523     Overloads = FR.Expression;
1524   } else if (E.getType() == Context.BoundMemberTy) {
1525     Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
1526     IsMemExpr = true;
1527   }
1528 
1529   bool Ambiguous = false;
1530 
1531   if (Overloads) {
1532     for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
1533          DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
1534       OverloadSet.addDecl(*it);
1535 
1536       // Check whether the function is a non-template, non-member which takes no
1537       // arguments.
1538       if (IsMemExpr)
1539         continue;
1540       if (const FunctionDecl *OverloadDecl
1541             = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
1542         if (OverloadDecl->getMinRequiredArguments() == 0) {
1543           if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) {
1544             ZeroArgCallReturnTy = QualType();
1545             Ambiguous = true;
1546           } else
1547             ZeroArgCallReturnTy = OverloadDecl->getReturnType();
1548         }
1549       }
1550     }
1551 
1552     // If it's not a member, use better machinery to try to resolve the call
1553     if (!IsMemExpr)
1554       return !ZeroArgCallReturnTy.isNull();
1555   }
1556 
1557   // Attempt to call the member with no arguments - this will correctly handle
1558   // member templates with defaults/deduction of template arguments, overloads
1559   // with default arguments, etc.
1560   if (IsMemExpr && !E.isTypeDependent()) {
1561     bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
1562     getDiagnostics().setSuppressAllDiagnostics(true);
1563     ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
1564                                              None, SourceLocation());
1565     getDiagnostics().setSuppressAllDiagnostics(Suppress);
1566     if (R.isUsable()) {
1567       ZeroArgCallReturnTy = R.get()->getType();
1568       return true;
1569     }
1570     return false;
1571   }
1572 
1573   if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
1574     if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
1575       if (Fun->getMinRequiredArguments() == 0)
1576         ZeroArgCallReturnTy = Fun->getReturnType();
1577       return true;
1578     }
1579   }
1580 
1581   // We don't have an expression that's convenient to get a FunctionDecl from,
1582   // but we can at least check if the type is "function of 0 arguments".
1583   QualType ExprTy = E.getType();
1584   const FunctionType *FunTy = nullptr;
1585   QualType PointeeTy = ExprTy->getPointeeType();
1586   if (!PointeeTy.isNull())
1587     FunTy = PointeeTy->getAs<FunctionType>();
1588   if (!FunTy)
1589     FunTy = ExprTy->getAs<FunctionType>();
1590 
1591   if (const FunctionProtoType *FPT =
1592       dyn_cast_or_null<FunctionProtoType>(FunTy)) {
1593     if (FPT->getNumParams() == 0)
1594       ZeroArgCallReturnTy = FunTy->getReturnType();
1595     return true;
1596   }
1597   return false;
1598 }
1599 
1600 /// \brief Give notes for a set of overloads.
1601 ///
1602 /// A companion to tryExprAsCall. In cases when the name that the programmer
1603 /// wrote was an overloaded function, we may be able to make some guesses about
1604 /// plausible overloads based on their return types; such guesses can be handed
1605 /// off to this method to be emitted as notes.
1606 ///
1607 /// \param Overloads - The overloads to note.
1608 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
1609 ///  -fshow-overloads=best, this is the location to attach to the note about too
1610 ///  many candidates. Typically this will be the location of the original
1611 ///  ill-formed expression.
1612 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
1613                           const SourceLocation FinalNoteLoc) {
1614   int ShownOverloads = 0;
1615   int SuppressedOverloads = 0;
1616   for (UnresolvedSetImpl::iterator It = Overloads.begin(),
1617        DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1618     // FIXME: Magic number for max shown overloads stolen from
1619     // OverloadCandidateSet::NoteCandidates.
1620     if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
1621       ++SuppressedOverloads;
1622       continue;
1623     }
1624 
1625     NamedDecl *Fn = (*It)->getUnderlyingDecl();
1626     S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
1627     ++ShownOverloads;
1628   }
1629 
1630   if (SuppressedOverloads)
1631     S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
1632       << SuppressedOverloads;
1633 }
1634 
1635 static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
1636                                    const UnresolvedSetImpl &Overloads,
1637                                    bool (*IsPlausibleResult)(QualType)) {
1638   if (!IsPlausibleResult)
1639     return noteOverloads(S, Overloads, Loc);
1640 
1641   UnresolvedSet<2> PlausibleOverloads;
1642   for (OverloadExpr::decls_iterator It = Overloads.begin(),
1643          DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1644     const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
1645     QualType OverloadResultTy = OverloadDecl->getReturnType();
1646     if (IsPlausibleResult(OverloadResultTy))
1647       PlausibleOverloads.addDecl(It.getDecl());
1648   }
1649   noteOverloads(S, PlausibleOverloads, Loc);
1650 }
1651 
1652 /// Determine whether the given expression can be called by just
1653 /// putting parentheses after it.  Notably, expressions with unary
1654 /// operators can't be because the unary operator will start parsing
1655 /// outside the call.
1656 static bool IsCallableWithAppend(Expr *E) {
1657   E = E->IgnoreImplicit();
1658   return (!isa<CStyleCastExpr>(E) &&
1659           !isa<UnaryOperator>(E) &&
1660           !isa<BinaryOperator>(E) &&
1661           !isa<CXXOperatorCallExpr>(E));
1662 }
1663 
1664 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1665                                 bool ForceComplain,
1666                                 bool (*IsPlausibleResult)(QualType)) {
1667   SourceLocation Loc = E.get()->getExprLoc();
1668   SourceRange Range = E.get()->getSourceRange();
1669 
1670   QualType ZeroArgCallTy;
1671   UnresolvedSet<4> Overloads;
1672   if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
1673       !ZeroArgCallTy.isNull() &&
1674       (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
1675     // At this point, we know E is potentially callable with 0
1676     // arguments and that it returns something of a reasonable type,
1677     // so we can emit a fixit and carry on pretending that E was
1678     // actually a CallExpr.
1679     SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
1680     Diag(Loc, PD)
1681       << /*zero-arg*/ 1 << Range
1682       << (IsCallableWithAppend(E.get())
1683           ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
1684           : FixItHint());
1685     notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1686 
1687     // FIXME: Try this before emitting the fixit, and suppress diagnostics
1688     // while doing so.
1689     E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None,
1690                       Range.getEnd().getLocWithOffset(1));
1691     return true;
1692   }
1693 
1694   if (!ForceComplain) return false;
1695 
1696   Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
1697   notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1698   E = ExprError();
1699   return true;
1700 }
1701 
1702 IdentifierInfo *Sema::getSuperIdentifier() const {
1703   if (!Ident_super)
1704     Ident_super = &Context.Idents.get("super");
1705   return Ident_super;
1706 }
1707 
1708 IdentifierInfo *Sema::getFloat128Identifier() const {
1709   if (!Ident___float128)
1710     Ident___float128 = &Context.Idents.get("__float128");
1711   return Ident___float128;
1712 }
1713 
1714 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
1715                                    CapturedRegionKind K) {
1716   CapturingScopeInfo *CSI = new CapturedRegionScopeInfo(
1717       getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
1718       (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0);
1719   CSI->ReturnType = Context.VoidTy;
1720   FunctionScopes.push_back(CSI);
1721 }
1722 
1723 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
1724   if (FunctionScopes.empty())
1725     return nullptr;
1726 
1727   return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
1728 }
1729 
1730 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
1731 Sema::getMismatchingDeleteExpressions() const {
1732   return DeleteExprs;
1733 }
1734 
1735 void Sema::setOpenCLExtensionForType(QualType T, llvm::StringRef ExtStr) {
1736   if (ExtStr.empty())
1737     return;
1738   llvm::SmallVector<StringRef, 1> Exts;
1739   ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
1740   auto CanT = T.getCanonicalType().getTypePtr();
1741   for (auto &I : Exts)
1742     OpenCLTypeExtMap[CanT].insert(I.str());
1743 }
1744 
1745 void Sema::setOpenCLExtensionForDecl(Decl *FD, StringRef ExtStr) {
1746   llvm::SmallVector<StringRef, 1> Exts;
1747   ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
1748   if (Exts.empty())
1749     return;
1750   for (auto &I : Exts)
1751     OpenCLDeclExtMap[FD].insert(I.str());
1752 }
1753 
1754 void Sema::setCurrentOpenCLExtensionForType(QualType T) {
1755   if (CurrOpenCLExtension.empty())
1756     return;
1757   setOpenCLExtensionForType(T, CurrOpenCLExtension);
1758 }
1759 
1760 void Sema::setCurrentOpenCLExtensionForDecl(Decl *D) {
1761   if (CurrOpenCLExtension.empty())
1762     return;
1763   setOpenCLExtensionForDecl(D, CurrOpenCLExtension);
1764 }
1765 
1766 bool Sema::isOpenCLDisabledDecl(Decl *FD) {
1767   auto Loc = OpenCLDeclExtMap.find(FD);
1768   if (Loc == OpenCLDeclExtMap.end())
1769     return false;
1770   for (auto &I : Loc->second) {
1771     if (!getOpenCLOptions().isEnabled(I))
1772       return true;
1773   }
1774   return false;
1775 }
1776 
1777 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
1778 bool Sema::checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc,
1779                                          DiagInfoT DiagInfo, MapT &Map,
1780                                          unsigned Selector,
1781                                          SourceRange SrcRange) {
1782   auto Loc = Map.find(D);
1783   if (Loc == Map.end())
1784     return false;
1785   bool Disabled = false;
1786   for (auto &I : Loc->second) {
1787     if (I != CurrOpenCLExtension && !getOpenCLOptions().isEnabled(I)) {
1788       Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo
1789                                                          << I << SrcRange;
1790       Disabled = true;
1791     }
1792   }
1793   return Disabled;
1794 }
1795 
1796 bool Sema::checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType QT) {
1797   // Check extensions for declared types.
1798   Decl *Decl = nullptr;
1799   if (auto TypedefT = dyn_cast<TypedefType>(QT.getTypePtr()))
1800     Decl = TypedefT->getDecl();
1801   if (auto TagT = dyn_cast<TagType>(QT.getCanonicalType().getTypePtr()))
1802     Decl = TagT->getDecl();
1803   auto Loc = DS.getTypeSpecTypeLoc();
1804   if (checkOpenCLDisabledTypeOrDecl(Decl, Loc, QT, OpenCLDeclExtMap))
1805     return true;
1806 
1807   // Check extensions for builtin types.
1808   return checkOpenCLDisabledTypeOrDecl(QT.getCanonicalType().getTypePtr(), Loc,
1809                                        QT, OpenCLTypeExtMap);
1810 }
1811 
1812 bool Sema::checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E) {
1813   IdentifierInfo *FnName = D.getIdentifier();
1814   return checkOpenCLDisabledTypeOrDecl(&D, E.getLocStart(), FnName,
1815                                        OpenCLDeclExtMap, 1, D.getSourceRange());
1816 }
1817