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