Bug Summary

File:clang/lib/Sema/SemaModule.cpp
Warning:line 577, 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 -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -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~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -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-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaModule.cpp

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

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