Bug Summary

File:clang/lib/Sema/SemaModule.cpp
Warning:line 579, column 3
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaModule.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-07-102640-14763-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaModule.cpp

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaModule.cpp

1//===--- SemaModule.cpp - Semantic Analysis for Modules -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for modules (C++ modules syntax,
10// Objective-C modules syntax, and Clang header modules).
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTConsumer.h"
15#include "clang/Lex/HeaderSearch.h"
16#include "clang/Lex/Preprocessor.h"
17#include "clang/Sema/SemaInternal.h"
18
19using namespace clang;
20using namespace sema;
21
22static void checkModuleImportContext(Sema &S, Module *M,
23 SourceLocation ImportLoc, DeclContext *DC,
24 bool FromInclude = false) {
25 SourceLocation ExternCLoc;
26
27 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
28 switch (LSD->getLanguage()) {
29 case LinkageSpecDecl::lang_c:
30 if (ExternCLoc.isInvalid())
31 ExternCLoc = LSD->getBeginLoc();
32 break;
33 case LinkageSpecDecl::lang_cxx:
34 case LinkageSpecDecl::lang_cxx_11:
35 case LinkageSpecDecl::lang_cxx_14:
36 break;
37 }
38 DC = LSD->getParent();
39 }
40
41 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
42 DC = DC->getParent();
43
44 if (!isa<TranslationUnitDecl>(DC)) {
45 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
46 ? diag::ext_module_import_not_at_top_level_noop
47 : diag::err_module_import_not_at_top_level_fatal)
48 << M->getFullModuleName() << DC;
49 S.Diag(cast<Decl>(DC)->getBeginLoc(),
50 diag::note_module_import_not_at_top_level)
51 << DC;
52 } else if (!M->IsExternC && ExternCLoc.isValid()) {
53 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
54 << M->getFullModuleName();
55 S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
56 }
57}
58
59Sema::DeclGroupPtrTy
60Sema::ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc) {
61 if (!ModuleScopes.empty() &&
62 ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment) {
63 // Under -std=c++2a -fmodules-ts, we can find an explicit 'module;' after
64 // already implicitly entering the global module fragment. That's OK.
65 assert(getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS &&((getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS
&& "unexpectedly encountered multiple global module fragment decls"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS && \"unexpectedly encountered multiple global module fragment decls\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaModule.cpp"
, 66, __PRETTY_FUNCTION__))
66 "unexpectedly encountered multiple global module fragment decls")((getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS
&& "unexpectedly encountered multiple global module fragment decls"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS && \"unexpectedly encountered multiple global module fragment decls\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaModule.cpp"
, 66, __PRETTY_FUNCTION__))
;
67 ModuleScopes.back().BeginLoc = ModuleLoc;
68 return nullptr;
69 }
70
71 // We start in the global module; all those declarations are implicitly
72 // module-private (though they do not have module linkage).
73 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
74 auto *GlobalModule = Map.createGlobalModuleFragmentForModuleUnit(ModuleLoc);
75 assert(GlobalModule && "module creation should not fail")((GlobalModule && "module creation should not fail") ?
static_cast<void> (0) : __assert_fail ("GlobalModule && \"module creation should not fail\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaModule.cpp"
, 75, __PRETTY_FUNCTION__))
;
76
77 // Enter the scope of the global module.
78 ModuleScopes.push_back({});
79 ModuleScopes.back().BeginLoc = ModuleLoc;
80 ModuleScopes.back().Module = GlobalModule;
81 VisibleModules.setVisible(GlobalModule, ModuleLoc);
82
83 // All declarations created from now on are owned by the global module.
84 auto *TU = Context.getTranslationUnitDecl();
85 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
86 TU->setLocalOwningModule(GlobalModule);
87
88 // FIXME: Consider creating an explicit representation of this declaration.
89 return nullptr;
90}
91
92Sema::DeclGroupPtrTy
93Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc,
94 ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl) {
95 assert((getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) &&(((getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules)
&& "should only have module decl in Modules TS or C++20"
) ? static_cast<void> (0) : __assert_fail ("(getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) && \"should only have module decl in Modules TS or C++20\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaModule.cpp"
, 96, __PRETTY_FUNCTION__))
96 "should only have module decl in Modules TS or C++20")(((getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules)
&& "should only have module decl in Modules TS or C++20"
) ? static_cast<void> (0) : __assert_fail ("(getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) && \"should only have module decl in Modules TS or C++20\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaModule.cpp"
, 96, __PRETTY_FUNCTION__))
;
97
98 // A module implementation unit requires that we are not compiling a module
99 // of any kind. A module interface unit requires that we are not compiling a
100 // module map.
101 switch (getLangOpts().getCompilingModule()) {
102 case LangOptions::CMK_None:
103 // It's OK to compile a module interface as a normal translation unit.
104 break;
105
106 case LangOptions::CMK_ModuleInterface:
107 if (MDK != ModuleDeclKind::Implementation)
108 break;
109
110 // We were asked to compile a module interface unit but this is a module
111 // implementation unit. That indicates the 'export' is missing.
112 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
113 << FixItHint::CreateInsertion(ModuleLoc, "export ");
114 MDK = ModuleDeclKind::Interface;
115 break;
116
117 case LangOptions::CMK_ModuleMap:
118 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
119 return nullptr;
120
121 case LangOptions::CMK_HeaderModule:
122 Diag(ModuleLoc, diag::err_module_decl_in_header_module);
123 return nullptr;
124 }
125
126 assert(ModuleScopes.size() <= 1 && "expected to be at global module scope")((ModuleScopes.size() <= 1 && "expected to be at global module scope"
) ? static_cast<void> (0) : __assert_fail ("ModuleScopes.size() <= 1 && \"expected to be at global module scope\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaModule.cpp"
, 126, __PRETTY_FUNCTION__))
;
127
128 // FIXME: Most of this work should be done by the preprocessor rather than
129 // here, in order to support macro import.
130
131 // Only one module-declaration is permitted per source file.
132 if (!ModuleScopes.empty() &&
133 ModuleScopes.back().Module->isModulePurview()) {
134 Diag(ModuleLoc, diag::err_module_redeclaration);
135 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
136 diag::note_prev_module_declaration);
137 return nullptr;
138 }
139
140 // Find the global module fragment we're adopting into this module, if any.
141 Module *GlobalModuleFragment = nullptr;
142 if (!ModuleScopes.empty() &&
143 ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment)
144 GlobalModuleFragment = ModuleScopes.back().Module;
145
146 // In C++20, the module-declaration must be the first declaration if there
147 // is no global module fragment.
148 if (getLangOpts().CPlusPlusModules && !IsFirstDecl && !GlobalModuleFragment) {
149 Diag(ModuleLoc, diag::err_module_decl_not_at_start);
150 SourceLocation BeginLoc =
151 ModuleScopes.empty()
152 ? SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID())
153 : ModuleScopes.back().BeginLoc;
154 if (BeginLoc.isValid()) {
155 Diag(BeginLoc, diag::note_global_module_introducer_missing)
156 << FixItHint::CreateInsertion(BeginLoc, "module;\n");
157 }
158 }
159
160 // Flatten the dots in a module name. Unlike Clang's hierarchical module map
161 // modules, the dots here are just another character that can appear in a
162 // module name.
163 std::string ModuleName;
164 for (auto &Piece : Path) {
165 if (!ModuleName.empty())
166 ModuleName += ".";
167 ModuleName += Piece.first->getName();
168 }
169
170 // If a module name was explicitly specified on the command line, it must be
171 // correct.
172 if (!getLangOpts().CurrentModule.empty() &&
173 getLangOpts().CurrentModule != ModuleName) {
174 Diag(Path.front().second, diag::err_current_module_name_mismatch)
175 << SourceRange(Path.front().second, Path.back().second)
176 << getLangOpts().CurrentModule;
177 return nullptr;
178 }
179 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
180
181 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
182 Module *Mod;
183
184 switch (MDK) {
185 case ModuleDeclKind::Interface: {
186 // We can't have parsed or imported a definition of this module or parsed a
187 // module map defining it already.
188 if (auto *M = Map.findModule(ModuleName)) {
189 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
190 if (M->DefinitionLoc.isValid())
191 Diag(M->DefinitionLoc, diag::note_prev_module_definition);
192 else if (const auto *FE = M->getASTFile())
193 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
194 << FE->getName();
195 Mod = M;
196 break;
197 }
198
199 // Create a Module for the module that we're defining.
200 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
201 GlobalModuleFragment);
202 assert(Mod && "module creation should not fail")((Mod && "module creation should not fail") ? static_cast
<void> (0) : __assert_fail ("Mod && \"module creation should not fail\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaModule.cpp"
, 202, __PRETTY_FUNCTION__))
;
203 break;
204 }
205
206 case ModuleDeclKind::Implementation:
207 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
208 PP.getIdentifierInfo(ModuleName), Path[0].second);
209 Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
210 Module::AllVisible,
211 /*IsInclusionDirective=*/false);
212 if (!Mod) {
213 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
214 // Create an empty module interface unit for error recovery.
215 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
216 GlobalModuleFragment);
217 }
218 break;
219 }
220
221 if (!GlobalModuleFragment) {
222 ModuleScopes.push_back({});
223 if (getLangOpts().ModulesLocalVisibility)
224 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
225 } else {
226 // We're done with the global module fragment now.
227 ActOnEndOfTranslationUnitFragment(TUFragmentKind::Global);
228 }
229
230 // Switch from the global module fragment (if any) to the named module.
231 ModuleScopes.back().BeginLoc = StartLoc;
232 ModuleScopes.back().Module = Mod;
233 ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
234 VisibleModules.setVisible(Mod, ModuleLoc);
235
236 // From now on, we have an owning module for all declarations we see.
237 // However, those declarations are module-private unless explicitly
238 // exported.
239 auto *TU = Context.getTranslationUnitDecl();
240 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
241 TU->setLocalOwningModule(Mod);
242
243 // FIXME: Create a ModuleDecl.
244 return nullptr;
245}
246
247Sema::DeclGroupPtrTy
248Sema::ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
249 SourceLocation PrivateLoc) {
250 // C++20 [basic.link]/2:
251 // A private-module-fragment shall appear only in a primary module
252 // interface unit.
253 switch (ModuleScopes.empty() ? Module::GlobalModuleFragment
254 : ModuleScopes.back().Module->Kind) {
255 case Module::ModuleMapModule:
256 case Module::GlobalModuleFragment:
257 Diag(PrivateLoc, diag::err_private_module_fragment_not_module);
258 return nullptr;
259
260 case Module::PrivateModuleFragment:
261 Diag(PrivateLoc, diag::err_private_module_fragment_redefined);
262 Diag(ModuleScopes.back().BeginLoc, diag::note_previous_definition);
263 return nullptr;
264
265 case Module::ModuleInterfaceUnit:
266 break;
267 }
268
269 if (!ModuleScopes.back().ModuleInterface) {
270 Diag(PrivateLoc, diag::err_private_module_fragment_not_module_interface);
271 Diag(ModuleScopes.back().BeginLoc,
272 diag::note_not_module_interface_add_export)
273 << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
274 return nullptr;
275 }
276
277 // FIXME: Check this isn't a module interface partition.
278 // FIXME: Check that this translation unit does not import any partitions;
279 // such imports would violate [basic.link]/2's "shall be the only module unit"
280 // restriction.
281
282 // We've finished the public fragment of the translation unit.
283 ActOnEndOfTranslationUnitFragment(TUFragmentKind::Normal);
284
285 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
286 Module *PrivateModuleFragment =
287 Map.createPrivateModuleFragmentForInterfaceUnit(
288 ModuleScopes.back().Module, PrivateLoc);
289 assert(PrivateModuleFragment && "module creation should not fail")((PrivateModuleFragment && "module creation should not fail"
) ? static_cast<void> (0) : __assert_fail ("PrivateModuleFragment && \"module creation should not fail\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaModule.cpp"
, 289, __PRETTY_FUNCTION__))
;
290
291 // Enter the scope of the private module fragment.
292 ModuleScopes.push_back({});
293 ModuleScopes.back().BeginLoc = ModuleLoc;
294 ModuleScopes.back().Module = PrivateModuleFragment;
295 ModuleScopes.back().ModuleInterface = true;
296 VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc);
297
298 // All declarations created from now on are scoped to the private module
299 // fragment (and are neither visible nor reachable in importers of the module
300 // interface).
301 auto *TU = Context.getTranslationUnitDecl();
302 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
303 TU->setLocalOwningModule(PrivateModuleFragment);
304
305 // FIXME: Consider creating an explicit representation of this declaration.
306 return nullptr;
307}
308
309DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
310 SourceLocation ExportLoc,
311 SourceLocation ImportLoc,
312 ModuleIdPath Path) {
313 // Flatten the module path for a Modules TS module name.
314 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
315 if (getLangOpts().ModulesTS) {
316 std::string ModuleName;
317 for (auto &Piece : Path) {
318 if (!ModuleName.empty())
319 ModuleName += ".";
320 ModuleName += Piece.first->getName();
321 }
322 ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
323 Path = ModuleIdPath(ModuleNameLoc);
324 }
325
326 Module *Mod =
327 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
328 /*IsInclusionDirective=*/false);
329 if (!Mod)
330 return true;
331
332 return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
333}
334
335/// Determine whether \p D is lexically within an export-declaration.
336static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
337 for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
338 if (auto *ED = dyn_cast<ExportDecl>(DC))
339 return ED;
340 return nullptr;
341}
342
343DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
344 SourceLocation ExportLoc,
345 SourceLocation ImportLoc,
346 Module *Mod, ModuleIdPath Path) {
347 VisibleModules.setVisible(Mod, ImportLoc);
348
349 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
350
351 // FIXME: we should support importing a submodule within a different submodule
352 // of the same top-level module. Until we do, make it an error rather than
353 // silently ignoring the import.
354 // Import-from-implementation is valid in the Modules TS. FIXME: Should we
355 // warn on a redundant import of the current module?
356 // FIXME: Import of a module from an implementation partition of the same
357 // module is permitted.
358 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
359 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) {
360 Diag(ImportLoc, getLangOpts().isCompilingModule()
361 ? diag::err_module_self_import
362 : diag::err_module_import_in_implementation)
363 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
364 }
365
366 SmallVector<SourceLocation, 2> IdentifierLocs;
367 Module *ModCheck = Mod;
368 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
369 // If we've run out of module parents, just drop the remaining identifiers.
370 // We need the length to be consistent.
371 if (!ModCheck)
372 break;
373 ModCheck = ModCheck->Parent;
374
375 IdentifierLocs.push_back(Path[I].second);
376 }
377
378 // If this was a header import, pad out with dummy locations.
379 // FIXME: Pass in and use the location of the header-name token in this case.
380 if (Path.empty()) {
381 for (; ModCheck; ModCheck = ModCheck->Parent) {
382 IdentifierLocs.push_back(SourceLocation());
383 }
384 }
385
386 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
387 Mod, IdentifierLocs);
388 CurContext->addDecl(Import);
389
390 // Sequence initialization of the imported module before that of the current
391 // module, if any.
392 if (!ModuleScopes.empty())
393 Context.addModuleInitializer(ModuleScopes.back().Module, Import);
394
395 // Re-export the module if needed.
396 if (!ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) {
397 if (ExportLoc.isValid() || getEnclosingExportDecl(Import))
398 getCurrentModule()->Exports.emplace_back(Mod, false);
399 } else if (ExportLoc.isValid()) {
400 Diag(ExportLoc, diag::err_export_not_in_module_interface);
401 }
402
403 return Import;
404}
405
406void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
407 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
408 BuildModuleInclude(DirectiveLoc, Mod);
409}
410
411void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
412 // Determine whether we're in the #include buffer for a module. The #includes
413 // in that buffer do not qualify as module imports; they're just an
414 // implementation detail of us building the module.
415 //
416 // FIXME: Should we even get ActOnModuleInclude calls for those?
417 bool IsInModuleIncludes =
418 TUKind == TU_Module &&
419 getSourceManager().isWrittenInMainFile(DirectiveLoc);
420
421 bool ShouldAddImport = !IsInModuleIncludes;
422
423 // If this module import was due to an inclusion directive, create an
424 // implicit import declaration to capture it in the AST.
425 if (ShouldAddImport) {
426 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
427 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
428 DirectiveLoc, Mod,
429 DirectiveLoc);
430 if (!ModuleScopes.empty())
431 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
432 TU->addDecl(ImportD);
433 Consumer.HandleImplicitImportDecl(ImportD);
434 }
435
436 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
437 VisibleModules.setVisible(Mod, DirectiveLoc);
438}
439
440void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
441 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
442
443 ModuleScopes.push_back({});
444 ModuleScopes.back().Module = Mod;
445 if (getLangOpts().ModulesLocalVisibility)
446 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
447
448 VisibleModules.setVisible(Mod, DirectiveLoc);
449
450 // The enclosing context is now part of this module.
451 // FIXME: Consider creating a child DeclContext to hold the entities
452 // lexically within the module.
453 if (getLangOpts().trackLocalOwningModule()) {
454 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
455 cast<Decl>(DC)->setModuleOwnershipKind(
456 getLangOpts().ModulesLocalVisibility
457 ? Decl::ModuleOwnershipKind::VisibleWhenImported
458 : Decl::ModuleOwnershipKind::Visible);
459 cast<Decl>(DC)->setLocalOwningModule(Mod);
460 }
461 }
462}
463
464void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
465 if (getLangOpts().ModulesLocalVisibility) {
466 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
467 // Leaving a module hides namespace names, so our visible namespace cache
468 // is now out of date.
469 VisibleNamespaceCache.clear();
470 }
471
472 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&((!ModuleScopes.empty() && ModuleScopes.back().Module
== Mod && "left the wrong module scope") ? static_cast
<void> (0) : __assert_fail ("!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && \"left the wrong module scope\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaModule.cpp"
, 473, __PRETTY_FUNCTION__))
473 "left the wrong module scope")((!ModuleScopes.empty() && ModuleScopes.back().Module
== Mod && "left the wrong module scope") ? static_cast
<void> (0) : __assert_fail ("!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && \"left the wrong module scope\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaModule.cpp"
, 473, __PRETTY_FUNCTION__))
;
474 ModuleScopes.pop_back();
475
476 // We got to the end of processing a local module. Create an
477 // ImportDecl as we would for an imported module.
478 FileID File = getSourceManager().getFileID(EomLoc);
479 SourceLocation DirectiveLoc;
480 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
481 // We reached the end of a #included module header. Use the #include loc.
482 assert(File != getSourceManager().getMainFileID() &&((File != getSourceManager().getMainFileID() && "end of submodule in main source file"
) ? static_cast<void> (0) : __assert_fail ("File != getSourceManager().getMainFileID() && \"end of submodule in main source file\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaModule.cpp"
, 483, __PRETTY_FUNCTION__))
483 "end of submodule in main source file")((File != getSourceManager().getMainFileID() && "end of submodule in main source file"
) ? static_cast<void> (0) : __assert_fail ("File != getSourceManager().getMainFileID() && \"end of submodule in main source file\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaModule.cpp"
, 483, __PRETTY_FUNCTION__))
;
484 DirectiveLoc = getSourceManager().getIncludeLoc(File);
485 } else {
486 // We reached an EOM pragma. Use the pragma location.
487 DirectiveLoc = EomLoc;
488 }
489 BuildModuleInclude(DirectiveLoc, Mod);
490
491 // Any further declarations are in whatever module we returned to.
492 if (getLangOpts().trackLocalOwningModule()) {
493 // The parser guarantees that this is the same context that we entered
494 // the module within.
495 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
496 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
497 if (!getCurrentModule())
498 cast<Decl>(DC)->setModuleOwnershipKind(
499 Decl::ModuleOwnershipKind::Unowned);
500 }
501 }
502}
503
504void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
505 Module *Mod) {
506 // Bail if we're not allowed to implicitly import a module here.
507 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
508 VisibleModules.isVisible(Mod))
509 return;
510
511 // Create the implicit import declaration.
512 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
513 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
514 Loc, Mod, Loc);
515 TU->addDecl(ImportD);
516 Consumer.HandleImplicitImportDecl(ImportD);
517
518 // Make the module visible.
519 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
520 VisibleModules.setVisible(Mod, Loc);
521}
522
523/// We have parsed the start of an export declaration, including the '{'
524/// (if present).
525Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
526 SourceLocation LBraceLoc) {
527 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
528
529 // Set this temporarily so we know the export-declaration was braced.
530 D->setRBraceLoc(LBraceLoc);
531
532 // C++2a [module.interface]p1:
533 // An export-declaration shall appear only [...] in the purview of a module
534 // interface unit. An export-declaration shall not appear directly or
535 // indirectly within [...] a private-module-fragment.
536 if (ModuleScopes.empty() || !ModuleScopes.back().Module->isModulePurview()) {
1
Taking true branch
537 Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
2
Calling '~SemaDiagnosticBuilder'
5
Returning from '~SemaDiagnosticBuilder'
538 } else if (!ModuleScopes.back().ModuleInterface) {
539 Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
540 Diag(ModuleScopes.back().BeginLoc,
541 diag::note_not_module_interface_add_export)
542 << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
543 } else if (ModuleScopes.back().Module->Kind ==
544 Module::PrivateModuleFragment) {
545 Diag(ExportLoc, diag::err_export_in_private_module_fragment);
546 Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
547 }
548
549 for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
6
Assuming pointer value is null
7
Loop condition is false. Execution continues on line 573
550 if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
551 // An export-declaration shall not appear directly or indirectly within
552 // an unnamed namespace [...]
553 if (ND->isAnonymousNamespace()) {
554 Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
555 Diag(ND->getLocation(), diag::note_anonymous_namespace);
556 // Don't diagnose internal-linkage declarations in this region.
557 D->setInvalidDecl();
558 break;
559 }
560
561 // A declaration is exported if it is [...] a namespace-definition
562 // that contains an exported declaration.
563 //
564 // Defer exporting the namespace until after we leave it, in order to
565 // avoid marking all subsequent declarations in the namespace as exported.
566 if (!DeferredExportedNamespaces.insert(ND).second)
567 break;
568 }
569 }
570
571 // [...] its declaration or declaration-seq shall not contain an
572 // export-declaration.
573 if (auto *ED = getEnclosingExportDecl(D)) {
8
Assuming 'ED' is null
9
Taking false branch
574 Diag(ExportLoc, diag::err_export_within_export);
575 if (ED->hasBraces())
576 Diag(ED->getLocation(), diag::note_export);
577 }
578
579 CurContext->addDecl(D);
10
Called C++ object pointer is null
580 PushDeclContext(S, D);
581 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
582 return D;
583}
584
585static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
586 SourceLocation BlockStart);
587
588namespace {
589enum class UnnamedDeclKind {
590 Empty,
591 StaticAssert,
592 Asm,
593 UsingDirective,
594 Context
595};
596}
597
598static llvm::Optional<UnnamedDeclKind> getUnnamedDeclKind(Decl *D) {
599 if (isa<EmptyDecl>(D))
600 return UnnamedDeclKind::Empty;
601 if (isa<StaticAssertDecl>(D))
602 return UnnamedDeclKind::StaticAssert;
603 if (isa<FileScopeAsmDecl>(D))
604 return UnnamedDeclKind::Asm;
605 if (isa<UsingDirectiveDecl>(D))
606 return UnnamedDeclKind::UsingDirective;
607 // Everything else either introduces one or more names or is ill-formed.
608 return llvm::None;
609}
610
611unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock) {
612 switch (UDK) {
613 case UnnamedDeclKind::Empty:
614 case UnnamedDeclKind::StaticAssert:
615 // Allow empty-declarations and static_asserts in an export block as an
616 // extension.
617 return InBlock ? diag::ext_export_no_name_block : diag::err_export_no_name;
618
619 case UnnamedDeclKind::UsingDirective:
620 // Allow exporting using-directives as an extension.
621 return diag::ext_export_using_directive;
622
623 case UnnamedDeclKind::Context:
624 // Allow exporting DeclContexts that transitively contain no declarations
625 // as an extension.
626 return diag::ext_export_no_names;
627
628 case UnnamedDeclKind::Asm:
629 return diag::err_export_no_name;
630 }
631 llvm_unreachable("unknown kind")::llvm::llvm_unreachable_internal("unknown kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaModule.cpp"
, 631)
;
632}
633
634static void diagExportedUnnamedDecl(Sema &S, UnnamedDeclKind UDK, Decl *D,
635 SourceLocation BlockStart) {
636 S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK, BlockStart.isValid()))
637 << (unsigned)UDK;
638 if (BlockStart.isValid())
639 S.Diag(BlockStart, diag::note_export);
640}
641
642/// Check that it's valid to export \p D.
643static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
644 // C++2a [module.interface]p3:
645 // An exported declaration shall declare at least one name
646 if (auto UDK = getUnnamedDeclKind(D))
647 diagExportedUnnamedDecl(S, *UDK, D, BlockStart);
648
649 // [...] shall not declare a name with internal linkage.
650 if (auto *ND = dyn_cast<NamedDecl>(D)) {
651 // Don't diagnose anonymous union objects; we'll diagnose their members
652 // instead.
653 if (ND->getDeclName() && ND->getFormalLinkage() == InternalLinkage) {
654 S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
655 if (BlockStart.isValid())
656 S.Diag(BlockStart, diag::note_export);
657 }
658 }
659
660 // C++2a [module.interface]p5:
661 // all entities to which all of the using-declarators ultimately refer
662 // shall have been introduced with a name having external linkage
663 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
664 NamedDecl *Target = USD->getUnderlyingDecl();
665 if (Target->getFormalLinkage() == InternalLinkage) {
666 S.Diag(USD->getLocation(), diag::err_export_using_internal) << Target;
667 S.Diag(Target->getLocation(), diag::note_using_decl_target);
668 if (BlockStart.isValid())
669 S.Diag(BlockStart, diag::note_export);
670 }
671 }
672
673 // Recurse into namespace-scope DeclContexts. (Only namespace-scope
674 // declarations are exported.)
675 if (auto *DC = dyn_cast<DeclContext>(D))
676 if (DC->getRedeclContext()->isFileContext() && !isa<EnumDecl>(D))
677 return checkExportedDeclContext(S, DC, BlockStart);
678 return false;
679}
680
681/// Check that it's valid to export all the declarations in \p DC.
682static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
683 SourceLocation BlockStart) {
684 bool AllUnnamed = true;
685 for (auto *D : DC->decls())
686 AllUnnamed &= checkExportedDecl(S, D, BlockStart);
687 return AllUnnamed;
688}
689
690/// Complete the definition of an export declaration.
691Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
692 auto *ED = cast<ExportDecl>(D);
693 if (RBraceLoc.isValid())
694 ED->setRBraceLoc(RBraceLoc);
695
696 PopDeclContext();
697
698 if (!D->isInvalidDecl()) {
699 SourceLocation BlockStart =
700 ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
701 for (auto *Child : ED->decls()) {
702 if (checkExportedDecl(*this, Child, BlockStart)) {
703 // If a top-level child is a linkage-spec declaration, it might contain
704 // no declarations (transitively), in which case it's ill-formed.
705 diagExportedUnnamedDecl(*this, UnnamedDeclKind::Context, Child,
706 BlockStart);
707 }
708 }
709 }
710
711 return D;
712}

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/Attr.h"
18#include "clang/AST/Availability.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExternalASTSource.h"
26#include "clang/AST/LocInfoType.h"
27#include "clang/AST/MangleNumberingContext.h"
28#include "clang/AST/NSAPI.h"
29#include "clang/AST/PrettyPrinter.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/AST/TypeOrdering.h"
33#include "clang/Basic/ExpressionTraits.h"
34#include "clang/Basic/Module.h"
35#include "clang/Basic/OpenMPKinds.h"
36#include "clang/Basic/PragmaKinds.h"
37#include "clang/Basic/Specifiers.h"
38#include "clang/Basic/TemplateKinds.h"
39#include "clang/Basic/TypeTraits.h"
40#include "clang/Sema/AnalysisBasedWarnings.h"
41#include "clang/Sema/CleanupInfo.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/ExternalSemaSource.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/ObjCMethodList.h"
46#include "clang/Sema/Ownership.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/TypoCorrection.h"
49#include "clang/Sema/Weak.h"
50#include "llvm/ADT/ArrayRef.h"
51#include "llvm/ADT/Optional.h"
52#include "llvm/ADT/SetVector.h"
53#include "llvm/ADT/SmallBitVector.h"
54#include "llvm/ADT/SmallPtrSet.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include <deque>
58#include <memory>
59#include <string>
60#include <tuple>
61#include <vector>
62
63namespace llvm {
64 class APSInt;
65 template <typename ValueT> struct DenseMapInfo;
66 template <typename ValueT, typename ValueInfoT> class DenseSet;
67 class SmallBitVector;
68 struct InlineAsmIdentifierInfo;
69}
70
71namespace clang {
72 class ADLResult;
73 class ASTConsumer;
74 class ASTContext;
75 class ASTMutationListener;
76 class ASTReader;
77 class ASTWriter;
78 class ArrayType;
79 class ParsedAttr;
80 class BindingDecl;
81 class BlockDecl;
82 class CapturedDecl;
83 class CXXBasePath;
84 class CXXBasePaths;
85 class CXXBindTemporaryExpr;
86 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
87 class CXXConstructorDecl;
88 class CXXConversionDecl;
89 class CXXDeleteExpr;
90 class CXXDestructorDecl;
91 class CXXFieldCollector;
92 class CXXMemberCallExpr;
93 class CXXMethodDecl;
94 class CXXScopeSpec;
95 class CXXTemporary;
96 class CXXTryStmt;
97 class CallExpr;
98 class ClassTemplateDecl;
99 class ClassTemplatePartialSpecializationDecl;
100 class ClassTemplateSpecializationDecl;
101 class VarTemplatePartialSpecializationDecl;
102 class CodeCompleteConsumer;
103 class CodeCompletionAllocator;
104 class CodeCompletionTUInfo;
105 class CodeCompletionResult;
106 class CoroutineBodyStmt;
107 class Decl;
108 class DeclAccessPair;
109 class DeclContext;
110 class DeclRefExpr;
111 class DeclaratorDecl;
112 class DeducedTemplateArgument;
113 class DependentDiagnostic;
114 class DesignatedInitExpr;
115 class Designation;
116 class EnableIfAttr;
117 class EnumConstantDecl;
118 class Expr;
119 class ExtVectorType;
120 class FormatAttr;
121 class FriendDecl;
122 class FunctionDecl;
123 class FunctionProtoType;
124 class FunctionTemplateDecl;
125 class ImplicitConversionSequence;
126 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
127 class InitListExpr;
128 class InitializationKind;
129 class InitializationSequence;
130 class InitializedEntity;
131 class IntegerLiteral;
132 class LabelStmt;
133 class LambdaExpr;
134 class LangOptions;
135 class LocalInstantiationScope;
136 class LookupResult;
137 class MacroInfo;
138 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
139 class ModuleLoader;
140 class MultiLevelTemplateArgumentList;
141 class NamedDecl;
142 class ObjCCategoryDecl;
143 class ObjCCategoryImplDecl;
144 class ObjCCompatibleAliasDecl;
145 class ObjCContainerDecl;
146 class ObjCImplDecl;
147 class ObjCImplementationDecl;
148 class ObjCInterfaceDecl;
149 class ObjCIvarDecl;
150 template <class T> class ObjCList;
151 class ObjCMessageExpr;
152 class ObjCMethodDecl;
153 class ObjCPropertyDecl;
154 class ObjCProtocolDecl;
155 class OMPThreadPrivateDecl;
156 class OMPRequiresDecl;
157 class OMPDeclareReductionDecl;
158 class OMPDeclareSimdDecl;
159 class OMPClause;
160 struct OMPVarListLocTy;
161 struct OverloadCandidate;
162 enum class OverloadCandidateParamOrder : char;
163 enum OverloadCandidateRewriteKind : unsigned;
164 class OverloadCandidateSet;
165 class OverloadExpr;
166 class ParenListExpr;
167 class ParmVarDecl;
168 class Preprocessor;
169 class PseudoDestructorTypeStorage;
170 class PseudoObjectExpr;
171 class QualType;
172 class StandardConversionSequence;
173 class Stmt;
174 class StringLiteral;
175 class SwitchStmt;
176 class TemplateArgument;
177 class TemplateArgumentList;
178 class TemplateArgumentLoc;
179 class TemplateDecl;
180 class TemplateInstantiationCallback;
181 class TemplateParameterList;
182 class TemplatePartialOrderingContext;
183 class TemplateTemplateParmDecl;
184 class Token;
185 class TypeAliasDecl;
186 class TypedefDecl;
187 class TypedefNameDecl;
188 class TypeLoc;
189 class TypoCorrectionConsumer;
190 class UnqualifiedId;
191 class UnresolvedLookupExpr;
192 class UnresolvedMemberExpr;
193 class UnresolvedSetImpl;
194 class UnresolvedSetIterator;
195 class UsingDecl;
196 class UsingShadowDecl;
197 class ValueDecl;
198 class VarDecl;
199 class VarTemplateSpecializationDecl;
200 class VisibilityAttr;
201 class VisibleDeclConsumer;
202 class IndirectFieldDecl;
203 struct DeductionFailureInfo;
204 class TemplateSpecCandidateSet;
205
206namespace sema {
207 class AccessedEntity;
208 class BlockScopeInfo;
209 class Capture;
210 class CapturedRegionScopeInfo;
211 class CapturingScopeInfo;
212 class CompoundScopeInfo;
213 class DelayedDiagnostic;
214 class DelayedDiagnosticPool;
215 class FunctionScopeInfo;
216 class LambdaScopeInfo;
217 class PossiblyUnreachableDiag;
218 class SemaPPCallbacks;
219 class TemplateDeductionInfo;
220}
221
222namespace threadSafety {
223 class BeforeSet;
224 void threadSafetyCleanup(BeforeSet* Cache);
225}
226
227// FIXME: No way to easily map from TemplateTypeParmTypes to
228// TemplateTypeParmDecls, so we have this horrible PointerUnion.
229typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
230 SourceLocation> UnexpandedParameterPack;
231
232/// Describes whether we've seen any nullability information for the given
233/// file.
234struct FileNullability {
235 /// The first pointer declarator (of any pointer kind) in the file that does
236 /// not have a corresponding nullability annotation.
237 SourceLocation PointerLoc;
238
239 /// The end location for the first pointer declarator in the file. Used for
240 /// placing fix-its.
241 SourceLocation PointerEndLoc;
242
243 /// Which kind of pointer declarator we saw.
244 uint8_t PointerKind;
245
246 /// Whether we saw any type nullability annotations in the given file.
247 bool SawTypeNullability = false;
248};
249
250/// A mapping from file IDs to a record of whether we've seen nullability
251/// information in that file.
252class FileNullabilityMap {
253 /// A mapping from file IDs to the nullability information for each file ID.
254 llvm::DenseMap<FileID, FileNullability> Map;
255
256 /// A single-element cache based on the file ID.
257 struct {
258 FileID File;
259 FileNullability Nullability;
260 } Cache;
261
262public:
263 FileNullability &operator[](FileID file) {
264 // Check the single-element cache.
265 if (file == Cache.File)
266 return Cache.Nullability;
267
268 // It's not in the single-element cache; flush the cache if we have one.
269 if (!Cache.File.isInvalid()) {
270 Map[Cache.File] = Cache.Nullability;
271 }
272
273 // Pull this entry into the cache.
274 Cache.File = file;
275 Cache.Nullability = Map[file];
276 return Cache.Nullability;
277 }
278};
279
280/// Keeps track of expected type during expression parsing. The type is tied to
281/// a particular token, all functions that update or consume the type take a
282/// start location of the token they are looking at as a parameter. This allows
283/// to avoid updating the type on hot paths in the parser.
284class PreferredTypeBuilder {
285public:
286 PreferredTypeBuilder() = default;
287 explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
288
289 void enterCondition(Sema &S, SourceLocation Tok);
290 void enterReturn(Sema &S, SourceLocation Tok);
291 void enterVariableInit(SourceLocation Tok, Decl *D);
292 /// Computing a type for the function argument may require running
293 /// overloading, so we postpone its computation until it is actually needed.
294 ///
295 /// Clients should be very careful when using this funciton, as it stores a
296 /// function_ref, clients should make sure all calls to get() with the same
297 /// location happen while function_ref is alive.
298 void enterFunctionArgument(SourceLocation Tok,
299 llvm::function_ref<QualType()> ComputeType);
300
301 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
302 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
303 SourceLocation OpLoc);
304 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
305 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
306 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
307 /// Handles all type casts, including C-style cast, C++ casts, etc.
308 void enterTypeCast(SourceLocation Tok, QualType CastType);
309
310 QualType get(SourceLocation Tok) const {
311 if (Tok != ExpectedLoc)
312 return QualType();
313 if (!Type.isNull())
314 return Type;
315 if (ComputeType)
316 return ComputeType();
317 return QualType();
318 }
319
320private:
321 /// Start position of a token for which we store expected type.
322 SourceLocation ExpectedLoc;
323 /// Expected type for a token starting at ExpectedLoc.
324 QualType Type;
325 /// A function to compute expected type at ExpectedLoc. It is only considered
326 /// if Type is null.
327 llvm::function_ref<QualType()> ComputeType;
328};
329
330/// Sema - This implements semantic analysis and AST building for C.
331class Sema {
332 Sema(const Sema &) = delete;
333 void operator=(const Sema &) = delete;
334
335 ///Source of additional semantic information.
336 ExternalSemaSource *ExternalSource;
337
338 ///Whether Sema has generated a multiplexer and has to delete it.
339 bool isMultiplexExternalSource;
340
341 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
342
343 bool isVisibleSlow(const NamedDecl *D);
344
345 /// Determine whether two declarations should be linked together, given that
346 /// the old declaration might not be visible and the new declaration might
347 /// not have external linkage.
348 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
349 const NamedDecl *New) {
350 if (isVisible(Old))
351 return true;
352 // See comment in below overload for why it's safe to compute the linkage
353 // of the new declaration here.
354 if (New->isExternallyDeclarable()) {
355 assert(Old->isExternallyDeclarable() &&((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 356, __PRETTY_FUNCTION__))
356 "should not have found a non-externally-declarable previous decl")((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 356, __PRETTY_FUNCTION__))
;
357 return true;
358 }
359 return false;
360 }
361 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
362
363 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
364 QualType ResultTy,
365 ArrayRef<QualType> Args);
366
367public:
368 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
369 typedef OpaquePtr<TemplateName> TemplateTy;
370 typedef OpaquePtr<QualType> TypeTy;
371
372 OpenCLOptions OpenCLFeatures;
373 FPOptions FPFeatures;
374
375 const LangOptions &LangOpts;
376 Preprocessor &PP;
377 ASTContext &Context;
378 ASTConsumer &Consumer;
379 DiagnosticsEngine &Diags;
380 SourceManager &SourceMgr;
381
382 /// Flag indicating whether or not to collect detailed statistics.
383 bool CollectStats;
384
385 /// Code-completion consumer.
386 CodeCompleteConsumer *CodeCompleter;
387
388 /// CurContext - This is the current declaration context of parsing.
389 DeclContext *CurContext;
390
391 /// Generally null except when we temporarily switch decl contexts,
392 /// like in \see ActOnObjCTemporaryExitContainerContext.
393 DeclContext *OriginalLexicalContext;
394
395 /// VAListTagName - The declaration name corresponding to __va_list_tag.
396 /// This is used as part of a hack to omit that class from ADL results.
397 DeclarationName VAListTagName;
398
399 bool MSStructPragmaOn; // True when \#pragma ms_struct on
400
401 /// Controls member pointer representation format under the MS ABI.
402 LangOptions::PragmaMSPointersToMembersKind
403 MSPointerToMemberRepresentationMethod;
404
405 /// Stack of active SEH __finally scopes. Can be empty.
406 SmallVector<Scope*, 2> CurrentSEHFinally;
407
408 /// Source location for newly created implicit MSInheritanceAttrs
409 SourceLocation ImplicitMSInheritanceAttrLoc;
410
411 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
412 /// `TransformTypos` in order to keep track of any TypoExprs that are created
413 /// recursively during typo correction and wipe them away if the correction
414 /// fails.
415 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
416
417 /// pragma clang section kind
418 enum PragmaClangSectionKind {
419 PCSK_Invalid = 0,
420 PCSK_BSS = 1,
421 PCSK_Data = 2,
422 PCSK_Rodata = 3,
423 PCSK_Text = 4,
424 PCSK_Relro = 5
425 };
426
427 enum PragmaClangSectionAction {
428 PCSA_Set = 0,
429 PCSA_Clear = 1
430 };
431
432 struct PragmaClangSection {
433 std::string SectionName;
434 bool Valid = false;
435 SourceLocation PragmaLocation;
436
437 void Act(SourceLocation PragmaLocation,
438 PragmaClangSectionAction Action,
439 StringLiteral* Name);
440 };
441
442 PragmaClangSection PragmaClangBSSSection;
443 PragmaClangSection PragmaClangDataSection;
444 PragmaClangSection PragmaClangRodataSection;
445 PragmaClangSection PragmaClangRelroSection;
446 PragmaClangSection PragmaClangTextSection;
447
448 enum PragmaMsStackAction {
449 PSK_Reset = 0x0, // #pragma ()
450 PSK_Set = 0x1, // #pragma (value)
451 PSK_Push = 0x2, // #pragma (push[, id])
452 PSK_Pop = 0x4, // #pragma (pop[, id])
453 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
454 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
455 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
456 };
457
458 template<typename ValueType>
459 struct PragmaStack {
460 struct Slot {
461 llvm::StringRef StackSlotLabel;
462 ValueType Value;
463 SourceLocation PragmaLocation;
464 SourceLocation PragmaPushLocation;
465 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
466 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
467 : StackSlotLabel(StackSlotLabel), Value(Value),
468 PragmaLocation(PragmaLocation),
469 PragmaPushLocation(PragmaPushLocation) {}
470 };
471 void Act(SourceLocation PragmaLocation,
472 PragmaMsStackAction Action,
473 llvm::StringRef StackSlotLabel,
474 ValueType Value);
475
476 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
477 // method body to restore the stacks on exit, so it works like this:
478 //
479 // struct S {
480 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
481 // void Method {}
482 // #pragma <name>(pop, InternalPragmaSlot)
483 // };
484 //
485 // It works even with #pragma vtordisp, although MSVC doesn't support
486 // #pragma vtordisp(push [, id], n)
487 // syntax.
488 //
489 // Push / pop a named sentinel slot.
490 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
491 assert((Action == PSK_Push || Action == PSK_Pop) &&(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 492, __PRETTY_FUNCTION__))
492 "Can only push / pop #pragma stack sentinels!")(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 492, __PRETTY_FUNCTION__))
;
493 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
494 }
495
496 // Constructors.
497 explicit PragmaStack(const ValueType &Default)
498 : DefaultValue(Default), CurrentValue(Default) {}
499
500 bool hasValue() const { return CurrentValue != DefaultValue; }
501
502 SmallVector<Slot, 2> Stack;
503 ValueType DefaultValue; // Value used for PSK_Reset action.
504 ValueType CurrentValue;
505 SourceLocation CurrentPragmaLocation;
506 };
507 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
508 // we shouldn't do so if they're in a module).
509
510 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
511 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
512 ///
513 /// 0: Suppress all vtordisps
514 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
515 /// structors
516 /// 2: Always insert vtordisps to support RTTI on partially constructed
517 /// objects
518 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
519 // #pragma pack.
520 // Sentinel to represent when the stack is set to mac68k alignment.
521 static const unsigned kMac68kAlignmentSentinel = ~0U;
522 PragmaStack<unsigned> PackStack;
523 // The current #pragma pack values and locations at each #include.
524 struct PackIncludeState {
525 unsigned CurrentValue;
526 SourceLocation CurrentPragmaLocation;
527 bool HasNonDefaultValue, ShouldWarnOnInclude;
528 };
529 SmallVector<PackIncludeState, 8> PackIncludeStack;
530 // Segment #pragmas.
531 PragmaStack<StringLiteral *> DataSegStack;
532 PragmaStack<StringLiteral *> BSSSegStack;
533 PragmaStack<StringLiteral *> ConstSegStack;
534 PragmaStack<StringLiteral *> CodeSegStack;
535
536 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
537 // Actions should be performed only if we enter / exit a C++ method body.
538 class PragmaStackSentinelRAII {
539 public:
540 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
541 ~PragmaStackSentinelRAII();
542
543 private:
544 Sema &S;
545 StringRef SlotLabel;
546 bool ShouldAct;
547 };
548
549 /// A mapping that describes the nullability we've seen in each header file.
550 FileNullabilityMap NullabilityMap;
551
552 /// Last section used with #pragma init_seg.
553 StringLiteral *CurInitSeg;
554 SourceLocation CurInitSegLoc;
555
556 /// VisContext - Manages the stack for \#pragma GCC visibility.
557 void *VisContext; // Really a "PragmaVisStack*"
558
559 /// This an attribute introduced by \#pragma clang attribute.
560 struct PragmaAttributeEntry {
561 SourceLocation Loc;
562 ParsedAttr *Attribute;
563 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
564 bool IsUsed;
565 };
566
567 /// A push'd group of PragmaAttributeEntries.
568 struct PragmaAttributeGroup {
569 /// The location of the push attribute.
570 SourceLocation Loc;
571 /// The namespace of this push group.
572 const IdentifierInfo *Namespace;
573 SmallVector<PragmaAttributeEntry, 2> Entries;
574 };
575
576 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
577
578 /// The declaration that is currently receiving an attribute from the
579 /// #pragma attribute stack.
580 const Decl *PragmaAttributeCurrentTargetDecl;
581
582 /// This represents the last location of a "#pragma clang optimize off"
583 /// directive if such a directive has not been closed by an "on" yet. If
584 /// optimizations are currently "on", this is set to an invalid location.
585 SourceLocation OptimizeOffPragmaLocation;
586
587 /// Flag indicating if Sema is building a recovery call expression.
588 ///
589 /// This flag is used to avoid building recovery call expressions
590 /// if Sema is already doing so, which would cause infinite recursions.
591 bool IsBuildingRecoveryCallExpr;
592
593 /// Used to control the generation of ExprWithCleanups.
594 CleanupInfo Cleanup;
595
596 /// ExprCleanupObjects - This is the stack of objects requiring
597 /// cleanup that are created by the current full expression. The
598 /// element type here is ExprWithCleanups::Object.
599 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
600
601 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
602 /// to a variable (constant) that may or may not be odr-used in this Expr, and
603 /// we won't know until all lvalue-to-rvalue and discarded value conversions
604 /// have been applied to all subexpressions of the enclosing full expression.
605 /// This is cleared at the end of each full expression.
606 using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
607 MaybeODRUseExprSet MaybeODRUseExprs;
608
609 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
610
611 /// Stack containing information about each of the nested
612 /// function, block, and method scopes that are currently active.
613 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
614
615 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
616 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
617 ExtVectorDeclsType;
618
619 /// ExtVectorDecls - This is a list all the extended vector types. This allows
620 /// us to associate a raw vector type with one of the ext_vector type names.
621 /// This is only necessary for issuing pretty diagnostics.
622 ExtVectorDeclsType ExtVectorDecls;
623
624 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
625 std::unique_ptr<CXXFieldCollector> FieldCollector;
626
627 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
628
629 /// Set containing all declared private fields that are not used.
630 NamedDeclSetType UnusedPrivateFields;
631
632 /// Set containing all typedefs that are likely unused.
633 llvm::SmallSetVector<const TypedefNameDecl *, 4>
634 UnusedLocalTypedefNameCandidates;
635
636 /// Delete-expressions to be analyzed at the end of translation unit
637 ///
638 /// This list contains class members, and locations of delete-expressions
639 /// that could not be proven as to whether they mismatch with new-expression
640 /// used in initializer of the field.
641 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
642 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
643 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
644
645 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
646
647 /// PureVirtualClassDiagSet - a set of class declarations which we have
648 /// emitted a list of pure virtual functions. Used to prevent emitting the
649 /// same list more than once.
650 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
651
652 /// ParsingInitForAutoVars - a set of declarations with auto types for which
653 /// we are currently parsing the initializer.
654 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
655
656 /// Look for a locally scoped extern "C" declaration by the given name.
657 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
658
659 typedef LazyVector<VarDecl *, ExternalSemaSource,
660 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
661 TentativeDefinitionsType;
662
663 /// All the tentative definitions encountered in the TU.
664 TentativeDefinitionsType TentativeDefinitions;
665
666 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
667 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
668 UnusedFileScopedDeclsType;
669
670 /// The set of file scoped decls seen so far that have not been used
671 /// and must warn if not used. Only contains the first declaration.
672 UnusedFileScopedDeclsType UnusedFileScopedDecls;
673
674 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
675 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
676 DelegatingCtorDeclsType;
677
678 /// All the delegating constructors seen so far in the file, used for
679 /// cycle detection at the end of the TU.
680 DelegatingCtorDeclsType DelegatingCtorDecls;
681
682 /// All the overriding functions seen during a class definition
683 /// that had their exception spec checks delayed, plus the overridden
684 /// function.
685 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
686 DelayedOverridingExceptionSpecChecks;
687
688 /// All the function redeclarations seen during a class definition that had
689 /// their exception spec checks delayed, plus the prior declaration they
690 /// should be checked against. Except during error recovery, the new decl
691 /// should always be a friend declaration, as that's the only valid way to
692 /// redeclare a special member before its class is complete.
693 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
694 DelayedEquivalentExceptionSpecChecks;
695
696 typedef llvm::MapVector<const FunctionDecl *,
697 std::unique_ptr<LateParsedTemplate>>
698 LateParsedTemplateMapT;
699 LateParsedTemplateMapT LateParsedTemplateMap;
700
701 /// Callback to the parser to parse templated functions when needed.
702 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
703 typedef void LateTemplateParserCleanupCB(void *P);
704 LateTemplateParserCB *LateTemplateParser;
705 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
706 void *OpaqueParser;
707
708 void SetLateTemplateParser(LateTemplateParserCB *LTP,
709 LateTemplateParserCleanupCB *LTPCleanup,
710 void *P) {
711 LateTemplateParser = LTP;
712 LateTemplateParserCleanup = LTPCleanup;
713 OpaqueParser = P;
714 }
715
716 class DelayedDiagnostics;
717
718 class DelayedDiagnosticsState {
719 sema::DelayedDiagnosticPool *SavedPool;
720 friend class Sema::DelayedDiagnostics;
721 };
722 typedef DelayedDiagnosticsState ParsingDeclState;
723 typedef DelayedDiagnosticsState ProcessingContextState;
724
725 /// A class which encapsulates the logic for delaying diagnostics
726 /// during parsing and other processing.
727 class DelayedDiagnostics {
728 /// The current pool of diagnostics into which delayed
729 /// diagnostics should go.
730 sema::DelayedDiagnosticPool *CurPool;
731
732 public:
733 DelayedDiagnostics() : CurPool(nullptr) {}
734
735 /// Adds a delayed diagnostic.
736 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
737
738 /// Determines whether diagnostics should be delayed.
739 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
740
741 /// Returns the current delayed-diagnostics pool.
742 sema::DelayedDiagnosticPool *getCurrentPool() const {
743 return CurPool;
744 }
745
746 /// Enter a new scope. Access and deprecation diagnostics will be
747 /// collected in this pool.
748 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
749 DelayedDiagnosticsState state;
750 state.SavedPool = CurPool;
751 CurPool = &pool;
752 return state;
753 }
754
755 /// Leave a delayed-diagnostic state that was previously pushed.
756 /// Do not emit any of the diagnostics. This is performed as part
757 /// of the bookkeeping of popping a pool "properly".
758 void popWithoutEmitting(DelayedDiagnosticsState state) {
759 CurPool = state.SavedPool;
760 }
761
762 /// Enter a new scope where access and deprecation diagnostics are
763 /// not delayed.
764 DelayedDiagnosticsState pushUndelayed() {
765 DelayedDiagnosticsState state;
766 state.SavedPool = CurPool;
767 CurPool = nullptr;
768 return state;
769 }
770
771 /// Undo a previous pushUndelayed().
772 void popUndelayed(DelayedDiagnosticsState state) {
773 assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 773, __PRETTY_FUNCTION__))
;
774 CurPool = state.SavedPool;
775 }
776 } DelayedDiagnostics;
777
778 /// A RAII object to temporarily push a declaration context.
779 class ContextRAII {
780 private:
781 Sema &S;
782 DeclContext *SavedContext;
783 ProcessingContextState SavedContextState;
784 QualType SavedCXXThisTypeOverride;
785
786 public:
787 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
788 : S(S), SavedContext(S.CurContext),
789 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
790 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
791 {
792 assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast
<void> (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 792, __PRETTY_FUNCTION__))
;
793 S.CurContext = ContextToPush;
794 if (NewThisContext)
795 S.CXXThisTypeOverride = QualType();
796 }
797
798 void pop() {
799 if (!SavedContext) return;
800 S.CurContext = SavedContext;
801 S.DelayedDiagnostics.popUndelayed(SavedContextState);
802 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
803 SavedContext = nullptr;
804 }
805
806 ~ContextRAII() {
807 pop();
808 }
809 };
810
811 /// Used to change context to isConstantEvaluated without pushing a heavy
812 /// ExpressionEvaluationContextRecord object.
813 bool isConstantEvaluatedOverride;
814
815 bool isConstantEvaluated() {
816 return ExprEvalContexts.back().isConstantEvaluated() ||
817 isConstantEvaluatedOverride;
818 }
819
820 /// RAII object to handle the state changes required to synthesize
821 /// a function body.
822 class SynthesizedFunctionScope {
823 Sema &S;
824 Sema::ContextRAII SavedContext;
825 bool PushedCodeSynthesisContext = false;
826
827 public:
828 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
829 : S(S), SavedContext(S, DC) {
830 S.PushFunctionScope();
831 S.PushExpressionEvaluationContext(
832 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
833 if (auto *FD = dyn_cast<FunctionDecl>(DC))
834 FD->setWillHaveBody(true);
835 else
836 assert(isa<ObjCMethodDecl>(DC))((isa<ObjCMethodDecl>(DC)) ? static_cast<void> (0
) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 836, __PRETTY_FUNCTION__))
;
837 }
838
839 void addContextNote(SourceLocation UseLoc) {
840 assert(!PushedCodeSynthesisContext)((!PushedCodeSynthesisContext) ? static_cast<void> (0) :
__assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 840, __PRETTY_FUNCTION__))
;
841
842 Sema::CodeSynthesisContext Ctx;
843 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
844 Ctx.PointOfInstantiation = UseLoc;
845 Ctx.Entity = cast<Decl>(S.CurContext);
846 S.pushCodeSynthesisContext(Ctx);
847
848 PushedCodeSynthesisContext = true;
849 }
850
851 ~SynthesizedFunctionScope() {
852 if (PushedCodeSynthesisContext)
853 S.popCodeSynthesisContext();
854 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
855 FD->setWillHaveBody(false);
856 S.PopExpressionEvaluationContext();
857 S.PopFunctionScopeInfo();
858 }
859 };
860
861 /// WeakUndeclaredIdentifiers - Identifiers contained in
862 /// \#pragma weak before declared. rare. may alias another
863 /// identifier, declared or undeclared
864 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
865
866 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
867 /// \#pragma redefine_extname before declared. Used in Solaris system headers
868 /// to define functions that occur in multiple standards to call the version
869 /// in the currently selected standard.
870 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
871
872
873 /// Load weak undeclared identifiers from the external source.
874 void LoadExternalWeakUndeclaredIdentifiers();
875
876 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
877 /// \#pragma weak during processing of other Decls.
878 /// I couldn't figure out a clean way to generate these in-line, so
879 /// we store them here and handle separately -- which is a hack.
880 /// It would be best to refactor this.
881 SmallVector<Decl*,2> WeakTopLevelDecl;
882
883 IdentifierResolver IdResolver;
884
885 /// Translation Unit Scope - useful to Objective-C actions that need
886 /// to lookup file scope declarations in the "ordinary" C decl namespace.
887 /// For example, user-defined classes, built-in "id" type, etc.
888 Scope *TUScope;
889
890 /// The C++ "std" namespace, where the standard library resides.
891 LazyDeclPtr StdNamespace;
892
893 /// The C++ "std::bad_alloc" class, which is defined by the C++
894 /// standard library.
895 LazyDeclPtr StdBadAlloc;
896
897 /// The C++ "std::align_val_t" enum class, which is defined by the C++
898 /// standard library.
899 LazyDeclPtr StdAlignValT;
900
901 /// The C++ "std::experimental" namespace, where the experimental parts
902 /// of the standard library resides.
903 NamespaceDecl *StdExperimentalNamespaceCache;
904
905 /// The C++ "std::initializer_list" template, which is defined in
906 /// \<initializer_list>.
907 ClassTemplateDecl *StdInitializerList;
908
909 /// The C++ "std::coroutine_traits" template, which is defined in
910 /// \<coroutine_traits>
911 ClassTemplateDecl *StdCoroutineTraitsCache;
912
913 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
914 RecordDecl *CXXTypeInfoDecl;
915
916 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
917 RecordDecl *MSVCGuidDecl;
918
919 /// Caches identifiers/selectors for NSFoundation APIs.
920 std::unique_ptr<NSAPI> NSAPIObj;
921
922 /// The declaration of the Objective-C NSNumber class.
923 ObjCInterfaceDecl *NSNumberDecl;
924
925 /// The declaration of the Objective-C NSValue class.
926 ObjCInterfaceDecl *NSValueDecl;
927
928 /// Pointer to NSNumber type (NSNumber *).
929 QualType NSNumberPointer;
930
931 /// Pointer to NSValue type (NSValue *).
932 QualType NSValuePointer;
933
934 /// The Objective-C NSNumber methods used to create NSNumber literals.
935 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
936
937 /// The declaration of the Objective-C NSString class.
938 ObjCInterfaceDecl *NSStringDecl;
939
940 /// Pointer to NSString type (NSString *).
941 QualType NSStringPointer;
942
943 /// The declaration of the stringWithUTF8String: method.
944 ObjCMethodDecl *StringWithUTF8StringMethod;
945
946 /// The declaration of the valueWithBytes:objCType: method.
947 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
948
949 /// The declaration of the Objective-C NSArray class.
950 ObjCInterfaceDecl *NSArrayDecl;
951
952 /// The declaration of the arrayWithObjects:count: method.
953 ObjCMethodDecl *ArrayWithObjectsMethod;
954
955 /// The declaration of the Objective-C NSDictionary class.
956 ObjCInterfaceDecl *NSDictionaryDecl;
957
958 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
959 ObjCMethodDecl *DictionaryWithObjectsMethod;
960
961 /// id<NSCopying> type.
962 QualType QIDNSCopying;
963
964 /// will hold 'respondsToSelector:'
965 Selector RespondsToSelectorSel;
966
967 /// A flag to remember whether the implicit forms of operator new and delete
968 /// have been declared.
969 bool GlobalNewDeleteDeclared;
970
971 /// A flag to indicate that we're in a context that permits abstract
972 /// references to fields. This is really a
973 bool AllowAbstractFieldReference;
974
975 /// Describes how the expressions currently being parsed are
976 /// evaluated at run-time, if at all.
977 enum class ExpressionEvaluationContext {
978 /// The current expression and its subexpressions occur within an
979 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
980 /// \c sizeof, where the type of the expression may be significant but
981 /// no code will be generated to evaluate the value of the expression at
982 /// run time.
983 Unevaluated,
984
985 /// The current expression occurs within a braced-init-list within
986 /// an unevaluated operand. This is mostly like a regular unevaluated
987 /// context, except that we still instantiate constexpr functions that are
988 /// referenced here so that we can perform narrowing checks correctly.
989 UnevaluatedList,
990
991 /// The current expression occurs within a discarded statement.
992 /// This behaves largely similarly to an unevaluated operand in preventing
993 /// definitions from being required, but not in other ways.
994 DiscardedStatement,
995
996 /// The current expression occurs within an unevaluated
997 /// operand that unconditionally permits abstract references to
998 /// fields, such as a SIZE operator in MS-style inline assembly.
999 UnevaluatedAbstract,
1000
1001 /// The current context is "potentially evaluated" in C++11 terms,
1002 /// but the expression is evaluated at compile-time (like the values of
1003 /// cases in a switch statement).
1004 ConstantEvaluated,
1005
1006 /// The current expression is potentially evaluated at run time,
1007 /// which means that code may be generated to evaluate the value of the
1008 /// expression at run time.
1009 PotentiallyEvaluated,
1010
1011 /// The current expression is potentially evaluated, but any
1012 /// declarations referenced inside that expression are only used if
1013 /// in fact the current expression is used.
1014 ///
1015 /// This value is used when parsing default function arguments, for which
1016 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1017 /// through varargs) but do not want to mark declarations as "referenced"
1018 /// until the default argument is used.
1019 PotentiallyEvaluatedIfUsed
1020 };
1021
1022 /// Data structure used to record current or nested
1023 /// expression evaluation contexts.
1024 struct ExpressionEvaluationContextRecord {
1025 /// The expression evaluation context.
1026 ExpressionEvaluationContext Context;
1027
1028 /// Whether the enclosing context needed a cleanup.
1029 CleanupInfo ParentCleanup;
1030
1031 /// Whether we are in a decltype expression.
1032 bool IsDecltype;
1033
1034 /// The number of active cleanup objects when we entered
1035 /// this expression evaluation context.
1036 unsigned NumCleanupObjects;
1037
1038 /// The number of typos encountered during this expression evaluation
1039 /// context (i.e. the number of TypoExprs created).
1040 unsigned NumTypos;
1041
1042 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1043
1044 /// The lambdas that are present within this context, if it
1045 /// is indeed an unevaluated context.
1046 SmallVector<LambdaExpr *, 2> Lambdas;
1047
1048 /// The declaration that provides context for lambda expressions
1049 /// and block literals if the normal declaration context does not
1050 /// suffice, e.g., in a default function argument.
1051 Decl *ManglingContextDecl;
1052
1053 /// If we are processing a decltype type, a set of call expressions
1054 /// for which we have deferred checking the completeness of the return type.
1055 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1056
1057 /// If we are processing a decltype type, a set of temporary binding
1058 /// expressions for which we have deferred checking the destructor.
1059 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1060
1061 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1062
1063 /// Expressions appearing as the LHS of a volatile assignment in this
1064 /// context. We produce a warning for these when popping the context if
1065 /// they are not discarded-value expressions nor unevaluated operands.
1066 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1067
1068 /// \brief Describes whether we are in an expression constext which we have
1069 /// to handle differently.
1070 enum ExpressionKind {
1071 EK_Decltype, EK_TemplateArgument, EK_Other
1072 } ExprContext;
1073
1074 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1075 unsigned NumCleanupObjects,
1076 CleanupInfo ParentCleanup,
1077 Decl *ManglingContextDecl,
1078 ExpressionKind ExprContext)
1079 : Context(Context), ParentCleanup(ParentCleanup),
1080 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1081 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1082
1083 bool isUnevaluated() const {
1084 return Context == ExpressionEvaluationContext::Unevaluated ||
1085 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1086 Context == ExpressionEvaluationContext::UnevaluatedList;
1087 }
1088 bool isConstantEvaluated() const {
1089 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1090 }
1091 };
1092
1093 /// A stack of expression evaluation contexts.
1094 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1095
1096 /// Emit a warning for all pending noderef expressions that we recorded.
1097 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1098
1099 /// Compute the mangling number context for a lambda expression or
1100 /// block literal. Also return the extra mangling decl if any.
1101 ///
1102 /// \param DC - The DeclContext containing the lambda expression or
1103 /// block literal.
1104 std::tuple<MangleNumberingContext *, Decl *>
1105 getCurrentMangleNumberContext(const DeclContext *DC);
1106
1107
1108 /// SpecialMemberOverloadResult - The overloading result for a special member
1109 /// function.
1110 ///
1111 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1112 /// integer are used to determine whether overload resolution succeeded.
1113 class SpecialMemberOverloadResult {
1114 public:
1115 enum Kind {
1116 NoMemberOrDeleted,
1117 Ambiguous,
1118 Success
1119 };
1120
1121 private:
1122 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1123
1124 public:
1125 SpecialMemberOverloadResult() : Pair() {}
1126 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1127 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1128
1129 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1130 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1131
1132 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1133 void setKind(Kind K) { Pair.setInt(K); }
1134 };
1135
1136 class SpecialMemberOverloadResultEntry
1137 : public llvm::FastFoldingSetNode,
1138 public SpecialMemberOverloadResult {
1139 public:
1140 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1141 : FastFoldingSetNode(ID)
1142 {}
1143 };
1144
1145 /// A cache of special member function overload resolution results
1146 /// for C++ records.
1147 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1148
1149 /// A cache of the flags available in enumerations with the flag_bits
1150 /// attribute.
1151 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1152
1153 /// The kind of translation unit we are processing.
1154 ///
1155 /// When we're processing a complete translation unit, Sema will perform
1156 /// end-of-translation-unit semantic tasks (such as creating
1157 /// initializers for tentative definitions in C) once parsing has
1158 /// completed. Modules and precompiled headers perform different kinds of
1159 /// checks.
1160 TranslationUnitKind TUKind;
1161
1162 llvm::BumpPtrAllocator BumpAlloc;
1163
1164 /// The number of SFINAE diagnostics that have been trapped.
1165 unsigned NumSFINAEErrors;
1166
1167 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1168 UnparsedDefaultArgInstantiationsMap;
1169
1170 /// A mapping from parameters with unparsed default arguments to the
1171 /// set of instantiations of each parameter.
1172 ///
1173 /// This mapping is a temporary data structure used when parsing
1174 /// nested class templates or nested classes of class templates,
1175 /// where we might end up instantiating an inner class before the
1176 /// default arguments of its methods have been parsed.
1177 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1178
1179 // Contains the locations of the beginning of unparsed default
1180 // argument locations.
1181 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1182
1183 /// UndefinedInternals - all the used, undefined objects which require a
1184 /// definition in this translation unit.
1185 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1186
1187 /// Determine if VD, which must be a variable or function, is an external
1188 /// symbol that nonetheless can't be referenced from outside this translation
1189 /// unit because its type has no linkage and it's not extern "C".
1190 bool isExternalWithNoLinkageType(ValueDecl *VD);
1191
1192 /// Obtain a sorted list of functions that are undefined but ODR-used.
1193 void getUndefinedButUsed(
1194 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1195
1196 /// Retrieves list of suspicious delete-expressions that will be checked at
1197 /// the end of translation unit.
1198 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1199 getMismatchingDeleteExpressions() const;
1200
1201 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1202 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1203
1204 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1205 /// We need to maintain a list, since selectors can have differing signatures
1206 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1207 /// of selectors are "overloaded").
1208 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1209 /// methods inside categories with a particular selector.
1210 GlobalMethodPool MethodPool;
1211
1212 /// Method selectors used in a \@selector expression. Used for implementation
1213 /// of -Wselector.
1214 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1215
1216 /// List of SourceLocations where 'self' is implicitly retained inside a
1217 /// block.
1218 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1219 ImplicitlyRetainedSelfLocs;
1220
1221 /// Kinds of C++ special members.
1222 enum CXXSpecialMember {
1223 CXXDefaultConstructor,
1224 CXXCopyConstructor,
1225 CXXMoveConstructor,
1226 CXXCopyAssignment,
1227 CXXMoveAssignment,
1228 CXXDestructor,
1229 CXXInvalid
1230 };
1231
1232 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1233 SpecialMemberDecl;
1234
1235 /// The C++ special members which we are currently in the process of
1236 /// declaring. If this process recursively triggers the declaration of the
1237 /// same special member, we should act as if it is not yet declared.
1238 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1239
1240 /// Kinds of defaulted comparison operator functions.
1241 enum class DefaultedComparisonKind : unsigned char {
1242 /// This is not a defaultable comparison operator.
1243 None,
1244 /// This is an operator== that should be implemented as a series of
1245 /// subobject comparisons.
1246 Equal,
1247 /// This is an operator<=> that should be implemented as a series of
1248 /// subobject comparisons.
1249 ThreeWay,
1250 /// This is an operator!= that should be implemented as a rewrite in terms
1251 /// of a == comparison.
1252 NotEqual,
1253 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1254 /// terms of a <=> comparison.
1255 Relational,
1256 };
1257
1258 /// The function definitions which were renamed as part of typo-correction
1259 /// to match their respective declarations. We want to keep track of them
1260 /// to ensure that we don't emit a "redefinition" error if we encounter a
1261 /// correctly named definition after the renamed definition.
1262 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1263
1264 /// Stack of types that correspond to the parameter entities that are
1265 /// currently being copy-initialized. Can be empty.
1266 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1267
1268 void ReadMethodPool(Selector Sel);
1269 void updateOutOfDateSelector(Selector Sel);
1270
1271 /// Private Helper predicate to check for 'self'.
1272 bool isSelfExpr(Expr *RExpr);
1273 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1274
1275 /// Cause the active diagnostic on the DiagosticsEngine to be
1276 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1277 /// should not be used elsewhere.
1278 void EmitCurrentDiagnostic(unsigned DiagID);
1279
1280 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1281 /// statements.
1282 class FPContractStateRAII {
1283 public:
1284 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1285 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1286
1287 private:
1288 Sema& S;
1289 FPOptions OldFPFeaturesState;
1290 };
1291
1292 void addImplicitTypedef(StringRef Name, QualType T);
1293
1294 bool WarnedStackExhausted = false;
1295
1296public:
1297 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1298 TranslationUnitKind TUKind = TU_Complete,
1299 CodeCompleteConsumer *CompletionConsumer = nullptr);
1300 ~Sema();
1301
1302 /// Perform initialization that occurs after the parser has been
1303 /// initialized but before it parses anything.
1304 void Initialize();
1305
1306 const LangOptions &getLangOpts() const { return LangOpts; }
1307 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1308 FPOptions &getFPOptions() { return FPFeatures; }
1309
1310 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1311 SourceManager &getSourceManager() const { return SourceMgr; }
1312 Preprocessor &getPreprocessor() const { return PP; }
1313 ASTContext &getASTContext() const { return Context; }
1314 ASTConsumer &getASTConsumer() const { return Consumer; }
1315 ASTMutationListener *getASTMutationListener() const;
1316 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1317
1318 ///Registers an external source. If an external source already exists,
1319 /// creates a multiplex external source and appends to it.
1320 ///
1321 ///\param[in] E - A non-null external sema source.
1322 ///
1323 void addExternalSource(ExternalSemaSource *E);
1324
1325 void PrintStats() const;
1326
1327 /// Warn that the stack is nearly exhausted.
1328 void warnStackExhausted(SourceLocation Loc);
1329
1330 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1331 /// guaranteed). Produces a warning if we're low on stack space and allocates
1332 /// more in that case. Use this in code that may recurse deeply (for example,
1333 /// in template instantiation) to avoid stack overflow.
1334 void runWithSufficientStackSpace(SourceLocation Loc,
1335 llvm::function_ref<void()> Fn);
1336
1337 /// Helper class that creates diagnostics with optional
1338 /// template instantiation stacks.
1339 ///
1340 /// This class provides a wrapper around the basic DiagnosticBuilder
1341 /// class that emits diagnostics. SemaDiagnosticBuilder is
1342 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1343 /// does) and, if the diagnostic comes from inside a template
1344 /// instantiation, printing the template instantiation stack as
1345 /// well.
1346 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1347 Sema &SemaRef;
1348 unsigned DiagID;
1349
1350 public:
1351 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1352 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1353
1354 // This is a cunning lie. DiagnosticBuilder actually performs move
1355 // construction in its copy constructor (but due to varied uses, it's not
1356 // possible to conveniently express this as actual move construction). So
1357 // the default copy ctor here is fine, because the base class disables the
1358 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1359 // in that case anwyay.
1360 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1361
1362 ~SemaDiagnosticBuilder() {
1363 // If we aren't active, there is nothing to do.
1364 if (!isActive()) return;
3
Taking false branch
1365
1366 // Otherwise, we need to emit the diagnostic. First flush the underlying
1367 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1368 // won't emit the diagnostic in its own destructor.
1369 //
1370 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1371 // do its own needless checks to see if the diagnostic needs to be
1372 // emitted. However, because we take care to ensure that the builder
1373 // objects never escape, a sufficiently smart compiler will be able to
1374 // eliminate that code.
1375 FlushCounts();
1376 Clear();
1377
1378 // Dispatch to Sema to emit the diagnostic.
1379 SemaRef.EmitCurrentDiagnostic(DiagID);
4
Value assigned to field 'CurContext'
1380 }
1381
1382 /// Teach operator<< to produce an object of the correct type.
1383 template<typename T>
1384 friend const SemaDiagnosticBuilder &operator<<(
1385 const SemaDiagnosticBuilder &Diag, const T &Value) {
1386 const DiagnosticBuilder &BaseDiag = Diag;
1387 BaseDiag << Value;
1388 return Diag;
1389 }
1390 };
1391
1392 /// Emit a diagnostic.
1393 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1394 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1395 return SemaDiagnosticBuilder(DB, *this, DiagID);
1396 }
1397
1398 /// Emit a partial diagnostic.
1399 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1400
1401 /// Build a partial diagnostic.
1402 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1403
1404 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1405
1406 /// Get a string to suggest for zero-initialization of a type.
1407 std::string
1408 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1409 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1410
1411 /// Calls \c Lexer::getLocForEndOfToken()
1412 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1413
1414 /// Retrieve the module loader associated with the preprocessor.
1415 ModuleLoader &getModuleLoader() const;
1416
1417 void emitAndClearUnusedLocalTypedefWarnings();
1418
1419 enum TUFragmentKind {
1420 /// The global module fragment, between 'module;' and a module-declaration.
1421 Global,
1422 /// A normal translation unit fragment. For a non-module unit, this is the
1423 /// entire translation unit. Otherwise, it runs from the module-declaration
1424 /// to the private-module-fragment (if any) or the end of the TU (if not).
1425 Normal,
1426 /// The private module fragment, between 'module :private;' and the end of
1427 /// the translation unit.
1428 Private
1429 };
1430
1431 void ActOnStartOfTranslationUnit();
1432 void ActOnEndOfTranslationUnit();
1433 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1434
1435 void CheckDelegatingCtorCycles();
1436
1437 Scope *getScopeForContext(DeclContext *Ctx);
1438
1439 void PushFunctionScope();
1440 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1441 sema::LambdaScopeInfo *PushLambdaScope();
1442
1443 /// This is used to inform Sema what the current TemplateParameterDepth
1444 /// is during Parsing. Currently it is used to pass on the depth
1445 /// when parsing generic lambda 'auto' parameters.
1446 void RecordParsingTemplateParameterDepth(unsigned Depth);
1447
1448 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1449 RecordDecl *RD, CapturedRegionKind K,
1450 unsigned OpenMPCaptureLevel = 0);
1451
1452 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1453 /// time after they've been popped.
1454 class PoppedFunctionScopeDeleter {
1455 Sema *Self;
1456
1457 public:
1458 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1459 void operator()(sema::FunctionScopeInfo *Scope) const;
1460 };
1461
1462 using PoppedFunctionScopePtr =
1463 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1464
1465 PoppedFunctionScopePtr
1466 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1467 const Decl *D = nullptr,
1468 QualType BlockType = QualType());
1469
1470 sema::FunctionScopeInfo *getCurFunction() const {
1471 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1472 }
1473
1474 sema::FunctionScopeInfo *getEnclosingFunction() const;
1475
1476 void setFunctionHasBranchIntoScope();
1477 void setFunctionHasBranchProtectedScope();
1478 void setFunctionHasIndirectGoto();
1479
1480 void PushCompoundScope(bool IsStmtExpr);
1481 void PopCompoundScope();
1482
1483 sema::CompoundScopeInfo &getCurCompoundScope() const;
1484
1485 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1486
1487 /// Retrieve the current block, if any.
1488 sema::BlockScopeInfo *getCurBlock();
1489
1490 /// Get the innermost lambda enclosing the current location, if any. This
1491 /// looks through intervening non-lambda scopes such as local functions and
1492 /// blocks.
1493 sema::LambdaScopeInfo *getEnclosingLambda() const;
1494
1495 /// Retrieve the current lambda scope info, if any.
1496 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1497 /// lambda scope info ignoring all inner capturing scopes that are not
1498 /// lambda scopes.
1499 sema::LambdaScopeInfo *
1500 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1501
1502 /// Retrieve the current generic lambda info, if any.
1503 sema::LambdaScopeInfo *getCurGenericLambda();
1504
1505 /// Retrieve the current captured region, if any.
1506 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1507
1508 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1509 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1510
1511 void ActOnComment(SourceRange Comment);
1512
1513 //===--------------------------------------------------------------------===//
1514 // Type Analysis / Processing: SemaType.cpp.
1515 //
1516
1517 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1518 const DeclSpec *DS = nullptr);
1519 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1520 const DeclSpec *DS = nullptr);
1521 QualType BuildPointerType(QualType T,
1522 SourceLocation Loc, DeclarationName Entity);
1523 QualType BuildReferenceType(QualType T, bool LValueRef,
1524 SourceLocation Loc, DeclarationName Entity);
1525 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1526 Expr *ArraySize, unsigned Quals,
1527 SourceRange Brackets, DeclarationName Entity);
1528 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1529 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1530 SourceLocation AttrLoc);
1531 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1532 SourceLocation AttrLoc);
1533
1534 /// Same as above, but constructs the AddressSpace index if not provided.
1535 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1536 SourceLocation AttrLoc);
1537
1538 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1539
1540 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1541
1542 /// Build a function type.
1543 ///
1544 /// This routine checks the function type according to C++ rules and
1545 /// under the assumption that the result type and parameter types have
1546 /// just been instantiated from a template. It therefore duplicates
1547 /// some of the behavior of GetTypeForDeclarator, but in a much
1548 /// simpler form that is only suitable for this narrow use case.
1549 ///
1550 /// \param T The return type of the function.
1551 ///
1552 /// \param ParamTypes The parameter types of the function. This array
1553 /// will be modified to account for adjustments to the types of the
1554 /// function parameters.
1555 ///
1556 /// \param Loc The location of the entity whose type involves this
1557 /// function type or, if there is no such entity, the location of the
1558 /// type that will have function type.
1559 ///
1560 /// \param Entity The name of the entity that involves the function
1561 /// type, if known.
1562 ///
1563 /// \param EPI Extra information about the function type. Usually this will
1564 /// be taken from an existing function with the same prototype.
1565 ///
1566 /// \returns A suitable function type, if there are no errors. The
1567 /// unqualified type will always be a FunctionProtoType.
1568 /// Otherwise, returns a NULL type.
1569 QualType BuildFunctionType(QualType T,
1570 MutableArrayRef<QualType> ParamTypes,
1571 SourceLocation Loc, DeclarationName Entity,
1572 const FunctionProtoType::ExtProtoInfo &EPI);
1573
1574 QualType BuildMemberPointerType(QualType T, QualType Class,
1575 SourceLocation Loc,
1576 DeclarationName Entity);
1577 QualType BuildBlockPointerType(QualType T,
1578 SourceLocation Loc, DeclarationName Entity);
1579 QualType BuildParenType(QualType T);
1580 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1581 QualType BuildReadPipeType(QualType T,
1582 SourceLocation Loc);
1583 QualType BuildWritePipeType(QualType T,
1584 SourceLocation Loc);
1585
1586 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1587 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1588
1589 /// Package the given type and TSI into a ParsedType.
1590 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1591 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1592 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1593 static QualType GetTypeFromParser(ParsedType Ty,
1594 TypeSourceInfo **TInfo = nullptr);
1595 CanThrowResult canThrow(const Expr *E);
1596 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1597 const FunctionProtoType *FPT);
1598 void UpdateExceptionSpec(FunctionDecl *FD,
1599 const FunctionProtoType::ExceptionSpecInfo &ESI);
1600 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1601 bool CheckDistantExceptionSpec(QualType T);
1602 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1603 bool CheckEquivalentExceptionSpec(
1604 const FunctionProtoType *Old, SourceLocation OldLoc,
1605 const FunctionProtoType *New, SourceLocation NewLoc);
1606 bool CheckEquivalentExceptionSpec(
1607 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1608 const FunctionProtoType *Old, SourceLocation OldLoc,
1609 const FunctionProtoType *New, SourceLocation NewLoc);
1610 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1611 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1612 const PartialDiagnostic &NestedDiagID,
1613 const PartialDiagnostic &NoteID,
1614 const PartialDiagnostic &NoThrowDiagID,
1615 const FunctionProtoType *Superset,
1616 SourceLocation SuperLoc,
1617 const FunctionProtoType *Subset,
1618 SourceLocation SubLoc);
1619 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1620 const PartialDiagnostic &NoteID,
1621 const FunctionProtoType *Target,
1622 SourceLocation TargetLoc,
1623 const FunctionProtoType *Source,
1624 SourceLocation SourceLoc);
1625
1626 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1627
1628 /// The parser has parsed the context-sensitive type 'instancetype'
1629 /// in an Objective-C message declaration. Return the appropriate type.
1630 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1631
1632 /// Abstract class used to diagnose incomplete types.
1633 struct TypeDiagnoser {
1634 TypeDiagnoser() {}
1635
1636 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1637 virtual ~TypeDiagnoser() {}
1638 };
1639
1640 static int getPrintable(int I) { return I; }
1641 static unsigned getPrintable(unsigned I) { return I; }
1642 static bool getPrintable(bool B) { return B; }
1643 static const char * getPrintable(const char *S) { return S; }
1644 static StringRef getPrintable(StringRef S) { return S; }
1645 static const std::string &getPrintable(const std::string &S) { return S; }
1646 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1647 return II;
1648 }
1649 static DeclarationName getPrintable(DeclarationName N) { return N; }
1650 static QualType getPrintable(QualType T) { return T; }
1651 static SourceRange getPrintable(SourceRange R) { return R; }
1652 static SourceRange getPrintable(SourceLocation L) { return L; }
1653 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1654 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1655
1656 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1657 unsigned DiagID;
1658 std::tuple<const Ts &...> Args;
1659
1660 template <std::size_t... Is>
1661 void emit(const SemaDiagnosticBuilder &DB,
1662 std::index_sequence<Is...>) const {
1663 // Apply all tuple elements to the builder in order.
1664 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1665 (void)Dummy;
1666 }
1667
1668 public:
1669 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1670 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1671 assert(DiagID != 0 && "no diagnostic for type diagnoser")((DiagID != 0 && "no diagnostic for type diagnoser") ?
static_cast<void> (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 1671, __PRETTY_FUNCTION__))
;
1672 }
1673
1674 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1675 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1676 emit(DB, std::index_sequence_for<Ts...>());
1677 DB << T;
1678 }
1679 };
1680
1681private:
1682 /// Methods for marking which expressions involve dereferencing a pointer
1683 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
1684 /// they are parsed, meaning that a noderef pointer may not be accessed. For
1685 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
1686 /// `*p`, but need to check that `address of` is called on it. This requires
1687 /// keeping a container of all pending expressions and checking if the address
1688 /// of them are eventually taken.
1689 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
1690 void CheckAddressOfNoDeref(const Expr *E);
1691 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
1692
1693 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1694 TypeDiagnoser *Diagnoser);
1695
1696 struct ModuleScope {
1697 SourceLocation BeginLoc;
1698 clang::Module *Module = nullptr;
1699 bool ModuleInterface = false;
1700 bool ImplicitGlobalModuleFragment = false;
1701 VisibleModuleSet OuterVisibleModules;
1702 };
1703 /// The modules we're currently parsing.
1704 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1705
1706 /// Namespace definitions that we will export when they finish.
1707 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
1708
1709 /// Get the module whose scope we are currently within.
1710 Module *getCurrentModule() const {
1711 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1712 }
1713
1714 VisibleModuleSet VisibleModules;
1715
1716public:
1717 /// Get the module owning an entity.
1718 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1719
1720 /// Make a merged definition of an existing hidden definition \p ND
1721 /// visible at the specified location.
1722 void makeMergedDefinitionVisible(NamedDecl *ND);
1723
1724 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
1725
1726 /// Determine whether a declaration is visible to name lookup.
1727 bool isVisible(const NamedDecl *D) {
1728 return !D->isHidden() || isVisibleSlow(D);
1729 }
1730
1731 /// Determine whether any declaration of an entity is visible.
1732 bool
1733 hasVisibleDeclaration(const NamedDecl *D,
1734 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1735 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1736 }
1737 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1738 llvm::SmallVectorImpl<Module *> *Modules);
1739
1740 bool hasVisibleMergedDefinition(NamedDecl *Def);
1741 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1742
1743 /// Determine if \p D and \p Suggested have a structurally compatible
1744 /// layout as described in C11 6.2.7/1.
1745 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1746
1747 /// Determine if \p D has a visible definition. If not, suggest a declaration
1748 /// that should be made visible to expose the definition.
1749 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1750 bool OnlyNeedComplete = false);
1751 bool hasVisibleDefinition(const NamedDecl *D) {
1752 NamedDecl *Hidden;
1753 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1754 }
1755
1756 /// Determine if the template parameter \p D has a visible default argument.
1757 bool
1758 hasVisibleDefaultArgument(const NamedDecl *D,
1759 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1760
1761 /// Determine if there is a visible declaration of \p D that is an explicit
1762 /// specialization declaration for a specialization of a template. (For a
1763 /// member specialization, use hasVisibleMemberSpecialization.)
1764 bool hasVisibleExplicitSpecialization(
1765 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1766
1767 /// Determine if there is a visible declaration of \p D that is a member
1768 /// specialization declaration (as opposed to an instantiated declaration).
1769 bool hasVisibleMemberSpecialization(
1770 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1771
1772 /// Determine if \p A and \p B are equivalent internal linkage declarations
1773 /// from different modules, and thus an ambiguity error can be downgraded to
1774 /// an extension warning.
1775 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1776 const NamedDecl *B);
1777 void diagnoseEquivalentInternalLinkageDeclarations(
1778 SourceLocation Loc, const NamedDecl *D,
1779 ArrayRef<const NamedDecl *> Equiv);
1780
1781 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
1782
1783 bool isCompleteType(SourceLocation Loc, QualType T) {
1784 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1785 }
1786 bool RequireCompleteType(SourceLocation Loc, QualType T,
1787 TypeDiagnoser &Diagnoser);
1788 bool RequireCompleteType(SourceLocation Loc, QualType T,
1789 unsigned DiagID);
1790
1791 template <typename... Ts>
1792 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1793 const Ts &...Args) {
1794 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1795 return RequireCompleteType(Loc, T, Diagnoser);
1796 }
1797
1798 void completeExprArrayBound(Expr *E);
1799 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1800 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1801
1802 template <typename... Ts>
1803 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1804 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1805 return RequireCompleteExprType(E, Diagnoser);
1806 }
1807
1808 bool RequireLiteralType(SourceLocation Loc, QualType T,
1809 TypeDiagnoser &Diagnoser);
1810 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1811
1812 template <typename... Ts>
1813 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1814 const Ts &...Args) {
1815 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1816 return RequireLiteralType(Loc, T, Diagnoser);
1817 }
1818
1819 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1820 const CXXScopeSpec &SS, QualType T,
1821 TagDecl *OwnedTagDecl = nullptr);
1822
1823 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1824 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1825 /// context, such as when building a type for decltype(auto).
1826 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1827 bool AsUnevaluated = true);
1828 QualType BuildUnaryTransformType(QualType BaseType,
1829 UnaryTransformType::UTTKind UKind,
1830 SourceLocation Loc);
1831
1832 //===--------------------------------------------------------------------===//
1833 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1834 //
1835
1836 struct SkipBodyInfo {
1837 SkipBodyInfo()
1838 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1839 New(nullptr) {}
1840 bool ShouldSkip;
1841 bool CheckSameAsPrevious;
1842 NamedDecl *Previous;
1843 NamedDecl *New;
1844 };
1845
1846 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1847
1848 void DiagnoseUseOfUnimplementedSelectors();
1849
1850 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1851
1852 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1853 Scope *S, CXXScopeSpec *SS = nullptr,
1854 bool isClassName = false, bool HasTrailingDot = false,
1855 ParsedType ObjectType = nullptr,
1856 bool IsCtorOrDtorName = false,
1857 bool WantNontrivialTypeSourceInfo = false,
1858 bool IsClassTemplateDeductionContext = true,
1859 IdentifierInfo **CorrectedII = nullptr);
1860 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1861 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1862 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1863 SourceLocation IILoc,
1864 Scope *S,
1865 CXXScopeSpec *SS,
1866 ParsedType &SuggestedType,
1867 bool IsTemplateName = false);
1868
1869 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1870 /// type name has failed in a dependent context. In these situations, we
1871 /// automatically form a DependentTypeName that will retry lookup in a related
1872 /// scope during instantiation.
1873 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1874 SourceLocation NameLoc,
1875 bool IsTemplateTypeArg);
1876
1877 /// Describes the result of the name lookup and resolution performed
1878 /// by \c ClassifyName().
1879 enum NameClassificationKind {
1880 /// This name is not a type or template in this context, but might be
1881 /// something else.
1882 NC_Unknown,
1883 /// Classification failed; an error has been produced.
1884 NC_Error,
1885 /// The name has been typo-corrected to a keyword.
1886 NC_Keyword,
1887 /// The name was classified as a type.
1888 NC_Type,
1889 /// The name was classified as a specific non-type, non-template
1890 /// declaration. ActOnNameClassifiedAsNonType should be called to
1891 /// convert the declaration to an expression.
1892 NC_NonType,
1893 /// The name was classified as an ADL-only function name.
1894 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
1895 /// result to an expression.
1896 NC_UndeclaredNonType,
1897 /// The name denotes a member of a dependent type that could not be
1898 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
1899 /// convert the result to an expression.
1900 NC_DependentNonType,
1901 /// The name was classified as a non-type, and an expression representing
1902 /// that name has been formed.
1903 NC_ContextIndependentExpr,
1904 /// The name was classified as a template whose specializations are types.
1905 NC_TypeTemplate,
1906 /// The name was classified as a variable template name.
1907 NC_VarTemplate,
1908 /// The name was classified as a function template name.
1909 NC_FunctionTemplate,
1910 /// The name was classified as an ADL-only function template name.
1911 NC_UndeclaredTemplate,
1912 };
1913
1914 class NameClassification {
1915 NameClassificationKind Kind;
1916 union {
1917 ExprResult Expr;
1918 NamedDecl *NonTypeDecl;
1919 TemplateName Template;
1920 ParsedType Type;
1921 };
1922
1923 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1924
1925 public:
1926 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1927
1928 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1929
1930 static NameClassification Error() {
1931 return NameClassification(NC_Error);
1932 }
1933
1934 static NameClassification Unknown() {
1935 return NameClassification(NC_Unknown);
1936 }
1937
1938 static NameClassification ContextIndependentExpr(ExprResult E) {
1939 NameClassification Result(NC_ContextIndependentExpr);
1940 Result.Expr = E;
1941 return Result;
1942 }
1943
1944 static NameClassification NonType(NamedDecl *D) {
1945 NameClassification Result(NC_NonType);
1946 Result.NonTypeDecl = D;
1947 return Result;
1948 }
1949
1950 static NameClassification UndeclaredNonType() {
1951 return NameClassification(NC_UndeclaredNonType);
1952 }
1953
1954 static NameClassification DependentNonType() {
1955 return NameClassification(NC_DependentNonType);
1956 }
1957
1958 static NameClassification TypeTemplate(TemplateName Name) {
1959 NameClassification Result(NC_TypeTemplate);
1960 Result.Template = Name;
1961 return Result;
1962 }
1963
1964 static NameClassification VarTemplate(TemplateName Name) {
1965 NameClassification Result(NC_VarTemplate);
1966 Result.Template = Name;
1967 return Result;
1968 }
1969
1970 static NameClassification FunctionTemplate(TemplateName Name) {
1971 NameClassification Result(NC_FunctionTemplate);
1972 Result.Template = Name;
1973 return Result;
1974 }
1975
1976 static NameClassification UndeclaredTemplate(TemplateName Name) {
1977 NameClassification Result(NC_UndeclaredTemplate);
1978 Result.Template = Name;
1979 return Result;
1980 }
1981
1982 NameClassificationKind getKind() const { return Kind; }
1983
1984 ExprResult getExpression() const {
1985 assert(Kind == NC_ContextIndependentExpr)((Kind == NC_ContextIndependentExpr) ? static_cast<void>
(0) : __assert_fail ("Kind == NC_ContextIndependentExpr", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 1985, __PRETTY_FUNCTION__))
;
1986 return Expr;
1987 }
1988
1989 ParsedType getType() const {
1990 assert(Kind == NC_Type)((Kind == NC_Type) ? static_cast<void> (0) : __assert_fail
("Kind == NC_Type", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 1990, __PRETTY_FUNCTION__))
;
1991 return Type;
1992 }
1993
1994 NamedDecl *getNonTypeDecl() const {
1995 assert(Kind == NC_NonType)((Kind == NC_NonType) ? static_cast<void> (0) : __assert_fail
("Kind == NC_NonType", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 1995, __PRETTY_FUNCTION__))
;
1996 return NonTypeDecl;
1997 }
1998
1999 TemplateName getTemplateName() const {
2000 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast
<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 2001, __PRETTY_FUNCTION__))
2001 Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate)((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast
<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 2001, __PRETTY_FUNCTION__))
;
2002 return Template;
2003 }
2004
2005 TemplateNameKind getTemplateNameKind() const {
2006 switch (Kind) {
2007 case NC_TypeTemplate:
2008 return TNK_Type_template;
2009 case NC_FunctionTemplate:
2010 return TNK_Function_template;
2011 case NC_VarTemplate:
2012 return TNK_Var_template;
2013 case NC_UndeclaredTemplate:
2014 return TNK_Undeclared_template;
2015 default:
2016 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 2016)
;
2017 }
2018 }
2019 };
2020
2021 /// Perform name lookup on the given name, classifying it based on
2022 /// the results of name lookup and the following token.
2023 ///
2024 /// This routine is used by the parser to resolve identifiers and help direct
2025 /// parsing. When the identifier cannot be found, this routine will attempt
2026 /// to correct the typo and classify based on the resulting name.
2027 ///
2028 /// \param S The scope in which we're performing name lookup.
2029 ///
2030 /// \param SS The nested-name-specifier that precedes the name.
2031 ///
2032 /// \param Name The identifier. If typo correction finds an alternative name,
2033 /// this pointer parameter will be updated accordingly.
2034 ///
2035 /// \param NameLoc The location of the identifier.
2036 ///
2037 /// \param NextToken The token following the identifier. Used to help
2038 /// disambiguate the name.
2039 ///
2040 /// \param CCC The correction callback, if typo correction is desired.
2041 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2042 IdentifierInfo *&Name, SourceLocation NameLoc,
2043 const Token &NextToken,
2044 CorrectionCandidateCallback *CCC = nullptr);
2045
2046 /// Act on the result of classifying a name as an undeclared (ADL-only)
2047 /// non-type declaration.
2048 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2049 SourceLocation NameLoc);
2050 /// Act on the result of classifying a name as an undeclared member of a
2051 /// dependent base class.
2052 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2053 IdentifierInfo *Name,
2054 SourceLocation NameLoc,
2055 bool IsAddressOfOperand);
2056 /// Act on the result of classifying a name as a specific non-type
2057 /// declaration.
2058 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2059 NamedDecl *Found,
2060 SourceLocation NameLoc,
2061 const Token &NextToken);
2062
2063 /// Describes the detailed kind of a template name. Used in diagnostics.
2064 enum class TemplateNameKindForDiagnostics {
2065 ClassTemplate,
2066 FunctionTemplate,
2067 VarTemplate,
2068 AliasTemplate,
2069 TemplateTemplateParam,
2070 Concept,
2071 DependentTemplate
2072 };
2073 TemplateNameKindForDiagnostics
2074 getTemplateNameKindForDiagnostics(TemplateName Name);
2075
2076 /// Determine whether it's plausible that E was intended to be a
2077 /// template-name.
2078 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2079 if (!getLangOpts().CPlusPlus || E.isInvalid())
2080 return false;
2081 Dependent = false;
2082 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2083 return !DRE->hasExplicitTemplateArgs();
2084 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2085 return !ME->hasExplicitTemplateArgs();
2086 Dependent = true;
2087 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2088 return !DSDRE->hasExplicitTemplateArgs();
2089 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2090 return !DSME->hasExplicitTemplateArgs();
2091 // Any additional cases recognized here should also be handled by
2092 // diagnoseExprIntendedAsTemplateName.
2093 return false;
2094 }
2095 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2096 SourceLocation Less,
2097 SourceLocation Greater);
2098
2099 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2100
2101 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2102 MultiTemplateParamsArg TemplateParameterLists);
2103 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2104 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2105 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2106 DeclarationName Name, SourceLocation Loc,
2107 bool IsTemplateId);
2108 void
2109 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2110 SourceLocation FallbackLoc,
2111 SourceLocation ConstQualLoc = SourceLocation(),
2112 SourceLocation VolatileQualLoc = SourceLocation(),
2113 SourceLocation RestrictQualLoc = SourceLocation(),
2114 SourceLocation AtomicQualLoc = SourceLocation(),
2115 SourceLocation UnalignedQualLoc = SourceLocation());
2116
2117 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2118 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2119 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2120 const LookupResult &R);
2121 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2122 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2123 const LookupResult &R);
2124 void CheckShadow(Scope *S, VarDecl *D);
2125
2126 /// Warn if 'E', which is an expression that is about to be modified, refers
2127 /// to a shadowing declaration.
2128 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2129
2130 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2131
2132private:
2133 /// Map of current shadowing declarations to shadowed declarations. Warn if
2134 /// it looks like the user is trying to modify the shadowing declaration.
2135 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2136
2137public:
2138 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2139 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2140 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2141 TypedefNameDecl *NewTD);
2142 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2143 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2144 TypeSourceInfo *TInfo,
2145 LookupResult &Previous);
2146 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2147 LookupResult &Previous, bool &Redeclaration);
2148 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2149 TypeSourceInfo *TInfo,
2150 LookupResult &Previous,
2151 MultiTemplateParamsArg TemplateParamLists,
2152 bool &AddToScope,
2153 ArrayRef<BindingDecl *> Bindings = None);
2154 NamedDecl *
2155 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2156 MultiTemplateParamsArg TemplateParamLists);
2157 // Returns true if the variable declaration is a redeclaration
2158 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2159 void CheckVariableDeclarationType(VarDecl *NewVD);
2160 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2161 Expr *Init);
2162 void CheckCompleteVariableDeclaration(VarDecl *VD);
2163 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2164 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2165
2166 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2167 TypeSourceInfo *TInfo,
2168 LookupResult &Previous,
2169 MultiTemplateParamsArg TemplateParamLists,
2170 bool &AddToScope);
2171 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2172
2173 enum class CheckConstexprKind {
2174 /// Diagnose issues that are non-constant or that are extensions.
2175 Diagnose,
2176 /// Identify whether this function satisfies the formal rules for constexpr
2177 /// functions in the current lanugage mode (with no extensions).
2178 CheckValid
2179 };
2180
2181 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2182 CheckConstexprKind Kind);
2183
2184 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2185 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2186 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2187 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2188 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2189 // Returns true if the function declaration is a redeclaration
2190 bool CheckFunctionDeclaration(Scope *S,
2191 FunctionDecl *NewFD, LookupResult &Previous,
2192 bool IsMemberSpecialization);
2193 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2194 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2195 QualType NewT, QualType OldT);
2196 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2197 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2198 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2199 bool IsDefinition);
2200 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2201 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2202 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2203 SourceLocation Loc,
2204 QualType T);
2205 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2206 SourceLocation NameLoc, IdentifierInfo *Name,
2207 QualType T, TypeSourceInfo *TSInfo,
2208 StorageClass SC);
2209 void ActOnParamDefaultArgument(Decl *param,
2210 SourceLocation EqualLoc,
2211 Expr *defarg);
2212 void ActOnParamUnparsedDefaultArgument(Decl *param,
2213 SourceLocation EqualLoc,
2214 SourceLocation ArgLoc);
2215 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2216 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2217 SourceLocation EqualLoc);
2218
2219 // Contexts where using non-trivial C union types can be disallowed. This is
2220 // passed to err_non_trivial_c_union_in_invalid_context.
2221 enum NonTrivialCUnionContext {
2222 // Function parameter.
2223 NTCUC_FunctionParam,
2224 // Function return.
2225 NTCUC_FunctionReturn,
2226 // Default-initialized object.
2227 NTCUC_DefaultInitializedObject,
2228 // Variable with automatic storage duration.
2229 NTCUC_AutoVar,
2230 // Initializer expression that might copy from another object.
2231 NTCUC_CopyInit,
2232 // Assignment.
2233 NTCUC_Assignment,
2234 // Compound literal.
2235 NTCUC_CompoundLiteral,
2236 // Block capture.
2237 NTCUC_BlockCapture,
2238 // lvalue-to-rvalue conversion of volatile type.
2239 NTCUC_LValueToRValueVolatile,
2240 };
2241
2242 /// Emit diagnostics if the initializer or any of its explicit or
2243 /// implicitly-generated subexpressions require copying or
2244 /// default-initializing a type that is or contains a C union type that is
2245 /// non-trivial to copy or default-initialize.
2246 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2247
2248 // These flags are passed to checkNonTrivialCUnion.
2249 enum NonTrivialCUnionKind {
2250 NTCUK_Init = 0x1,
2251 NTCUK_Destruct = 0x2,
2252 NTCUK_Copy = 0x4,
2253 };
2254
2255 /// Emit diagnostics if a non-trivial C union type or a struct that contains
2256 /// a non-trivial C union is used in an invalid context.
2257 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2258 NonTrivialCUnionContext UseContext,
2259 unsigned NonTrivialKind);
2260
2261 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2262 void ActOnUninitializedDecl(Decl *dcl);
2263 void ActOnInitializerError(Decl *Dcl);
2264
2265 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2266 void ActOnCXXForRangeDecl(Decl *D);
2267 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2268 IdentifierInfo *Ident,
2269 ParsedAttributes &Attrs,
2270 SourceLocation AttrEnd);
2271 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2272 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2273 void CheckStaticLocalForDllExport(VarDecl *VD);
2274 void FinalizeDeclaration(Decl *D);
2275 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2276 ArrayRef<Decl *> Group);
2277 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2278
2279 /// Should be called on all declarations that might have attached
2280 /// documentation comments.
2281 void ActOnDocumentableDecl(Decl *D);
2282 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2283
2284 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2285 SourceLocation LocAfterDecls);
2286 void CheckForFunctionRedefinition(
2287 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2288 SkipBodyInfo *SkipBody = nullptr);
2289 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2290 MultiTemplateParamsArg TemplateParamLists,
2291 SkipBodyInfo *SkipBody = nullptr);
2292 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2293 SkipBodyInfo *SkipBody = nullptr);
2294 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2295 bool isObjCMethodDecl(Decl *D) {
2296 return D && isa<ObjCMethodDecl>(D);
2297 }
2298
2299 /// Determine whether we can delay parsing the body of a function or
2300 /// function template until it is used, assuming we don't care about emitting
2301 /// code for that function.
2302 ///
2303 /// This will be \c false if we may need the body of the function in the
2304 /// middle of parsing an expression (where it's impractical to switch to
2305 /// parsing a different function), for instance, if it's constexpr in C++11
2306 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2307 bool canDelayFunctionBody(const Declarator &D);
2308
2309 /// Determine whether we can skip parsing the body of a function
2310 /// definition, assuming we don't care about analyzing its body or emitting
2311 /// code for that function.
2312 ///
2313 /// This will be \c false only if we may need the body of the function in
2314 /// order to parse the rest of the program (for instance, if it is
2315 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2316 bool canSkipFunctionBody(Decl *D);
2317
2318 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2319 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2320 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2321 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2322 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2323
2324 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2325 /// attribute for which parsing is delayed.
2326 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2327
2328 /// Diagnose any unused parameters in the given sequence of
2329 /// ParmVarDecl pointers.
2330 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2331
2332 /// Diagnose whether the size of parameters or return value of a
2333 /// function or obj-c method definition is pass-by-value and larger than a
2334 /// specified threshold.
2335 void
2336 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2337 QualType ReturnTy, NamedDecl *D);
2338
2339 void DiagnoseInvalidJumps(Stmt *Body);
2340 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2341 SourceLocation AsmLoc,
2342 SourceLocation RParenLoc);
2343
2344 /// Handle a C++11 empty-declaration and attribute-declaration.
2345 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2346 SourceLocation SemiLoc);
2347
2348 enum class ModuleDeclKind {
2349 Interface, ///< 'export module X;'
2350 Implementation, ///< 'module X;'
2351 };
2352
2353 /// The parser has processed a module-declaration that begins the definition
2354 /// of a module interface or implementation.
2355 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2356 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2357 ModuleIdPath Path, bool IsFirstDecl);
2358
2359 /// The parser has processed a global-module-fragment declaration that begins
2360 /// the definition of the global module fragment of the current module unit.
2361 /// \param ModuleLoc The location of the 'module' keyword.
2362 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2363
2364 /// The parser has processed a private-module-fragment declaration that begins
2365 /// the definition of the private module fragment of the current module unit.
2366 /// \param ModuleLoc The location of the 'module' keyword.
2367 /// \param PrivateLoc The location of the 'private' keyword.
2368 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2369 SourceLocation PrivateLoc);
2370
2371 /// The parser has processed a module import declaration.
2372 ///
2373 /// \param StartLoc The location of the first token in the declaration. This
2374 /// could be the location of an '@', 'export', or 'import'.
2375 /// \param ExportLoc The location of the 'export' keyword, if any.
2376 /// \param ImportLoc The location of the 'import' keyword.
2377 /// \param Path The module access path.
2378 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2379 SourceLocation ExportLoc,
2380 SourceLocation ImportLoc, ModuleIdPath Path);
2381 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2382 SourceLocation ExportLoc,
2383 SourceLocation ImportLoc, Module *M,
2384 ModuleIdPath Path = {});
2385
2386 /// The parser has processed a module import translated from a
2387 /// #include or similar preprocessing directive.
2388 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2389 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2390
2391 /// The parsed has entered a submodule.
2392 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2393 /// The parser has left a submodule.
2394 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2395
2396 /// Create an implicit import of the given module at the given
2397 /// source location, for error recovery, if possible.
2398 ///
2399 /// This routine is typically used when an entity found by name lookup
2400 /// is actually hidden within a module that we know about but the user
2401 /// has forgotten to import.
2402 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2403 Module *Mod);
2404
2405 /// Kinds of missing import. Note, the values of these enumerators correspond
2406 /// to %select values in diagnostics.
2407 enum class MissingImportKind {
2408 Declaration,
2409 Definition,
2410 DefaultArgument,
2411 ExplicitSpecialization,
2412 PartialSpecialization
2413 };
2414
2415 /// Diagnose that the specified declaration needs to be visible but
2416 /// isn't, and suggest a module import that would resolve the problem.
2417 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2418 MissingImportKind MIK, bool Recover = true);
2419 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2420 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2421 MissingImportKind MIK, bool Recover);
2422
2423 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2424 SourceLocation LBraceLoc);
2425 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2426 SourceLocation RBraceLoc);
2427
2428 /// We've found a use of a templated declaration that would trigger an
2429 /// implicit instantiation. Check that any relevant explicit specializations
2430 /// and partial specializations are visible, and diagnose if not.
2431 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2432
2433 /// We've found a use of a template specialization that would select a
2434 /// partial specialization. Check that the partial specialization is visible,
2435 /// and diagnose if not.
2436 void checkPartialSpecializationVisibility(SourceLocation Loc,
2437 NamedDecl *Spec);
2438
2439 /// Retrieve a suitable printing policy for diagnostics.
2440 PrintingPolicy getPrintingPolicy() const {
2441 return getPrintingPolicy(Context, PP);
2442 }
2443
2444 /// Retrieve a suitable printing policy for diagnostics.
2445 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2446 const Preprocessor &PP);
2447
2448 /// Scope actions.
2449 void ActOnPopScope(SourceLocation Loc, Scope *S);
2450 void ActOnTranslationUnitScope(Scope *S);
2451
2452 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2453 RecordDecl *&AnonRecord);
2454 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2455 MultiTemplateParamsArg TemplateParams,
2456 bool IsExplicitInstantiation,
2457 RecordDecl *&AnonRecord);
2458
2459 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2460 AccessSpecifier AS,
2461 RecordDecl *Record,
2462 const PrintingPolicy &Policy);
2463
2464 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2465 RecordDecl *Record);
2466
2467 /// Common ways to introduce type names without a tag for use in diagnostics.
2468 /// Keep in sync with err_tag_reference_non_tag.
2469 enum NonTagKind {
2470 NTK_NonStruct,
2471 NTK_NonClass,
2472 NTK_NonUnion,
2473 NTK_NonEnum,
2474 NTK_Typedef,
2475 NTK_TypeAlias,
2476 NTK_Template,
2477 NTK_TypeAliasTemplate,
2478 NTK_TemplateTemplateArgument,
2479 };
2480
2481 /// Given a non-tag type declaration, returns an enum useful for indicating
2482 /// what kind of non-tag type this is.
2483 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2484
2485 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2486 TagTypeKind NewTag, bool isDefinition,
2487 SourceLocation NewTagLoc,
2488 const IdentifierInfo *Name);
2489
2490 enum TagUseKind {
2491 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2492 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2493 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2494 TUK_Friend // Friend declaration: 'friend struct foo;'
2495 };
2496
2497 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2498 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2499 SourceLocation NameLoc, const ParsedAttributesView &Attr,
2500 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2501 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2502 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2503 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2504 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2505 SkipBodyInfo *SkipBody = nullptr);
2506
2507 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2508 unsigned TagSpec, SourceLocation TagLoc,
2509 CXXScopeSpec &SS, IdentifierInfo *Name,
2510 SourceLocation NameLoc,
2511 const ParsedAttributesView &Attr,
2512 MultiTemplateParamsArg TempParamLists);
2513
2514 TypeResult ActOnDependentTag(Scope *S,
2515 unsigned TagSpec,
2516 TagUseKind TUK,
2517 const CXXScopeSpec &SS,
2518 IdentifierInfo *Name,
2519 SourceLocation TagLoc,
2520 SourceLocation NameLoc);
2521
2522 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2523 IdentifierInfo *ClassName,
2524 SmallVectorImpl<Decl *> &Decls);
2525 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2526 Declarator &D, Expr *BitfieldWidth);
2527
2528 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2529 Declarator &D, Expr *BitfieldWidth,
2530 InClassInitStyle InitStyle,
2531 AccessSpecifier AS);
2532 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2533 SourceLocation DeclStart, Declarator &D,
2534 Expr *BitfieldWidth,
2535 InClassInitStyle InitStyle,
2536 AccessSpecifier AS,
2537 const ParsedAttr &MSPropertyAttr);
2538
2539 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2540 TypeSourceInfo *TInfo,
2541 RecordDecl *Record, SourceLocation Loc,
2542 bool Mutable, Expr *BitfieldWidth,
2543 InClassInitStyle InitStyle,
2544 SourceLocation TSSL,
2545 AccessSpecifier AS, NamedDecl *PrevDecl,
2546 Declarator *D = nullptr);
2547
2548 bool CheckNontrivialField(FieldDecl *FD);
2549 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2550
2551 enum TrivialABIHandling {
2552 /// The triviality of a method unaffected by "trivial_abi".
2553 TAH_IgnoreTrivialABI,
2554
2555 /// The triviality of a method affected by "trivial_abi".
2556 TAH_ConsiderTrivialABI
2557 };
2558
2559 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2560 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2561 bool Diagnose = false);
2562
2563 /// For a defaulted function, the kind of defaulted function that it is.
2564 class DefaultedFunctionKind {
2565 CXXSpecialMember SpecialMember : 8;
2566 DefaultedComparisonKind Comparison : 8;
2567
2568 public:
2569 DefaultedFunctionKind()
2570 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
2571 }
2572 DefaultedFunctionKind(CXXSpecialMember CSM)
2573 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
2574 DefaultedFunctionKind(DefaultedComparisonKind Comp)
2575 : SpecialMember(CXXInvalid), Comparison(Comp) {}
2576
2577 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
2578 bool isComparison() const {
2579 return Comparison != DefaultedComparisonKind::None;
2580 }
2581
2582 explicit operator bool() const {
2583 return isSpecialMember() || isComparison();
2584 }
2585
2586 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
2587 DefaultedComparisonKind asComparison() const { return Comparison; }
2588
2589 /// Get the index of this function kind for use in diagnostics.
2590 unsigned getDiagnosticIndex() const {
2591 static_assert(CXXInvalid > CXXDestructor,
2592 "invalid should have highest index");
2593 static_assert((unsigned)DefaultedComparisonKind::None == 0,
2594 "none should be equal to zero");
2595 return SpecialMember + (unsigned)Comparison;
2596 }
2597 };
2598
2599 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
2600
2601 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
2602 return getDefaultedFunctionKind(MD).asSpecialMember();
2603 }
2604 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
2605 return getDefaultedFunctionKind(FD).asComparison();
2606 }
2607
2608 void ActOnLastBitfield(SourceLocation DeclStart,
2609 SmallVectorImpl<Decl *> &AllIvarDecls);
2610 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2611 Declarator &D, Expr *BitfieldWidth,
2612 tok::ObjCKeywordKind visibility);
2613
2614 // This is used for both record definitions and ObjC interface declarations.
2615 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
2616 ArrayRef<Decl *> Fields, SourceLocation LBrac,
2617 SourceLocation RBrac, const ParsedAttributesView &AttrList);
2618
2619 /// ActOnTagStartDefinition - Invoked when we have entered the
2620 /// scope of a tag's definition (e.g., for an enumeration, class,
2621 /// struct, or union).
2622 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2623
2624 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2625 /// Differently from C++, actually parse the body and reject / error out
2626 /// in case of a structural mismatch.
2627 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2628 SkipBodyInfo &SkipBody);
2629
2630 typedef void *SkippedDefinitionContext;
2631
2632 /// Invoked when we enter a tag definition that we're skipping.
2633 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2634
2635 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2636
2637 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2638 /// C++ record definition's base-specifiers clause and are starting its
2639 /// member declarations.
2640 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2641 SourceLocation FinalLoc,
2642 bool IsFinalSpelledSealed,
2643 SourceLocation LBraceLoc);
2644
2645 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2646 /// the definition of a tag (enumeration, class, struct, or union).
2647 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2648 SourceRange BraceRange);
2649
2650 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2651
2652 void ActOnObjCContainerFinishDefinition();
2653
2654 /// Invoked when we must temporarily exit the objective-c container
2655 /// scope for parsing/looking-up C constructs.
2656 ///
2657 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2658 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2659 void ActOnObjCReenterContainerContext(DeclContext *DC);
2660
2661 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2662 /// error parsing the definition of a tag.
2663 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2664
2665 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2666 EnumConstantDecl *LastEnumConst,
2667 SourceLocation IdLoc,
2668 IdentifierInfo *Id,
2669 Expr *val);
2670 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2671 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2672 QualType EnumUnderlyingTy, bool IsFixed,
2673 const EnumDecl *Prev);
2674
2675 /// Determine whether the body of an anonymous enumeration should be skipped.
2676 /// \param II The name of the first enumerator.
2677 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2678 SourceLocation IILoc);
2679
2680 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2681 SourceLocation IdLoc, IdentifierInfo *Id,
2682 const ParsedAttributesView &Attrs,
2683 SourceLocation EqualLoc, Expr *Val);
2684 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2685 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
2686 const ParsedAttributesView &Attr);
2687
2688 DeclContext *getContainingDC(DeclContext *DC);
2689
2690 /// Set the current declaration context until it gets popped.
2691 void PushDeclContext(Scope *S, DeclContext *DC);
2692 void PopDeclContext();
2693
2694 /// EnterDeclaratorContext - Used when we must lookup names in the context
2695 /// of a declarator's nested name specifier.
2696 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2697 void ExitDeclaratorContext(Scope *S);
2698
2699 /// Push the parameters of D, which must be a function, into scope.
2700 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2701 void ActOnExitFunctionContext();
2702
2703 DeclContext *getFunctionLevelDeclContext();
2704
2705 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2706 /// to the function decl for the function being parsed. If we're currently
2707 /// in a 'block', this returns the containing context.
2708 FunctionDecl *getCurFunctionDecl();
2709
2710 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2711 /// the method decl for the method being parsed. If we're currently
2712 /// in a 'block', this returns the containing context.
2713 ObjCMethodDecl *getCurMethodDecl();
2714
2715 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2716 /// or C function we're in, otherwise return null. If we're currently
2717 /// in a 'block', this returns the containing context.
2718 NamedDecl *getCurFunctionOrMethodDecl();
2719
2720 /// Add this decl to the scope shadowed decl chains.
2721 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2722
2723 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2724 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2725 /// true if 'D' belongs to the given declaration context.
2726 ///
2727 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2728 /// enclosing namespace set of the context, rather than contained
2729 /// directly within it.
2730 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2731 bool AllowInlineNamespace = false);
2732
2733 /// Finds the scope corresponding to the given decl context, if it
2734 /// happens to be an enclosing scope. Otherwise return NULL.
2735 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2736
2737 /// Subroutines of ActOnDeclarator().
2738 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2739 TypeSourceInfo *TInfo);
2740 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2741
2742 /// Describes the kind of merge to perform for availability
2743 /// attributes (including "deprecated", "unavailable", and "availability").
2744 enum AvailabilityMergeKind {
2745 /// Don't merge availability attributes at all.
2746 AMK_None,
2747 /// Merge availability attributes for a redeclaration, which requires
2748 /// an exact match.
2749 AMK_Redeclaration,
2750 /// Merge availability attributes for an override, which requires
2751 /// an exact match or a weakening of constraints.
2752 AMK_Override,
2753 /// Merge availability attributes for an implementation of
2754 /// a protocol requirement.
2755 AMK_ProtocolImplementation,
2756 };
2757
2758 /// Describes the kind of priority given to an availability attribute.
2759 ///
2760 /// The sum of priorities deteremines the final priority of the attribute.
2761 /// The final priority determines how the attribute will be merged.
2762 /// An attribute with a lower priority will always remove higher priority
2763 /// attributes for the specified platform when it is being applied. An
2764 /// attribute with a higher priority will not be applied if the declaration
2765 /// already has an availability attribute with a lower priority for the
2766 /// specified platform. The final prirority values are not expected to match
2767 /// the values in this enumeration, but instead should be treated as a plain
2768 /// integer value. This enumeration just names the priority weights that are
2769 /// used to calculate that final vaue.
2770 enum AvailabilityPriority : int {
2771 /// The availability attribute was specified explicitly next to the
2772 /// declaration.
2773 AP_Explicit = 0,
2774
2775 /// The availability attribute was applied using '#pragma clang attribute'.
2776 AP_PragmaClangAttribute = 1,
2777
2778 /// The availability attribute for a specific platform was inferred from
2779 /// an availability attribute for another platform.
2780 AP_InferredFromOtherPlatform = 2
2781 };
2782
2783 /// Attribute merging methods. Return true if a new attribute was added.
2784 AvailabilityAttr *
2785 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
2786 IdentifierInfo *Platform, bool Implicit,
2787 VersionTuple Introduced, VersionTuple Deprecated,
2788 VersionTuple Obsoleted, bool IsUnavailable,
2789 StringRef Message, bool IsStrict, StringRef Replacement,
2790 AvailabilityMergeKind AMK, int Priority);
2791 TypeVisibilityAttr *
2792 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2793 TypeVisibilityAttr::VisibilityType Vis);
2794 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2795 VisibilityAttr::VisibilityType Vis);
2796 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
2797 StringRef Uuid);
2798 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
2799 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
2800 MSInheritanceAttr *
2801 mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase,
2802 MSInheritanceAttr::Spelling SemanticSpelling);
2803 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
2804 IdentifierInfo *Format, int FormatIdx,
2805 int FirstArg);
2806 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
2807 StringRef Name);
2808 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
2809 StringRef Name);
2810 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
2811 const AttributeCommonInfo &CI,
2812 const IdentifierInfo *Ident);
2813 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
2814 NoSpeculativeLoadHardeningAttr *
2815 mergeNoSpeculativeLoadHardeningAttr(Decl *D,
2816 const NoSpeculativeLoadHardeningAttr &AL);
2817 SpeculativeLoadHardeningAttr *
2818 mergeSpeculativeLoadHardeningAttr(Decl *D,
2819 const SpeculativeLoadHardeningAttr &AL);
2820 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
2821 const AttributeCommonInfo &CI);
2822 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
2823 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
2824 const InternalLinkageAttr &AL);
2825 CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
2826 CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
2827
2828 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2829 AvailabilityMergeKind AMK = AMK_Redeclaration);
2830 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2831 LookupResult &OldDecls);
2832 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2833 bool MergeTypeWithOld);
2834 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2835 Scope *S, bool MergeTypeWithOld);
2836 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2837 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2838 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2839 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2840 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2841 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2842 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2843
2844 // AssignmentAction - This is used by all the assignment diagnostic functions
2845 // to represent what is actually causing the operation
2846 enum AssignmentAction {
2847 AA_Assigning,
2848 AA_Passing,
2849 AA_Returning,
2850 AA_Converting,
2851 AA_Initializing,
2852 AA_Sending,
2853 AA_Casting,
2854 AA_Passing_CFAudited
2855 };
2856
2857 /// C++ Overloading.
2858 enum OverloadKind {
2859 /// This is a legitimate overload: the existing declarations are
2860 /// functions or function templates with different signatures.
2861 Ovl_Overload,
2862
2863 /// This is not an overload because the signature exactly matches
2864 /// an existing declaration.
2865 Ovl_Match,
2866
2867 /// This is not an overload because the lookup results contain a
2868 /// non-function.
2869 Ovl_NonFunction
2870 };
2871 OverloadKind CheckOverload(Scope *S,
2872 FunctionDecl *New,
2873 const LookupResult &OldDecls,
2874 NamedDecl *&OldDecl,
2875 bool IsForUsingDecl);
2876 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2877 bool ConsiderCudaAttrs = true);
2878
2879 ImplicitConversionSequence
2880 TryImplicitConversion(Expr *From, QualType ToType,
2881 bool SuppressUserConversions,
2882 bool AllowExplicit,
2883 bool InOverloadResolution,
2884 bool CStyle,
2885 bool AllowObjCWritebackConversion);
2886
2887 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2888 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2889 bool IsComplexPromotion(QualType FromType, QualType ToType);
2890 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2891 bool InOverloadResolution,
2892 QualType& ConvertedType, bool &IncompatibleObjC);
2893 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2894 QualType& ConvertedType, bool &IncompatibleObjC);
2895 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2896 QualType &ConvertedType);
2897 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2898 QualType& ConvertedType);
2899 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2900 const FunctionProtoType *NewType,
2901 unsigned *ArgPos = nullptr);
2902 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2903 QualType FromType, QualType ToType);
2904
2905 void maybeExtendBlockObject(ExprResult &E);
2906 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2907 bool CheckPointerConversion(Expr *From, QualType ToType,
2908 CastKind &Kind,
2909 CXXCastPath& BasePath,
2910 bool IgnoreBaseAccess,
2911 bool Diagnose = true);
2912 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2913 bool InOverloadResolution,
2914 QualType &ConvertedType);
2915 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2916 CastKind &Kind,
2917 CXXCastPath &BasePath,
2918 bool IgnoreBaseAccess);
2919 bool IsQualificationConversion(QualType FromType, QualType ToType,
2920 bool CStyle, bool &ObjCLifetimeConversion);
2921 bool IsFunctionConversion(QualType FromType, QualType ToType,
2922 QualType &ResultTy);
2923 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2924 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2925
2926 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2927 const VarDecl *NRVOCandidate,
2928 QualType ResultType,
2929 Expr *Value,
2930 bool AllowNRVO = true);
2931
2932 bool CanPerformAggregateInitializationForOverloadResolution(
2933 const InitializedEntity &Entity, InitListExpr *From);
2934
2935 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2936 ExprResult Init);
2937 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2938 SourceLocation EqualLoc,
2939 ExprResult Init,
2940 bool TopLevelOfInitList = false,
2941 bool AllowExplicit = false);
2942 ExprResult PerformObjectArgumentInitialization(Expr *From,
2943 NestedNameSpecifier *Qualifier,
2944 NamedDecl *FoundDecl,
2945 CXXMethodDecl *Method);
2946
2947 /// Check that the lifetime of the initializer (and its subobjects) is
2948 /// sufficient for initializing the entity, and perform lifetime extension
2949 /// (when permitted) if not.
2950 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
2951
2952 ExprResult PerformContextuallyConvertToBool(Expr *From);
2953 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2954
2955 /// Contexts in which a converted constant expression is required.
2956 enum CCEKind {
2957 CCEK_CaseValue, ///< Expression in a case label.
2958 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2959 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2960 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2961 CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
2962 CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
2963 };
2964 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2965 llvm::APSInt &Value, CCEKind CCE);
2966 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2967 APValue &Value, CCEKind CCE);
2968
2969 /// Abstract base class used to perform a contextual implicit
2970 /// conversion from an expression to any type passing a filter.
2971 class ContextualImplicitConverter {
2972 public:
2973 bool Suppress;
2974 bool SuppressConversion;
2975
2976 ContextualImplicitConverter(bool Suppress = false,
2977 bool SuppressConversion = false)
2978 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2979
2980 /// Determine whether the specified type is a valid destination type
2981 /// for this conversion.
2982 virtual bool match(QualType T) = 0;
2983
2984 /// Emits a diagnostic complaining that the expression does not have
2985 /// integral or enumeration type.
2986 virtual SemaDiagnosticBuilder
2987 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2988
2989 /// Emits a diagnostic when the expression has incomplete class type.
2990 virtual SemaDiagnosticBuilder
2991 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2992
2993 /// Emits a diagnostic when the only matching conversion function
2994 /// is explicit.
2995 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2996 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2997
2998 /// Emits a note for the explicit conversion function.
2999 virtual SemaDiagnosticBuilder
3000 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3001
3002 /// Emits a diagnostic when there are multiple possible conversion
3003 /// functions.
3004 virtual SemaDiagnosticBuilder
3005 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3006
3007 /// Emits a note for one of the candidate conversions.
3008 virtual SemaDiagnosticBuilder
3009 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3010
3011 /// Emits a diagnostic when we picked a conversion function
3012 /// (for cases when we are not allowed to pick a conversion function).
3013 virtual SemaDiagnosticBuilder diagnoseConversion(
3014 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3015
3016 virtual ~ContextualImplicitConverter() {}
3017 };
3018
3019 class ICEConvertDiagnoser : public ContextualImplicitConverter {
3020 bool AllowScopedEnumerations;
3021
3022 public:
3023 ICEConvertDiagnoser(bool AllowScopedEnumerations,
3024 bool Suppress, bool SuppressConversion)
3025 : ContextualImplicitConverter(Suppress, SuppressConversion),
3026 AllowScopedEnumerations(AllowScopedEnumerations) {}
3027
3028 /// Match an integral or (possibly scoped) enumeration type.
3029 bool match(QualType T) override;
3030
3031 SemaDiagnosticBuilder
3032 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3033 return diagnoseNotInt(S, Loc, T);
3034 }
3035
3036 /// Emits a diagnostic complaining that the expression does not have
3037 /// integral or enumeration type.
3038 virtual SemaDiagnosticBuilder
3039 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3040 };
3041
3042 /// Perform a contextual implicit conversion.
3043 ExprResult PerformContextualImplicitConversion(
3044 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3045
3046
3047 enum ObjCSubscriptKind {
3048 OS_Array,
3049 OS_Dictionary,
3050 OS_Error
3051 };
3052 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3053
3054 // Note that LK_String is intentionally after the other literals, as
3055 // this is used for diagnostics logic.
3056 enum ObjCLiteralKind {
3057 LK_Array,
3058 LK_Dictionary,
3059 LK_Numeric,
3060 LK_Boxed,
3061 LK_String,
3062 LK_Block,
3063 LK_None
3064 };
3065 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3066
3067 ExprResult PerformObjectMemberConversion(Expr *From,
3068 NestedNameSpecifier *Qualifier,
3069 NamedDecl *FoundDecl,
3070 NamedDecl *Member);
3071
3072 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3073 // TODO: make this is a typesafe union.
3074 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
3075 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3076
3077 using ADLCallKind = CallExpr::ADLCallKind;
3078
3079 void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3080 ArrayRef<Expr *> Args,
3081 OverloadCandidateSet &CandidateSet,
3082 bool SuppressUserConversions = false,
3083 bool PartialOverloading = false,
3084 bool AllowExplicit = true,
3085 bool AllowExplicitConversion = false,
3086 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3087 ConversionSequenceList EarlyConversions = None,
3088 OverloadCandidateParamOrder PO = {});
3089 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3090 ArrayRef<Expr *> Args,
3091 OverloadCandidateSet &CandidateSet,
3092 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3093 bool SuppressUserConversions = false,
3094 bool PartialOverloading = false,
3095 bool FirstArgumentIsBase = false);
3096 void AddMethodCandidate(DeclAccessPair FoundDecl,
3097 QualType ObjectType,
3098 Expr::Classification ObjectClassification,
3099 ArrayRef<Expr *> Args,
3100 OverloadCandidateSet& CandidateSet,
3101 bool SuppressUserConversion = false,
3102 OverloadCandidateParamOrder PO = {});
3103 void AddMethodCandidate(CXXMethodDecl *Method,
3104 DeclAccessPair FoundDecl,
3105 CXXRecordDecl *ActingContext, QualType ObjectType,
3106 Expr::Classification ObjectClassification,
3107 ArrayRef<Expr *> Args,
3108 OverloadCandidateSet& CandidateSet,
3109 bool SuppressUserConversions = false,
3110 bool PartialOverloading = false,
3111 ConversionSequenceList EarlyConversions = None,
3112 OverloadCandidateParamOrder PO = {});
3113 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3114 DeclAccessPair FoundDecl,
3115 CXXRecordDecl *ActingContext,
3116 TemplateArgumentListInfo *ExplicitTemplateArgs,
3117 QualType ObjectType,
3118 Expr::Classification ObjectClassification,
3119 ArrayRef<Expr *> Args,
3120 OverloadCandidateSet& CandidateSet,
3121 bool SuppressUserConversions = false,
3122 bool PartialOverloading = false,
3123 OverloadCandidateParamOrder PO = {});
3124 void AddTemplateOverloadCandidate(
3125 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3126 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3127 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3128 bool PartialOverloading = false, bool AllowExplicit = true,
3129 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3130 OverloadCandidateParamOrder PO = {});
3131 bool CheckNonDependentConversions(
3132 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3133 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3134 ConversionSequenceList &Conversions, bool SuppressUserConversions,
3135 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3136 Expr::Classification ObjectClassification = {},
3137 OverloadCandidateParamOrder PO = {});
3138 void AddConversionCandidate(
3139 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3140 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3141 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3142 bool AllowExplicit, bool AllowResultConversion = true);
3143 void AddTemplateConversionCandidate(
3144 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3145 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3146 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3147 bool AllowExplicit, bool AllowResultConversion = true);
3148 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3149 DeclAccessPair FoundDecl,
3150 CXXRecordDecl *ActingContext,
3151 const FunctionProtoType *Proto,
3152 Expr *Object, ArrayRef<Expr *> Args,
3153 OverloadCandidateSet& CandidateSet);
3154 void AddNonMemberOperatorCandidates(
3155 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3156 OverloadCandidateSet &CandidateSet,
3157 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3158 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3159 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3160 OverloadCandidateSet &CandidateSet,
3161 OverloadCandidateParamOrder PO = {});
3162 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3163 OverloadCandidateSet& CandidateSet,
3164 bool IsAssignmentOperator = false,
3165 unsigned NumContextualBoolArguments = 0);
3166 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3167 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3168 OverloadCandidateSet& CandidateSet);
3169 void AddArgumentDependentLookupCandidates(DeclarationName Name,
3170 SourceLocation Loc,
3171 ArrayRef<Expr *> Args,
3172 TemplateArgumentListInfo *ExplicitTemplateArgs,
3173 OverloadCandidateSet& CandidateSet,
3174 bool PartialOverloading = false);
3175
3176 // Emit as a 'note' the specific overload candidate
3177 void NoteOverloadCandidate(
3178 NamedDecl *Found, FunctionDecl *Fn,
3179 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3180 QualType DestType = QualType(), bool TakingAddress = false);
3181
3182 // Emit as a series of 'note's all template and non-templates identified by
3183 // the expression Expr
3184 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3185 bool TakingAddress = false);
3186
3187 /// Check the enable_if expressions on the given function. Returns the first
3188 /// failing attribute, or NULL if they were all successful.
3189 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
3190 bool MissingImplicitThis = false);
3191
3192 /// Find the failed Boolean condition within a given Boolean
3193 /// constant expression, and describe it with a string.
3194 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3195
3196 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3197 /// non-ArgDependent DiagnoseIfAttrs.
3198 ///
3199 /// Argument-dependent diagnose_if attributes should be checked each time a
3200 /// function is used as a direct callee of a function call.
3201 ///
3202 /// Returns true if any errors were emitted.
3203 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3204 const Expr *ThisArg,
3205 ArrayRef<const Expr *> Args,
3206 SourceLocation Loc);
3207
3208 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3209 /// ArgDependent DiagnoseIfAttrs.
3210 ///
3211 /// Argument-independent diagnose_if attributes should be checked on every use
3212 /// of a function.
3213 ///
3214 /// Returns true if any errors were emitted.
3215 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3216 SourceLocation Loc);
3217
3218 /// Returns whether the given function's address can be taken or not,
3219 /// optionally emitting a diagnostic if the address can't be taken.
3220 ///
3221 /// Returns false if taking the address of the function is illegal.
3222 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3223 bool Complain = false,
3224 SourceLocation Loc = SourceLocation());
3225
3226 // [PossiblyAFunctionType] --> [Return]
3227 // NonFunctionType --> NonFunctionType
3228 // R (A) --> R(A)
3229 // R (*)(A) --> R (A)
3230 // R (&)(A) --> R (A)
3231 // R (S::*)(A) --> R (A)
3232 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3233
3234 FunctionDecl *
3235 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3236 QualType TargetType,
3237 bool Complain,
3238 DeclAccessPair &Found,
3239 bool *pHadMultipleCandidates = nullptr);
3240
3241 FunctionDecl *
3242 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
3243 DeclAccessPair &FoundResult);
3244
3245 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
3246 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3247
3248 FunctionDecl *
3249 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3250 bool Complain = false,
3251 DeclAccessPair *Found = nullptr);
3252
3253 bool ResolveAndFixSingleFunctionTemplateSpecialization(
3254 ExprResult &SrcExpr,
3255 bool DoFunctionPointerConverion = false,
3256 bool Complain = false,
3257 SourceRange OpRangeForComplaining = SourceRange(),
3258 QualType DestTypeForComplaining = QualType(),
3259 unsigned DiagIDForComplaining = 0);
3260
3261
3262 Expr *FixOverloadedFunctionReference(Expr *E,
3263 DeclAccessPair FoundDecl,
3264 FunctionDecl *Fn);
3265 ExprResult FixOverloadedFunctionReference(ExprResult,
3266 DeclAccessPair FoundDecl,
3267 FunctionDecl *Fn);
3268
3269 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3270 ArrayRef<Expr *> Args,
3271 OverloadCandidateSet &CandidateSet,
3272 bool PartialOverloading = false);
3273
3274 // An enum used to represent the different possible results of building a
3275 // range-based for loop.
3276 enum ForRangeStatus {
3277 FRS_Success,
3278 FRS_NoViableFunction,
3279 FRS_DiagnosticIssued
3280 };
3281
3282 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3283 SourceLocation RangeLoc,
3284 const DeclarationNameInfo &NameInfo,
3285 LookupResult &MemberLookup,
3286 OverloadCandidateSet *CandidateSet,
3287 Expr *Range, ExprResult *CallExpr);
3288
3289 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3290 UnresolvedLookupExpr *ULE,
3291 SourceLocation LParenLoc,
3292 MultiExprArg Args,
3293 SourceLocation RParenLoc,
3294 Expr *ExecConfig,
3295 bool AllowTypoCorrection=true,
3296 bool CalleesAddressIsTaken=false);
3297
3298 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3299 MultiExprArg Args, SourceLocation RParenLoc,
3300 OverloadCandidateSet *CandidateSet,
3301 ExprResult *Result);
3302
3303 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3304 UnaryOperatorKind Opc,
3305 const UnresolvedSetImpl &Fns,
3306 Expr *input, bool RequiresADL = true);
3307
3308 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3309 BinaryOperatorKind Opc,
3310 const UnresolvedSetImpl &Fns,
3311 Expr *LHS, Expr *RHS,
3312 bool RequiresADL = true,
3313 bool AllowRewrittenCandidates = true);
3314
3315 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3316 SourceLocation RLoc,
3317 Expr *Base,Expr *Idx);
3318
3319 ExprResult
3320 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3321 SourceLocation LParenLoc,
3322 MultiExprArg Args,
3323 SourceLocation RParenLoc);
3324 ExprResult
3325 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3326 MultiExprArg Args,
3327 SourceLocation RParenLoc);
3328
3329 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3330 SourceLocation OpLoc,
3331 bool *NoArrowOperatorFound = nullptr);
3332
3333 /// CheckCallReturnType - Checks that a call expression's return type is
3334 /// complete. Returns true on failure. The location passed in is the location
3335 /// that best represents the call.
3336 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3337 CallExpr *CE, FunctionDecl *FD);
3338
3339 /// Helpers for dealing with blocks and functions.
3340 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3341 bool CheckParameterNames);
3342 void CheckCXXDefaultArguments(FunctionDecl *FD);
3343 void CheckExtraCXXDefaultArguments(Declarator &D);
3344 Scope *getNonFieldDeclScope(Scope *S);
3345
3346 /// \name Name lookup
3347 ///
3348 /// These routines provide name lookup that is used during semantic
3349 /// analysis to resolve the various kinds of names (identifiers,
3350 /// overloaded operator names, constructor names, etc.) into zero or
3351 /// more declarations within a particular scope. The major entry
3352 /// points are LookupName, which performs unqualified name lookup,
3353 /// and LookupQualifiedName, which performs qualified name lookup.
3354 ///
3355 /// All name lookup is performed based on some specific criteria,
3356 /// which specify what names will be visible to name lookup and how
3357 /// far name lookup should work. These criteria are important both
3358 /// for capturing language semantics (certain lookups will ignore
3359 /// certain names, for example) and for performance, since name
3360 /// lookup is often a bottleneck in the compilation of C++. Name
3361 /// lookup criteria is specified via the LookupCriteria enumeration.
3362 ///
3363 /// The results of name lookup can vary based on the kind of name
3364 /// lookup performed, the current language, and the translation
3365 /// unit. In C, for example, name lookup will either return nothing
3366 /// (no entity found) or a single declaration. In C++, name lookup
3367 /// can additionally refer to a set of overloaded functions or
3368 /// result in an ambiguity. All of the possible results of name
3369 /// lookup are captured by the LookupResult class, which provides
3370 /// the ability to distinguish among them.
3371 //@{
3372
3373 /// Describes the kind of name lookup to perform.
3374 enum LookupNameKind {
3375 /// Ordinary name lookup, which finds ordinary names (functions,
3376 /// variables, typedefs, etc.) in C and most kinds of names
3377 /// (functions, variables, members, types, etc.) in C++.
3378 LookupOrdinaryName = 0,
3379 /// Tag name lookup, which finds the names of enums, classes,
3380 /// structs, and unions.
3381 LookupTagName,
3382 /// Label name lookup.
3383 LookupLabel,
3384 /// Member name lookup, which finds the names of
3385 /// class/struct/union members.
3386 LookupMemberName,
3387 /// Look up of an operator name (e.g., operator+) for use with
3388 /// operator overloading. This lookup is similar to ordinary name
3389 /// lookup, but will ignore any declarations that are class members.
3390 LookupOperatorName,
3391 /// Look up of a name that precedes the '::' scope resolution
3392 /// operator in C++. This lookup completely ignores operator, object,
3393 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3394 LookupNestedNameSpecifierName,
3395 /// Look up a namespace name within a C++ using directive or
3396 /// namespace alias definition, ignoring non-namespace names (C++
3397 /// [basic.lookup.udir]p1).
3398 LookupNamespaceName,
3399 /// Look up all declarations in a scope with the given name,
3400 /// including resolved using declarations. This is appropriate
3401 /// for checking redeclarations for a using declaration.
3402 LookupUsingDeclName,
3403 /// Look up an ordinary name that is going to be redeclared as a
3404 /// name with linkage. This lookup ignores any declarations that
3405 /// are outside of the current scope unless they have linkage. See
3406 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3407 LookupRedeclarationWithLinkage,
3408 /// Look up a friend of a local class. This lookup does not look
3409 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3410 LookupLocalFriendName,
3411 /// Look up the name of an Objective-C protocol.
3412 LookupObjCProtocolName,
3413 /// Look up implicit 'self' parameter of an objective-c method.
3414 LookupObjCImplicitSelfParam,
3415 /// Look up the name of an OpenMP user-defined reduction operation.
3416 LookupOMPReductionName,
3417 /// Look up the name of an OpenMP user-defined mapper.
3418 LookupOMPMapperName,
3419 /// Look up any declaration with any name.
3420 LookupAnyName
3421 };
3422
3423 /// Specifies whether (or how) name lookup is being performed for a
3424 /// redeclaration (vs. a reference).
3425 enum RedeclarationKind {
3426 /// The lookup is a reference to this name that is not for the
3427 /// purpose of redeclaring the name.
3428 NotForRedeclaration = 0,
3429 /// The lookup results will be used for redeclaration of a name,
3430 /// if an entity by that name already exists and is visible.
3431 ForVisibleRedeclaration,
3432 /// The lookup results will be used for redeclaration of a name
3433 /// with external linkage; non-visible lookup results with external linkage
3434 /// may also be found.
3435 ForExternalRedeclaration
3436 };
3437
3438 RedeclarationKind forRedeclarationInCurContext() {
3439 // A declaration with an owning module for linkage can never link against
3440 // anything that is not visible. We don't need to check linkage here; if
3441 // the context has internal linkage, redeclaration lookup won't find things
3442 // from other TUs, and we can't safely compute linkage yet in general.
3443 if (cast<Decl>(CurContext)
3444 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3445 return ForVisibleRedeclaration;
3446 return ForExternalRedeclaration;
3447 }
3448
3449 /// The possible outcomes of name lookup for a literal operator.
3450 enum LiteralOperatorLookupResult {
3451 /// The lookup resulted in an error.
3452 LOLR_Error,
3453 /// The lookup found no match but no diagnostic was issued.
3454 LOLR_ErrorNoDiagnostic,
3455 /// The lookup found a single 'cooked' literal operator, which
3456 /// expects a normal literal to be built and passed to it.
3457 LOLR_Cooked,
3458 /// The lookup found a single 'raw' literal operator, which expects
3459 /// a string literal containing the spelling of the literal token.
3460 LOLR_Raw,
3461 /// The lookup found an overload set of literal operator templates,
3462 /// which expect the characters of the spelling of the literal token to be
3463 /// passed as a non-type template argument pack.
3464 LOLR_Template,
3465 /// The lookup found an overload set of literal operator templates,
3466 /// which expect the character type and characters of the spelling of the
3467 /// string literal token to be passed as template arguments.
3468 LOLR_StringTemplate
3469 };
3470
3471 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3472 CXXSpecialMember SM,
3473 bool ConstArg,
3474 bool VolatileArg,
3475 bool RValueThis,
3476 bool ConstThis,
3477 bool VolatileThis);
3478
3479 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3480 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3481 TypoRecoveryCallback;
3482
3483private:
3484 bool CppLookupName(LookupResult &R, Scope *S);
3485
3486 struct TypoExprState {
3487 std::unique_ptr<TypoCorrectionConsumer> Consumer;
3488 TypoDiagnosticGenerator DiagHandler;
3489 TypoRecoveryCallback RecoveryHandler;
3490 TypoExprState();
3491 TypoExprState(TypoExprState &&other) noexcept;
3492 TypoExprState &operator=(TypoExprState &&other) noexcept;
3493 };
3494
3495 /// The set of unhandled TypoExprs and their associated state.
3496 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3497
3498 /// Creates a new TypoExpr AST node.
3499 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3500 TypoDiagnosticGenerator TDG,
3501 TypoRecoveryCallback TRC);
3502
3503 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
3504 //
3505 // The boolean value will be true to indicate that the namespace was loaded
3506 // from an AST/PCH file, or false otherwise.
3507 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3508
3509 /// Whether we have already loaded known namespaces from an extenal
3510 /// source.
3511 bool LoadedExternalKnownNamespaces;
3512
3513 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
3514 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3515 /// should be skipped entirely.
3516 std::unique_ptr<TypoCorrectionConsumer>
3517 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3518 Sema::LookupNameKind LookupKind, Scope *S,
3519 CXXScopeSpec *SS,
3520 CorrectionCandidateCallback &CCC,
3521 DeclContext *MemberContext, bool EnteringContext,
3522 const ObjCObjectPointerType *OPT,
3523 bool ErrorRecovery);
3524
3525public:
3526 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3527
3528 /// Clears the state of the given TypoExpr.
3529 void clearDelayedTypo(TypoExpr *TE);
3530
3531 /// Look up a name, looking for a single declaration. Return
3532 /// null if the results were absent, ambiguous, or overloaded.
3533 ///
3534 /// It is preferable to use the elaborated form and explicitly handle
3535 /// ambiguity and overloaded.
3536 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3537 SourceLocation Loc,
3538 LookupNameKind NameKind,
3539 RedeclarationKind Redecl
3540 = NotForRedeclaration);
3541 bool LookupBuiltin(LookupResult &R);
3542 bool LookupName(LookupResult &R, Scope *S,
3543 bool AllowBuiltinCreation = false);
3544 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3545 bool InUnqualifiedLookup = false);
3546 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3547 CXXScopeSpec &SS);
3548 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3549 bool AllowBuiltinCreation = false,
3550 bool EnteringContext = false);
3551 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3552 RedeclarationKind Redecl
3553 = NotForRedeclaration);
3554 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3555
3556 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3557 QualType T1, QualType T2,
3558 UnresolvedSetImpl &Functions);
3559
3560 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3561 SourceLocation GnuLabelLoc = SourceLocation());
3562
3563 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3564 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3565 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3566 unsigned Quals);
3567 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3568 bool RValueThis, unsigned ThisQuals);
3569 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3570 unsigned Quals);
3571 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3572 bool RValueThis, unsigned ThisQuals);
3573 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3574
3575 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3576 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3577 ArrayRef<QualType> ArgTys,
3578 bool AllowRaw,
3579 bool AllowTemplate,
3580 bool AllowStringTemplate,
3581 bool DiagnoseMissing);
3582 bool isKnownName(StringRef name);
3583
3584 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
3585 enum class FunctionEmissionStatus {
3586 Emitted,
3587 CUDADiscarded, // Discarded due to CUDA/HIP hostness
3588 OMPDiscarded, // Discarded due to OpenMP hostness
3589 TemplateDiscarded, // Discarded due to uninstantiated templates
3590 Unknown,
3591 };
3592 FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl);
3593
3594 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
3595 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
3596
3597 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3598 ArrayRef<Expr *> Args, ADLResult &Functions);
3599
3600 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3601 VisibleDeclConsumer &Consumer,
3602 bool IncludeGlobalScope = true,
3603 bool LoadExternal = true);
3604 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3605 VisibleDeclConsumer &Consumer,
3606 bool IncludeGlobalScope = true,
3607 bool IncludeDependentBases = false,
3608 bool LoadExternal = true);
3609
3610 enum CorrectTypoKind {
3611 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3612 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3613 };
3614
3615 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3616 Sema::LookupNameKind LookupKind,
3617 Scope *S, CXXScopeSpec *SS,
3618 CorrectionCandidateCallback &CCC,
3619 CorrectTypoKind Mode,
3620 DeclContext *MemberContext = nullptr,
3621 bool EnteringContext = false,
3622 const ObjCObjectPointerType *OPT = nullptr,
3623 bool RecordFailure = true);
3624
3625 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3626 Sema::LookupNameKind LookupKind, Scope *S,
3627 CXXScopeSpec *SS,
3628 CorrectionCandidateCallback &CCC,
3629 TypoDiagnosticGenerator TDG,
3630 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3631 DeclContext *MemberContext = nullptr,
3632 bool EnteringContext = false,
3633 const ObjCObjectPointerType *OPT = nullptr);
3634
3635 /// Process any TypoExprs in the given Expr and its children,
3636 /// generating diagnostics as appropriate and returning a new Expr if there
3637 /// were typos that were all successfully corrected and ExprError if one or
3638 /// more typos could not be corrected.
3639 ///
3640 /// \param E The Expr to check for TypoExprs.
3641 ///
3642 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3643 /// initializer.
3644 ///
3645 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3646 /// it is an acceptable/usable result from a single combination of typo
3647 /// corrections. As long as the filter returns ExprError, different
3648 /// combinations of corrections will be tried until all are exhausted.
3649 ExprResult
3650 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3651 llvm::function_ref<ExprResult(Expr *)> Filter =
3652 [](Expr *E) -> ExprResult { return E; });
3653
3654 ExprResult
3655 CorrectDelayedTyposInExpr(Expr *E,
3656 llvm::function_ref<ExprResult(Expr *)> Filter) {
3657 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3658 }
3659
3660 ExprResult
3661 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3662 llvm::function_ref<ExprResult(Expr *)> Filter =
3663 [](Expr *E) -> ExprResult { return E; }) {
3664 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3665 }
3666
3667 ExprResult
3668 CorrectDelayedTyposInExpr(ExprResult ER,
3669 llvm::function_ref<ExprResult(Expr *)> Filter) {
3670 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3671 }
3672
3673 void diagnoseTypo(const TypoCorrection &Correction,
3674 const PartialDiagnostic &TypoDiag,
3675 bool ErrorRecovery = true);
3676
3677 void diagnoseTypo(const TypoCorrection &Correction,
3678 const PartialDiagnostic &TypoDiag,
3679 const PartialDiagnostic &PrevNote,
3680 bool ErrorRecovery = true);
3681
3682 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3683
3684 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3685 ArrayRef<Expr *> Args,
3686 AssociatedNamespaceSet &AssociatedNamespaces,
3687 AssociatedClassSet &AssociatedClasses);
3688
3689 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3690 bool ConsiderLinkage, bool AllowInlineNamespace);
3691
3692 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3693
3694 void DiagnoseAmbiguousLookup(LookupResult &Result);
3695 //@}
3696
3697 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3698 SourceLocation IdLoc,
3699 bool TypoCorrection = false);
3700 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3701 Scope *S, bool ForRedeclaration,
3702 SourceLocation Loc);
3703 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3704 Scope *S);
3705 void AddKnownFunctionAttributes(FunctionDecl *FD);
3706
3707 // More parsing and symbol table subroutines.
3708
3709 void ProcessPragmaWeak(Scope *S, Decl *D);
3710 // Decl attributes - this routine is the top level dispatcher.
3711 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3712 // Helper for delayed processing of attributes.
3713 void ProcessDeclAttributeDelayed(Decl *D,
3714 const ParsedAttributesView &AttrList);
3715 void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
3716 bool IncludeCXX11Attributes = true);
3717 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3718 const ParsedAttributesView &AttrList);
3719
3720 void checkUnusedDeclAttributes(Declarator &D);
3721
3722 /// Determine if type T is a valid subject for a nonnull and similar
3723 /// attributes. By default, we look through references (the behavior used by
3724 /// nonnull), but if the second parameter is true, then we treat a reference
3725 /// type as valid.
3726 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3727
3728 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
3729 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
3730 const FunctionDecl *FD = nullptr);
3731 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
3732 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
3733 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
3734 StringRef &Str,
3735 SourceLocation *ArgLocation = nullptr);
3736 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3737 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3738 bool checkMSInheritanceAttrOnDefinition(
3739 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3740 MSInheritanceAttr::Spelling SemanticSpelling);
3741
3742 void CheckAlignasUnderalignment(Decl *D);
3743
3744 /// Adjust the calling convention of a method to be the ABI default if it
3745 /// wasn't specified explicitly. This handles method types formed from
3746 /// function type typedefs and typename template arguments.
3747 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3748 SourceLocation Loc);
3749
3750 // Check if there is an explicit attribute, but only look through parens.
3751 // The intent is to look for an attribute on the current declarator, but not
3752 // one that came from a typedef.
3753 bool hasExplicitCallingConv(QualType T);
3754
3755 /// Get the outermost AttributedType node that sets a calling convention.
3756 /// Valid types should not have multiple attributes with different CCs.
3757 const AttributedType *getCallingConvAttributedType(QualType T) const;
3758
3759 /// Stmt attributes - this routine is the top level dispatcher.
3760 StmtResult ProcessStmtAttributes(Stmt *Stmt,
3761 const ParsedAttributesView &Attrs,
3762 SourceRange Range);
3763
3764 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3765 ObjCMethodDecl *MethodDecl,
3766 bool IsProtocolMethodDecl);
3767
3768 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3769 ObjCMethodDecl *Overridden,
3770 bool IsProtocolMethodDecl);
3771
3772 /// WarnExactTypedMethods - This routine issues a warning if method
3773 /// implementation declaration matches exactly that of its declaration.
3774 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3775 ObjCMethodDecl *MethodDecl,
3776 bool IsProtocolMethodDecl);
3777
3778 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3779
3780 /// CheckImplementationIvars - This routine checks if the instance variables
3781 /// listed in the implelementation match those listed in the interface.
3782 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3783 ObjCIvarDecl **Fields, unsigned nIvars,
3784 SourceLocation Loc);
3785
3786 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3787 /// remains unimplemented in the class or category \@implementation.
3788 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3789 ObjCContainerDecl* IDecl,
3790 bool IncompleteImpl = false);
3791
3792 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3793 /// which must be implemented by this implementation.
3794 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3795 ObjCContainerDecl *CDecl,
3796 bool SynthesizeProperties);
3797
3798 /// Diagnose any null-resettable synthesized setters.
3799 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3800
3801 /// DefaultSynthesizeProperties - This routine default synthesizes all
3802 /// properties which must be synthesized in the class's \@implementation.
3803 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3804 ObjCInterfaceDecl *IDecl,
3805 SourceLocation AtEnd);
3806 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3807
3808 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3809 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3810 /// declared in class 'IFace'.
3811 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3812 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3813
3814 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3815 /// backs the property is not used in the property's accessor.
3816 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3817 const ObjCImplementationDecl *ImplD);
3818
3819 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3820 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3821 /// It also returns ivar's property on success.
3822 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3823 const ObjCPropertyDecl *&PDecl) const;
3824
3825 /// Called by ActOnProperty to handle \@property declarations in
3826 /// class extensions.
3827 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3828 SourceLocation AtLoc,
3829 SourceLocation LParenLoc,
3830 FieldDeclarator &FD,
3831 Selector GetterSel,
3832 SourceLocation GetterNameLoc,
3833 Selector SetterSel,
3834 SourceLocation SetterNameLoc,
3835 const bool isReadWrite,
3836 unsigned &Attributes,
3837 const unsigned AttributesAsWritten,
3838 QualType T,
3839 TypeSourceInfo *TSI,
3840 tok::ObjCKeywordKind MethodImplKind);
3841
3842 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3843 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3844 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3845 ObjCContainerDecl *CDecl,
3846 SourceLocation AtLoc,
3847 SourceLocation LParenLoc,
3848 FieldDeclarator &FD,
3849 Selector GetterSel,
3850 SourceLocation GetterNameLoc,
3851 Selector SetterSel,
3852 SourceLocation SetterNameLoc,
3853 const bool isReadWrite,
3854 const unsigned Attributes,
3855 const unsigned AttributesAsWritten,
3856 QualType T,
3857 TypeSourceInfo *TSI,
3858 tok::ObjCKeywordKind MethodImplKind,
3859 DeclContext *lexicalDC = nullptr);
3860
3861 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3862 /// warning) when atomic property has one but not the other user-declared
3863 /// setter or getter.
3864 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3865 ObjCInterfaceDecl* IDecl);
3866
3867 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3868
3869 void DiagnoseMissingDesignatedInitOverrides(
3870 const ObjCImplementationDecl *ImplD,
3871 const ObjCInterfaceDecl *IFD);
3872
3873 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3874
3875 enum MethodMatchStrategy {
3876 MMS_loose,
3877 MMS_strict
3878 };
3879
3880 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3881 /// true, or false, accordingly.
3882 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3883 const ObjCMethodDecl *PrevMethod,
3884 MethodMatchStrategy strategy = MMS_strict);
3885
3886 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3887 /// or protocol against those declared in their implementations.
3888 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3889 const SelectorSet &ClsMap,
3890 SelectorSet &InsMapSeen,
3891 SelectorSet &ClsMapSeen,
3892 ObjCImplDecl* IMPDecl,
3893 ObjCContainerDecl* IDecl,
3894 bool &IncompleteImpl,
3895 bool ImmediateClass,
3896 bool WarnCategoryMethodImpl=false);
3897
3898 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3899 /// category matches with those implemented in its primary class and
3900 /// warns each time an exact match is found.
3901 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3902
3903 /// Add the given method to the list of globally-known methods.
3904 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3905
3906private:
3907 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3908 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3909 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3910
3911 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3912 /// optionally warns if there are multiple signatures.
3913 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3914 bool receiverIdOrClass,
3915 bool instance);
3916
3917public:
3918 /// - Returns instance or factory methods in global method pool for
3919 /// given selector. It checks the desired kind first, if none is found, and
3920 /// parameter checkTheOther is set, it then checks the other kind. If no such
3921 /// method or only one method is found, function returns false; otherwise, it
3922 /// returns true.
3923 bool
3924 CollectMultipleMethodsInGlobalPool(Selector Sel,
3925 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3926 bool InstanceFirst, bool CheckTheOther,
3927 const ObjCObjectType *TypeBound = nullptr);
3928
3929 bool
3930 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3931 SourceRange R, bool receiverIdOrClass,
3932 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3933
3934 void
3935 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3936 Selector Sel, SourceRange R,
3937 bool receiverIdOrClass);
3938
3939private:
3940 /// - Returns a selector which best matches given argument list or
3941 /// nullptr if none could be found
3942 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3943 bool IsInstance,
3944 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3945
3946
3947 /// Record the typo correction failure and return an empty correction.
3948 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3949 bool RecordFailure = true) {
3950 if (RecordFailure)
3951 TypoCorrectionFailures[Typo].insert(TypoLoc);
3952 return TypoCorrection();
3953 }
3954
3955public:
3956 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3957 /// unit are added to a global pool. This allows us to efficiently associate
3958 /// a selector with a method declaraation for purposes of typechecking
3959 /// messages sent to "id" (where the class of the object is unknown).
3960 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3961 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3962 }
3963
3964 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3965 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3966 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3967 }
3968
3969 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3970 /// pool.
3971 void AddAnyMethodToGlobalPool(Decl *D);
3972
3973 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3974 /// there are multiple signatures.
3975 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3976 bool receiverIdOrClass=false) {
3977 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3978 /*instance*/true);
3979 }
3980
3981 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3982 /// there are multiple signatures.
3983 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3984 bool receiverIdOrClass=false) {
3985 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3986 /*instance*/false);
3987 }
3988
3989 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3990 QualType ObjectType=QualType());
3991 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3992 /// implementation.
3993 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3994
3995 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3996 /// initialization.
3997 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3998 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3999
4000 //===--------------------------------------------------------------------===//
4001 // Statement Parsing Callbacks: SemaStmt.cpp.
4002public:
4003 class FullExprArg {
4004 public:
4005 FullExprArg() : E(nullptr) { }
4006 FullExprArg(Sema &actions) : E(nullptr) { }
4007
4008 ExprResult release() {
4009 return E;
4010 }
4011
4012 Expr *get() const { return E; }
4013
4014 Expr *operator->() {
4015 return E;
4016 }
4017
4018 private:
4019 // FIXME: No need to make the entire Sema class a friend when it's just
4020 // Sema::MakeFullExpr that needs access to the constructor below.
4021 friend class Sema;
4022
4023 explicit FullExprArg(Expr *expr) : E(expr) {}
4024
4025 Expr *E;
4026 };
4027
4028 FullExprArg MakeFullExpr(Expr *Arg) {
4029 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4030 }
4031 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
4032 return FullExprArg(
4033 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4034 }
4035 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
4036 ExprResult FE =
4037 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4038 /*DiscardedValue*/ true);
4039 return FullExprArg(FE.get());
4040 }
4041
4042 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4043 StmtResult ActOnExprStmtError();
4044
4045 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
4046 bool HasLeadingEmptyMacro = false);
4047
4048 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4049 void ActOnFinishOfCompoundStmt();
4050 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4051 ArrayRef<Stmt *> Elts, bool isStmtExpr);
4052
4053 /// A RAII object to enter scope of a compound statement.
4054 class CompoundScopeRAII {
4055 public:
4056 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
4057 S.ActOnStartOfCompoundStmt(IsStmtExpr);
4058 }
4059
4060 ~CompoundScopeRAII() {
4061 S.ActOnFinishOfCompoundStmt();
4062 }
4063
4064 private:
4065 Sema &S;
4066 };
4067
4068 /// An RAII helper that pops function a function scope on exit.
4069 struct FunctionScopeRAII {
4070 Sema &S;
4071 bool Active;
4072 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
4073 ~FunctionScopeRAII() {
4074 if (Active)
4075 S.PopFunctionScopeInfo();
4076 }
4077 void disable() { Active = false; }
4078 };
4079
4080 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4081 SourceLocation StartLoc,
4082 SourceLocation EndLoc);
4083 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4084 StmtResult ActOnForEachLValueExpr(Expr *E);
4085 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4086 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4087 SourceLocation DotDotDotLoc, ExprResult RHS,
4088 SourceLocation ColonLoc);
4089 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4090
4091 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4092 SourceLocation ColonLoc,
4093 Stmt *SubStmt, Scope *CurScope);
4094 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4095 SourceLocation ColonLoc, Stmt *SubStmt);
4096
4097 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
4098 ArrayRef<const Attr*> Attrs,
4099 Stmt *SubStmt);
4100
4101 class ConditionResult;
4102 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4103 Stmt *InitStmt,
4104 ConditionResult Cond, Stmt *ThenVal,
4105 SourceLocation ElseLoc, Stmt *ElseVal);
4106 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4107 Stmt *InitStmt,
4108 ConditionResult Cond, Stmt *ThenVal,
4109 SourceLocation ElseLoc, Stmt *ElseVal);
4110 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4111 Stmt *InitStmt,
4112 ConditionResult Cond);
4113 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4114 Stmt *Switch, Stmt *Body);
4115 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
4116 Stmt *Body);
4117 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4118 SourceLocation WhileLoc, SourceLocation CondLParen,
4119 Expr *Cond, SourceLocation CondRParen);
4120
4121 StmtResult ActOnForStmt(SourceLocation ForLoc,
4122 SourceLocation LParenLoc,
4123 Stmt *First,
4124 ConditionResult Second,
4125 FullExprArg Third,
4126 SourceLocation RParenLoc,
4127 Stmt *Body);
4128 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4129 Expr *collection);
4130 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4131 Stmt *First, Expr *collection,
4132 SourceLocation RParenLoc);
4133 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4134
4135 enum BuildForRangeKind {
4136 /// Initial building of a for-range statement.
4137 BFRK_Build,
4138 /// Instantiation or recovery rebuild of a for-range statement. Don't
4139 /// attempt any typo-correction.
4140 BFRK_Rebuild,
4141 /// Determining whether a for-range statement could be built. Avoid any
4142 /// unnecessary or irreversible actions.
4143 BFRK_Check
4144 };
4145
4146 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4147 SourceLocation CoawaitLoc,
4148 Stmt *InitStmt,
4149 Stmt *LoopVar,
4150 SourceLocation ColonLoc, Expr *Collection,
4151 SourceLocation RParenLoc,
4152 BuildForRangeKind Kind);
4153 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4154 SourceLocation CoawaitLoc,
4155 Stmt *InitStmt,
4156 SourceLocation ColonLoc,
4157 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4158 Expr *Cond, Expr *Inc,
4159 Stmt *LoopVarDecl,
4160 SourceLocation RParenLoc,
4161 BuildForRangeKind Kind);
4162 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
4163
4164 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
4165 SourceLocation LabelLoc,
4166 LabelDecl *TheDecl);
4167 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
4168 SourceLocation StarLoc,
4169 Expr *DestExp);
4170 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
4171 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
4172
4173 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4174 CapturedRegionKind Kind, unsigned NumParams);
4175 typedef std::pair<StringRef, QualType> CapturedParamNameType;
4176 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4177 CapturedRegionKind Kind,
4178 ArrayRef<CapturedParamNameType> Params,
4179 unsigned OpenMPCaptureLevel = 0);
4180 StmtResult ActOnCapturedRegionEnd(Stmt *S);
4181 void ActOnCapturedRegionError();
4182 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
4183 SourceLocation Loc,
4184 unsigned NumParams);
4185
4186 enum CopyElisionSemanticsKind {
4187 CES_Strict = 0,
4188 CES_AllowParameters = 1,
4189 CES_AllowDifferentTypes = 2,
4190 CES_AllowExceptionVariables = 4,
4191 CES_FormerDefault = (CES_AllowParameters),
4192 CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
4193 CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
4194 CES_AllowExceptionVariables),
4195 };
4196
4197 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
4198 CopyElisionSemanticsKind CESK);
4199 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
4200 CopyElisionSemanticsKind CESK);
4201
4202 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4203 Scope *CurScope);
4204 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4205 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4206
4207 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4208 bool IsVolatile, unsigned NumOutputs,
4209 unsigned NumInputs, IdentifierInfo **Names,
4210 MultiExprArg Constraints, MultiExprArg Exprs,
4211 Expr *AsmString, MultiExprArg Clobbers,
4212 unsigned NumLabels,
4213 SourceLocation RParenLoc);
4214
4215 void FillInlineAsmIdentifierInfo(Expr *Res,
4216 llvm::InlineAsmIdentifierInfo &Info);
4217 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4218 SourceLocation TemplateKWLoc,
4219 UnqualifiedId &Id,
4220 bool IsUnevaluatedContext);
4221 bool LookupInlineAsmField(StringRef Base, StringRef Member,
4222 unsigned &Offset, SourceLocation AsmLoc);
4223 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4224 SourceLocation AsmLoc);
4225 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4226 ArrayRef<Token> AsmToks,
4227 StringRef AsmString,
4228 unsigned NumOutputs, unsigned NumInputs,
4229 ArrayRef<StringRef> Constraints,
4230 ArrayRef<StringRef> Clobbers,
4231 ArrayRef<Expr*> Exprs,
4232 SourceLocation EndLoc);
4233 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4234 SourceLocation Location,
4235 bool AlwaysCreate);
4236
4237 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4238 SourceLocation StartLoc,
4239 SourceLocation IdLoc, IdentifierInfo *Id,
4240 bool Invalid = false);
4241
4242 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4243
4244 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4245 Decl *Parm, Stmt *Body);
4246
4247 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
4248
4249 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4250 MultiStmtArg Catch, Stmt *Finally);
4251
4252 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
4253 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4254 Scope *CurScope);
4255 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
4256 Expr *operand);
4257 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
4258 Expr *SynchExpr,
4259 Stmt *SynchBody);
4260
4261 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
4262
4263 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
4264 SourceLocation StartLoc,
4265 SourceLocation IdLoc,
4266 IdentifierInfo *Id);
4267
4268 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
4269
4270 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
4271 Decl *ExDecl, Stmt *HandlerBlock);
4272 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4273 ArrayRef<Stmt *> Handlers);
4274
4275 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
4276 SourceLocation TryLoc, Stmt *TryBlock,
4277 Stmt *Handler);
4278 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
4279 Expr *FilterExpr,
4280 Stmt *Block);
4281 void ActOnStartSEHFinallyBlock();
4282 void ActOnAbortSEHFinallyBlock();
4283 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
4284 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
4285
4286 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
4287
4288 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4289
4290 /// If it's a file scoped decl that must warn if not used, keep track
4291 /// of it.
4292 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4293
4294 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
4295 /// whose result is unused, warn.
4296 void DiagnoseUnusedExprResult(const Stmt *S);
4297 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4298 void DiagnoseUnusedDecl(const NamedDecl *ND);
4299
4300 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
4301 /// statement as a \p Body, and it is located on the same line.
4302 ///
4303 /// This helps prevent bugs due to typos, such as:
4304 /// if (condition);
4305 /// do_stuff();
4306 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4307 const Stmt *Body,
4308 unsigned DiagID);
4309
4310 /// Warn if a for/while loop statement \p S, which is followed by
4311 /// \p PossibleBody, has a suspicious null statement as a body.
4312 void DiagnoseEmptyLoopBody(const Stmt *S,
4313 const Stmt *PossibleBody);
4314
4315 /// Warn if a value is moved to itself.
4316 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
4317 SourceLocation OpLoc);
4318
4319 /// Warn if we're implicitly casting from a _Nullable pointer type to a
4320 /// _Nonnull one.
4321 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
4322 SourceLocation Loc);
4323
4324 /// Warn when implicitly casting 0 to nullptr.
4325 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
4326
4327 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
4328 return DelayedDiagnostics.push(pool);
4329 }
4330 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
4331
4332 typedef ProcessingContextState ParsingClassState;
4333 ParsingClassState PushParsingClass() {
4334 return DelayedDiagnostics.pushUndelayed();
4335 }
4336 void PopParsingClass(ParsingClassState state) {
4337 DelayedDiagnostics.popUndelayed(state);
4338 }
4339
4340 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
4341
4342 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4343 const ObjCInterfaceDecl *UnknownObjCClass,
4344 bool ObjCPropertyAccess,
4345 bool AvoidPartialAvailabilityChecks = false,
4346 ObjCInterfaceDecl *ClassReceiver = nullptr);
4347
4348 bool makeUnavailableInSystemHeader(SourceLocation loc,
4349 UnavailableAttr::ImplicitReason reason);
4350
4351 /// Issue any -Wunguarded-availability warnings in \c FD
4352 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
4353
4354 //===--------------------------------------------------------------------===//
4355 // Expression Parsing Callbacks: SemaExpr.cpp.
4356
4357 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4358 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4359 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4360 bool ObjCPropertyAccess = false,
4361 bool AvoidPartialAvailabilityChecks = false,
4362 ObjCInterfaceDecl *ClassReciever = nullptr);
4363 void NoteDeletedFunction(FunctionDecl *FD);
4364 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
4365 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
4366 ObjCMethodDecl *Getter,
4367 SourceLocation Loc);
4368 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
4369 ArrayRef<Expr *> Args);
4370
4371 void PushExpressionEvaluationContext(
4372 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
4373 ExpressionEvaluationContextRecord::ExpressionKind Type =
4374 ExpressionEvaluationContextRecord::EK_Other);
4375 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
4376 void PushExpressionEvaluationContext(
4377 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
4378 ExpressionEvaluationContextRecord::ExpressionKind Type =
4379 ExpressionEvaluationContextRecord::EK_Other);
4380 void PopExpressionEvaluationContext();
4381
4382 void DiscardCleanupsInEvaluationContext();
4383
4384 ExprResult TransformToPotentiallyEvaluated(Expr *E);
4385 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
4386
4387 ExprResult CheckUnevaluatedOperand(Expr *E);
4388 void CheckUnusedVolatileAssignment(Expr *E);
4389
4390 ExprResult ActOnConstantExpression(ExprResult Res);
4391
4392 // Functions for marking a declaration referenced. These functions also
4393 // contain the relevant logic for marking if a reference to a function or
4394 // variable is an odr-use (in the C++11 sense). There are separate variants
4395 // for expressions referring to a decl; these exist because odr-use marking
4396 // needs to be delayed for some constant variables when we build one of the
4397 // named expressions.
4398 //
4399 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4400 // should usually be true. This only needs to be set to false if the lack of
4401 // odr-use cannot be determined from the current context (for instance,
4402 // because the name denotes a virtual function and was written without an
4403 // explicit nested-name-specifier).
4404 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4405 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4406 bool MightBeOdrUse = true);
4407 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4408 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4409 void MarkMemberReferenced(MemberExpr *E);
4410 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
4411 void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
4412 unsigned CapturingScopeIndex);
4413
4414 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
4415 void CleanupVarDeclMarking();
4416
4417 enum TryCaptureKind {
4418 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4419 };
4420
4421 /// Try to capture the given variable.
4422 ///
4423 /// \param Var The variable to capture.
4424 ///
4425 /// \param Loc The location at which the capture occurs.
4426 ///
4427 /// \param Kind The kind of capture, which may be implicit (for either a
4428 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4429 ///
4430 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4431 /// an explicit lambda capture.
4432 ///
4433 /// \param BuildAndDiagnose Whether we are actually supposed to add the
4434 /// captures or diagnose errors. If false, this routine merely check whether
4435 /// the capture can occur without performing the capture itself or complaining
4436 /// if the variable cannot be captured.
4437 ///
4438 /// \param CaptureType Will be set to the type of the field used to capture
4439 /// this variable in the innermost block or lambda. Only valid when the
4440 /// variable can be captured.
4441 ///
4442 /// \param DeclRefType Will be set to the type of a reference to the capture
4443 /// from within the current scope. Only valid when the variable can be
4444 /// captured.
4445 ///
4446 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4447 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4448 /// This is useful when enclosing lambdas must speculatively capture
4449 /// variables that may or may not be used in certain specializations of
4450 /// a nested generic lambda.
4451 ///
4452 /// \returns true if an error occurred (i.e., the variable cannot be
4453 /// captured) and false if the capture succeeded.
4454 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4455 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4456 QualType &CaptureType,
4457 QualType &DeclRefType,
4458 const unsigned *const FunctionScopeIndexToStopAt);
4459
4460 /// Try to capture the given variable.
4461 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4462 TryCaptureKind Kind = TryCapture_Implicit,
4463 SourceLocation EllipsisLoc = SourceLocation());
4464
4465 /// Checks if the variable must be captured.
4466 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4467
4468 /// Given a variable, determine the type that a reference to that
4469 /// variable will have in the given scope.
4470 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4471
4472 /// Mark all of the declarations referenced within a particular AST node as
4473 /// referenced. Used when template instantiation instantiates a non-dependent
4474 /// type -- entities referenced by the type are now referenced.
4475 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4476 void MarkDeclarationsReferencedInExpr(Expr *E,
4477 bool SkipLocalVariables = false);
4478
4479 /// Try to recover by turning the given expression into a
4480 /// call. Returns true if recovery was attempted or an error was
4481 /// emitted; this may also leave the ExprResult invalid.
4482 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4483 bool ForceComplain = false,
4484 bool (*IsPlausibleResult)(QualType) = nullptr);
4485
4486 /// Figure out if an expression could be turned into a call.
4487 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4488 UnresolvedSetImpl &NonTemplateOverloads);
4489
4490 /// Conditionally issue a diagnostic based on the current
4491 /// evaluation context.
4492 ///
4493 /// \param Statement If Statement is non-null, delay reporting the
4494 /// diagnostic until the function body is parsed, and then do a basic
4495 /// reachability analysis to determine if the statement is reachable.
4496 /// If it is unreachable, the diagnostic will not be emitted.
4497 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4498 const PartialDiagnostic &PD);
4499 /// Similar, but diagnostic is only produced if all the specified statements
4500 /// are reachable.
4501 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
4502 const PartialDiagnostic &PD);
4503
4504 // Primary Expressions.
4505 SourceRange getExprRange(Expr *E) const;
4506
4507 ExprResult ActOnIdExpression(
4508 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4509 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4510 CorrectionCandidateCallback *CCC = nullptr,
4511 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4512
4513 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4514 TemplateArgumentListInfo &Buffer,
4515 DeclarationNameInfo &NameInfo,
4516 const TemplateArgumentListInfo *&TemplateArgs);
4517
4518 bool
4519 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4520 CorrectionCandidateCallback &CCC,
4521 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4522 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4523
4524 DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
4525 IdentifierInfo *II);
4526 ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
4527
4528 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4529 IdentifierInfo *II,
4530 bool AllowBuiltinCreation=false);
4531
4532 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4533 SourceLocation TemplateKWLoc,
4534 const DeclarationNameInfo &NameInfo,
4535 bool isAddressOfOperand,
4536 const TemplateArgumentListInfo *TemplateArgs);
4537
4538 /// If \p D cannot be odr-used in the current expression evaluation context,
4539 /// return a reason explaining why. Otherwise, return NOUR_None.
4540 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
4541
4542 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4543 SourceLocation Loc,
4544 const CXXScopeSpec *SS = nullptr);
4545 DeclRefExpr *
4546 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4547 const DeclarationNameInfo &NameInfo,
4548 const CXXScopeSpec *SS = nullptr,
4549 NamedDecl *FoundD = nullptr,
4550 SourceLocation TemplateKWLoc = SourceLocation(),
4551 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4552 DeclRefExpr *
4553 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4554 const DeclarationNameInfo &NameInfo,
4555 NestedNameSpecifierLoc NNS,
4556 NamedDecl *FoundD = nullptr,
4557 SourceLocation TemplateKWLoc = SourceLocation(),
4558 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4559
4560 ExprResult
4561 BuildAnonymousStructUnionMemberReference(
4562 const CXXScopeSpec &SS,
4563 SourceLocation nameLoc,
4564 IndirectFieldDecl *indirectField,
4565 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4566 Expr *baseObjectExpr = nullptr,
4567 SourceLocation opLoc = SourceLocation());
4568
4569 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4570 SourceLocation TemplateKWLoc,
4571 LookupResult &R,
4572 const TemplateArgumentListInfo *TemplateArgs,
4573 const Scope *S);
4574 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4575 SourceLocation TemplateKWLoc,
4576 LookupResult &R,
4577 const TemplateArgumentListInfo *TemplateArgs,
4578 bool IsDefiniteInstance,
4579 const Scope *S);
4580 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4581 const LookupResult &R,
4582 bool HasTrailingLParen);
4583
4584 ExprResult
4585 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4586 const DeclarationNameInfo &NameInfo,
4587 bool IsAddressOfOperand, const Scope *S,
4588 TypeSourceInfo **RecoveryTSI = nullptr);
4589
4590 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4591 SourceLocation TemplateKWLoc,
4592 const DeclarationNameInfo &NameInfo,
4593 const TemplateArgumentListInfo *TemplateArgs);
4594
4595 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4596 LookupResult &R,
4597 bool NeedsADL,
4598 bool AcceptInvalidDecl = false);
4599 ExprResult BuildDeclarationNameExpr(
4600 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4601 NamedDecl *FoundD = nullptr,
4602 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4603 bool AcceptInvalidDecl = false);
4604
4605 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4606 DeclarationNameInfo &SuffixInfo,
4607 ArrayRef<Expr *> Args,
4608 SourceLocation LitEndLoc,
4609 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4610
4611 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4612 PredefinedExpr::IdentKind IK);
4613 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4614 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4615
4616 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4617
4618 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4619 ExprResult ActOnCharacterConstant(const Token &Tok,
4620 Scope *UDLScope = nullptr);
4621 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4622 ExprResult ActOnParenListExpr(SourceLocation L,
4623 SourceLocation R,
4624 MultiExprArg Val);
4625
4626 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4627 /// fragments (e.g. "foo" "bar" L"baz").
4628 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4629 Scope *UDLScope = nullptr);
4630
4631 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4632 SourceLocation DefaultLoc,
4633 SourceLocation RParenLoc,
4634 Expr *ControllingExpr,
4635 ArrayRef<ParsedType> ArgTypes,
4636 ArrayRef<Expr *> ArgExprs);
4637 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4638 SourceLocation DefaultLoc,
4639 SourceLocation RParenLoc,
4640 Expr *ControllingExpr,
4641 ArrayRef<TypeSourceInfo *> Types,
4642 ArrayRef<Expr *> Exprs);
4643
4644 // Binary/Unary Operators. 'Tok' is the token for the operator.
4645 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4646 Expr *InputExpr);
4647 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4648 UnaryOperatorKind Opc, Expr *Input);
4649 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4650 tok::TokenKind Op, Expr *Input);
4651
4652 bool isQualifiedMemberAccess(Expr *E);
4653 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4654
4655 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4656 SourceLocation OpLoc,
4657 UnaryExprOrTypeTrait ExprKind,
4658 SourceRange R);
4659 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4660 UnaryExprOrTypeTrait ExprKind);
4661 ExprResult
4662 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4663 UnaryExprOrTypeTrait ExprKind,
4664 bool IsType, void *TyOrEx,
4665 SourceRange ArgRange);
4666
4667 ExprResult CheckPlaceholderExpr(Expr *E);
4668 bool CheckVecStepExpr(Expr *E);
4669
4670 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4671 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4672 SourceRange ExprRange,
4673 UnaryExprOrTypeTrait ExprKind);
4674 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4675 SourceLocation OpLoc,
4676 IdentifierInfo &Name,
4677 SourceLocation NameLoc,
4678 SourceLocation RParenLoc);
4679 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4680 tok::TokenKind Kind, Expr *Input);
4681
4682 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4683 Expr *Idx, SourceLocation RLoc);
4684 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4685 Expr *Idx, SourceLocation RLoc);
4686 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4687 Expr *LowerBound, SourceLocation ColonLoc,
4688 Expr *Length, SourceLocation RBLoc);
4689
4690 // This struct is for use by ActOnMemberAccess to allow
4691 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4692 // changing the access operator from a '.' to a '->' (to see if that is the
4693 // change needed to fix an error about an unknown member, e.g. when the class
4694 // defines a custom operator->).
4695 struct ActOnMemberAccessExtraArgs {
4696 Scope *S;
4697 UnqualifiedId &Id;
4698 Decl *ObjCImpDecl;
4699 };
4700
4701 ExprResult BuildMemberReferenceExpr(
4702 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4703 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4704 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4705 const TemplateArgumentListInfo *TemplateArgs,
4706 const Scope *S,
4707 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4708
4709 ExprResult
4710 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4711 bool IsArrow, const CXXScopeSpec &SS,
4712 SourceLocation TemplateKWLoc,
4713 NamedDecl *FirstQualifierInScope, LookupResult &R,
4714 const TemplateArgumentListInfo *TemplateArgs,
4715 const Scope *S,
4716 bool SuppressQualifierCheck = false,
4717 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4718
4719 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4720 SourceLocation OpLoc,
4721 const CXXScopeSpec &SS, FieldDecl *Field,
4722 DeclAccessPair FoundDecl,
4723 const DeclarationNameInfo &MemberNameInfo);
4724
4725 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4726
4727 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4728 const CXXScopeSpec &SS,
4729 const LookupResult &R);
4730
4731 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4732 bool IsArrow, SourceLocation OpLoc,
4733 const CXXScopeSpec &SS,
4734 SourceLocation TemplateKWLoc,
4735 NamedDecl *FirstQualifierInScope,
4736 const DeclarationNameInfo &NameInfo,
4737 const TemplateArgumentListInfo *TemplateArgs);
4738
4739 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4740 SourceLocation OpLoc,
4741 tok::TokenKind OpKind,
4742 CXXScopeSpec &SS,
4743 SourceLocation TemplateKWLoc,
4744 UnqualifiedId &Member,
4745 Decl *ObjCImpDecl);
4746
4747 MemberExpr *
4748 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4749 const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
4750 ValueDecl *Member, DeclAccessPair FoundDecl,
4751 bool HadMultipleCandidates,
4752 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4753 ExprValueKind VK, ExprObjectKind OK,
4754 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4755 MemberExpr *
4756 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4757 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
4758 ValueDecl *Member, DeclAccessPair FoundDecl,
4759 bool HadMultipleCandidates,
4760 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4761 ExprValueKind VK, ExprObjectKind OK,
4762 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4763
4764 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4765 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4766 FunctionDecl *FDecl,
4767 const FunctionProtoType *Proto,
4768 ArrayRef<Expr *> Args,
4769 SourceLocation RParenLoc,
4770 bool ExecConfig = false);
4771 void CheckStaticArrayArgument(SourceLocation CallLoc,
4772 ParmVarDecl *Param,
4773 const Expr *ArgExpr);
4774
4775 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4776 /// This provides the location of the left/right parens and a list of comma
4777 /// locations.
4778 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4779 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4780 Expr *ExecConfig = nullptr);
4781 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4782 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4783 Expr *ExecConfig = nullptr,
4784 bool IsExecConfig = false);
4785 enum class AtomicArgumentOrder { API, AST };
4786 ExprResult
4787 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4788 SourceLocation RParenLoc, MultiExprArg Args,
4789 AtomicExpr::AtomicOp Op,
4790 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
4791 ExprResult
4792 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
4793 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
4794 Expr *Config = nullptr, bool IsExecConfig = false,
4795 ADLCallKind UsesADL = ADLCallKind::NotADL);
4796
4797 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4798 MultiExprArg ExecConfig,
4799 SourceLocation GGGLoc);
4800
4801 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4802 Declarator &D, ParsedType &Ty,
4803 SourceLocation RParenLoc, Expr *CastExpr);
4804 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4805 TypeSourceInfo *Ty,
4806 SourceLocation RParenLoc,
4807 Expr *Op);
4808 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4809
4810 /// Build an altivec or OpenCL literal.
4811 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4812 SourceLocation RParenLoc, Expr *E,
4813 TypeSourceInfo *TInfo);
4814
4815 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4816
4817 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4818 ParsedType Ty,
4819 SourceLocation RParenLoc,
4820 Expr *InitExpr);
4821
4822 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4823 TypeSourceInfo *TInfo,
4824 SourceLocation RParenLoc,
4825 Expr *LiteralExpr);
4826
4827 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4828 MultiExprArg InitArgList,
4829 SourceLocation RBraceLoc);
4830
4831 ExprResult BuildInitList(SourceLocation LBraceLoc,
4832 MultiExprArg InitArgList,
4833 SourceLocation RBraceLoc);
4834
4835 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4836 SourceLocation EqualOrColonLoc,
4837 bool GNUSyntax,
4838 ExprResult Init);
4839
4840private:
4841 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4842
4843public:
4844 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4845 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4846 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4847 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4848 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4849 Expr *LHSExpr, Expr *RHSExpr);
4850
4851 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4852
4853 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4854 /// in the case of a the GNU conditional expr extension.
4855 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4856 SourceLocation ColonLoc,
4857 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4858
4859 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4860 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4861 LabelDecl *TheDecl);
4862
4863 void ActOnStartStmtExpr();
4864 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4865 SourceLocation RPLoc); // "({..})"
4866 // Handle the final expression in a statement expression.
4867 ExprResult ActOnStmtExprResult(ExprResult E);
4868 void ActOnStmtExprError();
4869
4870 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4871 struct OffsetOfComponent {
4872 SourceLocation LocStart, LocEnd;
4873 bool isBrackets; // true if [expr], false if .ident
4874 union {
4875 IdentifierInfo *IdentInfo;
4876 Expr *E;
4877 } U;
4878 };
4879
4880 /// __builtin_offsetof(type, a.b[123][456].c)
4881 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4882 TypeSourceInfo *TInfo,
4883 ArrayRef<OffsetOfComponent> Components,
4884 SourceLocation RParenLoc);
4885 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4886 SourceLocation BuiltinLoc,
4887 SourceLocation TypeLoc,
4888 ParsedType ParsedArgTy,
4889 ArrayRef<OffsetOfComponent> Components,
4890 SourceLocation RParenLoc);
4891
4892 // __builtin_choose_expr(constExpr, expr1, expr2)
4893 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4894 Expr *CondExpr, Expr *LHSExpr,
4895 Expr *RHSExpr, SourceLocation RPLoc);
4896
4897 // __builtin_va_arg(expr, type)
4898 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4899 SourceLocation RPLoc);
4900 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4901 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4902
4903 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
4904 // __builtin_COLUMN()
4905 ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
4906 SourceLocation BuiltinLoc,
4907 SourceLocation RPLoc);
4908
4909 // Build a potentially resolved SourceLocExpr.
4910 ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
4911 SourceLocation BuiltinLoc, SourceLocation RPLoc,
4912 DeclContext *ParentContext);
4913
4914 // __null
4915 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4916
4917 bool CheckCaseExpression(Expr *E);
4918
4919 /// Describes the result of an "if-exists" condition check.
4920 enum IfExistsResult {
4921 /// The symbol exists.
4922 IER_Exists,
4923
4924 /// The symbol does not exist.
4925 IER_DoesNotExist,
4926
4927 /// The name is a dependent name, so the results will differ
4928 /// from one instantiation to the next.
4929 IER_Dependent,
4930
4931 /// An error occurred.
4932 IER_Error
4933 };
4934
4935 IfExistsResult
4936 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4937 const DeclarationNameInfo &TargetNameInfo);
4938
4939 IfExistsResult
4940 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4941 bool IsIfExists, CXXScopeSpec &SS,
4942 UnqualifiedId &Name);
4943
4944 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4945 bool IsIfExists,
4946 NestedNameSpecifierLoc QualifierLoc,
4947 DeclarationNameInfo NameInfo,
4948 Stmt *Nested);
4949 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4950 bool IsIfExists,
4951 CXXScopeSpec &SS, UnqualifiedId &Name,
4952 Stmt *Nested);
4953
4954 //===------------------------- "Block" Extension ------------------------===//
4955
4956 /// ActOnBlockStart - This callback is invoked when a block literal is
4957 /// started.
4958 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4959
4960 /// ActOnBlockArguments - This callback allows processing of block arguments.
4961 /// If there are no arguments, this is still invoked.
4962 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4963 Scope *CurScope);
4964
4965 /// ActOnBlockError - If there is an error parsing a block, this callback
4966 /// is invoked to pop the information about the block from the action impl.
4967 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4968
4969 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4970 /// literal was successfully completed. ^(int x){...}
4971 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4972 Scope *CurScope);
4973
4974 //===---------------------------- Clang Extensions ----------------------===//
4975
4976 /// __builtin_convertvector(...)
4977 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4978 SourceLocation BuiltinLoc,
4979 SourceLocation RParenLoc);
4980
4981 //===---------------------------- OpenCL Features -----------------------===//
4982
4983 /// __builtin_astype(...)
4984 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4985 SourceLocation BuiltinLoc,
4986 SourceLocation RParenLoc);
4987
4988 //===---------------------------- C++ Features --------------------------===//
4989
4990 // Act on C++ namespaces
4991 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4992 SourceLocation NamespaceLoc,
4993 SourceLocation IdentLoc, IdentifierInfo *Ident,
4994 SourceLocation LBrace,
4995 const ParsedAttributesView &AttrList,
4996 UsingDirectiveDecl *&UsingDecl);
4997 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4998
4999 NamespaceDecl *getStdNamespace() const;
5000 NamespaceDecl *getOrCreateStdNamespace();
5001
5002 NamespaceDecl *lookupStdExperimentalNamespace();
5003
5004 CXXRecordDecl *getStdBadAlloc() const;
5005 EnumDecl *getStdAlignValT() const;
5006
5007private:
5008 // A cache representing if we've fully checked the various comparison category
5009 // types stored in ASTContext. The bit-index corresponds to the integer value
5010 // of a ComparisonCategoryType enumerator.
5011 llvm::SmallBitVector FullyCheckedComparisonCategories;
5012
5013 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
5014 CXXScopeSpec &SS,
5015 ParsedType TemplateTypeTy,
5016 IdentifierInfo *MemberOrBase);
5017
5018public:
5019 /// Lookup the specified comparison category types in the standard
5020 /// library, an check the VarDecls possibly returned by the operator<=>
5021 /// builtins for that type.
5022 ///
5023 /// \return The type of the comparison category type corresponding to the
5024 /// specified Kind, or a null type if an error occurs
5025 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5026 SourceLocation Loc);
5027
5028 /// Tests whether Ty is an instance of std::initializer_list and, if
5029 /// it is and Element is not NULL, assigns the element type to Element.
5030 bool isStdInitializerList(QualType Ty, QualType *Element);
5031
5032 /// Looks for the std::initializer_list template and instantiates it
5033 /// with Element, or emits an error if it's not found.
5034 ///
5035 /// \returns The instantiated template, or null on error.
5036 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5037
5038 /// Determine whether Ctor is an initializer-list constructor, as
5039 /// defined in [dcl.init.list]p2.
5040 bool isInitListConstructor(const FunctionDecl *Ctor);
5041
5042 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5043 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5044 SourceLocation IdentLoc,
5045 IdentifierInfo *NamespcName,
5046 const ParsedAttributesView &AttrList);
5047
5048 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5049
5050 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
5051 SourceLocation NamespaceLoc,
5052 SourceLocation AliasLoc,
5053 IdentifierInfo *Alias,
5054 CXXScopeSpec &SS,
5055 SourceLocation IdentLoc,
5056 IdentifierInfo *Ident);
5057
5058 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5059 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
5060 const LookupResult &PreviousDecls,
5061 UsingShadowDecl *&PrevShadow);
5062 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
5063 NamedDecl *Target,
5064 UsingShadowDecl *PrevDecl);
5065
5066 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5067 bool HasTypenameKeyword,
5068 const CXXScopeSpec &SS,
5069 SourceLocation NameLoc,
5070 const LookupResult &Previous);
5071 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
5072 bool HasTypename,
5073 const CXXScopeSpec &SS,
5074 const DeclarationNameInfo &NameInfo,
5075 SourceLocation NameLoc);
5076
5077 NamedDecl *BuildUsingDeclaration(
5078 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
5079 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
5080 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
5081 const ParsedAttributesView &AttrList, bool IsInstantiation);
5082 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5083 ArrayRef<NamedDecl *> Expansions);
5084
5085 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5086
5087 /// Given a derived-class using shadow declaration for a constructor and the
5088 /// correspnding base class constructor, find or create the implicit
5089 /// synthesized derived class constructor to use for this initialization.
5090 CXXConstructorDecl *
5091 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5092 ConstructorUsingShadowDecl *DerivedShadow);
5093
5094 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5095 SourceLocation UsingLoc,
5096 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5097 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5098 const ParsedAttributesView &AttrList);
5099 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5100 MultiTemplateParamsArg TemplateParams,
5101 SourceLocation UsingLoc, UnqualifiedId &Name,
5102 const ParsedAttributesView &AttrList,
5103 TypeResult Type, Decl *DeclFromDeclSpec);
5104
5105 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5106 /// including handling of its default argument expressions.
5107 ///
5108 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5109 ExprResult
5110 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5111 NamedDecl *FoundDecl,
5112 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5113 bool HadMultipleCandidates, bool IsListInitialization,
5114 bool IsStdInitListInitialization,
5115 bool RequiresZeroInit, unsigned ConstructKind,
5116 SourceRange ParenRange);
5117
5118 /// Build a CXXConstructExpr whose constructor has already been resolved if
5119 /// it denotes an inherited constructor.
5120 ExprResult
5121 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5122 CXXConstructorDecl *Constructor, bool Elidable,
5123 MultiExprArg Exprs,
5124 bool HadMultipleCandidates, bool IsListInitialization,
5125 bool IsStdInitListInitialization,
5126 bool RequiresZeroInit, unsigned ConstructKind,
5127 SourceRange ParenRange);
5128
5129 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5130 // the constructor can be elidable?
5131 ExprResult
5132 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5133 NamedDecl *FoundDecl,
5134 CXXConstructorDecl *Constructor, bool Elidable,
5135 MultiExprArg Exprs, bool HadMultipleCandidates,
5136 bool IsListInitialization,
5137 bool IsStdInitListInitialization, bool RequiresZeroInit,
5138 unsigned ConstructKind, SourceRange ParenRange);
5139
5140 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
5141
5142
5143 /// Instantiate or parse a C++ default argument expression as necessary.
5144 /// Return true on error.
5145 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5146 ParmVarDecl *Param);
5147
5148 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
5149 /// the default expr if needed.
5150 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5151 FunctionDecl *FD,
5152 ParmVarDecl *Param);
5153
5154 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5155 /// constructed variable.
5156 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
5157
5158 /// Helper class that collects exception specifications for
5159 /// implicitly-declared special member functions.
5160 class ImplicitExceptionSpecification {
5161 // Pointer to allow copying
5162 Sema *Self;
5163 // We order exception specifications thus:
5164 // noexcept is the most restrictive, but is only used in C++11.
5165 // throw() comes next.
5166 // Then a throw(collected exceptions)
5167 // Finally no specification, which is expressed as noexcept(false).
5168 // throw(...) is used instead if any called function uses it.
5169 ExceptionSpecificationType ComputedEST;
5170 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5171 SmallVector<QualType, 4> Exceptions;
5172
5173 void ClearExceptions() {
5174 ExceptionsSeen.clear();
5175 Exceptions.clear();
5176 }
5177
5178 public:
5179 explicit ImplicitExceptionSpecification(Sema &Self)
5180 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5181 if (!Self.getLangOpts().CPlusPlus11)
5182 ComputedEST = EST_DynamicNone;
5183 }
5184
5185 /// Get the computed exception specification type.
5186 ExceptionSpecificationType getExceptionSpecType() const {
5187 assert(!isComputedNoexcept(ComputedEST) &&((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 5188, __PRETTY_FUNCTION__))
5188 "noexcept(expr) should not be a possible result")((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 5188, __PRETTY_FUNCTION__))
;
5189 return ComputedEST;
5190 }
5191
5192 /// The number of exceptions in the exception specification.
5193 unsigned size() const { return Exceptions.size(); }
5194
5195 /// The set of exceptions in the exception specification.
5196 const QualType *data() const { return Exceptions.data(); }
5197
5198 /// Integrate another called method into the collected data.
5199 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5200
5201 /// Integrate an invoked expression into the collected data.
5202 void CalledExpr(Expr *E);
5203
5204 /// Overwrite an EPI's exception specification with this
5205 /// computed exception specification.
5206 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5207 FunctionProtoType::ExceptionSpecInfo ESI;
5208 ESI.Type = getExceptionSpecType();
5209 if (ESI.Type == EST_Dynamic) {
5210 ESI.Exceptions = Exceptions;
5211 } else if (ESI.Type == EST_None) {
5212 /// C++11 [except.spec]p14:
5213 /// The exception-specification is noexcept(false) if the set of
5214 /// potential exceptions of the special member function contains "any"
5215 ESI.Type = EST_NoexceptFalse;
5216 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
5217 tok::kw_false).get();
5218 }
5219 return ESI;
5220 }
5221 };
5222
5223 /// Determine what sort of exception specification a defaulted
5224 /// copy constructor of a class will have.
5225 ImplicitExceptionSpecification
5226 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
5227 CXXMethodDecl *MD);
5228
5229 /// Determine what sort of exception specification a defaulted
5230 /// default constructor of a class will have, and whether the parameter
5231 /// will be const.
5232 ImplicitExceptionSpecification
5233 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
5234
5235 /// Determine what sort of exception specification a defaulted
5236 /// copy assignment operator of a class will have, and whether the
5237 /// parameter will be const.
5238 ImplicitExceptionSpecification
5239 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
5240
5241 /// Determine what sort of exception specification a defaulted move
5242 /// constructor of a class will have.
5243 ImplicitExceptionSpecification
5244 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
5245
5246 /// Determine what sort of exception specification a defaulted move
5247 /// assignment operator of a class will have.
5248 ImplicitExceptionSpecification
5249 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
5250
5251 /// Determine what sort of exception specification a defaulted
5252 /// destructor of a class will have.
5253 ImplicitExceptionSpecification
5254 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
5255
5256 /// Determine what sort of exception specification an inheriting
5257 /// constructor of a class will have.
5258 ImplicitExceptionSpecification
5259 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
5260 CXXConstructorDecl *CD);
5261
5262 /// Evaluate the implicit exception specification for a defaulted
5263 /// special member function.
5264 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
5265
5266 /// Check the given noexcept-specifier, convert its expression, and compute
5267 /// the appropriate ExceptionSpecificationType.
5268 ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
5269 ExceptionSpecificationType &EST);
5270
5271 /// Check the given exception-specification and update the
5272 /// exception specification information with the results.
5273 void checkExceptionSpecification(bool IsTopLevel,
5274 ExceptionSpecificationType EST,
5275 ArrayRef<ParsedType> DynamicExceptions,
5276 ArrayRef<SourceRange> DynamicExceptionRanges,
5277 Expr *NoexceptExpr,
5278 SmallVectorImpl<QualType> &Exceptions,
5279 FunctionProtoType::ExceptionSpecInfo &ESI);
5280
5281 /// Determine if we're in a case where we need to (incorrectly) eagerly
5282 /// parse an exception specification to work around a libstdc++ bug.
5283 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
5284
5285 /// Add an exception-specification to the given member function
5286 /// (or member function template). The exception-specification was parsed
5287 /// after the method itself was declared.
5288 void actOnDelayedExceptionSpecification(Decl *Method,
5289 ExceptionSpecificationType EST,
5290 SourceRange SpecificationRange,
5291 ArrayRef<ParsedType> DynamicExceptions,
5292 ArrayRef<SourceRange> DynamicExceptionRanges,
5293 Expr *NoexceptExpr);
5294
5295 class InheritedConstructorInfo;
5296
5297 /// Determine if a special member function should have a deleted
5298 /// definition when it is defaulted.
5299 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5300 InheritedConstructorInfo *ICI = nullptr,
5301 bool Diagnose = false);
5302
5303