Bug Summary

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

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

1//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
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// This file implements C++ template instantiation.
9//
10//===----------------------------------------------------------------------===/
11
12#include "clang/Sema/SemaInternal.h"
13#include "TreeTransform.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/PrettyDeclStackTrace.h"
21#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/Stack.h"
23#include "clang/Sema/DeclSpec.h"
24#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Template.h"
27#include "clang/Sema/TemplateDeduction.h"
28#include "clang/Sema/TemplateInstCallback.h"
29#include "llvm/Support/TimeProfiler.h"
30
31using namespace clang;
32using namespace sema;
33
34//===----------------------------------------------------------------------===/
35// Template Instantiation Support
36//===----------------------------------------------------------------------===/
37
38/// Retrieve the template argument list(s) that should be used to
39/// instantiate the definition of the given declaration.
40///
41/// \param D the declaration for which we are computing template instantiation
42/// arguments.
43///
44/// \param Innermost if non-NULL, the innermost template argument list.
45///
46/// \param RelativeToPrimary true if we should get the template
47/// arguments relative to the primary template, even when we're
48/// dealing with a specialization. This is only relevant for function
49/// template specializations.
50///
51/// \param Pattern If non-NULL, indicates the pattern from which we will be
52/// instantiating the definition of the given declaration, \p D. This is
53/// used to determine the proper set of template instantiation arguments for
54/// friend function template specializations.
55MultiLevelTemplateArgumentList
56Sema::getTemplateInstantiationArgs(NamedDecl *D,
57 const TemplateArgumentList *Innermost,
58 bool RelativeToPrimary,
59 const FunctionDecl *Pattern) {
60 // Accumulate the set of template argument lists in this structure.
61 MultiLevelTemplateArgumentList Result;
62
63 if (Innermost)
64 Result.addOuterTemplateArguments(Innermost);
65
66 DeclContext *Ctx = dyn_cast<DeclContext>(D);
67 if (!Ctx) {
68 Ctx = D->getDeclContext();
69
70 // Add template arguments from a variable template instantiation. For a
71 // class-scope explicit specialization, there are no template arguments
72 // at this level, but there may be enclosing template arguments.
73 VarTemplateSpecializationDecl *Spec =
74 dyn_cast<VarTemplateSpecializationDecl>(D);
75 if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
76 // We're done when we hit an explicit specialization.
77 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
78 !isa<VarTemplatePartialSpecializationDecl>(Spec))
79 return Result;
80
81 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
82
83 // If this variable template specialization was instantiated from a
84 // specialized member that is a variable template, we're done.
85 assert(Spec->getSpecializedTemplate() && "No variable template?")((Spec->getSpecializedTemplate() && "No variable template?"
) ? static_cast<void> (0) : __assert_fail ("Spec->getSpecializedTemplate() && \"No variable template?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 85, __PRETTY_FUNCTION__))
;
86 llvm::PointerUnion<VarTemplateDecl*,
87 VarTemplatePartialSpecializationDecl*> Specialized
88 = Spec->getSpecializedTemplateOrPartial();
89 if (VarTemplatePartialSpecializationDecl *Partial =
90 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
91 if (Partial->isMemberSpecialization())
92 return Result;
93 } else {
94 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
95 if (Tmpl->isMemberSpecialization())
96 return Result;
97 }
98 }
99
100 // If we have a template template parameter with translation unit context,
101 // then we're performing substitution into a default template argument of
102 // this template template parameter before we've constructed the template
103 // that will own this template template parameter. In this case, we
104 // use empty template parameter lists for all of the outer templates
105 // to avoid performing any substitutions.
106 if (Ctx->isTranslationUnit()) {
107 if (TemplateTemplateParmDecl *TTP
108 = dyn_cast<TemplateTemplateParmDecl>(D)) {
109 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
110 Result.addOuterTemplateArguments(None);
111 return Result;
112 }
113 }
114 }
115
116 while (!Ctx->isFileContext()) {
117 // Add template arguments from a class template instantiation.
118 ClassTemplateSpecializationDecl *Spec
119 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
120 if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
121 // We're done when we hit an explicit specialization.
122 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
123 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
124 break;
125
126 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
127
128 // If this class template specialization was instantiated from a
129 // specialized member that is a class template, we're done.
130 assert(Spec->getSpecializedTemplate() && "No class template?")((Spec->getSpecializedTemplate() && "No class template?"
) ? static_cast<void> (0) : __assert_fail ("Spec->getSpecializedTemplate() && \"No class template?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 130, __PRETTY_FUNCTION__))
;
131 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
132 break;
133 }
134 // Add template arguments from a function template specialization.
135 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
136 if (!RelativeToPrimary &&
137 Function->getTemplateSpecializationKindForInstantiation() ==
138 TSK_ExplicitSpecialization)
139 break;
140
141 if (const TemplateArgumentList *TemplateArgs
142 = Function->getTemplateSpecializationArgs()) {
143 // Add the template arguments for this specialization.
144 Result.addOuterTemplateArguments(TemplateArgs);
145
146 // If this function was instantiated from a specialized member that is
147 // a function template, we're done.
148 assert(Function->getPrimaryTemplate() && "No function template?")((Function->getPrimaryTemplate() && "No function template?"
) ? static_cast<void> (0) : __assert_fail ("Function->getPrimaryTemplate() && \"No function template?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 148, __PRETTY_FUNCTION__))
;
149 if (Function->getPrimaryTemplate()->isMemberSpecialization())
150 break;
151
152 // If this function is a generic lambda specialization, we are done.
153 if (isGenericLambdaCallOperatorSpecialization(Function))
154 break;
155
156 } else if (FunctionTemplateDecl *FunTmpl
157 = Function->getDescribedFunctionTemplate()) {
158 // Add the "injected" template arguments.
159 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
160 }
161
162 // If this is a friend declaration and it declares an entity at
163 // namespace scope, take arguments from its lexical parent
164 // instead of its semantic parent, unless of course the pattern we're
165 // instantiating actually comes from the file's context!
166 if (Function->getFriendObjectKind() &&
167 Function->getDeclContext()->isFileContext() &&
168 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
169 Ctx = Function->getLexicalDeclContext();
170 RelativeToPrimary = false;
171 continue;
172 }
173 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
174 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
175 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
176 const TemplateSpecializationType *TST =
177 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
178 Result.addOuterTemplateArguments(
179 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
180 if (ClassTemplate->isMemberSpecialization())
181 break;
182 }
183 }
184
185 Ctx = Ctx->getParent();
186 RelativeToPrimary = false;
187 }
188
189 return Result;
190}
191
192bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
193 switch (Kind) {
194 case TemplateInstantiation:
195 case ExceptionSpecInstantiation:
196 case DefaultTemplateArgumentInstantiation:
197 case DefaultFunctionArgumentInstantiation:
198 case ExplicitTemplateArgumentSubstitution:
199 case DeducedTemplateArgumentSubstitution:
200 case PriorTemplateArgumentSubstitution:
201 case ConstraintsCheck:
202 return true;
203
204 case DefaultTemplateArgumentChecking:
205 case DeclaringSpecialMember:
206 case DefiningSynthesizedFunction:
207 case ExceptionSpecEvaluation:
208 case ConstraintSubstitution:
209 case RewritingOperatorAsSpaceship:
210 return false;
211
212 // This function should never be called when Kind's value is Memoization.
213 case Memoization:
214 break;
215 }
216
217 llvm_unreachable("Invalid SynthesisKind!")::llvm::llvm_unreachable_internal("Invalid SynthesisKind!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 217)
;
218}
219
220Sema::InstantiatingTemplate::InstantiatingTemplate(
221 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
222 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
223 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
224 sema::TemplateDeductionInfo *DeductionInfo)
225 : SemaRef(SemaRef) {
226 // Don't allow further instantiation if a fatal error and an uncompilable
227 // error have occurred. Any diagnostics we might have raised will not be
228 // visible, and we do not need to construct a correct AST.
229 if (SemaRef.Diags.hasFatalErrorOccurred() &&
36
Assuming the condition is false
230 SemaRef.Diags.hasUncompilableErrorOccurred()) {
231 Invalid = true;
232 return;
233 }
234 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
37
Calling 'InstantiatingTemplate::CheckInstantiationDepth'
43
Returning from 'InstantiatingTemplate::CheckInstantiationDepth'
235 if (!Invalid
43.1
Field 'Invalid' is false
43.1
Field 'Invalid' is false
) {
44
Taking true branch
236 CodeSynthesisContext Inst;
237 Inst.Kind = Kind;
238 Inst.PointOfInstantiation = PointOfInstantiation;
239 Inst.Entity = Entity;
240 Inst.Template = Template;
241 Inst.TemplateArgs = TemplateArgs.data();
242 Inst.NumTemplateArgs = TemplateArgs.size();
243 Inst.DeductionInfo = DeductionInfo;
244 Inst.InstantiationRange = InstantiationRange;
245 SemaRef.pushCodeSynthesisContext(Inst);
246
247 AlreadyInstantiating =
248 !SemaRef.InstantiatingSpecializations
45
Assuming field 'second' is true
249 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
250 .second;
251 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
252 }
253}
254
255Sema::InstantiatingTemplate::InstantiatingTemplate(
256 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
257 SourceRange InstantiationRange)
258 : InstantiatingTemplate(SemaRef,
35
Calling constructor for 'InstantiatingTemplate'
46
Returning from constructor for 'InstantiatingTemplate'
259 CodeSynthesisContext::TemplateInstantiation,
260 PointOfInstantiation, InstantiationRange, Entity) {}
261
262Sema::InstantiatingTemplate::InstantiatingTemplate(
263 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
264 ExceptionSpecification, SourceRange InstantiationRange)
265 : InstantiatingTemplate(
266 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
267 PointOfInstantiation, InstantiationRange, Entity) {}
268
269Sema::InstantiatingTemplate::InstantiatingTemplate(
270 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
271 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
272 SourceRange InstantiationRange)
273 : InstantiatingTemplate(
274 SemaRef,
275 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
276 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
277 Template, TemplateArgs) {}
278
279Sema::InstantiatingTemplate::InstantiatingTemplate(
280 Sema &SemaRef, SourceLocation PointOfInstantiation,
281 FunctionTemplateDecl *FunctionTemplate,
282 ArrayRef<TemplateArgument> TemplateArgs,
283 CodeSynthesisContext::SynthesisKind Kind,
284 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
285 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
286 InstantiationRange, FunctionTemplate, nullptr,
287 TemplateArgs, &DeductionInfo) {
288 assert(((Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? static_cast<void> (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 290, __PRETTY_FUNCTION__))
289 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||((Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? static_cast<void> (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 290, __PRETTY_FUNCTION__))
290 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution)((Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? static_cast<void> (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 290, __PRETTY_FUNCTION__))
;
291}
292
293Sema::InstantiatingTemplate::InstantiatingTemplate(
294 Sema &SemaRef, SourceLocation PointOfInstantiation,
295 TemplateDecl *Template,
296 ArrayRef<TemplateArgument> TemplateArgs,
297 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
298 : InstantiatingTemplate(
299 SemaRef,
300 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
301 PointOfInstantiation, InstantiationRange, Template, nullptr,
302 TemplateArgs, &DeductionInfo) {}
303
304Sema::InstantiatingTemplate::InstantiatingTemplate(
305 Sema &SemaRef, SourceLocation PointOfInstantiation,
306 ClassTemplatePartialSpecializationDecl *PartialSpec,
307 ArrayRef<TemplateArgument> TemplateArgs,
308 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
309 : InstantiatingTemplate(
310 SemaRef,
311 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
312 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
313 TemplateArgs, &DeductionInfo) {}
314
315Sema::InstantiatingTemplate::InstantiatingTemplate(
316 Sema &SemaRef, SourceLocation PointOfInstantiation,
317 VarTemplatePartialSpecializationDecl *PartialSpec,
318 ArrayRef<TemplateArgument> TemplateArgs,
319 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
320 : InstantiatingTemplate(
321 SemaRef,
322 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
323 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
324 TemplateArgs, &DeductionInfo) {}
325
326Sema::InstantiatingTemplate::InstantiatingTemplate(
327 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
328 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
329 : InstantiatingTemplate(
330 SemaRef,
331 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
332 PointOfInstantiation, InstantiationRange, Param, nullptr,
333 TemplateArgs) {}
334
335Sema::InstantiatingTemplate::InstantiatingTemplate(
336 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
337 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
338 SourceRange InstantiationRange)
339 : InstantiatingTemplate(
340 SemaRef,
341 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
342 PointOfInstantiation, InstantiationRange, Param, Template,
343 TemplateArgs) {}
344
345Sema::InstantiatingTemplate::InstantiatingTemplate(
346 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
347 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
348 SourceRange InstantiationRange)
349 : InstantiatingTemplate(
350 SemaRef,
351 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
352 PointOfInstantiation, InstantiationRange, Param, Template,
353 TemplateArgs) {}
354
355Sema::InstantiatingTemplate::InstantiatingTemplate(
356 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
357 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
358 SourceRange InstantiationRange)
359 : InstantiatingTemplate(
360 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
361 PointOfInstantiation, InstantiationRange, Param, Template,
362 TemplateArgs) {}
363
364Sema::InstantiatingTemplate::InstantiatingTemplate(
365 Sema &SemaRef, SourceLocation PointOfInstantiation,
366 ConstraintsCheck, TemplateDecl *Template,
367 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
368 : InstantiatingTemplate(
369 SemaRef, CodeSynthesisContext::ConstraintsCheck,
370 PointOfInstantiation, InstantiationRange, Template, nullptr,
371 TemplateArgs) {}
372
373Sema::InstantiatingTemplate::InstantiatingTemplate(
374 Sema &SemaRef, SourceLocation PointOfInstantiation,
375 ConstraintSubstitution, TemplateDecl *Template,
376 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
377 : InstantiatingTemplate(
378 SemaRef, CodeSynthesisContext::ConstraintSubstitution,
379 PointOfInstantiation, InstantiationRange, Template, nullptr,
380 {}, &DeductionInfo) {}
381
382void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
383 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
384 InNonInstantiationSFINAEContext = false;
385
386 CodeSynthesisContexts.push_back(Ctx);
387
388 if (!Ctx.isInstantiationRecord())
389 ++NonInstantiationEntries;
390
391 // Check to see if we're low on stack space. We can't do anything about this
392 // from here, but we can at least warn the user.
393 if (isStackNearlyExhausted())
394 warnStackExhausted(Ctx.PointOfInstantiation);
395}
396
397void Sema::popCodeSynthesisContext() {
398 auto &Active = CodeSynthesisContexts.back();
399 if (!Active.isInstantiationRecord()) {
400 assert(NonInstantiationEntries > 0)((NonInstantiationEntries > 0) ? static_cast<void> (
0) : __assert_fail ("NonInstantiationEntries > 0", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 400, __PRETTY_FUNCTION__))
;
401 --NonInstantiationEntries;
402 }
403
404 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
405
406 // Name lookup no longer looks in this template's defining module.
407 assert(CodeSynthesisContexts.size() >=((CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules
.size() && "forgot to remove a lookup module for a template instantiation"
) ? static_cast<void> (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 409, __PRETTY_FUNCTION__))
408 CodeSynthesisContextLookupModules.size() &&((CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules
.size() && "forgot to remove a lookup module for a template instantiation"
) ? static_cast<void> (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 409, __PRETTY_FUNCTION__))
409 "forgot to remove a lookup module for a template instantiation")((CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules
.size() && "forgot to remove a lookup module for a template instantiation"
) ? static_cast<void> (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 409, __PRETTY_FUNCTION__))
;
410 if (CodeSynthesisContexts.size() ==
411 CodeSynthesisContextLookupModules.size()) {
412 if (Module *M = CodeSynthesisContextLookupModules.back())
413 LookupModulesCache.erase(M);
414 CodeSynthesisContextLookupModules.pop_back();
415 }
416
417 // If we've left the code synthesis context for the current context stack,
418 // stop remembering that we've emitted that stack.
419 if (CodeSynthesisContexts.size() ==
420 LastEmittedCodeSynthesisContextDepth)
421 LastEmittedCodeSynthesisContextDepth = 0;
422
423 CodeSynthesisContexts.pop_back();
424}
425
426void Sema::InstantiatingTemplate::Clear() {
427 if (!Invalid) {
428 if (!AlreadyInstantiating) {
429 auto &Active = SemaRef.CodeSynthesisContexts.back();
430 SemaRef.InstantiatingSpecializations.erase(
431 std::make_pair(Active.Entity, Active.Kind));
432 }
433
434 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
435 SemaRef.CodeSynthesisContexts.back());
436
437 SemaRef.popCodeSynthesisContext();
438 Invalid = true;
439 }
440}
441
442bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
443 SourceLocation PointOfInstantiation,
444 SourceRange InstantiationRange) {
445 assert(SemaRef.NonInstantiationEntries <=((SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts
.size()) ? static_cast<void> (0) : __assert_fail ("SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 446, __PRETTY_FUNCTION__))
38
Assuming the condition is true
39
'?' condition is true
446 SemaRef.CodeSynthesisContexts.size())((SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts
.size()) ? static_cast<void> (0) : __assert_fail ("SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 446, __PRETTY_FUNCTION__))
;
447 if ((SemaRef.CodeSynthesisContexts.size() -
40
Assuming the condition is true
41
Taking true branch
448 SemaRef.NonInstantiationEntries)
449 <= SemaRef.getLangOpts().InstantiationDepth)
450 return false;
42
Returning zero, which participates in a condition later
451
452 SemaRef.Diag(PointOfInstantiation,
453 diag::err_template_recursion_depth_exceeded)
454 << SemaRef.getLangOpts().InstantiationDepth
455 << InstantiationRange;
456 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
457 << SemaRef.getLangOpts().InstantiationDepth;
458 return true;
459}
460
461/// Prints the current instantiation stack through a series of
462/// notes.
463void Sema::PrintInstantiationStack() {
464 // Determine which template instantiations to skip, if any.
465 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
466 unsigned Limit = Diags.getTemplateBacktraceLimit();
467 if (Limit && Limit < CodeSynthesisContexts.size()) {
468 SkipStart = Limit / 2 + Limit % 2;
469 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
470 }
471
472 // FIXME: In all of these cases, we need to show the template arguments
473 unsigned InstantiationIdx = 0;
474 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
475 Active = CodeSynthesisContexts.rbegin(),
476 ActiveEnd = CodeSynthesisContexts.rend();
477 Active != ActiveEnd;
478 ++Active, ++InstantiationIdx) {
479 // Skip this instantiation?
480 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
481 if (InstantiationIdx == SkipStart) {
482 // Note that we're skipping instantiations.
483 Diags.Report(Active->PointOfInstantiation,
484 diag::note_instantiation_contexts_suppressed)
485 << unsigned(CodeSynthesisContexts.size() - Limit);
486 }
487 continue;
488 }
489
490 switch (Active->Kind) {
491 case CodeSynthesisContext::TemplateInstantiation: {
492 Decl *D = Active->Entity;
493 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
494 unsigned DiagID = diag::note_template_member_class_here;
495 if (isa<ClassTemplateSpecializationDecl>(Record))
496 DiagID = diag::note_template_class_instantiation_here;
497 Diags.Report(Active->PointOfInstantiation, DiagID)
498 << Record << Active->InstantiationRange;
499 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
500 unsigned DiagID;
501 if (Function->getPrimaryTemplate())
502 DiagID = diag::note_function_template_spec_here;
503 else
504 DiagID = diag::note_template_member_function_here;
505 Diags.Report(Active->PointOfInstantiation, DiagID)
506 << Function
507 << Active->InstantiationRange;
508 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
509 Diags.Report(Active->PointOfInstantiation,
510 VD->isStaticDataMember()?
511 diag::note_template_static_data_member_def_here
512 : diag::note_template_variable_def_here)
513 << VD
514 << Active->InstantiationRange;
515 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
516 Diags.Report(Active->PointOfInstantiation,
517 diag::note_template_enum_def_here)
518 << ED
519 << Active->InstantiationRange;
520 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
521 Diags.Report(Active->PointOfInstantiation,
522 diag::note_template_nsdmi_here)
523 << FD << Active->InstantiationRange;
524 } else {
525 Diags.Report(Active->PointOfInstantiation,
526 diag::note_template_type_alias_instantiation_here)
527 << cast<TypeAliasTemplateDecl>(D)
528 << Active->InstantiationRange;
529 }
530 break;
531 }
532
533 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
534 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
535 SmallVector<char, 128> TemplateArgsStr;
536 llvm::raw_svector_ostream OS(TemplateArgsStr);
537 Template->printName(OS);
538 printTemplateArgumentList(OS, Active->template_arguments(),
539 getPrintingPolicy());
540 Diags.Report(Active->PointOfInstantiation,
541 diag::note_default_arg_instantiation_here)
542 << OS.str()
543 << Active->InstantiationRange;
544 break;
545 }
546
547 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
548 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
549 Diags.Report(Active->PointOfInstantiation,
550 diag::note_explicit_template_arg_substitution_here)
551 << FnTmpl
552 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
553 Active->TemplateArgs,
554 Active->NumTemplateArgs)
555 << Active->InstantiationRange;
556 break;
557 }
558
559 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
560 if (FunctionTemplateDecl *FnTmpl =
561 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
562 Diags.Report(Active->PointOfInstantiation,
563 diag::note_function_template_deduction_instantiation_here)
564 << FnTmpl
565 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
566 Active->TemplateArgs,
567 Active->NumTemplateArgs)
568 << Active->InstantiationRange;
569 } else {
570 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
571 isa<VarTemplateSpecializationDecl>(Active->Entity);
572 bool IsTemplate = false;
573 TemplateParameterList *Params;
574 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
575 IsTemplate = true;
576 Params = D->getTemplateParameters();
577 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
578 Active->Entity)) {
579 Params = D->getTemplateParameters();
580 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
581 Active->Entity)) {
582 Params = D->getTemplateParameters();
583 } else {
584 llvm_unreachable("unexpected template kind")::llvm::llvm_unreachable_internal("unexpected template kind",
"/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 584)
;
585 }
586
587 Diags.Report(Active->PointOfInstantiation,
588 diag::note_deduced_template_arg_substitution_here)
589 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
590 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
591 Active->NumTemplateArgs)
592 << Active->InstantiationRange;
593 }
594 break;
595 }
596
597 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
598 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
599 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
600
601 SmallVector<char, 128> TemplateArgsStr;
602 llvm::raw_svector_ostream OS(TemplateArgsStr);
603 FD->printName(OS);
604 printTemplateArgumentList(OS, Active->template_arguments(),
605 getPrintingPolicy());
606 Diags.Report(Active->PointOfInstantiation,
607 diag::note_default_function_arg_instantiation_here)
608 << OS.str()
609 << Active->InstantiationRange;
610 break;
611 }
612
613 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
614 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
615 std::string Name;
616 if (!Parm->getName().empty())
617 Name = std::string(" '") + Parm->getName().str() + "'";
618
619 TemplateParameterList *TemplateParams = nullptr;
620 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
621 TemplateParams = Template->getTemplateParameters();
622 else
623 TemplateParams =
624 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
625 ->getTemplateParameters();
626 Diags.Report(Active->PointOfInstantiation,
627 diag::note_prior_template_arg_substitution)
628 << isa<TemplateTemplateParmDecl>(Parm)
629 << Name
630 << getTemplateArgumentBindingsText(TemplateParams,
631 Active->TemplateArgs,
632 Active->NumTemplateArgs)
633 << Active->InstantiationRange;
634 break;
635 }
636
637 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
638 TemplateParameterList *TemplateParams = nullptr;
639 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
640 TemplateParams = Template->getTemplateParameters();
641 else
642 TemplateParams =
643 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
644 ->getTemplateParameters();
645
646 Diags.Report(Active->PointOfInstantiation,
647 diag::note_template_default_arg_checking)
648 << getTemplateArgumentBindingsText(TemplateParams,
649 Active->TemplateArgs,
650 Active->NumTemplateArgs)
651 << Active->InstantiationRange;
652 break;
653 }
654
655 case CodeSynthesisContext::ExceptionSpecEvaluation:
656 Diags.Report(Active->PointOfInstantiation,
657 diag::note_evaluating_exception_spec_here)
658 << cast<FunctionDecl>(Active->Entity);
659 break;
660
661 case CodeSynthesisContext::ExceptionSpecInstantiation:
662 Diags.Report(Active->PointOfInstantiation,
663 diag::note_template_exception_spec_instantiation_here)
664 << cast<FunctionDecl>(Active->Entity)
665 << Active->InstantiationRange;
666 break;
667
668 case CodeSynthesisContext::DeclaringSpecialMember:
669 Diags.Report(Active->PointOfInstantiation,
670 diag::note_in_declaration_of_implicit_special_member)
671 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
672 break;
673
674 case CodeSynthesisContext::DefiningSynthesizedFunction: {
675 // FIXME: For synthesized members other than special members, produce a note.
676 auto *MD = dyn_cast<CXXMethodDecl>(Active->Entity);
677 auto CSM = MD ? getSpecialMember(MD) : CXXInvalid;
678 if (CSM != CXXInvalid) {
679 Diags.Report(Active->PointOfInstantiation,
680 diag::note_member_synthesized_at)
681 << CSM << Context.getTagDeclType(MD->getParent());
682 }
683 break;
684 }
685
686 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
687 Diags.Report(Active->Entity->getLocation(),
688 diag::note_rewriting_operator_as_spaceship);
689 break;
690
691 case CodeSynthesisContext::Memoization:
692 break;
693
694 case CodeSynthesisContext::ConstraintsCheck:
695 if (auto *CD = dyn_cast<ConceptDecl>(Active->Entity)) {
696 SmallVector<char, 128> TemplateArgsStr;
697 llvm::raw_svector_ostream OS(TemplateArgsStr);
698 CD->printName(OS);
699 printTemplateArgumentList(OS, Active->template_arguments(),
700 getPrintingPolicy());
701 Diags.Report(Active->PointOfInstantiation,
702 diag::note_concept_specialization_here)
703 << OS.str()
704 << Active->InstantiationRange;
705 break;
706 }
707 // TODO: Concepts - implement this for constrained templates and partial
708 // specializations.
709 llvm_unreachable("only concept constraints are supported right now")::llvm::llvm_unreachable_internal("only concept constraints are supported right now"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 709)
;
710 break;
711
712 case CodeSynthesisContext::ConstraintSubstitution:
713 Diags.Report(Active->PointOfInstantiation,
714 diag::note_constraint_substitution_here)
715 << Active->InstantiationRange;
716 break;
717 }
718 }
719}
720
721Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
722 if (InNonInstantiationSFINAEContext)
723 return Optional<TemplateDeductionInfo *>(nullptr);
724
725 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
726 Active = CodeSynthesisContexts.rbegin(),
727 ActiveEnd = CodeSynthesisContexts.rend();
728 Active != ActiveEnd;
729 ++Active)
730 {
731 switch (Active->Kind) {
732 case CodeSynthesisContext::TemplateInstantiation:
733 // An instantiation of an alias template may or may not be a SFINAE
734 // context, depending on what else is on the stack.
735 if (isa<TypeAliasTemplateDecl>(Active->Entity))
736 break;
737 LLVM_FALLTHROUGH[[gnu::fallthrough]];
738 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
739 case CodeSynthesisContext::ExceptionSpecInstantiation:
740 case CodeSynthesisContext::ConstraintsCheck:
741 // This is a template instantiation, so there is no SFINAE.
742 return None;
743
744 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
745 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
746 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
747 // A default template argument instantiation and substitution into
748 // template parameters with arguments for prior parameters may or may
749 // not be a SFINAE context; look further up the stack.
750 break;
751
752 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
753 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
754 case CodeSynthesisContext::ConstraintSubstitution:
755 // We're either substituting explicitly-specified template arguments
756 // or deduced template arguments or a constraint expression, so SFINAE
757 // applies.
758 assert(Active->DeductionInfo && "Missing deduction info pointer")((Active->DeductionInfo && "Missing deduction info pointer"
) ? static_cast<void> (0) : __assert_fail ("Active->DeductionInfo && \"Missing deduction info pointer\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 758, __PRETTY_FUNCTION__))
;
759 return Active->DeductionInfo;
760
761 case CodeSynthesisContext::DeclaringSpecialMember:
762 case CodeSynthesisContext::DefiningSynthesizedFunction:
763 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
764 // This happens in a context unrelated to template instantiation, so
765 // there is no SFINAE.
766 return None;
767
768 case CodeSynthesisContext::ExceptionSpecEvaluation:
769 // FIXME: This should not be treated as a SFINAE context, because
770 // we will cache an incorrect exception specification. However, clang
771 // bootstrap relies this! See PR31692.
772 break;
773
774 case CodeSynthesisContext::Memoization:
775 break;
776 }
777
778 // The inner context was transparent for SFINAE. If it occurred within a
779 // non-instantiation SFINAE context, then SFINAE applies.
780 if (Active->SavedInNonInstantiationSFINAEContext)
781 return Optional<TemplateDeductionInfo *>(nullptr);
782 }
783
784 return None;
785}
786
787//===----------------------------------------------------------------------===/
788// Template Instantiation for Types
789//===----------------------------------------------------------------------===/
790namespace {
791 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
792 const MultiLevelTemplateArgumentList &TemplateArgs;
793 SourceLocation Loc;
794 DeclarationName Entity;
795
796 public:
797 typedef TreeTransform<TemplateInstantiator> inherited;
798
799 TemplateInstantiator(Sema &SemaRef,
800 const MultiLevelTemplateArgumentList &TemplateArgs,
801 SourceLocation Loc,
802 DeclarationName Entity)
803 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
804 Entity(Entity) { }
805
806 /// Determine whether the given type \p T has already been
807 /// transformed.
808 ///
809 /// For the purposes of template instantiation, a type has already been
810 /// transformed if it is NULL or if it is not dependent.
811 bool AlreadyTransformed(QualType T);
812
813 /// Returns the location of the entity being instantiated, if known.
814 SourceLocation getBaseLocation() { return Loc; }
815
816 /// Returns the name of the entity being instantiated, if any.
817 DeclarationName getBaseEntity() { return Entity; }
818
819 /// Sets the "base" location and entity when that
820 /// information is known based on another transformation.
821 void setBase(SourceLocation Loc, DeclarationName Entity) {
822 this->Loc = Loc;
823 this->Entity = Entity;
824 }
825
826 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
827 SourceRange PatternRange,
828 ArrayRef<UnexpandedParameterPack> Unexpanded,
829 bool &ShouldExpand, bool &RetainExpansion,
830 Optional<unsigned> &NumExpansions) {
831 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
832 PatternRange, Unexpanded,
833 TemplateArgs,
834 ShouldExpand,
835 RetainExpansion,
836 NumExpansions);
837 }
838
839 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
840 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
841 }
842
843 TemplateArgument ForgetPartiallySubstitutedPack() {
844 TemplateArgument Result;
845 if (NamedDecl *PartialPack
846 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
847 MultiLevelTemplateArgumentList &TemplateArgs
848 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
849 unsigned Depth, Index;
850 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
851 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
852 Result = TemplateArgs(Depth, Index);
853 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
854 }
855 }
856
857 return Result;
858 }
859
860 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
861 if (Arg.isNull())
862 return;
863
864 if (NamedDecl *PartialPack
865 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
866 MultiLevelTemplateArgumentList &TemplateArgs
867 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
868 unsigned Depth, Index;
869 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
870 TemplateArgs.setArgument(Depth, Index, Arg);
871 }
872 }
873
874 /// Transform the given declaration by instantiating a reference to
875 /// this declaration.
876 Decl *TransformDecl(SourceLocation Loc, Decl *D);
877
878 void transformAttrs(Decl *Old, Decl *New) {
879 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
880 }
881
882 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
883 if (Old->isParameterPack()) {
884 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
885 for (auto *New : NewDecls)
886 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
887 Old, cast<VarDecl>(New));
888 return;
889 }
890
891 assert(NewDecls.size() == 1 &&((NewDecls.size() == 1 && "should only have multiple expansions for a pack"
) ? static_cast<void> (0) : __assert_fail ("NewDecls.size() == 1 && \"should only have multiple expansions for a pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 892, __PRETTY_FUNCTION__))
892 "should only have multiple expansions for a pack")((NewDecls.size() == 1 && "should only have multiple expansions for a pack"
) ? static_cast<void> (0) : __assert_fail ("NewDecls.size() == 1 && \"should only have multiple expansions for a pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 892, __PRETTY_FUNCTION__))
;
893 Decl *New = NewDecls.front();
894
895 // If we've instantiated the call operator of a lambda or the call
896 // operator template of a generic lambda, update the "instantiation of"
897 // information.
898 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
899 if (NewMD && isLambdaCallOperator(NewMD)) {
900 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
901 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
902 NewTD->setInstantiatedFromMemberTemplate(
903 OldMD->getDescribedFunctionTemplate());
904 else
905 NewMD->setInstantiationOfMemberFunction(OldMD,
906 TSK_ImplicitInstantiation);
907 }
908
909 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
910
911 // We recreated a local declaration, but not by instantiating it. There
912 // may be pending dependent diagnostics to produce.
913 if (auto *DC = dyn_cast<DeclContext>(Old))
914 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
915 }
916
917 /// Transform the definition of the given declaration by
918 /// instantiating it.
919 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
920
921 /// Transform the first qualifier within a scope by instantiating the
922 /// declaration.
923 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
924
925 /// Rebuild the exception declaration and register the declaration
926 /// as an instantiated local.
927 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
928 TypeSourceInfo *Declarator,
929 SourceLocation StartLoc,
930 SourceLocation NameLoc,
931 IdentifierInfo *Name);
932
933 /// Rebuild the Objective-C exception declaration and register the
934 /// declaration as an instantiated local.
935 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
936 TypeSourceInfo *TSInfo, QualType T);
937
938 /// Check for tag mismatches when instantiating an
939 /// elaborated type.
940 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
941 ElaboratedTypeKeyword Keyword,
942 NestedNameSpecifierLoc QualifierLoc,
943 QualType T);
944
945 TemplateName
946 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
947 SourceLocation NameLoc,
948 QualType ObjectType = QualType(),
949 NamedDecl *FirstQualifierInScope = nullptr,
950 bool AllowInjectedClassName = false);
951
952 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
953
954 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
955 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
956 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
957
958 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
959 NonTypeTemplateParmDecl *D);
960 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
961 SubstNonTypeTemplateParmPackExpr *E);
962
963 /// Rebuild a DeclRefExpr for a VarDecl reference.
964 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
965
966 /// Transform a reference to a function or init-capture parameter pack.
967 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
968
969 /// Transform a FunctionParmPackExpr which was built when we couldn't
970 /// expand a function parameter pack reference which refers to an expanded
971 /// pack.
972 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
973
974 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
975 FunctionProtoTypeLoc TL) {
976 // Call the base version; it will forward to our overridden version below.
977 return inherited::TransformFunctionProtoType(TLB, TL);
978 }
979
980 template<typename Fn>
981 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
982 FunctionProtoTypeLoc TL,
983 CXXRecordDecl *ThisContext,
984 Qualifiers ThisTypeQuals,
985 Fn TransformExceptionSpec);
986
987 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
988 int indexAdjustment,
989 Optional<unsigned> NumExpansions,
990 bool ExpectParameterPack);
991
992 /// Transforms a template type parameter type by performing
993 /// substitution of the corresponding template type argument.
994 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
995 TemplateTypeParmTypeLoc TL);
996
997 /// Transforms an already-substituted template type parameter pack
998 /// into either itself (if we aren't substituting into its pack expansion)
999 /// or the appropriate substituted argument.
1000 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1001 SubstTemplateTypeParmPackTypeLoc TL);
1002
1003 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1004 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1005 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
1006 }
1007
1008 TemplateParameterList *TransformTemplateParameterList(
1009 TemplateParameterList *OrigTPL) {
1010 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1011
1012 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1013 TemplateDeclInstantiator DeclInstantiator(getSema(),
1014 /* DeclContext *Owner */ Owner, TemplateArgs);
1015 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1016 }
1017 private:
1018 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
1019 SourceLocation loc,
1020 TemplateArgument arg);
1021 };
1022}
1023
1024bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1025 if (T.isNull())
1026 return true;
1027
1028 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
1029 return false;
1030
1031 getSema().MarkDeclarationsReferencedInType(Loc, T);
1032 return true;
1033}
1034
1035static TemplateArgument
1036getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
1037 assert(S.ArgumentPackSubstitutionIndex >= 0)((S.ArgumentPackSubstitutionIndex >= 0) ? static_cast<void
> (0) : __assert_fail ("S.ArgumentPackSubstitutionIndex >= 0"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1037, __PRETTY_FUNCTION__))
;
1038 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size())((S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size()) ?
static_cast<void> (0) : __assert_fail ("S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1038, __PRETTY_FUNCTION__))
;
1039 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
1040 if (Arg.isPackExpansion())
1041 Arg = Arg.getPackExpansionPattern();
1042 return Arg;
1043}
1044
1045Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1046 if (!D)
1047 return nullptr;
1048
1049 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1050 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1051 // If the corresponding template argument is NULL or non-existent, it's
1052 // because we are performing instantiation from explicitly-specified
1053 // template arguments in a function template, but there were some
1054 // arguments left unspecified.
1055 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1056 TTP->getPosition()))
1057 return D;
1058
1059 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1060
1061 if (TTP->isParameterPack()) {
1062 assert(Arg.getKind() == TemplateArgument::Pack &&((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1063, __PRETTY_FUNCTION__))
1063 "Missing argument pack")((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1063, __PRETTY_FUNCTION__))
;
1064 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1065 }
1066
1067 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1068 assert(!Template.isNull() && Template.getAsTemplateDecl() &&((!Template.isNull() && Template.getAsTemplateDecl() &&
"Wrong kind of template template argument") ? static_cast<
void> (0) : __assert_fail ("!Template.isNull() && Template.getAsTemplateDecl() && \"Wrong kind of template template argument\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1069, __PRETTY_FUNCTION__))
1069 "Wrong kind of template template argument")((!Template.isNull() && Template.getAsTemplateDecl() &&
"Wrong kind of template template argument") ? static_cast<
void> (0) : __assert_fail ("!Template.isNull() && Template.getAsTemplateDecl() && \"Wrong kind of template template argument\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1069, __PRETTY_FUNCTION__))
;
1070 return Template.getAsTemplateDecl();
1071 }
1072
1073 // Fall through to find the instantiated declaration for this template
1074 // template parameter.
1075 }
1076
1077 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1078}
1079
1080Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1081 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1082 if (!Inst)
1083 return nullptr;
1084
1085 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1086 return Inst;
1087}
1088
1089NamedDecl *
1090TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1091 SourceLocation Loc) {
1092 // If the first part of the nested-name-specifier was a template type
1093 // parameter, instantiate that type parameter down to a tag type.
1094 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1095 const TemplateTypeParmType *TTP
1096 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1097
1098 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1099 // FIXME: This needs testing w/ member access expressions.
1100 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1101
1102 if (TTP->isParameterPack()) {
1103 assert(Arg.getKind() == TemplateArgument::Pack &&((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1104, __PRETTY_FUNCTION__))
1104 "Missing argument pack")((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1104, __PRETTY_FUNCTION__))
;
1105
1106 if (getSema().ArgumentPackSubstitutionIndex == -1)
1107 return nullptr;
1108
1109 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1110 }
1111
1112 QualType T = Arg.getAsType();
1113 if (T.isNull())
1114 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1115
1116 if (const TagType *Tag = T->getAs<TagType>())
1117 return Tag->getDecl();
1118
1119 // The resulting type is not a tag; complain.
1120 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1121 return nullptr;
1122 }
1123 }
1124
1125 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1126}
1127
1128VarDecl *
1129TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1130 TypeSourceInfo *Declarator,
1131 SourceLocation StartLoc,
1132 SourceLocation NameLoc,
1133 IdentifierInfo *Name) {
1134 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1135 StartLoc, NameLoc, Name);
1136 if (Var)
1137 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1138 return Var;
1139}
1140
1141VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1142 TypeSourceInfo *TSInfo,
1143 QualType T) {
1144 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1145 if (Var)
1146 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1147 return Var;
1148}
1149
1150QualType
1151TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1152 ElaboratedTypeKeyword Keyword,
1153 NestedNameSpecifierLoc QualifierLoc,
1154 QualType T) {
1155 if (const TagType *TT = T->getAs<TagType>()) {
1156 TagDecl* TD = TT->getDecl();
1157
1158 SourceLocation TagLocation = KeywordLoc;
1159
1160 IdentifierInfo *Id = TD->getIdentifier();
1161
1162 // TODO: should we even warn on struct/class mismatches for this? Seems
1163 // like it's likely to produce a lot of spurious errors.
1164 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1165 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1166 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1167 TagLocation, Id)) {
1168 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1169 << Id
1170 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1171 TD->getKindName());
1172 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1173 }
1174 }
1175 }
1176
1177 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1178 Keyword,
1179 QualifierLoc,
1180 T);
1181}
1182
1183TemplateName TemplateInstantiator::TransformTemplateName(
1184 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1185 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1186 bool AllowInjectedClassName) {
1187 if (TemplateTemplateParmDecl *TTP
1188 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1189 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1190 // If the corresponding template argument is NULL or non-existent, it's
1191 // because we are performing instantiation from explicitly-specified
1192 // template arguments in a function template, but there were some
1193 // arguments left unspecified.
1194 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1195 TTP->getPosition()))
1196 return Name;
1197
1198 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1199
1200 if (TTP->isParameterPack()) {
1201 assert(Arg.getKind() == TemplateArgument::Pack &&((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1202, __PRETTY_FUNCTION__))
1202 "Missing argument pack")((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1202, __PRETTY_FUNCTION__))
;
1203
1204 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1205 // We have the template argument pack to substitute, but we're not
1206 // actually expanding the enclosing pack expansion yet. So, just
1207 // keep the entire argument pack.
1208 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1209 }
1210
1211 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1212 }
1213
1214 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1215 assert(!Template.isNull() && "Null template template argument")((!Template.isNull() && "Null template template argument"
) ? static_cast<void> (0) : __assert_fail ("!Template.isNull() && \"Null template template argument\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1215, __PRETTY_FUNCTION__))
;
1216 assert(!Template.getAsQualifiedTemplateName() &&((!Template.getAsQualifiedTemplateName() && "template decl to substitute is qualified?"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsQualifiedTemplateName() && \"template decl to substitute is qualified?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1217, __PRETTY_FUNCTION__))
1217 "template decl to substitute is qualified?")((!Template.getAsQualifiedTemplateName() && "template decl to substitute is qualified?"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsQualifiedTemplateName() && \"template decl to substitute is qualified?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1217, __PRETTY_FUNCTION__))
;
1218
1219 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1220 return Template;
1221 }
1222 }
1223
1224 if (SubstTemplateTemplateParmPackStorage *SubstPack
1225 = Name.getAsSubstTemplateTemplateParmPack()) {
1226 if (getSema().ArgumentPackSubstitutionIndex == -1)
1227 return Name;
1228
1229 TemplateArgument Arg = SubstPack->getArgumentPack();
1230 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1231 return Arg.getAsTemplate().getNameToSubstitute();
1232 }
1233
1234 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1235 FirstQualifierInScope,
1236 AllowInjectedClassName);
1237}
1238
1239ExprResult
1240TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1241 if (!E->isTypeDependent())
1242 return E;
1243
1244 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
1245}
1246
1247ExprResult
1248TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1249 NonTypeTemplateParmDecl *NTTP) {
1250 // If the corresponding template argument is NULL or non-existent, it's
1251 // because we are performing instantiation from explicitly-specified
1252 // template arguments in a function template, but there were some
1253 // arguments left unspecified.
1254 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1255 NTTP->getPosition()))
1256 return E;
1257
1258 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1259
1260 if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1261 // We're performing a partial substitution, so the substituted argument
1262 // could be dependent. As a result we can't create a SubstNonType*Expr
1263 // node now, since that represents a fully-substituted argument.
1264 // FIXME: We should have some AST representation for this.
1265 if (Arg.getKind() == TemplateArgument::Pack) {
1266 // FIXME: This won't work for alias templates.
1267 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&((Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion
() && "unexpected pack arguments in partial substitution"
) ? static_cast<void> (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in partial substitution\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1268, __PRETTY_FUNCTION__))
1268 "unexpected pack arguments in partial substitution")((Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion
() && "unexpected pack arguments in partial substitution"
) ? static_cast<void> (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in partial substitution\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1268, __PRETTY_FUNCTION__))
;
1269 Arg = Arg.pack_begin()->getPackExpansionPattern();
1270 }
1271 assert(Arg.getKind() == TemplateArgument::Expression &&((Arg.getKind() == TemplateArgument::Expression && "unexpected nontype template argument kind in partial substitution"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Expression && \"unexpected nontype template argument kind in partial substitution\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1272, __PRETTY_FUNCTION__))
1272 "unexpected nontype template argument kind in partial substitution")((Arg.getKind() == TemplateArgument::Expression && "unexpected nontype template argument kind in partial substitution"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Expression && \"unexpected nontype template argument kind in partial substitution\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1272, __PRETTY_FUNCTION__))
;
1273 return Arg.getAsExpr();
1274 }
1275
1276 if (NTTP->isParameterPack()) {
1277 assert(Arg.getKind() == TemplateArgument::Pack &&((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1278, __PRETTY_FUNCTION__))
1278 "Missing argument pack")((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1278, __PRETTY_FUNCTION__))
;
1279
1280 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1281 // We have an argument pack, but we can't select a particular argument
1282 // out of it yet. Therefore, we'll build an expression to hold on to that
1283 // argument pack.
1284 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1285 E->getLocation(),
1286 NTTP->getDeclName());
1287 if (TargetType.isNull())
1288 return ExprError();
1289
1290 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1291 TargetType.getNonLValueExprType(SemaRef.Context),
1292 TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
1293 E->getLocation(), Arg);
1294 }
1295
1296 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1297 }
1298
1299 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1300}
1301
1302const LoopHintAttr *
1303TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1304 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1305
1306 if (TransformedExpr == LH->getValue())
1307 return LH;
1308
1309 // Generate error if there is a problem with the value.
1310 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1311 return LH;
1312
1313 // Create new LoopHintValueAttr with integral expression in place of the
1314 // non-type template parameter.
1315 return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1316 LH->getState(), TransformedExpr, *LH);
1317}
1318
1319ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1320 NonTypeTemplateParmDecl *parm,
1321 SourceLocation loc,
1322 TemplateArgument arg) {
1323 ExprResult result;
1324 QualType type;
1325
1326 // The template argument itself might be an expression, in which
1327 // case we just return that expression.
1328 if (arg.getKind() == TemplateArgument::Expression) {
1329 Expr *argExpr = arg.getAsExpr();
1330 result = argExpr;
1331 type = argExpr->getType();
1332
1333 } else if (arg.getKind() == TemplateArgument::Declaration ||
1334 arg.getKind() == TemplateArgument::NullPtr) {
1335 ValueDecl *VD;
1336 if (arg.getKind() == TemplateArgument::Declaration) {
1337 VD = arg.getAsDecl();
1338
1339 // Find the instantiation of the template argument. This is
1340 // required for nested templates.
1341 VD = cast_or_null<ValueDecl>(
1342 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1343 if (!VD)
1344 return ExprError();
1345 } else {
1346 // Propagate NULL template argument.
1347 VD = nullptr;
1348 }
1349
1350 // Derive the type we want the substituted decl to have. This had
1351 // better be non-dependent, or these checks will have serious problems.
1352 if (parm->isExpandedParameterPack()) {
1353 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1354 } else if (parm->isParameterPack() &&
1355 isa<PackExpansionType>(parm->getType())) {
1356 type = SemaRef.SubstType(
1357 cast<PackExpansionType>(parm->getType())->getPattern(),
1358 TemplateArgs, loc, parm->getDeclName());
1359 } else {
1360 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1361 TemplateArgs, loc, parm->getDeclName());
1362 }
1363 assert(!type.isNull() && "type substitution failed for param type")((!type.isNull() && "type substitution failed for param type"
) ? static_cast<void> (0) : __assert_fail ("!type.isNull() && \"type substitution failed for param type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1363, __PRETTY_FUNCTION__))
;
1364 assert(!type->isDependentType() && "param type still dependent")((!type->isDependentType() && "param type still dependent"
) ? static_cast<void> (0) : __assert_fail ("!type->isDependentType() && \"param type still dependent\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1364, __PRETTY_FUNCTION__))
;
1365 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1366
1367 if (!result.isInvalid()) type = result.get()->getType();
1368 } else {
1369 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1370
1371 // Note that this type can be different from the type of 'result',
1372 // e.g. if it's an enum type.
1373 type = arg.getIntegralType();
1374 }
1375 if (result.isInvalid()) return ExprError();
1376
1377 Expr *resultExpr = result.get();
1378 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1379 type, resultExpr->getValueKind(), loc, parm, resultExpr);
1380}
1381
1382ExprResult
1383TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1384 SubstNonTypeTemplateParmPackExpr *E) {
1385 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1386 // We aren't expanding the parameter pack, so just return ourselves.
1387 return E;
1388 }
1389
1390 TemplateArgument Arg = E->getArgumentPack();
1391 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1392 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1393 E->getParameterPackLocation(),
1394 Arg);
1395}
1396
1397ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1398 SourceLocation Loc) {
1399 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1400 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1401}
1402
1403ExprResult
1404TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1405 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1406 // We can expand this parameter pack now.
1407 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1408 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
1409 if (!VD)
1410 return ExprError();
1411 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
1412 }
1413
1414 QualType T = TransformType(E->getType());
1415 if (T.isNull())
1416 return ExprError();
1417
1418 // Transform each of the parameter expansions into the corresponding
1419 // parameters in the instantiation of the function decl.
1420 SmallVector<VarDecl *, 8> Vars;
1421 Vars.reserve(E->getNumExpansions());
1422 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1423 I != End; ++I) {
1424 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
1425 if (!D)
1426 return ExprError();
1427 Vars.push_back(D);
1428 }
1429
1430 auto *PackExpr =
1431 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
1432 E->getParameterPackLocation(), Vars);
1433 getSema().MarkFunctionParmPackReferenced(PackExpr);
1434 return PackExpr;
1435}
1436
1437ExprResult
1438TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1439 VarDecl *PD) {
1440 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1441 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1442 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1443 assert(Found && "no instantiation for parameter pack")((Found && "no instantiation for parameter pack") ? static_cast
<void> (0) : __assert_fail ("Found && \"no instantiation for parameter pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1443, __PRETTY_FUNCTION__))
;
1444
1445 Decl *TransformedDecl;
1446 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1447 // If this is a reference to a function parameter pack which we can
1448 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1449 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1450 QualType T = TransformType(E->getType());
1451 if (T.isNull())
1452 return ExprError();
1453 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
1454 E->getExprLoc(), *Pack);
1455 getSema().MarkFunctionParmPackReferenced(PackExpr);
1456 return PackExpr;
1457 }
1458
1459 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1460 } else {
1461 TransformedDecl = Found->get<Decl*>();
1462 }
1463
1464 // We have either an unexpanded pack or a specific expansion.
1465 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
1466}
1467
1468ExprResult
1469TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1470 NamedDecl *D = E->getDecl();
1471
1472 // Handle references to non-type template parameters and non-type template
1473 // parameter packs.
1474 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1475 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1476 return TransformTemplateParmRefExpr(E, NTTP);
1477
1478 // We have a non-type template parameter that isn't fully substituted;
1479 // FindInstantiatedDecl will find it in the local instantiation scope.
1480 }
1481
1482 // Handle references to function parameter packs.
1483 if (VarDecl *PD = dyn_cast<VarDecl>(D))
1484 if (PD->isParameterPack())
1485 return TransformFunctionParmPackRefExpr(E, PD);
1486
1487 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1488}
1489
1490ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1491 CXXDefaultArgExpr *E) {
1492 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->((!cast<FunctionDecl>(E->getParam()->getDeclContext
())-> getDescribedFunctionTemplate() && "Default arg expressions are never formed in dependent cases."
) ? static_cast<void> (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1494, __PRETTY_FUNCTION__))
1493 getDescribedFunctionTemplate() &&((!cast<FunctionDecl>(E->getParam()->getDeclContext
())-> getDescribedFunctionTemplate() && "Default arg expressions are never formed in dependent cases."
) ? static_cast<void> (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1494, __PRETTY_FUNCTION__))
1494 "Default arg expressions are never formed in dependent cases.")((!cast<FunctionDecl>(E->getParam()->getDeclContext
())-> getDescribedFunctionTemplate() && "Default arg expressions are never formed in dependent cases."
) ? static_cast<void> (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1494, __PRETTY_FUNCTION__))
;
1495 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1496 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1497 E->getParam());
1498}
1499
1500template<typename Fn>
1501QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1502 FunctionProtoTypeLoc TL,
1503 CXXRecordDecl *ThisContext,
1504 Qualifiers ThisTypeQuals,
1505 Fn TransformExceptionSpec) {
1506 // We need a local instantiation scope for this function prototype.
1507 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1508 return inherited::TransformFunctionProtoType(
1509 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1510}
1511
1512ParmVarDecl *
1513TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1514 int indexAdjustment,
1515 Optional<unsigned> NumExpansions,
1516 bool ExpectParameterPack) {
1517 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1518 NumExpansions, ExpectParameterPack);
1519}
1520
1521QualType
1522TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1523 TemplateTypeParmTypeLoc TL) {
1524 const TemplateTypeParmType *T = TL.getTypePtr();
1525 if (T->getDepth() < TemplateArgs.getNumLevels()) {
1526 // Replace the template type parameter with its corresponding
1527 // template argument.
1528
1529 // If the corresponding template argument is NULL or doesn't exist, it's
1530 // because we are performing instantiation from explicitly-specified
1531 // template arguments in a function template class, but there were some
1532 // arguments left unspecified.
1533 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1534 TemplateTypeParmTypeLoc NewTL
1535 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1536 NewTL.setNameLoc(TL.getNameLoc());
1537 return TL.getType();
1538 }
1539
1540 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1541
1542 if (T->isParameterPack()) {
1543 assert(Arg.getKind() == TemplateArgument::Pack &&((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1544, __PRETTY_FUNCTION__))
1544 "Missing argument pack")((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1544, __PRETTY_FUNCTION__))
;
1545
1546 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1547 // We have the template argument pack, but we're not expanding the
1548 // enclosing pack expansion yet. Just save the template argument
1549 // pack for later substitution.
1550 QualType Result
1551 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1552 SubstTemplateTypeParmPackTypeLoc NewTL
1553 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1554 NewTL.setNameLoc(TL.getNameLoc());
1555 return Result;
1556 }
1557
1558 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1559 }
1560
1561 assert(Arg.getKind() == TemplateArgument::Type &&((Arg.getKind() == TemplateArgument::Type && "Template argument kind mismatch"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"Template argument kind mismatch\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1562, __PRETTY_FUNCTION__))
1562 "Template argument kind mismatch")((Arg.getKind() == TemplateArgument::Type && "Template argument kind mismatch"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"Template argument kind mismatch\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1562, __PRETTY_FUNCTION__))
;
1563
1564 QualType Replacement = Arg.getAsType();
1565
1566 // TODO: only do this uniquing once, at the start of instantiation.
1567 QualType Result
1568 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1569 SubstTemplateTypeParmTypeLoc NewTL
1570 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1571 NewTL.setNameLoc(TL.getNameLoc());
1572 return Result;
1573 }
1574
1575 // The template type parameter comes from an inner template (e.g.,
1576 // the template parameter list of a member template inside the
1577 // template we are instantiating). Create a new template type
1578 // parameter with the template "level" reduced by one.
1579 TemplateTypeParmDecl *NewTTPDecl = nullptr;
1580 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1581 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1582 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1583
1584 QualType Result = getSema().Context.getTemplateTypeParmType(
1585 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1586 T->isParameterPack(), NewTTPDecl);
1587 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1588 NewTL.setNameLoc(TL.getNameLoc());
1589 return Result;
1590}
1591
1592QualType
1593TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1594 TypeLocBuilder &TLB,
1595 SubstTemplateTypeParmPackTypeLoc TL) {
1596 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1597 // We aren't expanding the parameter pack, so just return ourselves.
1598 SubstTemplateTypeParmPackTypeLoc NewTL
1599 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1600 NewTL.setNameLoc(TL.getNameLoc());
1601 return TL.getType();
1602 }
1603
1604 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1605 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1606 QualType Result = Arg.getAsType();
1607
1608 Result = getSema().Context.getSubstTemplateTypeParmType(
1609 TL.getTypePtr()->getReplacedParameter(),
1610 Result);
1611 SubstTemplateTypeParmTypeLoc NewTL
1612 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1613 NewTL.setNameLoc(TL.getNameLoc());
1614 return Result;
1615}
1616
1617/// Perform substitution on the type T with a given set of template
1618/// arguments.
1619///
1620/// This routine substitutes the given template arguments into the
1621/// type T and produces the instantiated type.
1622///
1623/// \param T the type into which the template arguments will be
1624/// substituted. If this type is not dependent, it will be returned
1625/// immediately.
1626///
1627/// \param Args the template arguments that will be
1628/// substituted for the top-level template parameters within T.
1629///
1630/// \param Loc the location in the source code where this substitution
1631/// is being performed. It will typically be the location of the
1632/// declarator (if we're instantiating the type of some declaration)
1633/// or the location of the type in the source code (if, e.g., we're
1634/// instantiating the type of a cast expression).
1635///
1636/// \param Entity the name of the entity associated with a declaration
1637/// being instantiated (if any). May be empty to indicate that there
1638/// is no such entity (if, e.g., this is a type that occurs as part of
1639/// a cast expression) or that the entity has no name (e.g., an
1640/// unnamed function parameter).
1641///
1642/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1643/// acceptable as the top level type of the result.
1644///
1645/// \returns If the instantiation succeeds, the instantiated
1646/// type. Otherwise, produces diagnostics and returns a NULL type.
1647TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1648 const MultiLevelTemplateArgumentList &Args,
1649 SourceLocation Loc,
1650 DeclarationName Entity,
1651 bool AllowDeducedTST) {
1652 assert(!CodeSynthesisContexts.empty() &&((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1654, __PRETTY_FUNCTION__))
1653 "Cannot perform an instantiation without some context on the "((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1654, __PRETTY_FUNCTION__))
1654 "instantiation stack")((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1654, __PRETTY_FUNCTION__))
;
1655
1656 if (!T->getType()->isInstantiationDependentType() &&
1657 !T->getType()->isVariablyModifiedType())
1658 return T;
1659
1660 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1661 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1662 : Instantiator.TransformType(T);
1663}
1664
1665TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1666 const MultiLevelTemplateArgumentList &Args,
1667 SourceLocation Loc,
1668 DeclarationName Entity) {
1669 assert(!CodeSynthesisContexts.empty() &&((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1671, __PRETTY_FUNCTION__))
1670 "Cannot perform an instantiation without some context on the "((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1671, __PRETTY_FUNCTION__))
1671 "instantiation stack")((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1671, __PRETTY_FUNCTION__))
;
1672
1673 if (TL.getType().isNull())
1674 return nullptr;
1675
1676 if (!TL.getType()->isInstantiationDependentType() &&
1677 !TL.getType()->isVariablyModifiedType()) {
1678 // FIXME: Make a copy of the TypeLoc data here, so that we can
1679 // return a new TypeSourceInfo. Inefficient!
1680 TypeLocBuilder TLB;
1681 TLB.pushFullCopy(TL);
1682 return TLB.getTypeSourceInfo(Context, TL.getType());
1683 }
1684
1685 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1686 TypeLocBuilder TLB;
1687 TLB.reserve(TL.getFullDataSize());
1688 QualType Result = Instantiator.TransformType(TLB, TL);
1689 if (Result.isNull())
1690 return nullptr;
1691
1692 return TLB.getTypeSourceInfo(Context, Result);
1693}
1694
1695/// Deprecated form of the above.
1696QualType Sema::SubstType(QualType T,
1697 const MultiLevelTemplateArgumentList &TemplateArgs,
1698 SourceLocation Loc, DeclarationName Entity) {
1699 assert(!CodeSynthesisContexts.empty() &&((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1701, __PRETTY_FUNCTION__))
1700 "Cannot perform an instantiation without some context on the "((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1701, __PRETTY_FUNCTION__))
1701 "instantiation stack")((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1701, __PRETTY_FUNCTION__))
;
1702
1703 // If T is not a dependent type or a variably-modified type, there
1704 // is nothing to do.
1705 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
1706 return T;
1707
1708 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1709 return Instantiator.TransformType(T);
1710}
1711
1712static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
1713 if (T->getType()->isInstantiationDependentType() ||
1714 T->getType()->isVariablyModifiedType())
1715 return true;
1716
1717 TypeLoc TL = T->getTypeLoc().IgnoreParens();
1718 if (!TL.getAs<FunctionProtoTypeLoc>())
1719 return false;
1720
1721 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
1722 for (ParmVarDecl *P : FP.getParams()) {
1723 // This must be synthesized from a typedef.
1724 if (!P) continue;
1725
1726 // If there are any parameters, a new TypeSourceInfo that refers to the
1727 // instantiated parameters must be built.
1728 return true;
1729 }
1730
1731 return false;
1732}
1733
1734/// A form of SubstType intended specifically for instantiating the
1735/// type of a FunctionDecl. Its purpose is solely to force the
1736/// instantiation of default-argument expressions and to avoid
1737/// instantiating an exception-specification.
1738TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1739 const MultiLevelTemplateArgumentList &Args,
1740 SourceLocation Loc,
1741 DeclarationName Entity,
1742 CXXRecordDecl *ThisContext,
1743 Qualifiers ThisTypeQuals) {
1744 assert(!CodeSynthesisContexts.empty() &&((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1746, __PRETTY_FUNCTION__))
1745 "Cannot perform an instantiation without some context on the "((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1746, __PRETTY_FUNCTION__))
1746 "instantiation stack")((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1746, __PRETTY_FUNCTION__))
;
1747
1748 if (!NeedsInstantiationAsFunctionType(T))
1749 return T;
1750
1751 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1752
1753 TypeLocBuilder TLB;
1754
1755 TypeLoc TL = T->getTypeLoc();
1756 TLB.reserve(TL.getFullDataSize());
1757
1758 QualType Result;
1759
1760 if (FunctionProtoTypeLoc Proto =
1761 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1762 // Instantiate the type, other than its exception specification. The
1763 // exception specification is instantiated in InitFunctionInstantiation
1764 // once we've built the FunctionDecl.
1765 // FIXME: Set the exception specification to EST_Uninstantiated here,
1766 // instead of rebuilding the function type again later.
1767 Result = Instantiator.TransformFunctionProtoType(
1768 TLB, Proto, ThisContext, ThisTypeQuals,
1769 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1770 bool &Changed) { return false; });
1771 } else {
1772 Result = Instantiator.TransformType(TLB, TL);
1773 }
1774 if (Result.isNull())
1775 return nullptr;
1776
1777 return TLB.getTypeSourceInfo(Context, Result);
1778}
1779
1780bool Sema::SubstExceptionSpec(SourceLocation Loc,
1781 FunctionProtoType::ExceptionSpecInfo &ESI,
1782 SmallVectorImpl<QualType> &ExceptionStorage,
1783 const MultiLevelTemplateArgumentList &Args) {
1784 assert(ESI.Type != EST_Uninstantiated)((ESI.Type != EST_Uninstantiated) ? static_cast<void> (
0) : __assert_fail ("ESI.Type != EST_Uninstantiated", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1784, __PRETTY_FUNCTION__))
;
1785
1786 bool Changed = false;
1787 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
1788 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
1789 Changed);
1790}
1791
1792void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1793 const MultiLevelTemplateArgumentList &Args) {
1794 FunctionProtoType::ExceptionSpecInfo ESI =
1795 Proto->getExtProtoInfo().ExceptionSpec;
1796
1797 SmallVector<QualType, 4> ExceptionStorage;
1798 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
1799 ESI, ExceptionStorage, Args))
1800 // On error, recover by dropping the exception specification.
1801 ESI.Type = EST_None;
1802
1803 UpdateExceptionSpec(New, ESI);
1804}
1805
1806ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1807 const MultiLevelTemplateArgumentList &TemplateArgs,
1808 int indexAdjustment,
1809 Optional<unsigned> NumExpansions,
1810 bool ExpectParameterPack) {
1811 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1812 TypeSourceInfo *NewDI = nullptr;
1813
1814 TypeLoc OldTL = OldDI->getTypeLoc();
1815 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1816
1817 // We have a function parameter pack. Substitute into the pattern of the
1818 // expansion.
1819 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1820 OldParm->getLocation(), OldParm->getDeclName());
1821 if (!NewDI)
1822 return nullptr;
1823
1824 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1825 // We still have unexpanded parameter packs, which means that
1826 // our function parameter is still a function parameter pack.
1827 // Therefore, make its type a pack expansion type.
1828 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1829 NumExpansions);
1830 } else if (ExpectParameterPack) {
1831 // We expected to get a parameter pack but didn't (because the type
1832 // itself is not a pack expansion type), so complain. This can occur when
1833 // the substitution goes through an alias template that "loses" the
1834 // pack expansion.
1835 Diag(OldParm->getLocation(),
1836 diag::err_function_parameter_pack_without_parameter_packs)
1837 << NewDI->getType();
1838 return nullptr;
1839 }
1840 } else {
1841 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1842 OldParm->getDeclName());
1843 }
1844
1845 if (!NewDI)
1846 return nullptr;
1847
1848 if (NewDI->getType()->isVoidType()) {
1849 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1850 return nullptr;
1851 }
1852
1853 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1854 OldParm->getInnerLocStart(),
1855 OldParm->getLocation(),
1856 OldParm->getIdentifier(),
1857 NewDI->getType(), NewDI,
1858 OldParm->getStorageClass());
1859 if (!NewParm)
1860 return nullptr;
1861
1862 // Mark the (new) default argument as uninstantiated (if any).
1863 if (OldParm->hasUninstantiatedDefaultArg()) {
1864 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1865 NewParm->setUninstantiatedDefaultArg(Arg);
1866 } else if (OldParm->hasUnparsedDefaultArg()) {
1867 NewParm->setUnparsedDefaultArg();
1868 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1869 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1870 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
1871 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1872 // Instantiate default arguments for methods of local classes (DR1484)
1873 // and non-defining declarations.
1874 Sema::ContextRAII SavedContext(*this, OwningFunc);
1875 LocalInstantiationScope Local(*this, true);
1876 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
1877 if (NewArg.isUsable()) {
1878 // It would be nice if we still had this.
1879 SourceLocation EqualLoc = NewArg.get()->getBeginLoc();
1880 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1881 }
1882 } else {
1883 // FIXME: if we non-lazily instantiated non-dependent default args for
1884 // non-dependent parameter types we could remove a bunch of duplicate
1885 // conversion warnings for such arguments.
1886 NewParm->setUninstantiatedDefaultArg(Arg);
1887 }
1888 }
1889
1890 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1891
1892 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1893 // Add the new parameter to the instantiated parameter pack.
1894 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1895 } else {
1896 // Introduce an Old -> New mapping
1897 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1898 }
1899
1900 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1901 // can be anything, is this right ?
1902 NewParm->setDeclContext(CurContext);
1903
1904 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1905 OldParm->getFunctionScopeIndex() + indexAdjustment);
1906
1907 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1908
1909 return NewParm;
1910}
1911
1912/// Substitute the given template arguments into the given set of
1913/// parameters, producing the set of parameter types that would be generated
1914/// from such a substitution.
1915bool Sema::SubstParmTypes(
1916 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1917 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1918 const MultiLevelTemplateArgumentList &TemplateArgs,
1919 SmallVectorImpl<QualType> &ParamTypes,
1920 SmallVectorImpl<ParmVarDecl *> *OutParams,
1921 ExtParameterInfoBuilder &ParamInfos) {
1922 assert(!CodeSynthesisContexts.empty() &&((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1924, __PRETTY_FUNCTION__))
1923 "Cannot perform an instantiation without some context on the "((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1924, __PRETTY_FUNCTION__))
1924 "instantiation stack")((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1924, __PRETTY_FUNCTION__))
;
1925
1926 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1927 DeclarationName());
1928 return Instantiator.TransformFunctionTypeParams(
1929 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
1930}
1931
1932/// Perform substitution on the base class specifiers of the
1933/// given class template specialization.
1934///
1935/// Produces a diagnostic and returns true on error, returns false and
1936/// attaches the instantiated base classes to the class template
1937/// specialization if successful.
1938bool
1939Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1940 CXXRecordDecl *Pattern,
1941 const MultiLevelTemplateArgumentList &TemplateArgs) {
1942 bool Invalid = false;
1943 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1944 for (const auto &Base : Pattern->bases()) {
1945 if (!Base.getType()->isDependentType()) {
1946 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
1947 if (RD->isInvalidDecl())
1948 Instantiation->setInvalidDecl();
1949 }
1950 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
1951 continue;
1952 }
1953
1954 SourceLocation EllipsisLoc;
1955 TypeSourceInfo *BaseTypeLoc;
1956 if (Base.isPackExpansion()) {
1957 // This is a pack expansion. See whether we should expand it now, or
1958 // wait until later.
1959 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1960 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
1961 Unexpanded);
1962 bool ShouldExpand = false;
1963 bool RetainExpansion = false;
1964 Optional<unsigned> NumExpansions;
1965 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1966 Base.getSourceRange(),
1967 Unexpanded,
1968 TemplateArgs, ShouldExpand,
1969 RetainExpansion,
1970 NumExpansions)) {
1971 Invalid = true;
1972 continue;
1973 }
1974
1975 // If we should expand this pack expansion now, do so.
1976 if (ShouldExpand) {
1977 for (unsigned I = 0; I != *NumExpansions; ++I) {
1978 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1979
1980 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1981 TemplateArgs,
1982 Base.getSourceRange().getBegin(),
1983 DeclarationName());
1984 if (!BaseTypeLoc) {
1985 Invalid = true;
1986 continue;
1987 }
1988
1989 if (CXXBaseSpecifier *InstantiatedBase
1990 = CheckBaseSpecifier(Instantiation,
1991 Base.getSourceRange(),
1992 Base.isVirtual(),
1993 Base.getAccessSpecifierAsWritten(),
1994 BaseTypeLoc,
1995 SourceLocation()))
1996 InstantiatedBases.push_back(InstantiatedBase);
1997 else
1998 Invalid = true;
1999 }
2000
2001 continue;
2002 }
2003
2004 // The resulting base specifier will (still) be a pack expansion.
2005 EllipsisLoc = Base.getEllipsisLoc();
2006 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2007 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2008 TemplateArgs,
2009 Base.getSourceRange().getBegin(),
2010 DeclarationName());
2011 } else {
2012 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2013 TemplateArgs,
2014 Base.getSourceRange().getBegin(),
2015 DeclarationName());
2016 }
2017
2018 if (!BaseTypeLoc) {
2019 Invalid = true;
2020 continue;
2021 }
2022
2023 if (CXXBaseSpecifier *InstantiatedBase
2024 = CheckBaseSpecifier(Instantiation,
2025 Base.getSourceRange(),
2026 Base.isVirtual(),
2027 Base.getAccessSpecifierAsWritten(),
2028 BaseTypeLoc,
2029 EllipsisLoc))
2030 InstantiatedBases.push_back(InstantiatedBase);
2031 else
2032 Invalid = true;
2033 }
2034
2035 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
2036 Invalid = true;
2037
2038 return Invalid;
2039}
2040
2041// Defined via #include from SemaTemplateInstantiateDecl.cpp
2042namespace clang {
2043 namespace sema {
2044 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
2045 const MultiLevelTemplateArgumentList &TemplateArgs);
2046 Attr *instantiateTemplateAttributeForDecl(
2047 const Attr *At, ASTContext &C, Sema &S,
2048 const MultiLevelTemplateArgumentList &TemplateArgs);
2049 }
2050}
2051
2052/// Instantiate the definition of a class from a given pattern.
2053///
2054/// \param PointOfInstantiation The point of instantiation within the
2055/// source code.
2056///
2057/// \param Instantiation is the declaration whose definition is being
2058/// instantiated. This will be either a class template specialization
2059/// or a member class of a class template specialization.
2060///
2061/// \param Pattern is the pattern from which the instantiation
2062/// occurs. This will be either the declaration of a class template or
2063/// the declaration of a member class of a class template.
2064///
2065/// \param TemplateArgs The template arguments to be substituted into
2066/// the pattern.
2067///
2068/// \param TSK the kind of implicit or explicit instantiation to perform.
2069///
2070/// \param Complain whether to complain if the class cannot be instantiated due
2071/// to the lack of a definition.
2072///
2073/// \returns true if an error occurred, false otherwise.
2074bool
2075Sema::InstantiateClass(SourceLocation PointOfInstantiation,
2076 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
2077 const MultiLevelTemplateArgumentList &TemplateArgs,
2078 TemplateSpecializationKind TSK,
2079 bool Complain) {
2080 CXXRecordDecl *PatternDef
2081 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
27
Assuming the object is a 'CXXRecordDecl'
2082 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
28
Assuming the condition is false
29
Taking false branch
2083 Instantiation->getInstantiatedFromMemberClass(),
2084 Pattern, PatternDef, TSK, Complain))
2085 return true;
2086
2087 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
2088 std::string Name;
2089 llvm::raw_string_ostream OS(Name);
2090 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
2091 /*Qualified=*/true);
2092 return Name;
2093 });
2094
2095 Pattern = PatternDef;
2096
2097 // Record the point of instantiation.
2098 if (MemberSpecializationInfo *MSInfo
30
Assuming 'MSInfo' is null
31
Taking false branch
2099 = Instantiation->getMemberSpecializationInfo()) {
2100 MSInfo->setTemplateSpecializationKind(TSK);
2101 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2102 } else if (ClassTemplateSpecializationDecl *Spec
32.1
'Spec' is null
32.1
'Spec' is null
33
Taking false branch
2103 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
32
Assuming 'Instantiation' is not a 'ClassTemplateSpecializationDecl'
2104 Spec->setTemplateSpecializationKind(TSK); 2105 Spec->setPointOfInstantiation(PointOfInstantiation); 2106 } 2107 2108 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
34
Calling constructor for 'InstantiatingTemplate'
47
Returning from constructor for 'InstantiatingTemplate'
2109 if (Inst.isInvalid())
48
Calling 'InstantiatingTemplate::isInvalid'
50
Returning from 'InstantiatingTemplate::isInvalid'
51
Taking false branch
2110 return true; 2111 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller")((!Inst.isAlreadyInstantiating() && "should have been caught by caller"
) ? static_cast<void> (0) : __assert_fail ("!Inst.isAlreadyInstantiating() && \"should have been caught by caller\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2111, __PRETTY_FUNCTION__))
;
52
'?' condition is true
2112 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), 2113 "instantiating class definition"); 2114 2115 // Enter the scope of this instantiation. We don't use 2116 // PushDeclContext because we don't have a scope. 2117 ContextRAII SavedContext(*this, Instantiation); 2118 EnterExpressionEvaluationContext EvalContext( 2119 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 2120 2121 // If this is an instantiation of a local class, merge this local 2122 // instantiation scope with the enclosing scope. Otherwise, every 2123 // instantiation of a class has its own local instantiation scope. 2124 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod(); 2125 LocalInstantiationScope Scope(*this, MergeWithParentScope); 2126 2127 // Some class state isn't processed immediately but delayed till class 2128 // instantiation completes. We may not be ready to handle any delayed state 2129 // already on the stack as it might correspond to a different class, so save 2130 // it now and put it back later. 2131 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this); 2132 2133 // Pull attributes from the pattern onto the instantiation. 2134 InstantiateAttrs(TemplateArgs, Pattern, Instantiation); 2135 2136 // Start the definition of this instantiation. 2137 Instantiation->startDefinition(); 2138 2139 // The instantiation is visible here, even if it was first declared in an 2140 // unimported module. 2141 Instantiation->setVisibleDespiteOwningModule(); 2142 2143 // FIXME: This loses the as-written tag kind for an explicit instantiation. 2144 Instantiation->setTagKind(Pattern->getTagKind()); 2145 2146 // Do substitution on the base class specifiers. 2147 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
53
Taking false branch
2148 Instantiation->setInvalidDecl(); 2149 2150 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs); 2151 SmallVector<Decl*, 4> Fields; 2152 // Delay instantiation of late parsed attributes. 2153 LateInstantiatedAttrVec LateAttrs; 2154 Instantiator.enableLateAttributeInstantiation(&LateAttrs); 2155 2156 bool MightHaveConstexprVirtualFunctions = false; 2157 for (auto *Member : Pattern->decls()) { 2158 // Don't instantiate members not belonging in this semantic context. 2159 // e.g. for: 2160 // @code 2161 // template <int i> class A { 2162 // class B *g; 2163 // }; 2164 // @endcode 2165 // 'class B' has the template as lexical context but semantically it is 2166 // introduced in namespace scope. 2167 if (Member->getDeclContext() != Pattern) 2168 continue; 2169 2170 // BlockDecls can appear in a default-member-initializer. They must be the 2171 // child of a BlockExpr, so we only know how to instantiate them from there. 2172 if (isa<BlockDecl>(Member)) 2173 continue; 2174 2175 if (Member->isInvalidDecl()) { 2176 Instantiation->setInvalidDecl(); 2177 continue; 2178 } 2179 2180 Decl *NewMember = Instantiator.Visit(Member); 2181 if (NewMember) { 2182 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) { 2183 Fields.push_back(Field); 2184 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) { 2185 // C++11 [temp.inst]p1: The implicit instantiation of a class template 2186 // specialization causes the implicit instantiation of the definitions 2187 // of unscoped member enumerations. 2188 // Record a point of instantiation for this implicit instantiation. 2189 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() && 2190 Enum->isCompleteDefinition()) { 2191 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo(); 2192 assert(MSInfo && "no spec info for member enum specialization")((MSInfo && "no spec info for member enum specialization"
) ? static_cast<void> (0) : __assert_fail ("MSInfo && \"no spec info for member enum specialization\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2192, __PRETTY_FUNCTION__))
; 2193 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation); 2194 MSInfo->setPointOfInstantiation(PointOfInstantiation); 2195 } 2196 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) { 2197 if (SA->isFailed()) { 2198 // A static_assert failed. Bail out; instantiating this 2199 // class is probably not meaningful. 2200 Instantiation->setInvalidDecl(); 2201 break; 2202 } 2203 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) { 2204 if (MD->isConstexpr() && !MD->getFriendObjectKind() && 2205 (MD->isVirtualAsWritten() || Instantiation->getNumBases())) 2206 MightHaveConstexprVirtualFunctions = true; 2207 } 2208 2209 if (NewMember->isInvalidDecl()) 2210 Instantiation->setInvalidDecl(); 2211 } else { 2212 // FIXME: Eventually, a NULL return will mean that one of the 2213 // instantiations was a semantic disaster, and we'll want to mark the 2214 // declaration invalid. 2215 // For now, we expect to skip some members that we can't yet handle. 2216 } 2217 } 2218 2219 // Finish checking fields. 2220 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields, 2221 SourceLocation(), SourceLocation(), ParsedAttributesView()); 2222 CheckCompletedCXXClass(Instantiation); 2223 2224 // Default arguments are parsed, if not instantiated. We can go instantiate 2225 // default arg exprs for default constructors if necessary now. 2226 ActOnFinishCXXNonNestedClass(Instantiation); 2227 2228 // Instantiate late parsed attributes, and attach them to their decls. 2229 // See Sema::InstantiateAttrs 2230 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
55
Loop condition is true. Entering loop body
2231 E = LateAttrs.end(); I != E; ++I) {
54
Assuming 'I' is not equal to 'E'
2232 assert(CurrentInstantiationScope == Instantiator.getStartingScope())((CurrentInstantiationScope == Instantiator.getStartingScope(
)) ? static_cast<void> (0) : __assert_fail ("CurrentInstantiationScope == Instantiator.getStartingScope()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2232, __PRETTY_FUNCTION__))
;
56
Assuming the condition is true
57
'?' condition is true
2233 CurrentInstantiationScope = I->Scope; 2234 2235 // Allow 'this' within late-parsed attributes. 2236 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
58
Assuming field 'NewDecl' is not a 'NamedDecl'
59
'ND' initialized to a null pointer value
2237 CXXRecordDecl *ThisContext = 2238 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
60
Called C++ object pointer is null
2239 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(), 2240 ND && ND->isCXXInstanceMember()); 2241 2242 Attr *NewAttr = 2243 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs); 2244 I->NewDecl->addAttr(NewAttr); 2245 LocalInstantiationScope::deleteScopes(I->Scope, 2246 Instantiator.getStartingScope()); 2247 } 2248 Instantiator.disableLateAttributeInstantiation(); 2249 LateAttrs.clear(); 2250 2251 ActOnFinishDelayedMemberInitializers(Instantiation); 2252 2253 // FIXME: We should do something similar for explicit instantiations so they 2254 // end up in the right module. 2255 if (TSK == TSK_ImplicitInstantiation) { 2256 Instantiation->setLocation(Pattern->getLocation()); 2257 Instantiation->setLocStart(Pattern->getInnerLocStart()); 2258 Instantiation->setBraceRange(Pattern->getBraceRange()); 2259 } 2260 2261 if (!Instantiation->isInvalidDecl()) { 2262 // Perform any dependent diagnostics from the pattern. 2263 PerformDependentDiagnostics(Pattern, TemplateArgs); 2264 2265 // Instantiate any out-of-line class template partial 2266 // specializations now. 2267 for (TemplateDeclInstantiator::delayed_partial_spec_iterator 2268 P = Instantiator.delayed_partial_spec_begin(), 2269 PEnd = Instantiator.delayed_partial_spec_end(); 2270 P != PEnd; ++P) { 2271 if (!Instantiator.InstantiateClassTemplatePartialSpecialization( 2272 P->first, P->second)) { 2273 Instantiation->setInvalidDecl(); 2274 break; 2275 } 2276 } 2277 2278 // Instantiate any out-of-line variable template partial 2279 // specializations now. 2280 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator 2281 P = Instantiator.delayed_var_partial_spec_begin(), 2282 PEnd = Instantiator.delayed_var_partial_spec_end(); 2283 P != PEnd; ++P) { 2284 if (!Instantiator.InstantiateVarTemplatePartialSpecialization( 2285 P->first, P->second)) { 2286 Instantiation->setInvalidDecl(); 2287 break; 2288 } 2289 } 2290 } 2291 2292 // Exit the scope of this instantiation. 2293 SavedContext.pop(); 2294 2295 if (!Instantiation->isInvalidDecl()) { 2296 Consumer.HandleTagDeclDefinition(Instantiation); 2297 2298 // Always emit the vtable for an explicit instantiation definition 2299 // of a polymorphic class template specialization. Otherwise, eagerly 2300 // instantiate only constexpr virtual functions in preparation for their use 2301 // in constant evaluation. 2302 if (TSK == TSK_ExplicitInstantiationDefinition) 2303 MarkVTableUsed(PointOfInstantiation, Instantiation, true); 2304 else if (MightHaveConstexprVirtualFunctions) 2305 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation, 2306 /*ConstexprOnly*/ true); 2307 } 2308 2309 return Instantiation->isInvalidDecl(); 2310} 2311 2312/// Instantiate the definition of an enum from a given pattern. 2313/// 2314/// \param PointOfInstantiation The point of instantiation within the 2315/// source code. 2316/// \param Instantiation is the declaration whose definition is being 2317/// instantiated. This will be a member enumeration of a class 2318/// temploid specialization, or a local enumeration within a 2319/// function temploid specialization. 2320/// \param Pattern The templated declaration from which the instantiation 2321/// occurs. 2322/// \param TemplateArgs The template arguments to be substituted into 2323/// the pattern. 2324/// \param TSK The kind of implicit or explicit instantiation to perform. 2325/// 2326/// \return \c true if an error occurred, \c false otherwise. 2327bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation, 2328 EnumDecl *Instantiation, EnumDecl *Pattern, 2329 const MultiLevelTemplateArgumentList &TemplateArgs, 2330 TemplateSpecializationKind TSK) { 2331 EnumDecl *PatternDef = Pattern->getDefinition(); 2332 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation, 2333 Instantiation->getInstantiatedFromMemberEnum(), 2334 Pattern, PatternDef, TSK,/*Complain*/true)) 2335 return true; 2336 Pattern = PatternDef; 2337 2338 // Record the point of instantiation. 2339 if (MemberSpecializationInfo *MSInfo 2340 = Instantiation->getMemberSpecializationInfo()) { 2341 MSInfo->setTemplateSpecializationKind(TSK); 2342 MSInfo->setPointOfInstantiation(PointOfInstantiation); 2343 } 2344 2345 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); 2346 if (Inst.isInvalid()) 2347 return true; 2348 if (Inst.isAlreadyInstantiating()) 2349 return false; 2350 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), 2351 "instantiating enum definition"); 2352 2353 // The instantiation is visible here, even if it was first declared in an 2354 // unimported module. 2355 Instantiation->setVisibleDespiteOwningModule(); 2356 2357 // Enter the scope of this instantiation. We don't use 2358 // PushDeclContext because we don't have a scope. 2359 ContextRAII SavedContext(*this, Instantiation); 2360 EnterExpressionEvaluationContext EvalContext( 2361 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 2362 2363 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true); 2364 2365 // Pull attributes from the pattern onto the instantiation. 2366 InstantiateAttrs(TemplateArgs, Pattern, Instantiation); 2367 2368 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs); 2369 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern); 2370 2371 // Exit the scope of this instantiation. 2372 SavedContext.pop(); 2373 2374 return Instantiation->isInvalidDecl(); 2375} 2376 2377 2378/// Instantiate the definition of a field from the given pattern. 2379/// 2380/// \param PointOfInstantiation The point of instantiation within the 2381/// source code. 2382/// \param Instantiation is the declaration whose definition is being 2383/// instantiated. This will be a class of a class temploid 2384/// specialization, or a local enumeration within a function temploid 2385/// specialization. 2386/// \param Pattern The templated declaration from which the instantiation 2387/// occurs. 2388/// \param TemplateArgs The template arguments to be substituted into 2389/// the pattern. 2390/// 2391/// \return \c true if an error occurred, \c false otherwise. 2392bool Sema::InstantiateInClassInitializer( 2393 SourceLocation PointOfInstantiation, FieldDecl *Instantiation, 2394 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) { 2395 // If there is no initializer, we don't need to do anything. 2396 if (!Pattern->hasInClassInitializer()) 2397 return false; 2398 2399 assert(Instantiation->getInClassInitStyle() ==((Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle
() && "pattern and instantiation disagree about init style"
) ? static_cast<void> (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2401, __PRETTY_FUNCTION__))
2400 Pattern->getInClassInitStyle() &&((Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle
() && "pattern and instantiation disagree about init style"
) ? static_cast<void> (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2401, __PRETTY_FUNCTION__))
2401 "pattern and instantiation disagree about init style")((Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle
() && "pattern and instantiation disagree about init style"
) ? static_cast<void> (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2401, __PRETTY_FUNCTION__))
; 2402 2403 // Error out if we haven't parsed the initializer of the pattern yet because 2404 // we are waiting for the closing brace of the outer class. 2405 Expr *OldInit = Pattern->getInClassInitializer(); 2406 if (!OldInit) { 2407 RecordDecl *PatternRD = Pattern->getParent(); 2408 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext(); 2409 Diag(PointOfInstantiation, 2410 diag::err_in_class_initializer_not_yet_parsed) 2411 << OutermostClass << Pattern; 2412 Diag(Pattern->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); 2413 Instantiation->setInvalidDecl(); 2414 return true; 2415 } 2416 2417 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); 2418 if (Inst.isInvalid()) 2419 return true; 2420 if (Inst.isAlreadyInstantiating()) { 2421 // Error out if we hit an instantiation cycle for this initializer. 2422 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle) 2423 << Instantiation; 2424 return true; 2425 } 2426 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), 2427 "instantiating default member init"); 2428 2429 // Enter the scope of this instantiation. We don't use PushDeclContext because 2430 // we don't have a scope. 2431 ContextRAII SavedContext(*this, Instantiation->getParent()); 2432 EnterExpressionEvaluationContext EvalContext( 2433 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 2434 2435 LocalInstantiationScope Scope(*this, true); 2436 2437 // Instantiate the initializer. 2438 ActOnStartCXXInClassMemberInitializer(); 2439 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers()); 2440 2441 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs, 2442 /*CXXDirectInit=*/false); 2443 Expr *Init = NewInit.get(); 2444 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class")(((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class"
) ? static_cast<void> (0) : __assert_fail ("(!Init || !isa<ParenListExpr>(Init)) && \"call-style init in class\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2444, __PRETTY_FUNCTION__))
; 2445 ActOnFinishCXXInClassMemberInitializer( 2446 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init); 2447 2448 if (auto *L = getASTMutationListener()) 2449 L->DefaultMemberInitializerInstantiated(Instantiation); 2450 2451 // Return true if the in-class initializer is still missing. 2452 return !Instantiation->getInClassInitializer(); 2453} 2454 2455namespace { 2456 /// A partial specialization whose template arguments have matched 2457 /// a given template-id. 2458 struct PartialSpecMatchResult { 2459 ClassTemplatePartialSpecializationDecl *Partial; 2460 TemplateArgumentList *Args; 2461 }; 2462} 2463 2464bool Sema::usesPartialOrExplicitSpecialization( 2465 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) { 2466 if (ClassTemplateSpec->getTemplateSpecializationKind() == 2467 TSK_ExplicitSpecialization) 2468 return true; 2469 2470 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 2471 ClassTemplateSpec->getSpecializedTemplate() 2472 ->getPartialSpecializations(PartialSpecs); 2473 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { 2474 TemplateDeductionInfo Info(Loc); 2475 if (!DeduceTemplateArguments(PartialSpecs[I], 2476 ClassTemplateSpec->getTemplateArgs(), Info)) 2477 return true; 2478 } 2479 2480 return false; 2481} 2482 2483/// Get the instantiation pattern to use to instantiate the definition of a 2484/// given ClassTemplateSpecializationDecl (either the pattern of the primary 2485/// template or of a partial specialization). 2486static CXXRecordDecl * 2487getPatternForClassTemplateSpecialization( 2488 Sema &S, SourceLocation PointOfInstantiation, 2489 ClassTemplateSpecializationDecl *ClassTemplateSpec, 2490 TemplateSpecializationKind TSK, bool Complain) { 2491 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec); 2492 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 2493 return nullptr; 2494 2495 llvm::PointerUnion<ClassTemplateDecl *, 2496 ClassTemplatePartialSpecializationDecl *> 2497 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial(); 2498 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) { 2499 // Find best matching specialization. 2500 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); 2501 2502 // C++ [temp.class.spec.match]p1: 2503 // When a class template is used in a context that requires an 2504 // instantiation of the class, it is necessary to determine 2505 // whether the instantiation is to be generated using the primary 2506 // template or one of the partial specializations. This is done by 2507 // matching the template arguments of the class template 2508 // specialization with the template argument lists of the partial 2509 // specializations. 2510 typedef PartialSpecMatchResult MatchResult; 2511 SmallVector<MatchResult, 4> Matched; 2512 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 2513 Template->getPartialSpecializations(PartialSpecs); 2514 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation); 2515 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { 2516 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I]; 2517 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 2518 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments( 2519 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) { 2520 // Store the failed-deduction information for use in diagnostics, later. 2521 // TODO: Actually use the failed-deduction info? 2522 FailedCandidates.addCandidate().set( 2523 DeclAccessPair::make(Template, AS_public), Partial, 2524 MakeDeductionFailureInfo(S.Context, Result, Info)); 2525 (void)Result; 2526 } else { 2527 Matched.push_back(PartialSpecMatchResult()); 2528 Matched.back().Partial = Partial; 2529 Matched.back().Args = Info.take(); 2530 } 2531 } 2532 2533 // If we're dealing with a member template where the template parameters 2534 // have been instantiated, this provides the original template parameters 2535 // from which the member template's parameters were instantiated. 2536 2537 if (Matched.size() >= 1) { 2538 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin(); 2539 if (Matched.size() == 1) { 2540 // -- If exactly one matching specialization is found, the 2541 // instantiation is generated from that specialization. 2542 // We don't need to do anything for this. 2543 } else { 2544 // -- If more than one matching specialization is found, the 2545 // partial order rules (14.5.4.2) are used to determine 2546 // whether one of the specializations is more specialized 2547 // than the others. If none of the specializations is more 2548 // specialized than all of the other matching 2549 // specializations, then the use of the class template is 2550 // ambiguous and the program is ill-formed. 2551 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1, 2552 PEnd = Matched.end(); 2553 P != PEnd; ++P) { 2554 if (S.getMoreSpecializedPartialSpecialization( 2555 P->Partial, Best->Partial, PointOfInstantiation) == 2556 P->Partial) 2557 Best = P; 2558 } 2559 2560 // Determine if the best partial specialization is more specialized than 2561 // the others. 2562 bool Ambiguous = false; 2563 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(), 2564 PEnd = Matched.end(); 2565 P != PEnd; ++P) { 2566 if (P != Best && S.getMoreSpecializedPartialSpecialization( 2567 P->Partial, Best->Partial, 2568 PointOfInstantiation) != Best->Partial) { 2569 Ambiguous = true; 2570 break; 2571 } 2572 } 2573 2574 if (Ambiguous) { 2575 // Partial ordering did not produce a clear winner. Complain. 2576 Inst.Clear(); 2577 ClassTemplateSpec->setInvalidDecl(); 2578 S.Diag(PointOfInstantiation, 2579 diag::err_partial_spec_ordering_ambiguous) 2580 << ClassTemplateSpec; 2581 2582 // Print the matching partial specializations. 2583 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(), 2584 PEnd = Matched.end(); 2585 P != PEnd; ++P) 2586 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match) 2587 << S.getTemplateArgumentBindingsText( 2588 P->Partial->getTemplateParameters(), *P->Args); 2589 2590 return nullptr; 2591 } 2592 } 2593 2594 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args); 2595 } else { 2596 // -- If no matches are found, the instantiation is generated 2597 // from the primary template. 2598 } 2599 } 2600 2601 CXXRecordDecl *Pattern = nullptr; 2602 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial(); 2603 if (auto *PartialSpec = 2604 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) { 2605 // Instantiate using the best class template partial specialization. 2606 while (PartialSpec->getInstantiatedFromMember()) { 2607 // If we've found an explicit specialization of this class template, 2608 // stop here and use that as the pattern. 2609 if (PartialSpec->isMemberSpecialization()) 2610 break; 2611 2612 PartialSpec = PartialSpec->getInstantiatedFromMember(); 2613 } 2614 Pattern = PartialSpec; 2615 } else { 2616 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); 2617 while (Template->getInstantiatedFromMemberTemplate()) { 2618 // If we've found an explicit specialization of this class template, 2619 // stop here and use that as the pattern. 2620 if (Template->isMemberSpecialization()) 2621 break; 2622 2623 Template = Template->getInstantiatedFromMemberTemplate(); 2624 } 2625 Pattern = Template->getTemplatedDecl(); 2626 } 2627 2628 return Pattern; 2629} 2630 2631bool Sema::InstantiateClassTemplateSpecialization( 2632 SourceLocation PointOfInstantiation, 2633 ClassTemplateSpecializationDecl *ClassTemplateSpec, 2634 TemplateSpecializationKind TSK, bool Complain) { 2635 // Perform the actual instantiation on the canonical declaration. 2636 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>( 2637 ClassTemplateSpec->getCanonicalDecl()); 2638 if (ClassTemplateSpec->isInvalidDecl()) 2639 return true; 2640 2641 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization( 2642 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain); 2643 if (!Pattern) 2644 return true; 2645 2646 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern, 2647 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, 2648 Complain); 2649} 2650 2651/// Instantiates the definitions of all of the member 2652/// of the given class, which is an instantiation of a class template 2653/// or a member class of a template. 2654void 2655Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, 2656 CXXRecordDecl *Instantiation, 2657 const MultiLevelTemplateArgumentList &TemplateArgs, 2658 TemplateSpecializationKind TSK) { 2659 // FIXME: We need to notify the ASTMutationListener that we did all of these 2660 // things, in case we have an explicit instantiation definition in a PCM, a 2661 // module, or preamble, and the declaration is in an imported AST. 2662 assert((((TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration
|| (TSK == TSK_ImplicitInstantiation && Instantiation
->isLocalClass())) && "Unexpected template specialization kind!"
) ? static_cast<void> (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2666, __PRETTY_FUNCTION__))
1
Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDefinition
2
Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDeclaration
3
Assuming 'TSK' is equal to TSK_ImplicitInstantiation
4
'?' condition is true
2663 (TSK == TSK_ExplicitInstantiationDefinition ||(((TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration
|| (TSK == TSK_ImplicitInstantiation && Instantiation
->isLocalClass())) && "Unexpected template specialization kind!"
) ? static_cast<void> (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2666, __PRETTY_FUNCTION__))
2664 TSK == TSK_ExplicitInstantiationDeclaration ||(((TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration
|| (TSK == TSK_ImplicitInstantiation && Instantiation
->isLocalClass())) && "Unexpected template specialization kind!"
) ? static_cast<void> (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2666, __PRETTY_FUNCTION__))
2665 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&(((TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration
|| (TSK == TSK_ImplicitInstantiation && Instantiation
->isLocalClass())) && "Unexpected template specialization kind!"
) ? static_cast<void> (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2666, __PRETTY_FUNCTION__))
2666 "Unexpected template specialization kind!")(((TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration
|| (TSK == TSK_ImplicitInstantiation && Instantiation
->isLocalClass())) && "Unexpected template specialization kind!"
) ? static_cast<void> (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2666, __PRETTY_FUNCTION__))
; 2667 for (auto *D : Instantiation->decls()) { 2668 bool SuppressNew = false; 2669 if (auto *Function
5.1
'Function' is null
5.1
'Function' is null
= dyn_cast<FunctionDecl>(D)) {
5
Assuming 'D' is not a 'FunctionDecl'
6
Taking false branch
2670 if (FunctionDecl *Pattern = 2671 Function->getInstantiatedFromMemberFunction()) { 2672 2673 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>()) 2674 continue; 2675 2676 MemberSpecializationInfo *MSInfo = 2677 Function->getMemberSpecializationInfo(); 2678 assert(MSInfo && "No member specialization information?")((MSInfo && "No member specialization information?") ?
static_cast<void> (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2678, __PRETTY_FUNCTION__))
; 2679 if (MSInfo->getTemplateSpecializationKind() 2680 == TSK_ExplicitSpecialization) 2681 continue; 2682 2683 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 2684 Function, 2685 MSInfo->getTemplateSpecializationKind(), 2686 MSInfo->getPointOfInstantiation(), 2687 SuppressNew) || 2688 SuppressNew) 2689 continue; 2690 2691 // C++11 [temp.explicit]p8: 2692 // An explicit instantiation definition that names a class template 2693 // specialization explicitly instantiates the class template 2694 // specialization and is only an explicit instantiation definition 2695 // of members whose definition is visible at the point of 2696 // instantiation. 2697 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined()) 2698 continue; 2699 2700 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation); 2701 2702 if (Function->isDefined()) { 2703 // Let the ASTConsumer know that this function has been explicitly 2704 // instantiated now, and its linkage might have changed. 2705 Consumer.HandleTopLevelDecl(DeclGroupRef(Function)); 2706 } else if (TSK == TSK_ExplicitInstantiationDefinition) { 2707 InstantiateFunctionDefinition(PointOfInstantiation, Function); 2708 } else if (TSK == TSK_ImplicitInstantiation) { 2709 PendingLocalImplicitInstantiations.push_back( 2710 std::make_pair(Function, PointOfInstantiation)); 2711 } 2712 } 2713 } else if (auto *Var
7.1
'Var' is null
7.1
'Var' is null
= dyn_cast<VarDecl>(D)) {
7
Assuming 'D' is not a 'VarDecl'
8
Taking false branch
2714 if (isa<VarTemplateSpecializationDecl>(Var)) 2715 continue; 2716 2717 if (Var->isStaticDataMember()) { 2718 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>()) 2719 continue; 2720 2721 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 2722 assert(MSInfo && "No member specialization information?")((MSInfo && "No member specialization information?") ?
static_cast<void> (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2722, __PRETTY_FUNCTION__))
; 2723 if (MSInfo->getTemplateSpecializationKind() 2724 == TSK_ExplicitSpecialization) 2725 continue; 2726 2727 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 2728 Var, 2729 MSInfo->getTemplateSpecializationKind(), 2730 MSInfo->getPointOfInstantiation(), 2731 SuppressNew) || 2732 SuppressNew) 2733 continue; 2734 2735 if (TSK == TSK_ExplicitInstantiationDefinition) { 2736 // C++0x [temp.explicit]p8: 2737 // An explicit instantiation definition that names a class template 2738 // specialization explicitly instantiates the class template 2739 // specialization and is only an explicit instantiation definition 2740 // of members whose definition is visible at the point of 2741 // instantiation. 2742 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition()) 2743 continue; 2744 2745 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 2746 InstantiateVariableDefinition(PointOfInstantiation, Var); 2747 } else { 2748 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 2749 } 2750 } 2751 } else if (auto *Record
9.1
'Record' is non-null
9.1
'Record' is non-null
= dyn_cast<CXXRecordDecl>(D)) {
9
Assuming 'D' is a 'CXXRecordDecl'
10
Taking true branch
2752 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
11
Taking false branch
2753 continue; 2754 2755 // Always skip the injected-class-name, along with any 2756 // redeclarations of nested classes, since both would cause us 2757 // to try to instantiate the members of a class twice. 2758 // Skip closure types; they'll get instantiated when we instantiate 2759 // the corresponding lambda-expression. 2760 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
12
Assuming the condition is false
13
Taking false branch
2761 Record->isLambda()) 2762 continue; 2763 2764 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo(); 2765 assert(MSInfo && "No member specialization information?")((MSInfo && "No member specialization information?") ?
static_cast<void> (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2765, __PRETTY_FUNCTION__))
;
14
Assuming 'MSInfo' is non-null
15
'?' condition is true
2766 2767 if (MSInfo->getTemplateSpecializationKind()
16
Assuming the condition is false
17
Taking false branch
2768 == TSK_ExplicitSpecialization) 2769 continue; 2770 2771 if (Context.getTargetInfo().getTriple().isOSWindows() && 2772 TSK == TSK_ExplicitInstantiationDeclaration) { 2773 // On Windows, explicit instantiation decl of the outer class doesn't 2774 // affect the inner class. Typically extern template declarations are 2775 // used in combination with dll import/export annotations, but those 2776 // are not propagated from the outer class templates to inner classes. 2777 // Therefore, do not instantiate inner classes on this platform, so 2778 // that users don't end up with undefined symbols during linking. 2779 continue; 2780 } 2781 2782 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
18
Assuming the condition is false
19
Assuming the condition is false
20
Taking false branch
2783 Record, 2784 MSInfo->getTemplateSpecializationKind(), 2785 MSInfo->getPointOfInstantiation(), 2786 SuppressNew) || 2787 SuppressNew) 2788 continue; 2789 2790 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 2791 assert(Pattern && "Missing instantiated-from-template information")((Pattern && "Missing instantiated-from-template information"
) ? static_cast<void> (0) : __assert_fail ("Pattern && \"Missing instantiated-from-template information\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2791, __PRETTY_FUNCTION__))
;
21
Assuming 'Pattern' is non-null
22
'?' condition is true
2792 2793 if (!Record->getDefinition()) {
23
Taking true branch
2794 if (!Pattern->getDefinition()) {
24
Assuming the condition is false
25
Taking false branch
2795 // C++0x [temp.explicit]p8: 2796 // An explicit instantiation definition that names a class template 2797 // specialization explicitly instantiates the class template 2798 // specialization and is only an explicit instantiation definition 2799 // of members whose definition is visible at the point of 2800 // instantiation. 2801 if (TSK == TSK_ExplicitInstantiationDeclaration) { 2802 MSInfo->setTemplateSpecializationKind(TSK); 2803 MSInfo->setPointOfInstantiation(PointOfInstantiation); 2804 } 2805 2806 continue; 2807 } 2808 2809 InstantiateClass(PointOfInstantiation, Record, Pattern,
26
Calling 'Sema::InstantiateClass'
2810 TemplateArgs, 2811 TSK); 2812 } else { 2813 if (TSK == TSK_ExplicitInstantiationDefinition && 2814 Record->getTemplateSpecializationKind() == 2815 TSK_ExplicitInstantiationDeclaration) { 2816 Record->setTemplateSpecializationKind(TSK); 2817 MarkVTableUsed(PointOfInstantiation, Record, true); 2818 } 2819 } 2820 2821 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 2822 if (Pattern) 2823 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs, 2824 TSK); 2825 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) { 2826 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo(); 2827 assert(MSInfo && "No member specialization information?")((MSInfo && "No member specialization information?") ?
static_cast<void> (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2827, __PRETTY_FUNCTION__))
; 2828 2829 if (MSInfo->getTemplateSpecializationKind() 2830 == TSK_ExplicitSpecialization) 2831 continue; 2832 2833 if (CheckSpecializationInstantiationRedecl( 2834 PointOfInstantiation, TSK, Enum, 2835 MSInfo->getTemplateSpecializationKind(), 2836 MSInfo->getPointOfInstantiation(), SuppressNew) || 2837 SuppressNew) 2838 continue; 2839 2840 if (Enum->getDefinition()) 2841 continue; 2842 2843 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern(); 2844 assert(Pattern && "Missing instantiated-from-template information")((Pattern && "Missing instantiated-from-template information"
) ? static_cast<void> (0) : __assert_fail ("Pattern && \"Missing instantiated-from-template information\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2844, __PRETTY_FUNCTION__))
; 2845 2846 if (TSK == TSK_ExplicitInstantiationDefinition) { 2847 if (!Pattern->getDefinition()) 2848 continue; 2849 2850 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK); 2851 } else { 2852 MSInfo->setTemplateSpecializationKind(TSK); 2853 MSInfo->setPointOfInstantiation(PointOfInstantiation); 2854 } 2855 } else if (auto *Field = dyn_cast<FieldDecl>(D)) { 2856 // No need to instantiate in-class initializers during explicit 2857 // instantiation. 2858 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) { 2859 CXXRecordDecl *ClassPattern = 2860 Instantiation->getTemplateInstantiationPattern(); 2861 DeclContext::lookup_result Lookup = 2862 ClassPattern->lookup(Field->getDeclName()); 2863 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front()); 2864 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern, 2865 TemplateArgs); 2866 } 2867 } 2868 } 2869} 2870 2871/// Instantiate the definitions of all of the members of the 2872/// given class template specialization, which was named as part of an 2873/// explicit instantiation. 2874void 2875Sema::InstantiateClassTemplateSpecializationMembers( 2876 SourceLocation PointOfInstantiation, 2877 ClassTemplateSpecializationDecl *ClassTemplateSpec, 2878 TemplateSpecializationKind TSK) { 2879 // C++0x [temp.explicit]p7: 2880 // An explicit instantiation that names a class template 2881 // specialization is an explicit instantion of the same kind 2882 // (declaration or definition) of each of its members (not 2883 // including members inherited from base classes) that has not 2884 // been previously explicitly specialized in the translation unit 2885 // containing the explicit instantiation, except as described 2886 // below. 2887 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec, 2888 getTemplateInstantiationArgs(ClassTemplateSpec), 2889 TSK); 2890} 2891 2892StmtResult 2893Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) { 2894 if (!S) 2895 return S; 2896 2897 TemplateInstantiator Instantiator(*this, TemplateArgs, 2898 SourceLocation(), 2899 DeclarationName()); 2900 return Instantiator.TransformStmt(S); 2901} 2902 2903ExprResult 2904Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) { 2905 if (!E) 2906 return E; 2907 2908 TemplateInstantiator Instantiator(*this, TemplateArgs, 2909 SourceLocation(), 2910 DeclarationName()); 2911 return Instantiator.TransformExpr(E); 2912} 2913 2914ExprResult Sema::SubstInitializer(Expr *Init, 2915 const MultiLevelTemplateArgumentList &TemplateArgs, 2916 bool CXXDirectInit) { 2917 TemplateInstantiator Instantiator(*this, TemplateArgs, 2918 SourceLocation(), 2919 DeclarationName()); 2920 return Instantiator.TransformInitializer(Init, CXXDirectInit); 2921} 2922 2923bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, 2924 const MultiLevelTemplateArgumentList &TemplateArgs, 2925 SmallVectorImpl<Expr *> &Outputs) { 2926 if (Exprs.empty()) 2927 return false; 2928 2929 TemplateInstantiator Instantiator(*this, TemplateArgs, 2930 SourceLocation(), 2931 DeclarationName()); 2932 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(), 2933 IsCall, Outputs); 2934} 2935 2936NestedNameSpecifierLoc 2937Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 2938 const MultiLevelTemplateArgumentList &TemplateArgs) { 2939 if (!NNS) 2940 return NestedNameSpecifierLoc(); 2941 2942 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(), 2943 DeclarationName()); 2944 return Instantiator.TransformNestedNameSpecifierLoc(NNS); 2945} 2946 2947/// Do template substitution on declaration name info. 2948DeclarationNameInfo 2949Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 2950 const MultiLevelTemplateArgumentList &TemplateArgs) { 2951 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(), 2952 NameInfo.getName()); 2953 return Instantiator.TransformDeclarationNameInfo(NameInfo); 2954} 2955 2956TemplateName 2957Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, 2958 TemplateName Name, SourceLocation Loc, 2959 const MultiLevelTemplateArgumentList &TemplateArgs) { 2960 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, 2961 DeclarationName()); 2962 CXXScopeSpec SS; 2963 SS.Adopt(QualifierLoc); 2964 return Instantiator.TransformTemplateName(SS, Name, Loc); 2965} 2966 2967bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 2968 TemplateArgumentListInfo &Result, 2969 const MultiLevelTemplateArgumentList &TemplateArgs) { 2970 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), 2971 DeclarationName()); 2972 2973 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result); 2974} 2975 2976static const Decl *getCanonicalParmVarDecl(const Decl *D) { 2977 // When storing ParmVarDecls in the local instantiation scope, we always 2978 // want to use the ParmVarDecl from the canonical function declaration, 2979 // since the map is then valid for any redeclaration or definition of that 2980 // function. 2981 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) { 2982 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 2983 unsigned i = PV->getFunctionScopeIndex(); 2984 // This parameter might be from a freestanding function type within the 2985 // function and isn't necessarily referring to one of FD's parameters. 2986 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV) 2987 return FD->getCanonicalDecl()->getParamDecl(i); 2988 } 2989 } 2990 return D; 2991} 2992 2993 2994llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> * 2995LocalInstantiationScope::findInstantiationOf(const Decl *D) { 2996 D = getCanonicalParmVarDecl(D); 2997 for (LocalInstantiationScope *Current = this; Current; 2998 Current = Current->Outer) { 2999 3000 // Check if we found something within this scope. 3001 const Decl *CheckD = D; 3002 do { 3003 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD); 3004 if (Found != Current->LocalDecls.end()) 3005 return &Found->second; 3006 3007 // If this is a tag declaration, it's possible that we need to look for 3008 // a previous declaration. 3009 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD)) 3010 CheckD = Tag->getPreviousDecl(); 3011 else 3012 CheckD = nullptr; 3013 } while (CheckD); 3014 3015 // If we aren't combined with our outer scope, we're done. 3016 if (!Current->CombineWithOuterScope) 3017 break; 3018 } 3019 3020 // If we're performing a partial substitution during template argument 3021 // deduction, we may not have values for template parameters yet. 3022 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 3023 isa<TemplateTemplateParmDecl>(D)) 3024 return nullptr; 3025 3026 // Local types referenced prior to definition may require instantiation. 3027 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 3028 if (RD->isLocalClass()) 3029 return nullptr; 3030 3031 // Enumeration types referenced prior to definition may appear as a result of 3032 // error recovery. 3033 if (isa<EnumDecl>(D)) 3034 return nullptr; 3035 3036 // If we didn't find the decl, then we either have a sema bug, or we have a 3037 // forward reference to a label declaration. Return null to indicate that 3038 // we have an uninstantiated label. 3039 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope")((isa<LabelDecl>(D) && "declaration not instantiated in this scope"
) ? static_cast<void> (0) : __assert_fail ("isa<LabelDecl>(D) && \"declaration not instantiated in this scope\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3039, __PRETTY_FUNCTION__))
; 3040 return nullptr; 3041} 3042 3043void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) { 3044 D = getCanonicalParmVarDecl(D); 3045 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D]; 3046 if (Stored.isNull()) { 3047#ifndef NDEBUG 3048 // It should not be present in any surrounding scope either. 3049 LocalInstantiationScope *Current = this; 3050 while (Current->CombineWithOuterScope && Current->Outer) { 3051 Current = Current->Outer; 3052 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&((Current->LocalDecls.find(D) == Current->LocalDecls.end
() && "Instantiated local in inner and outer scopes")
? static_cast<void> (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Instantiated local in inner and outer scopes\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3053, __PRETTY_FUNCTION__))
3053 "Instantiated local in inner and outer scopes")((Current->LocalDecls.find(D) == Current->LocalDecls.end
() && "Instantiated local in inner and outer scopes")
? static_cast<void> (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Instantiated local in inner and outer scopes\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3053, __PRETTY_FUNCTION__))
; 3054 } 3055#endif 3056 Stored = Inst; 3057 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) { 3058 Pack->push_back(cast<VarDecl>(Inst)); 3059 } else { 3060 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local")((Stored.get<Decl *>() == Inst && "Already instantiated this local"
) ? static_cast<void> (0) : __assert_fail ("Stored.get<Decl *>() == Inst && \"Already instantiated this local\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3060, __PRETTY_FUNCTION__))
; 3061 } 3062} 3063 3064void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D, 3065 VarDecl *Inst) { 3066 D = getCanonicalParmVarDecl(D); 3067 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>(); 3068 Pack->push_back(Inst); 3069} 3070 3071void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) { 3072#ifndef NDEBUG 3073 // This should be the first time we've been told about this decl. 3074 for (LocalInstantiationScope *Current = this; 3075 Current && Current->CombineWithOuterScope; Current = Current->Outer) 3076 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&((Current->LocalDecls.find(D) == Current->LocalDecls.end
() && "Creating local pack after instantiation of local"
) ? static_cast<void> (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Creating local pack after instantiation of local\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3077, __PRETTY_FUNCTION__))
3077 "Creating local pack after instantiation of local")((Current->LocalDecls.find(D) == Current->LocalDecls.end
() && "Creating local pack after instantiation of local"
) ? static_cast<void> (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Creating local pack after instantiation of local\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3077, __PRETTY_FUNCTION__))
; 3078#endif 3079 3080 D = getCanonicalParmVarDecl(D); 3081 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D]; 3082 DeclArgumentPack *Pack = new DeclArgumentPack; 3083 Stored = Pack; 3084 ArgumentPacks.push_back(Pack); 3085} 3086 3087void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack, 3088 const TemplateArgument *ExplicitArgs, 3089 unsigned NumExplicitArgs) { 3090 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&(((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack
) && "Already have a partially-substituted pack") ? static_cast
<void> (0) : __assert_fail ("(!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && \"Already have a partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3091, __PRETTY_FUNCTION__))
3091 "Already have a partially-substituted pack")(((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack
) && "Already have a partially-substituted pack") ? static_cast
<void> (0) : __assert_fail ("(!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && \"Already have a partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3091, __PRETTY_FUNCTION__))
; 3092 assert((!PartiallySubstitutedPack(((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? static_cast<void> (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3094, __PRETTY_FUNCTION__))
3093 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&(((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? static_cast<void> (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3094, __PRETTY_FUNCTION__))
3094 "Wrong number of arguments in partially-substituted pack")(((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? static_cast<void> (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3094, __PRETTY_FUNCTION__))
; 3095 PartiallySubstitutedPack = Pack; 3096 ArgsInPartiallySubstitutedPack = ExplicitArgs; 3097 NumArgsInPartiallySubstitutedPack = NumExplicitArgs; 3098} 3099 3100NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack( 3101 const TemplateArgument **ExplicitArgs, 3102 unsigned *NumExplicitArgs) const { 3103 if (ExplicitArgs) 3104 *ExplicitArgs = nullptr; 3105 if (NumExplicitArgs) 3106 *NumExplicitArgs = 0; 3107 3108 for (const LocalInstantiationScope *Current = this; Current; 3109 Current = Current->Outer) { 3110 if (Current->PartiallySubstitutedPack) { 3111 if (ExplicitArgs) 3112 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack; 3113 if (NumExplicitArgs) 3114 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack; 3115 3116 return Current->PartiallySubstitutedPack; 3117 } 3118 3119 if (!Current->CombineWithOuterScope) 3120 break; 3121 } 3122 3123 return nullptr; 3124}

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

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/Attr.h"
18#include "clang/AST/Availability.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExternalASTSource.h"
26#include "clang/AST/LocInfoType.h"
27#include "clang/AST/MangleNumberingContext.h"
28#include "clang/AST/NSAPI.h"
29#include "clang/AST/PrettyPrinter.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/AST/TypeOrdering.h"
33#include "clang/Basic/ExpressionTraits.h"
34#include "clang/Basic/Module.h"
35#include "clang/Basic/OpenMPKinds.h"
36#include "clang/Basic/PragmaKinds.h"
37#include "clang/Basic/Specifiers.h"
38#include "clang/Basic/TemplateKinds.h"
39#include "clang/Basic/TypeTraits.h"
40#include "clang/Sema/AnalysisBasedWarnings.h"
41#include "clang/Sema/CleanupInfo.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/ExternalSemaSource.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/ObjCMethodList.h"
46#include "clang/Sema/Ownership.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/TypoCorrection.h"
49#include "clang/Sema/Weak.h"
50#include "llvm/ADT/ArrayRef.h"
51#include "llvm/ADT/Optional.h"
52#include "llvm/ADT/SetVector.h"
53#include "llvm/ADT/SmallBitVector.h"
54#include "llvm/ADT/SmallPtrSet.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include <deque>
58#include <memory>
59#include <string>
60#include <tuple>
61#include <vector>
62
63namespace llvm {
64 class APSInt;
65 template <typename ValueT> struct DenseMapInfo;
66 template <typename ValueT, typename ValueInfoT> class DenseSet;
67 class SmallBitVector;
68 struct InlineAsmIdentifierInfo;
69}
70
71namespace clang {
72 class ADLResult;
73 class ASTConsumer;
74 class ASTContext;
75 class ASTMutationListener;
76 class ASTReader;
77 class ASTWriter;
78 class ArrayType;
79 class ParsedAttr;
80 class BindingDecl;
81 class BlockDecl;
82 class CapturedDecl;
83 class CXXBasePath;
84 class CXXBasePaths;
85 class CXXBindTemporaryExpr;
86 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
87 class CXXConstructorDecl;
88 class CXXConversionDecl;
89 class CXXDeleteExpr;
90 class CXXDestructorDecl;
91 class CXXFieldCollector;
92 class CXXMemberCallExpr;
93 class CXXMethodDecl;
94 class CXXScopeSpec;
95 class CXXTemporary;
96 class CXXTryStmt;
97 class CallExpr;
98 class ClassTemplateDecl;
99 class ClassTemplatePartialSpecializationDecl;
100 class ClassTemplateSpecializationDecl;
101 class VarTemplatePartialSpecializationDecl;
102 class CodeCompleteConsumer;
103 class CodeCompletionAllocator;
104 class CodeCompletionTUInfo;
105 class CodeCompletionResult;
106 class CoroutineBodyStmt;
107 class Decl;
108 class DeclAccessPair;
109 class DeclContext;
110 class DeclRefExpr;
111 class DeclaratorDecl;
112 class DeducedTemplateArgument;
113 class DependentDiagnostic;
114 class DesignatedInitExpr;
115 class Designation;
116 class EnableIfAttr;
117 class EnumConstantDecl;
118 class Expr;
119 class ExtVectorType;
120 class FormatAttr;
121 class FriendDecl;
122 class FunctionDecl;
123 class FunctionProtoType;
124 class FunctionTemplateDecl;
125 class ImplicitConversionSequence;
126 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
127 class InitListExpr;
128 class InitializationKind;
129 class InitializationSequence;
130 class InitializedEntity;
131 class IntegerLiteral;
132 class LabelStmt;
133 class LambdaExpr;
134 class LangOptions;
135 class LocalInstantiationScope;
136 class LookupResult;
137 class MacroInfo;
138 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
139 class ModuleLoader;
140 class MultiLevelTemplateArgumentList;
141 class NamedDecl;
142 class ObjCCategoryDecl;
143 class ObjCCategoryImplDecl;
144 class ObjCCompatibleAliasDecl;
145 class ObjCContainerDecl;
146 class ObjCImplDecl;
147 class ObjCImplementationDecl;
148 class ObjCInterfaceDecl;
149 class ObjCIvarDecl;
150 template <class T> class ObjCList;
151 class ObjCMessageExpr;
152 class ObjCMethodDecl;
153 class ObjCPropertyDecl;
154 class ObjCProtocolDecl;
155 class OMPThreadPrivateDecl;
156 class OMPRequiresDecl;
157 class OMPDeclareReductionDecl;
158 class OMPDeclareSimdDecl;
159 class OMPClause;
160 struct OMPVarListLocTy;
161 struct OverloadCandidate;
162 enum class OverloadCandidateParamOrder : char;
163 enum OverloadCandidateRewriteKind : unsigned;
164 class OverloadCandidateSet;
165 class OverloadExpr;
166 class ParenListExpr;
167 class ParmVarDecl;
168 class Preprocessor;
169 class PseudoDestructorTypeStorage;
170 class PseudoObjectExpr;
171 class QualType;
172 class StandardConversionSequence;
173 class Stmt;
174 class StringLiteral;
175 class SwitchStmt;
176 class TemplateArgument;
177 class TemplateArgumentList;
178 class TemplateArgumentLoc;
179 class TemplateDecl;
180 class TemplateInstantiationCallback;
181 class TemplateParameterList;
182 class TemplatePartialOrderingContext;
183 class TemplateTemplateParmDecl;
184 class Token;
185 class TypeAliasDecl;
186 class TypedefDecl;
187 class TypedefNameDecl;
188 class TypeLoc;
189 class TypoCorrectionConsumer;
190 class UnqualifiedId;
191 class UnresolvedLookupExpr;
192 class UnresolvedMemberExpr;
193 class UnresolvedSetImpl;
194 class UnresolvedSetIterator;
195 class UsingDecl;
196 class UsingShadowDecl;
197 class ValueDecl;
198 class VarDecl;
199 class VarTemplateSpecializationDecl;
200 class VisibilityAttr;
201 class VisibleDeclConsumer;
202 class IndirectFieldDecl;
203 struct DeductionFailureInfo;
204 class TemplateSpecCandidateSet;
205
206namespace sema {
207 class AccessedEntity;
208 class BlockScopeInfo;
209 class Capture;
210 class CapturedRegionScopeInfo;
211 class CapturingScopeInfo;
212 class CompoundScopeInfo;
213 class DelayedDiagnostic;
214 class DelayedDiagnosticPool;
215 class FunctionScopeInfo;
216 class LambdaScopeInfo;
217 class PossiblyUnreachableDiag;
218 class SemaPPCallbacks;
219 class TemplateDeductionInfo;
220}
221
222namespace threadSafety {
223 class BeforeSet;
224 void threadSafetyCleanup(BeforeSet* Cache);
225}
226
227// FIXME: No way to easily map from TemplateTypeParmTypes to
228// TemplateTypeParmDecls, so we have this horrible PointerUnion.
229typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
230 SourceLocation> UnexpandedParameterPack;
231
232/// Describes whether we've seen any nullability information for the given
233/// file.
234struct FileNullability {
235 /// The first pointer declarator (of any pointer kind) in the file that does
236 /// not have a corresponding nullability annotation.
237 SourceLocation PointerLoc;
238
239 /// The end location for the first pointer declarator in the file. Used for
240 /// placing fix-its.
241 SourceLocation PointerEndLoc;
242
243 /// Which kind of pointer declarator we saw.
244 uint8_t PointerKind;
245
246 /// Whether we saw any type nullability annotations in the given file.
247 bool SawTypeNullability = false;
248};
249
250/// A mapping from file IDs to a record of whether we've seen nullability
251/// information in that file.
252class FileNullabilityMap {
253 /// A mapping from file IDs to the nullability information for each file ID.
254 llvm::DenseMap<FileID, FileNullability> Map;
255
256 /// A single-element cache based on the file ID.
257 struct {
258 FileID File;
259 FileNullability Nullability;
260 } Cache;
261
262public:
263 FileNullability &operator[](FileID file) {
264 // Check the single-element cache.
265 if (file == Cache.File)
266 return Cache.Nullability;
267
268 // It's not in the single-element cache; flush the cache if we have one.
269 if (!Cache.File.isInvalid()) {
270 Map[Cache.File] = Cache.Nullability;
271 }
272
273 // Pull this entry into the cache.
274 Cache.File = file;
275 Cache.Nullability = Map[file];
276 return Cache.Nullability;
277 }
278};
279
280/// Keeps track of expected type during expression parsing. The type is tied to
281/// a particular token, all functions that update or consume the type take a
282/// start location of the token they are looking at as a parameter. This allows
283/// to avoid updating the type on hot paths in the parser.
284class PreferredTypeBuilder {
285public:
286 PreferredTypeBuilder() = default;
287 explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
288
289 void enterCondition(Sema &S, SourceLocation Tok);
290 void enterReturn(Sema &S, SourceLocation Tok);
291 void enterVariableInit(SourceLocation Tok, Decl *D);
292 /// Computing a type for the function argument may require running
293 /// overloading, so we postpone its computation until it is actually needed.
294 ///
295 /// Clients should be very careful when using this funciton, as it stores a
296 /// function_ref, clients should make sure all calls to get() with the same
297 /// location happen while function_ref is alive.
298 void enterFunctionArgument(SourceLocation Tok,
299 llvm::function_ref<QualType()> ComputeType);
300
301 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
302 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
303 SourceLocation OpLoc);
304 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
305 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
306 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
307 /// Handles all type casts, including C-style cast, C++ casts, etc.
308 void enterTypeCast(SourceLocation Tok, QualType CastType);
309
310 QualType get(SourceLocation Tok) const {
311 if (Tok != ExpectedLoc)
312 return QualType();
313 if (!Type.isNull())
314 return Type;
315 if (ComputeType)
316 return ComputeType();
317 return QualType();
318 }
319
320private:
321 /// Start position of a token for which we store expected type.
322 SourceLocation ExpectedLoc;
323 /// Expected type for a token starting at ExpectedLoc.
324 QualType Type;
325 /// A function to compute expected type at ExpectedLoc. It is only considered
326 /// if Type is null.
327 llvm::function_ref<QualType()> ComputeType;
328};
329
330/// Sema - This implements semantic analysis and AST building for C.
331class Sema {
332 Sema(const Sema &) = delete;
333 void operator=(const Sema &) = delete;
334
335 ///Source of additional semantic information.
336 ExternalSemaSource *ExternalSource;
337
338 ///Whether Sema has generated a multiplexer and has to delete it.
339 bool isMultiplexExternalSource;
340
341 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
342
343 bool isVisibleSlow(const NamedDecl *D);
344
345 /// Determine whether two declarations should be linked together, given that
346 /// the old declaration might not be visible and the new declaration might
347 /// not have external linkage.
348 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
349 const NamedDecl *New) {
350 if (isVisible(Old))
351 return true;
352 // See comment in below overload for why it's safe to compute the linkage
353 // of the new declaration here.
354 if (New->isExternallyDeclarable()) {
355 assert(Old->isExternallyDeclarable() &&((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 356, __PRETTY_FUNCTION__))
356 "should not have found a non-externally-declarable previous decl")((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 356, __PRETTY_FUNCTION__))
;
357 return true;
358 }
359 return false;
360 }
361 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
362
363 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
364 QualType ResultTy,
365 ArrayRef<QualType> Args);
366
367public:
368 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
369 typedef OpaquePtr<TemplateName> TemplateTy;
370 typedef OpaquePtr<QualType> TypeTy;
371
372 OpenCLOptions OpenCLFeatures;
373 FPOptions FPFeatures;
374
375 const LangOptions &LangOpts;
376 Preprocessor &PP;
377 ASTContext &Context;
378 ASTConsumer &Consumer;
379 DiagnosticsEngine &Diags;
380 SourceManager &SourceMgr;
381
382 /// Flag indicating whether or not to collect detailed statistics.
383 bool CollectStats;
384
385 /// Code-completion consumer.
386 CodeCompleteConsumer *CodeCompleter;
387
388 /// CurContext - This is the current declaration context of parsing.
389 DeclContext *CurContext;
390
391 /// Generally null except when we temporarily switch decl contexts,
392 /// like in \see ActOnObjCTemporaryExitContainerContext.
393 DeclContext *OriginalLexicalContext;
394
395 /// VAListTagName - The declaration name corresponding to __va_list_tag.
396 /// This is used as part of a hack to omit that class from ADL results.
397 DeclarationName VAListTagName;
398
399 bool MSStructPragmaOn; // True when \#pragma ms_struct on
400
401 /// Controls member pointer representation format under the MS ABI.
402 LangOptions::PragmaMSPointersToMembersKind
403 MSPointerToMemberRepresentationMethod;
404
405 /// Stack of active SEH __finally scopes. Can be empty.
406 SmallVector<Scope*, 2> CurrentSEHFinally;
407
408 /// Source location for newly created implicit MSInheritanceAttrs
409 SourceLocation ImplicitMSInheritanceAttrLoc;
410
411 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
412 /// `TransformTypos` in order to keep track of any TypoExprs that are created
413 /// recursively during typo correction and wipe them away if the correction
414 /// fails.
415 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
416
417 /// pragma clang section kind
418 enum PragmaClangSectionKind {
419 PCSK_Invalid = 0,
420 PCSK_BSS = 1,
421 PCSK_Data = 2,
422 PCSK_Rodata = 3,
423 PCSK_Text = 4,
424 PCSK_Relro = 5
425 };
426
427 enum PragmaClangSectionAction {
428 PCSA_Set = 0,
429 PCSA_Clear = 1
430 };
431
432 struct PragmaClangSection {
433 std::string SectionName;
434 bool Valid = false;
435 SourceLocation PragmaLocation;
436
437 void Act(SourceLocation PragmaLocation,
438 PragmaClangSectionAction Action,
439 StringLiteral* Name);
440 };
441
442 PragmaClangSection PragmaClangBSSSection;
443 PragmaClangSection PragmaClangDataSection;
444 PragmaClangSection PragmaClangRodataSection;
445 PragmaClangSection PragmaClangRelroSection;
446 PragmaClangSection PragmaClangTextSection;
447
448 enum PragmaMsStackAction {
449 PSK_Reset = 0x0, // #pragma ()
450 PSK_Set = 0x1, // #pragma (value)
451 PSK_Push = 0x2, // #pragma (push[, id])
452 PSK_Pop = 0x4, // #pragma (pop[, id])
453 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
454 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
455 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
456 };
457
458 template<typename ValueType>
459 struct PragmaStack {
460 struct Slot {
461 llvm::StringRef StackSlotLabel;
462 ValueType Value;
463 SourceLocation PragmaLocation;
464 SourceLocation PragmaPushLocation;
465 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
466 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
467 : StackSlotLabel(StackSlotLabel), Value(Value),
468 PragmaLocation(PragmaLocation),
469 PragmaPushLocation(PragmaPushLocation) {}
470 };
471 void Act(SourceLocation PragmaLocation,
472 PragmaMsStackAction Action,
473 llvm::StringRef StackSlotLabel,
474 ValueType Value);
475
476 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
477 // method body to restore the stacks on exit, so it works like this:
478 //
479 // struct S {
480 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
481 // void Method {}
482 // #pragma <name>(pop, InternalPragmaSlot)
483 // };
484 //
485 // It works even with #pragma vtordisp, although MSVC doesn't support
486 // #pragma vtordisp(push [, id], n)
487 // syntax.
488 //
489 // Push / pop a named sentinel slot.
490 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
491 assert((Action == PSK_Push || Action == PSK_Pop) &&(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 492, __PRETTY_FUNCTION__))
492 "Can only push / pop #pragma stack sentinels!")(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 492, __PRETTY_FUNCTION__))
;
493 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
494 }
495
496 // Constructors.
497 explicit PragmaStack(const ValueType &Default)
498 : DefaultValue(Default), CurrentValue(Default) {}
499
500 bool hasValue() const { return CurrentValue != DefaultValue; }
501
502 SmallVector<Slot, 2> Stack;
503 ValueType DefaultValue; // Value used for PSK_Reset action.
504 ValueType CurrentValue;
505 SourceLocation CurrentPragmaLocation;
506 };
507 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
508 // we shouldn't do so if they're in a module).
509
510 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
511 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
512 ///
513 /// 0: Suppress all vtordisps
514 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
515 /// structors
516 /// 2: Always insert vtordisps to support RTTI on partially constructed
517 /// objects
518 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
519 // #pragma pack.
520 // Sentinel to represent when the stack is set to mac68k alignment.
521 static const unsigned kMac68kAlignmentSentinel = ~0U;
522 PragmaStack<unsigned> PackStack;
523 // The current #pragma pack values and locations at each #include.
524 struct PackIncludeState {
525 unsigned CurrentValue;
526 SourceLocation CurrentPragmaLocation;
527 bool HasNonDefaultValue, ShouldWarnOnInclude;
528 };
529 SmallVector<PackIncludeState, 8> PackIncludeStack;
530 // Segment #pragmas.
531 PragmaStack<StringLiteral *> DataSegStack;
532 PragmaStack<StringLiteral *> BSSSegStack;
533 PragmaStack<StringLiteral *> ConstSegStack;
534 PragmaStack<StringLiteral *> CodeSegStack;
535
536 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
537 // Actions should be performed only if we enter / exit a C++ method body.
538 class PragmaStackSentinelRAII {
539 public:
540 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
541 ~PragmaStackSentinelRAII();
542
543 private:
544 Sema &S;
545 StringRef SlotLabel;
546 bool ShouldAct;
547 };
548
549 /// A mapping that describes the nullability we've seen in each header file.
550 FileNullabilityMap NullabilityMap;
551
552 /// Last section used with #pragma init_seg.
553 StringLiteral *CurInitSeg;
554 SourceLocation CurInitSegLoc;
555
556 /// VisContext - Manages the stack for \#pragma GCC visibility.
557 void *VisContext; // Really a "PragmaVisStack*"
558
559 /// This an attribute introduced by \#pragma clang attribute.
560 struct PragmaAttributeEntry {
561 SourceLocation Loc;
562 ParsedAttr *Attribute;
563 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
564 bool IsUsed;
565 };
566
567 /// A push'd group of PragmaAttributeEntries.
568 struct PragmaAttributeGroup {
569 /// The location of the push attribute.
570 SourceLocation Loc;
571 /// The namespace of this push group.
572 const IdentifierInfo *Namespace;
573 SmallVector<PragmaAttributeEntry, 2> Entries;
574 };
575
576 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
577
578 /// The declaration that is currently receiving an attribute from the
579 /// #pragma attribute stack.
580 const Decl *PragmaAttributeCurrentTargetDecl;
581
582 /// This represents the last location of a "#pragma clang optimize off"
583 /// directive if such a directive has not been closed by an "on" yet. If
584 /// optimizations are currently "on", this is set to an invalid location.
585 SourceLocation OptimizeOffPragmaLocation;
586
587 /// Flag indicating if Sema is building a recovery call expression.
588 ///
589 /// This flag is used to avoid building recovery call expressions
590 /// if Sema is already doing so, which would cause infinite recursions.
591 bool IsBuildingRecoveryCallExpr;
592
593 /// Used to control the generation of ExprWithCleanups.
594 CleanupInfo Cleanup;
595
596 /// ExprCleanupObjects - This is the stack of objects requiring
597 /// cleanup that are created by the current full expression. The
598 /// element type here is ExprWithCleanups::Object.
599 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
600
601 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
602 /// to a variable (constant) that may or may not be odr-used in this Expr, and
603 /// we won't know until all lvalue-to-rvalue and discarded value conversions
604 /// have been applied to all subexpressions of the enclosing full expression.
605 /// This is cleared at the end of each full expression.
606 using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
607 MaybeODRUseExprSet MaybeODRUseExprs;
608
609 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
610
611 /// Stack containing information about each of the nested
612 /// function, block, and method scopes that are currently active.
613 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
614
615 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
616 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
617 ExtVectorDeclsType;
618
619 /// ExtVectorDecls - This is a list all the extended vector types. This allows
620 /// us to associate a raw vector type with one of the ext_vector type names.
621 /// This is only necessary for issuing pretty diagnostics.
622 ExtVectorDeclsType ExtVectorDecls;
623
624 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
625 std::unique_ptr<CXXFieldCollector> FieldCollector;
626
627 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
628
629 /// Set containing all declared private fields that are not used.
630 NamedDeclSetType UnusedPrivateFields;
631
632 /// Set containing all typedefs that are likely unused.
633 llvm::SmallSetVector<const TypedefNameDecl *, 4>
634 UnusedLocalTypedefNameCandidates;
635
636 /// Delete-expressions to be analyzed at the end of translation unit
637 ///
638 /// This list contains class members, and locations of delete-expressions
639 /// that could not be proven as to whether they mismatch with new-expression
640 /// used in initializer of the field.
641 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
642 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
643 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
644
645 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
646
647 /// PureVirtualClassDiagSet - a set of class declarations which we have
648 /// emitted a list of pure virtual functions. Used to prevent emitting the
649 /// same list more than once.
650 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
651
652 /// ParsingInitForAutoVars - a set of declarations with auto types for which
653 /// we are currently parsing the initializer.
654 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
655
656 /// Look for a locally scoped extern "C" declaration by the given name.
657 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
658
659 typedef LazyVector<VarDecl *, ExternalSemaSource,
660 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
661 TentativeDefinitionsType;
662
663 /// All the tentative definitions encountered in the TU.
664 TentativeDefinitionsType TentativeDefinitions;
665
666 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
667 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
668 UnusedFileScopedDeclsType;
669
670 /// The set of file scoped decls seen so far that have not been used
671 /// and must warn if not used. Only contains the first declaration.
672 UnusedFileScopedDeclsType UnusedFileScopedDecls;
673
674 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
675 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
676 DelegatingCtorDeclsType;
677
678 /// All the delegating constructors seen so far in the file, used for
679 /// cycle detection at the end of the TU.
680 DelegatingCtorDeclsType DelegatingCtorDecls;
681
682 /// All the overriding functions seen during a class definition
683 /// that had their exception spec checks delayed, plus the overridden
684 /// function.
685 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
686 DelayedOverridingExceptionSpecChecks;
687
688 /// All the function redeclarations seen during a class definition that had
689 /// their exception spec checks delayed, plus the prior declaration they
690 /// should be checked against. Except during error recovery, the new decl
691 /// should always be a friend declaration, as that's the only valid way to
692 /// redeclare a special member before its class is complete.
693 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
694 DelayedEquivalentExceptionSpecChecks;
695
696 typedef llvm::MapVector<const FunctionDecl *,
697 std::unique_ptr<LateParsedTemplate>>
698 LateParsedTemplateMapT;
699 LateParsedTemplateMapT LateParsedTemplateMap;
700
701 /// Callback to the parser to parse templated functions when needed.
702 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
703 typedef void LateTemplateParserCleanupCB(void *P);
704 LateTemplateParserCB *LateTemplateParser;
705 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
706 void *OpaqueParser;
707
708 void SetLateTemplateParser(LateTemplateParserCB *LTP,
709 LateTemplateParserCleanupCB *LTPCleanup,
710 void *P) {
711 LateTemplateParser = LTP;
712 LateTemplateParserCleanup = LTPCleanup;
713 OpaqueParser = P;
714 }
715
716 class DelayedDiagnostics;
717
718 class DelayedDiagnosticsState {
719 sema::DelayedDiagnosticPool *SavedPool;
720 friend class Sema::DelayedDiagnostics;
721 };
722 typedef DelayedDiagnosticsState ParsingDeclState;
723 typedef DelayedDiagnosticsState ProcessingContextState;
724
725 /// A class which encapsulates the logic for delaying diagnostics
726 /// during parsing and other processing.
727 class DelayedDiagnostics {
728 /// The current pool of diagnostics into which delayed
729 /// diagnostics should go.
730 sema::DelayedDiagnosticPool *CurPool;
731
732 public:
733 DelayedDiagnostics() : CurPool(nullptr) {}
734
735 /// Adds a delayed diagnostic.
736 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
737
738 /// Determines whether diagnostics should be delayed.
739 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
740
741 /// Returns the current delayed-diagnostics pool.
742 sema::DelayedDiagnosticPool *getCurrentPool() const {
743 return CurPool;
744 }
745
746 /// Enter a new scope. Access and deprecation diagnostics will be
747 /// collected in this pool.
748 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
749 DelayedDiagnosticsState state;
750 state.SavedPool = CurPool;
751 CurPool = &pool;
752 return state;
753 }
754
755 /// Leave a delayed-diagnostic state that was previously pushed.
756 /// Do not emit any of the diagnostics. This is performed as part
757 /// of the bookkeeping of popping a pool "properly".
758 void popWithoutEmitting(DelayedDiagnosticsState state) {
759 CurPool = state.SavedPool;
760 }
761
762 /// Enter a new scope where access and deprecation diagnostics are
763 /// not delayed.
764 DelayedDiagnosticsState pushUndelayed() {
765 DelayedDiagnosticsState state;
766 state.SavedPool = CurPool;
767 CurPool = nullptr;
768 return state;
769 }
770
771 /// Undo a previous pushUndelayed().
772 void popUndelayed(DelayedDiagnosticsState state) {
773 assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 773, __PRETTY_FUNCTION__))
;
774 CurPool = state.SavedPool;
775 }
776 } DelayedDiagnostics;
777
778 /// A RAII object to temporarily push a declaration context.
779 class ContextRAII {
780 private:
781 Sema &S;
782 DeclContext *SavedContext;
783 ProcessingContextState SavedContextState;
784 QualType SavedCXXThisTypeOverride;
785
786 public:
787 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
788 : S(S), SavedContext(S.CurContext),
789 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
790 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
791 {
792 assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast
<void> (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 792, __PRETTY_FUNCTION__))
;
793 S.CurContext = ContextToPush;
794 if (NewThisContext)
795 S.CXXThisTypeOverride = QualType();
796 }
797
798 void pop() {
799 if (!SavedContext) return;
800 S.CurContext = SavedContext;
801 S.DelayedDiagnostics.popUndelayed(SavedContextState);
802 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
803 SavedContext = nullptr;
804 }
805
806 ~ContextRAII() {
807 pop();
808 }
809 };
810
811 /// Used to change context to isConstantEvaluated without pushing a heavy
812 /// ExpressionEvaluationContextRecord object.
813 bool isConstantEvaluatedOverride;
814
815 bool isConstantEvaluated() {
816 return ExprEvalContexts.back().isConstantEvaluated() ||
817 isConstantEvaluatedOverride;
818 }
819
820 /// RAII object to handle the state changes required to synthesize
821 /// a function body.
822 class SynthesizedFunctionScope {
823 Sema &S;
824 Sema::ContextRAII SavedContext;
825 bool PushedCodeSynthesisContext = false;
826
827 public:
828 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
829 : S(S), SavedContext(S, DC) {
830 S.PushFunctionScope();
831 S.PushExpressionEvaluationContext(
832 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
833 if (auto *FD = dyn_cast<FunctionDecl>(DC))
834 FD->setWillHaveBody(true);
835 else
836 assert(isa<ObjCMethodDecl>(DC))((isa<ObjCMethodDecl>(DC)) ? static_cast<void> (0
) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 836, __PRETTY_FUNCTION__))
;
837 }
838
839 void addContextNote(SourceLocation UseLoc) {
840 assert(!PushedCodeSynthesisContext)((!PushedCodeSynthesisContext) ? static_cast<void> (0) :
__assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 840, __PRETTY_FUNCTION__))
;
841
842 Sema::CodeSynthesisContext Ctx;
843 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
844 Ctx.PointOfInstantiation = UseLoc;
845 Ctx.Entity = cast<Decl>(S.CurContext);
846 S.pushCodeSynthesisContext(Ctx);
847
848 PushedCodeSynthesisContext = true;
849 }
850
851 ~SynthesizedFunctionScope() {
852 if (PushedCodeSynthesisContext)
853 S.popCodeSynthesisContext();
854 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
855 FD->setWillHaveBody(false);
856 S.PopExpressionEvaluationContext();
857 S.PopFunctionScopeInfo();
858 }
859 };
860
861 /// WeakUndeclaredIdentifiers - Identifiers contained in
862 /// \#pragma weak before declared. rare. may alias another
863 /// identifier, declared or undeclared
864 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
865
866 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
867 /// \#pragma redefine_extname before declared. Used in Solaris system headers
868 /// to define functions that occur in multiple standards to call the version
869 /// in the currently selected standard.
870 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
871
872
873 /// Load weak undeclared identifiers from the external source.
874 void LoadExternalWeakUndeclaredIdentifiers();
875
876 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
877 /// \#pragma weak during processing of other Decls.
878 /// I couldn't figure out a clean way to generate these in-line, so
879 /// we store them here and handle separately -- which is a hack.
880 /// It would be best to refactor this.
881 SmallVector<Decl*,2> WeakTopLevelDecl;
882
883 IdentifierResolver IdResolver;
884
885 /// Translation Unit Scope - useful to Objective-C actions that need
886 /// to lookup file scope declarations in the "ordinary" C decl namespace.
887 /// For example, user-defined classes, built-in "id" type, etc.
888 Scope *TUScope;
889
890 /// The C++ "std" namespace, where the standard library resides.
891 LazyDeclPtr StdNamespace;
892
893 /// The C++ "std::bad_alloc" class, which is defined by the C++
894 /// standard library.
895 LazyDeclPtr StdBadAlloc;
896
897 /// The C++ "std::align_val_t" enum class, which is defined by the C++
898 /// standard library.
899 LazyDeclPtr StdAlignValT;
900
901 /// The C++ "std::experimental" namespace, where the experimental parts
902 /// of the standard library resides.
903 NamespaceDecl *StdExperimentalNamespaceCache;
904
905 /// The C++ "std::initializer_list" template, which is defined in
906 /// \<initializer_list>.
907 ClassTemplateDecl *StdInitializerList;
908
909 /// The C++ "std::coroutine_traits" template, which is defined in
910 /// \<coroutine_traits>
911 ClassTemplateDecl *StdCoroutineTraitsCache;
912
913 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
914 RecordDecl *CXXTypeInfoDecl;
915
916 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
917 RecordDecl *MSVCGuidDecl;
918
919 /// Caches identifiers/selectors for NSFoundation APIs.
920 std::unique_ptr<NSAPI> NSAPIObj;
921
922 /// The declaration of the Objective-C NSNumber class.
923 ObjCInterfaceDecl *NSNumberDecl;
924
925 /// The declaration of the Objective-C NSValue class.
926 ObjCInterfaceDecl *NSValueDecl;
927
928 /// Pointer to NSNumber type (NSNumber *).
929 QualType NSNumberPointer;
930
931 /// Pointer to NSValue type (NSValue *).
932 QualType NSValuePointer;
933
934 /// The Objective-C NSNumber methods used to create NSNumber literals.
935 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
936
937 /// The declaration of the Objective-C NSString class.
938 ObjCInterfaceDecl *NSStringDecl;
939
940 /// Pointer to NSString type (NSString *).
941 QualType NSStringPointer;
942
943 /// The declaration of the stringWithUTF8String: method.
944 ObjCMethodDecl *StringWithUTF8StringMethod;
945
946 /// The declaration of the valueWithBytes:objCType: method.
947 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
948
949 /// The declaration of the Objective-C NSArray class.
950 ObjCInterfaceDecl *NSArrayDecl;
951
952 /// The declaration of the arrayWithObjects:count: method.
953 ObjCMethodDecl *ArrayWithObjectsMethod;
954
955 /// The declaration of the Objective-C NSDictionary class.
956 ObjCInterfaceDecl *NSDictionaryDecl;
957
958 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
959 ObjCMethodDecl *DictionaryWithObjectsMethod;
960
961 /// id<NSCopying> type.
962 QualType QIDNSCopying;
963
964 /// will hold 'respondsToSelector:'
965 Selector RespondsToSelectorSel;
966
967 /// A flag to remember whether the implicit forms of operator new and delete
968 /// have been declared.
969 bool GlobalNewDeleteDeclared;
970
971 /// A flag to indicate that we're in a context that permits abstract
972 /// references to fields. This is really a
973 bool AllowAbstractFieldReference;
974
975 /// Describes how the expressions currently being parsed are
976 /// evaluated at run-time, if at all.
977 enum class ExpressionEvaluationContext {
978 /// The current expression and its subexpressions occur within an
979 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
980 /// \c sizeof, where the type of the expression may be significant but
981 /// no code will be generated to evaluate the value of the expression at
982 /// run time.
983 Unevaluated,
984
985 /// The current expression occurs within a braced-init-list within
986 /// an unevaluated operand. This is mostly like a regular unevaluated
987 /// context, except that we still instantiate constexpr functions that are
988 /// referenced here so that we can perform narrowing checks correctly.
989 UnevaluatedList,
990
991 /// The current expression occurs within a discarded statement.
992 /// This behaves largely similarly to an unevaluated operand in preventing
993 /// definitions from being required, but not in other ways.
994 DiscardedStatement,
995
996 /// The current expression occurs within an unevaluated
997 /// operand that unconditionally permits abstract references to
998 /// fields, such as a SIZE operator in MS-style inline assembly.
999 UnevaluatedAbstract,
1000
1001 /// The current context is "potentially evaluated" in C++11 terms,
1002 /// but the expression is evaluated at compile-time (like the values of
1003 /// cases in a switch statement).
1004 ConstantEvaluated,
1005
1006 /// The current expression is potentially evaluated at run time,
1007 /// which means that code may be generated to evaluate the value of the
1008 /// expression at run time.
1009 PotentiallyEvaluated,
1010
1011 /// The current expression is potentially evaluated, but any
1012 /// declarations referenced inside that expression are only used if
1013 /// in fact the current expression is used.
1014 ///
1015 /// This value is used when parsing default function arguments, for which
1016 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1017 /// through varargs) but do not want to mark declarations as "referenced"
1018 /// until the default argument is used.
1019 PotentiallyEvaluatedIfUsed
1020 };
1021
1022 /// Data structure used to record current or nested
1023 /// expression evaluation contexts.
1024 struct ExpressionEvaluationContextRecord {
1025 /// The expression evaluation context.
1026 ExpressionEvaluationContext Context;
1027
1028 /// Whether the enclosing context needed a cleanup.
1029 CleanupInfo ParentCleanup;
1030
1031 /// Whether we are in a decltype expression.
1032 bool IsDecltype;
1033
1034 /// The number of active cleanup objects when we entered
1035 /// this expression evaluation context.
1036 unsigned NumCleanupObjects;
1037
1038 /// The number of typos encountered during this expression evaluation
1039 /// context (i.e. the number of TypoExprs created).
1040 unsigned NumTypos;
1041
1042 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1043
1044 /// The lambdas that are present within this context, if it
1045 /// is indeed an unevaluated context.
1046 SmallVector<LambdaExpr *, 2> Lambdas;
1047
1048 /// The declaration that provides context for lambda expressions
1049 /// and block literals if the normal declaration context does not
1050 /// suffice, e.g., in a default function argument.
1051 Decl *ManglingContextDecl;
1052
1053 /// If we are processing a decltype type, a set of call expressions
1054 /// for which we have deferred checking the completeness of the return type.
1055 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1056
1057 /// If we are processing a decltype type, a set of temporary binding
1058 /// expressions for which we have deferred checking the destructor.
1059 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1060
1061 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1062
1063 /// Expressions appearing as the LHS of a volatile assignment in this
1064 /// context. We produce a warning for these when popping the context if
1065 /// they are not discarded-value expressions nor unevaluated operands.
1066 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1067
1068 /// \brief Describes whether we are in an expression constext which we have
1069 /// to handle differently.
1070 enum ExpressionKind {
1071 EK_Decltype, EK_TemplateArgument, EK_Other
1072 } ExprContext;
1073
1074 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1075 unsigned NumCleanupObjects,
1076 CleanupInfo ParentCleanup,
1077 Decl *ManglingContextDecl,
1078 ExpressionKind ExprContext)
1079 : Context(Context), ParentCleanup(ParentCleanup),
1080 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1081 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1082
1083 bool isUnevaluated() const {
1084 return Context == ExpressionEvaluationContext::Unevaluated ||
1085 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1086 Context == ExpressionEvaluationContext::UnevaluatedList;
1087 }
1088 bool isConstantEvaluated() const {
1089 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1090 }
1091 };
1092
1093 /// A stack of expression evaluation contexts.
1094 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1095
1096 /// Emit a warning for all pending noderef expressions that we recorded.
1097 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1098
1099 /// Compute the mangling number context for a lambda expression or
1100 /// block literal. Also return the extra mangling decl if any.
1101 ///
1102 /// \param DC - The DeclContext containing the lambda expression or
1103 /// block literal.
1104 std::tuple<MangleNumberingContext *, Decl *>
1105 getCurrentMangleNumberContext(const DeclContext *DC);
1106
1107
1108 /// SpecialMemberOverloadResult - The overloading result for a special member
1109 /// function.
1110 ///
1111 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1112 /// integer are used to determine whether overload resolution succeeded.
1113 class SpecialMemberOverloadResult {
1114 public:
1115 enum Kind {
1116 NoMemberOrDeleted,
1117 Ambiguous,
1118 Success
1119 };
1120
1121 private:
1122 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1123
1124 public:
1125 SpecialMemberOverloadResult() : Pair() {}
1126 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1127 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1128
1129 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1130 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1131
1132 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1133 void setKind(Kind K) { Pair.setInt(K); }
1134 };
1135
1136 class SpecialMemberOverloadResultEntry
1137 : public llvm::FastFoldingSetNode,
1138 public SpecialMemberOverloadResult {
1139 public:
1140 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1141 : FastFoldingSetNode(ID)
1142 {}
1143 };
1144
1145 /// A cache of special member function overload resolution results
1146 /// for C++ records.
1147 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1148
1149 /// A cache of the flags available in enumerations with the flag_bits
1150 /// attribute.
1151 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1152
1153 /// The kind of translation unit we are processing.
1154 ///
1155 /// When we're processing a complete translation unit, Sema will perform
1156 /// end-of-translation-unit semantic tasks (such as creating
1157 /// initializers for tentative definitions in C) once parsing has
1158 /// completed. Modules and precompiled headers perform different kinds of
1159 /// checks.
1160 TranslationUnitKind TUKind;
1161
1162 llvm::BumpPtrAllocator BumpAlloc;
1163
1164 /// The number of SFINAE diagnostics that have been trapped.
1165 unsigned NumSFINAEErrors;
1166
1167 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1168 UnparsedDefaultArgInstantiationsMap;
1169
1170 /// A mapping from parameters with unparsed default arguments to the
1171 /// set of instantiations of each parameter.
1172 ///
1173 /// This mapping is a temporary data structure used when parsing
1174 /// nested class templates or nested classes of class templates,
1175 /// where we might end up instantiating an inner class before the
1176 /// default arguments of its methods have been parsed.
1177 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1178
1179 // Contains the locations of the beginning of unparsed default
1180 // argument locations.
1181 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1182
1183 /// UndefinedInternals - all the used, undefined objects which require a
1184 /// definition in this translation unit.
1185 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1186
1187 /// Determine if VD, which must be a variable or function, is an external
1188 /// symbol that nonetheless can't be referenced from outside this translation
1189 /// unit because its type has no linkage and it's not extern "C".
1190 bool isExternalWithNoLinkageType(ValueDecl *VD);
1191
1192 /// Obtain a sorted list of functions that are undefined but ODR-used.
1193 void getUndefinedButUsed(
1194 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1195
1196 /// Retrieves list of suspicious delete-expressions that will be checked at
1197 /// the end of translation unit.
1198 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1199 getMismatchingDeleteExpressions() const;
1200
1201 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1202 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1203
1204 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1205 /// We need to maintain a list, since selectors can have differing signatures
1206 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1207 /// of selectors are "overloaded").
1208 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1209 /// methods inside categories with a particular selector.
1210 GlobalMethodPool MethodPool;
1211
1212 /// Method selectors used in a \@selector expression. Used for implementation
1213 /// of -Wselector.
1214 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1215
1216 /// List of SourceLocations where 'self' is implicitly retained inside a
1217 /// block.
1218 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1219 ImplicitlyRetainedSelfLocs;
1220
1221 /// Kinds of C++ special members.
1222 enum CXXSpecialMember {
1223 CXXDefaultConstructor,
1224 CXXCopyConstructor,
1225 CXXMoveConstructor,
1226 CXXCopyAssignment,
1227 CXXMoveAssignment,
1228 CXXDestructor,
1229 CXXInvalid
1230 };
1231
1232 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1233 SpecialMemberDecl;
1234
1235 /// The C++ special members which we are currently in the process of
1236 /// declaring. If this process recursively triggers the declaration of the
1237 /// same special member, we should act as if it is not yet declared.
1238 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1239
1240 /// Kinds of defaulted comparison operator functions.
1241 enum class DefaultedComparisonKind : unsigned char {
1242 /// This is not a defaultable comparison operator.
1243 None,
1244 /// This is an operator== that should be implemented as a series of
1245 /// subobject comparisons.
1246 Equal,
1247 /// This is an operator<=> that should be implemented as a series of
1248 /// subobject comparisons.
1249 ThreeWay,
1250 /// This is an operator!= that should be implemented as a rewrite in terms
1251 /// of a == comparison.
1252 NotEqual,
1253 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1254 /// terms of a <=> comparison.
1255 Relational,
1256 };
1257
1258 /// The function definitions which were renamed as part of typo-correction
1259 /// to match their respective declarations. We want to keep track of them
1260 /// to ensure that we don't emit a "redefinition" error if we encounter a
1261 /// correctly named definition after the renamed definition.
1262 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1263
1264 /// Stack of types that correspond to the parameter entities that are
1265 /// currently being copy-initialized. Can be empty.
1266 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1267
1268 void ReadMethodPool(Selector Sel);
1269 void updateOutOfDateSelector(Selector Sel);
1270
1271 /// Private Helper predicate to check for 'self'.
1272 bool isSelfExpr(Expr *RExpr);
1273 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1274
1275 /// Cause the active diagnostic on the DiagosticsEngine to be
1276 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1277 /// should not be used elsewhere.
1278 void EmitCurrentDiagnostic(unsigned DiagID);
1279
1280 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1281 /// statements.
1282 class FPContractStateRAII {
1283 public:
1284 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1285 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1286
1287 private:
1288 Sema& S;
1289 FPOptions OldFPFeaturesState;
1290 };
1291
1292 void addImplicitTypedef(StringRef Name, QualType T);
1293
1294 bool WarnedStackExhausted = false;
1295
1296public:
1297 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1298 TranslationUnitKind TUKind = TU_Complete,
1299 CodeCompleteConsumer *CompletionConsumer = nullptr);
1300 ~Sema();
1301
1302 /// Perform initialization that occurs after the parser has been
1303 /// initialized but before it parses anything.
1304 void Initialize();
1305
1306 const LangOptions &getLangOpts() const { return LangOpts; }
1307 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1308 FPOptions &getFPOptions() { return FPFeatures; }
1309
1310 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1311 SourceManager &getSourceManager() const { return SourceMgr; }
1312 Preprocessor &getPreprocessor() const { return PP; }
1313 ASTContext &getASTContext() const { return Context; }
1314 ASTConsumer &getASTConsumer() const { return Consumer; }
1315 ASTMutationListener *getASTMutationListener() const;
1316 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1317
1318 ///Registers an external source. If an external source already exists,
1319 /// creates a multiplex external source and appends to it.
1320 ///
1321 ///\param[in] E - A non-null external sema source.
1322 ///
1323 void addExternalSource(ExternalSemaSource *E);
1324
1325 void PrintStats() const;
1326
1327 /// Warn that the stack is nearly exhausted.
1328 void warnStackExhausted(SourceLocation Loc);
1329
1330 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1331 /// guaranteed). Produces a warning if we're low on stack space and allocates
1332 /// more in that case. Use this in code that may recurse deeply (for example,
1333 /// in template instantiation) to avoid stack overflow.
1334 void runWithSufficientStackSpace(SourceLocation Loc,
1335 llvm::function_ref<void()> Fn);
1336
1337 /// Helper class that creates diagnostics with optional
1338 /// template instantiation stacks.
1339 ///
1340 /// This class provides a wrapper around the basic DiagnosticBuilder
1341 /// class that emits diagnostics. SemaDiagnosticBuilder is
1342 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1343 /// does) and, if the diagnostic comes from inside a template
1344 /// instantiation, printing the template instantiation stack as
1345 /// well.
1346 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1347 Sema &SemaRef;
1348 unsigned DiagID;
1349
1350 public:
1351 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1352 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1353
1354 // This is a cunning lie. DiagnosticBuilder actually performs move
1355 // construction in its copy constructor (but due to varied uses, it's not
1356 // possible to conveniently express this as actual move construction). So
1357 // the default copy ctor here is fine, because the base class disables the
1358 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1359 // in that case anwyay.
1360 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1361
1362 ~SemaDiagnosticBuilder() {
1363 // If we aren't active, there is nothing to do.
1364 if (!isActive()) return;
1365
1366 // Otherwise, we need to emit the diagnostic. First flush the underlying
1367 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1368 // won't emit the diagnostic in its own destructor.
1369 //
1370 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1371 // do its own needless checks to see if the diagnostic needs to be
1372 // emitted. However, because we take care to ensure that the builder
1373 // objects never escape, a sufficiently smart compiler will be able to
1374 // eliminate that code.
1375 FlushCounts();
1376 Clear();
1377
1378 // Dispatch to Sema to emit the diagnostic.
1379 SemaRef.EmitCurrentDiagnostic(DiagID);
1380 }
1381
1382 /// Teach operator<< to produce an object of the correct type.
1383 template<typename T>
1384 friend const SemaDiagnosticBuilder &operator<<(
1385 const SemaDiagnosticBuilder &Diag, const T &Value) {
1386 const DiagnosticBuilder &BaseDiag = Diag;
1387 BaseDiag << Value;
1388 return Diag;
1389 }
1390 };
1391
1392 /// Emit a diagnostic.
1393 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1394 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1395 return SemaDiagnosticBuilder(DB, *this, DiagID);
1396 }
1397
1398 /// Emit a partial diagnostic.
1399 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1400
1401 /// Build a partial diagnostic.
1402 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1403
1404 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1405
1406 /// Get a string to suggest for zero-initialization of a type.
1407 std::string
1408 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1409 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1410
1411 /// Calls \c Lexer::getLocForEndOfToken()
1412 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1413
1414 /// Retrieve the module loader associated with the preprocessor.
1415 ModuleLoader &getModuleLoader() const;
1416
1417 void emitAndClearUnusedLocalTypedefWarnings();
1418
1419 enum TUFragmentKind {
1420 /// The global module fragment, between 'module;' and a module-declaration.
1421 Global,
1422 /// A normal translation unit fragment. For a non-module unit, this is the
1423 /// entire translation unit. Otherwise, it runs from the module-declaration
1424 /// to the private-module-fragment (if any) or the end of the TU (if not).
1425 Normal,
1426 /// The private module fragment, between 'module :private;' and the end of
1427 /// the translation unit.
1428 Private
1429 };
1430
1431 void ActOnStartOfTranslationUnit();
1432 void ActOnEndOfTranslationUnit();
1433 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1434
1435 void CheckDelegatingCtorCycles();
1436
1437 Scope *getScopeForContext(DeclContext *Ctx);
1438
1439 void PushFunctionScope();
1440 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1441 sema::LambdaScopeInfo *PushLambdaScope();
1442
1443 /// This is used to inform Sema what the current TemplateParameterDepth
1444 /// is during Parsing. Currently it is used to pass on the depth
1445 /// when parsing generic lambda 'auto' parameters.
1446 void RecordParsingTemplateParameterDepth(unsigned Depth);
1447
1448 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1449 RecordDecl *RD, CapturedRegionKind K,
1450 unsigned OpenMPCaptureLevel = 0);
1451
1452 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1453 /// time after they've been popped.
1454 class PoppedFunctionScopeDeleter {
1455 Sema *Self;
1456
1457 public:
1458 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1459 void operator()(sema::FunctionScopeInfo *Scope) const;
1460 };
1461
1462 using PoppedFunctionScopePtr =
1463 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1464
1465 PoppedFunctionScopePtr
1466 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1467 const Decl *D = nullptr,
1468 QualType BlockType = QualType());
1469
1470 sema::FunctionScopeInfo *getCurFunction() const {
1471 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1472 }
1473
1474 sema::FunctionScopeInfo *getEnclosingFunction() const;
1475
1476 void setFunctionHasBranchIntoScope();
1477 void setFunctionHasBranchProtectedScope();
1478 void setFunctionHasIndirectGoto();
1479
1480 void PushCompoundScope(bool IsStmtExpr);
1481 void PopCompoundScope();
1482
1483 sema::CompoundScopeInfo &getCurCompoundScope() const;
1484
1485 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1486
1487 /// Retrieve the current block, if any.
1488 sema::BlockScopeInfo *getCurBlock();
1489
1490 /// Get the innermost lambda enclosing the current location, if any. This
1491 /// looks through intervening non-lambda scopes such as local functions and
1492 /// blocks.
1493 sema::LambdaScopeInfo *getEnclosingLambda() const;
1494
1495 /// Retrieve the current lambda scope info, if any.
1496 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1497 /// lambda scope info ignoring all inner capturing scopes that are not
1498 /// lambda scopes.
1499 sema::LambdaScopeInfo *
1500 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1501
1502 /// Retrieve the current generic lambda info, if any.
1503 sema::LambdaScopeInfo *getCurGenericLambda();
1504
1505 /// Retrieve the current captured region, if any.
1506 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1507
1508 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1509 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1510
1511 void ActOnComment(SourceRange Comment);
1512
1513 //===--------------------------------------------------------------------===//
1514 // Type Analysis / Processing: SemaType.cpp.
1515 //
1516
1517 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1518 const DeclSpec *DS = nullptr);
1519 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1520 const DeclSpec *DS = nullptr);
1521 QualType BuildPointerType(QualType T,
1522 SourceLocation Loc, DeclarationName Entity);
1523 QualType BuildReferenceType(QualType T, bool LValueRef,
1524 SourceLocation Loc, DeclarationName Entity);
1525 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1526 Expr *ArraySize, unsigned Quals,
1527 SourceRange Brackets, DeclarationName Entity);
1528 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1529 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1530 SourceLocation AttrLoc);
1531 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1532 SourceLocation AttrLoc);
1533
1534 /// Same as above, but constructs the AddressSpace index if not provided.
1535 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1536 SourceLocation AttrLoc);
1537
1538 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1539
1540 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1541
1542 /// Build a function type.
1543 ///
1544 /// This routine checks the function type according to C++ rules and
1545 /// under the assumption that the result type and parameter types have
1546 /// just been instantiated from a template. It therefore duplicates
1547 /// some of the behavior of GetTypeForDeclarator, but in a much
1548 /// simpler form that is only suitable for this narrow use case.
1549 ///
1550 /// \param T The return type of the function.
1551 ///
1552 /// \param ParamTypes The parameter types of the function. This array
1553 /// will be modified to account for adjustments to the types of the
1554 /// function parameters.
1555 ///
1556 /// \param Loc The location of the entity whose type involves this
1557 /// function type or, if there is no such entity, the location of the
1558 /// type that will have function type.
1559 ///
1560 /// \param Entity The name of the entity that involves the function
1561 /// type, if known.
1562 ///
1563 /// \param EPI Extra information about the function type. Usually this will
1564 /// be taken from an existing function with the same prototype.
1565 ///
1566 /// \returns A suitable function type, if there are no errors. The
1567 /// unqualified type will always be a FunctionProtoType.
1568 /// Otherwise, returns a NULL type.
1569 QualType BuildFunctionType(QualType T,
1570 MutableArrayRef<QualType> ParamTypes,
1571 SourceLocation Loc, DeclarationName Entity,
1572 const FunctionProtoType::ExtProtoInfo &EPI);
1573
1574 QualType BuildMemberPointerType(QualType T, QualType Class,
1575 SourceLocation Loc,
1576 DeclarationName Entity);
1577 QualType BuildBlockPointerType(QualType T,
1578 SourceLocation Loc, DeclarationName Entity);
1579 QualType BuildParenType(QualType T);
1580 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1581 QualType BuildReadPipeType(QualType T,
1582 SourceLocation Loc);
1583 QualType BuildWritePipeType(QualType T,
1584 SourceLocation Loc);
1585
1586 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1587 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1588
1589 /// Package the given type and TSI into a ParsedType.
1590 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1591 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1592 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1593 static QualType GetTypeFromParser(ParsedType Ty,
1594 TypeSourceInfo **TInfo = nullptr);
1595 CanThrowResult canThrow(const Expr *E);
1596 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1597 const FunctionProtoType *FPT);
1598 void UpdateExceptionSpec(FunctionDecl *FD,
1599 const FunctionProtoType::ExceptionSpecInfo &ESI);
1600 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1601 bool CheckDistantExceptionSpec(QualType T);
1602 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1603 bool CheckEquivalentExceptionSpec(
1604 const FunctionProtoType *Old, SourceLocation OldLoc,
1605 const FunctionProtoType *New, SourceLocation NewLoc);
1606 bool CheckEquivalentExceptionSpec(
1607 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1608 const FunctionProtoType *Old, SourceLocation OldLoc,
1609 const FunctionProtoType *New, SourceLocation NewLoc);
1610 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1611 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1612 const PartialDiagnostic &NestedDiagID,
1613 const PartialDiagnostic &NoteID,
1614 const PartialDiagnostic &NoThrowDiagID,
1615 const FunctionProtoType *Superset,
1616 SourceLocation SuperLoc,
1617 const FunctionProtoType *Subset,
1618 SourceLocation SubLoc);
1619 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1620 const PartialDiagnostic &NoteID,
1621 const FunctionProtoType *Target,
1622 SourceLocation TargetLoc,
1623 const FunctionProtoType *Source,
1624 SourceLocation SourceLoc);
1625
1626 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1627
1628 /// The parser has parsed the context-sensitive type 'instancetype'
1629 /// in an Objective-C message declaration. Return the appropriate type.
1630 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1631
1632 /// Abstract class used to diagnose incomplete types.
1633 struct TypeDiagnoser {
1634 TypeDiagnoser() {}
1635
1636 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1637 virtual ~TypeDiagnoser() {}
1638 };
1639
1640 static int getPrintable(int I) { return I; }
1641 static unsigned getPrintable(unsigned I) { return I; }
1642 static bool getPrintable(bool B) { return B; }
1643 static const char * getPrintable(const char *S) { return S; }
1644 static StringRef getPrintable(StringRef S) { return S; }
1645 static const std::string &getPrintable(const std::string &S) { return S; }
1646 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1647 return II;
1648 }
1649 static DeclarationName getPrintable(DeclarationName N) { return N; }
1650 static QualType getPrintable(QualType T) { return T; }
1651 static SourceRange getPrintable(SourceRange R) { return R; }
1652 static SourceRange getPrintable(SourceLocation L) { return L; }
1653 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1654 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1655
1656 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1657 unsigned DiagID;
1658 std::tuple<const Ts &...> Args;
1659
1660 template <std::size_t... Is>
1661 void emit(const SemaDiagnosticBuilder &DB,
1662 std::index_sequence<Is...>) const {
1663 // Apply all tuple elements to the builder in order.
1664 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1665 (void)Dummy;
1666 }
1667
1668 public:
1669 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1670 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1671 assert(DiagID != 0 && "no diagnostic for type diagnoser")((DiagID != 0 && "no diagnostic for type diagnoser") ?
static_cast<void> (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 1671, __PRETTY_FUNCTION__))
;
1672 }
1673
1674 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1675 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1676 emit(DB, std::index_sequence_for<Ts...>());
1677 DB << T;
1678 }
1679 };
1680
1681private:
1682 /// Methods for marking which expressions involve dereferencing a pointer
1683 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
1684 /// they are parsed, meaning that a noderef pointer may not be accessed. For
1685 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
1686 /// `*p`, but need to check that `address of` is called on it. This requires
1687 /// keeping a container of all pending expressions and checking if the address
1688 /// of them are eventually taken.
1689 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
1690 void CheckAddressOfNoDeref(const Expr *E);
1691 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
1692
1693 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1694 TypeDiagnoser *Diagnoser);
1695
1696 struct ModuleScope {
1697 SourceLocation BeginLoc;
1698 clang::Module *Module = nullptr;
1699 bool ModuleInterface = false;
1700 bool ImplicitGlobalModuleFragment = false;
1701 VisibleModuleSet OuterVisibleModules;
1702 };
1703 /// The modules we're currently parsing.
1704 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1705
1706 /// Namespace definitions that we will export when they finish.
1707 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
1708
1709 /// Get the module whose scope we are currently within.
1710 Module *getCurrentModule() const {
1711 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1712 }
1713
1714 VisibleModuleSet VisibleModules;
1715
1716public:
1717 /// Get the module owning an entity.
1718 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1719
1720 /// Make a merged definition of an existing hidden definition \p ND
1721 /// visible at the specified location.
1722 void makeMergedDefinitionVisible(NamedDecl *ND);
1723
1724 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
1725
1726 /// Determine whether a declaration is visible to name lookup.
1727 bool isVisible(const NamedDecl *D) {
1728 return !D->isHidden() || isVisibleSlow(D);
1729 }
1730
1731 /// Determine whether any declaration of an entity is visible.
1732 bool
1733 hasVisibleDeclaration(const NamedDecl *D,
1734 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1735 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1736 }
1737 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1738 llvm::SmallVectorImpl<Module *> *Modules);
1739
1740 bool hasVisibleMergedDefinition(NamedDecl *Def);
1741 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1742
1743 /// Determine if \p D and \p Suggested have a structurally compatible
1744 /// layout as described in C11 6.2.7/1.
1745 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1746
1747 /// Determine if \p D has a visible definition. If not, suggest a declaration
1748 /// that should be made visible to expose the definition.
1749 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1750 bool OnlyNeedComplete = false);
1751 bool hasVisibleDefinition(const NamedDecl *D) {
1752 NamedDecl *Hidden;
1753 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1754 }
1755
1756 /// Determine if the template parameter \p D has a visible default argument.
1757 bool
1758 hasVisibleDefaultArgument(const NamedDecl *D,
1759 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1760
1761 /// Determine if there is a visible declaration of \p D that is an explicit
1762 /// specialization declaration for a specialization of a template. (For a
1763 /// member specialization, use hasVisibleMemberSpecialization.)
1764 bool hasVisibleExplicitSpecialization(
1765 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1766
1767 /// Determine if there is a visible declaration of \p D that is a member
1768 /// specialization declaration (as opposed to an instantiated declaration).
1769 bool hasVisibleMemberSpecialization(
1770 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1771
1772 /// Determine if \p A and \p B are equivalent internal linkage declarations
1773 /// from different modules, and thus an ambiguity error can be downgraded to
1774 /// an extension warning.
1775 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1776 const NamedDecl *B);
1777 void diagnoseEquivalentInternalLinkageDeclarations(
1778 SourceLocation Loc, const NamedDecl *D,
1779 ArrayRef<const NamedDecl *> Equiv);
1780
1781 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
1782
1783 bool isCompleteType(SourceLocation Loc, QualType T) {
1784 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1785 }
1786 bool RequireCompleteType(SourceLocation Loc, QualType T,
1787 TypeDiagnoser &Diagnoser);
1788 bool RequireCompleteType(SourceLocation Loc, QualType T,
1789 unsigned DiagID);
1790
1791 template <typename... Ts>
1792 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1793 const Ts &...Args) {
1794 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1795 return RequireCompleteType(Loc, T, Diagnoser);
1796 }
1797
1798 void completeExprArrayBound(Expr *E);
1799 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1800 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1801
1802 template <typename... Ts>
1803 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1804 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1805 return RequireCompleteExprType(E, Diagnoser);
1806 }
1807
1808 bool RequireLiteralType(SourceLocation Loc, QualType T,
1809 TypeDiagnoser &Diagnoser);
1810 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1811
1812 template <typename... Ts>
1813 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1814 const Ts &...Args) {
1815 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1816 return RequireLiteralType(Loc, T, Diagnoser);
1817 }
1818
1819 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1820 const CXXScopeSpec &SS, QualType T,
1821 TagDecl *OwnedTagDecl = nullptr);
1822
1823 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1824 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1825 /// context, such as when building a type for decltype(auto).
1826 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1827 bool AsUnevaluated = true);
1828 QualType BuildUnaryTransformType(QualType BaseType,
1829 UnaryTransformType::UTTKind UKind,
1830 SourceLocation Loc);
1831
1832 //===--------------------------------------------------------------------===//
1833 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1834 //
1835
1836 struct SkipBodyInfo {
1837 SkipBodyInfo()
1838 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1839 New(nullptr) {}
1840 bool ShouldSkip;
1841 bool CheckSameAsPrevious;
1842 NamedDecl *Previous;
1843 NamedDecl *New;
1844 };
1845
1846 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1847
1848 void DiagnoseUseOfUnimplementedSelectors();
1849
1850 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1851
1852 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1853 Scope *S, CXXScopeSpec *SS = nullptr,
1854 bool isClassName = false, bool HasTrailingDot = false,
1855 ParsedType ObjectType = nullptr,
1856 bool IsCtorOrDtorName = false,
1857 bool WantNontrivialTypeSourceInfo = false,
1858 bool IsClassTemplateDeductionContext = true,
1859 IdentifierInfo **CorrectedII = nullptr);
1860 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1861 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1862 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1863 SourceLocation IILoc,
1864 Scope *S,
1865 CXXScopeSpec *SS,
1866 ParsedType &SuggestedType,
1867 bool IsTemplateName = false);
1868
1869 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1870 /// type name has failed in a dependent context. In these situations, we
1871 /// automatically form a DependentTypeName that will retry lookup in a related
1872 /// scope during instantiation.
1873 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1874 SourceLocation NameLoc,
1875 bool IsTemplateTypeArg);
1876
1877 /// Describes the result of the name lookup and resolution performed
1878 /// by \c ClassifyName().
1879 enum NameClassificationKind {
1880 /// This name is not a type or template in this context, but might be
1881 /// something else.
1882 NC_Unknown,
1883 /// Classification failed; an error has been produced.
1884 NC_Error,
1885 /// The name has been typo-corrected to a keyword.
1886 NC_Keyword,
1887 /// The name was classified as a type.
1888 NC_Type,
1889 /// The name was classified as a specific non-type, non-template
1890 /// declaration. ActOnNameClassifiedAsNonType should be called to
1891 /// convert the declaration to an expression.
1892 NC_NonType,
1893 /// The name was classified as an ADL-only function name.
1894 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
1895 /// result to an expression.
1896 NC_UndeclaredNonType,
1897 /// The name denotes a member of a dependent type that could not be
1898 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
1899 /// convert the result to an expression.
1900 NC_DependentNonType,
1901 /// The name was classified as a non-type, and an expression representing
1902 /// that name has been formed.
1903 NC_ContextIndependentExpr,
1904 /// The name was classified as a template whose specializations are types.
1905 NC_TypeTemplate,
1906 /// The name was classified as a variable template name.
1907 NC_VarTemplate,
1908 /// The name was classified as a function template name.
1909 NC_FunctionTemplate,
1910 /// The name was classified as an ADL-only function template name.
1911 NC_UndeclaredTemplate,
1912 };
1913
1914 class NameClassification {
1915 NameClassificationKind Kind;
1916 union {
1917 ExprResult Expr;
1918 NamedDecl *NonTypeDecl;
1919 TemplateName Template;
1920 ParsedType Type;
1921 };
1922
1923 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1924
1925 public:
1926 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1927
1928 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1929
1930 static NameClassification Error() {
1931 return NameClassification(NC_Error);
1932 }
1933
1934 static NameClassification Unknown() {
1935 return NameClassification(NC_Unknown);
1936 }
1937
1938 static NameClassification ContextIndependentExpr(ExprResult E) {
1939 NameClassification Result(NC_ContextIndependentExpr);
1940 Result.Expr = E;
1941 return Result;
1942 }
1943
1944 static NameClassification NonType(NamedDecl *D) {
1945 NameClassification Result(NC_NonType);
1946 Result.NonTypeDecl = D;
1947 return Result;
1948 }
1949
1950 static NameClassification UndeclaredNonType() {
1951 return NameClassification(NC_UndeclaredNonType);
1952 }
1953
1954 static NameClassification DependentNonType() {
1955 return NameClassification(NC_DependentNonType);
1956 }
1957
1958 static NameClassification TypeTemplate(TemplateName Name) {
1959 NameClassification Result(NC_TypeTemplate);
1960 Result.Template = Name;
1961 return Result;
1962 }
1963
1964 static NameClassification VarTemplate(TemplateName Name) {
1965 NameClassification Result(NC_VarTemplate);
1966 Result.Template = Name;
1967 return Result;
1968 }
1969
1970 static NameClassification FunctionTemplate(TemplateName Name) {
1971 NameClassification Result(NC_FunctionTemplate);
1972 Result.Template = Name;
1973 return Result;
1974 }
1975
1976 static NameClassification UndeclaredTemplate(TemplateName Name) {
1977 NameClassification Result(NC_UndeclaredTemplate);
1978 Result.Template = Name;
1979 return Result;
1980 }
1981
1982 NameClassificationKind getKind() const { return Kind; }
1983
1984 ExprResult getExpression() const {
1985 assert(Kind == NC_ContextIndependentExpr)((Kind == NC_ContextIndependentExpr) ? static_cast<void>
(0) : __assert_fail ("Kind == NC_ContextIndependentExpr", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 1985, __PRETTY_FUNCTION__))
;
1986 return Expr;
1987 }
1988
1989 ParsedType getType() const {
1990 assert(Kind == NC_Type)((Kind == NC_Type) ? static_cast<void> (0) : __assert_fail
("Kind == NC_Type", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 1990, __PRETTY_FUNCTION__))
;
1991 return Type;
1992 }
1993
1994 NamedDecl *getNonTypeDecl() const {
1995 assert(Kind == NC_NonType)((Kind == NC_NonType) ? static_cast<void> (0) : __assert_fail
("Kind == NC_NonType", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 1995, __PRETTY_FUNCTION__))
;
1996 return NonTypeDecl;
1997 }
1998
1999 TemplateName getTemplateName() const {
2000 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast
<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 2001, __PRETTY_FUNCTION__))
2001 Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate)((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast
<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 2001, __PRETTY_FUNCTION__))
;
2002 return Template;
2003 }
2004
2005 TemplateNameKind getTemplateNameKind() const {
2006 switch (Kind) {
2007 case NC_TypeTemplate:
2008 return TNK_Type_template;
2009 case NC_FunctionTemplate:
2010 return TNK_Function_template;
2011 case NC_VarTemplate:
2012 return TNK_Var_template;
2013 case NC_UndeclaredTemplate:
2014 return TNK_Undeclared_template;
2015 default:
2016 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 2016)
;
2017 }
2018 }
2019 };
2020
2021 /// Perform name lookup on the given name, classifying it based on
2022 /// the results of name lookup and the following token.
2023 ///
2024 /// This routine is used by the parser to resolve identifiers and help direct
2025 /// parsing. When the identifier cannot be found, this routine will attempt
2026 /// to correct the typo and classify based on the resulting name.
2027 ///
2028 /// \param S The scope in which we're performing name lookup.
2029 ///
2030 /// \param SS The nested-name-specifier that precedes the name.
2031 ///
2032 /// \param Name The identifier. If typo correction finds an alternative name,
2033 /// this pointer parameter will be updated accordingly.
2034 ///
2035 /// \param NameLoc The location of the identifier.
2036 ///
2037 /// \param NextToken The token following the identifier. Used to help
2038 /// disambiguate the name.
2039 ///
2040 /// \param CCC The correction callback, if typo correction is desired.
2041 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2042 IdentifierInfo *&Name, SourceLocation NameLoc,
2043 const Token &NextToken,
2044 CorrectionCandidateCallback *CCC = nullptr);
2045
2046 /// Act on the result of classifying a name as an undeclared (ADL-only)
2047 /// non-type declaration.
2048 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2049 SourceLocation NameLoc);
2050 /// Act on the result of classifying a name as an undeclared member of a
2051 /// dependent base class.
2052 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2053 IdentifierInfo *Name,
2054 SourceLocation NameLoc,
2055 bool IsAddressOfOperand);
2056 /// Act on the result of classifying a name as a specific non-type
2057 /// declaration.
2058 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2059 NamedDecl *Found,
2060 SourceLocation NameLoc,
2061 const Token &NextToken);
2062
2063 /// Describes the detailed kind of a template name. Used in diagnostics.
2064 enum class TemplateNameKindForDiagnostics {
2065 ClassTemplate,
2066 FunctionTemplate,
2067 VarTemplate,
2068 AliasTemplate,
2069 TemplateTemplateParam,
2070 Concept,
2071 DependentTemplate
2072 };
2073 TemplateNameKindForDiagnostics
2074 getTemplateNameKindForDiagnostics(TemplateName Name);
2075
2076 /// Determine whether it's plausible that E was intended to be a
2077 /// template-name.
2078 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2079 if (!getLangOpts().CPlusPlus || E.isInvalid())
2080 return false;
2081 Dependent = false;
2082 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2083 return !DRE->hasExplicitTemplateArgs();
2084 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2085 return !ME->hasExplicitTemplateArgs();
2086 Dependent = true;
2087 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2088 return !DSDRE->hasExplicitTemplateArgs();
2089 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2090 return !DSME->hasExplicitTemplateArgs();
2091 // Any additional cases recognized here should also be handled by
2092 // diagnoseExprIntendedAsTemplateName.
2093 return false;
2094 }
2095 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2096 SourceLocation Less,
2097 SourceLocation Greater);
2098
2099 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2100
2101 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2102 MultiTemplateParamsArg TemplateParameterLists);
2103 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2104 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2105 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2106 DeclarationName Name, SourceLocation Loc,
2107 bool IsTemplateId);
2108 void
2109 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2110 SourceLocation FallbackLoc,
2111 SourceLocation ConstQualLoc = SourceLocation(),
2112 SourceLocation VolatileQualLoc = SourceLocation(),
2113 SourceLocation RestrictQualLoc = SourceLocation(),
2114 SourceLocation AtomicQualLoc = SourceLocation(),
2115 SourceLocation UnalignedQualLoc = SourceLocation());
2116
2117 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2118 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2119 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2120 const LookupResult &R);
2121 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2122 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2123 const LookupResult &R);
2124 void CheckShadow(Scope *S, VarDecl *D);
2125
2126 /// Warn if 'E', which is an expression that is about to be modified, refers
2127 /// to a shadowing declaration.
2128 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2129
2130 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2131
2132private:
2133 /// Map of current shadowing declarations to shadowed declarations. Warn if
2134 /// it looks like the user is trying to modify the shadowing declaration.
2135 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2136
2137public:
2138 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2139 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2140 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2141 TypedefNameDecl *NewTD);
2142 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2143 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2144 TypeSourceInfo *TInfo,
2145 LookupResult &Previous);
2146 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2147 LookupResult &Previous, bool &Redeclaration);
2148 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2149 TypeSourceInfo *TInfo,
2150 LookupResult &Previous,
2151 MultiTemplateParamsArg TemplateParamLists,
2152 bool &AddToScope,
2153 ArrayRef<BindingDecl *> Bindings = None);
2154 NamedDecl *
2155 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2156 MultiTemplateParamsArg TemplateParamLists);
2157 // Returns true if the variable declaration is a redeclaration
2158 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2159 void CheckVariableDeclarationType(VarDecl *NewVD);
2160 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2161 Expr *Init);
2162 void CheckCompleteVariableDeclaration(VarDecl *VD);
2163 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2164 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2165
2166 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2167 TypeSourceInfo *TInfo,
2168 LookupResult &Previous,
2169 MultiTemplateParamsArg TemplateParamLists,
2170 bool &AddToScope);
2171 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2172
2173 enum class CheckConstexprKind {
2174 /// Diagnose issues that are non-constant or that are extensions.
2175 Diagnose,
2176 /// Identify whether this function satisfies the formal rules for constexpr
2177 /// functions in the current lanugage mode (with no extensions).
2178 CheckValid
2179 };
2180
2181 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2182 CheckConstexprKind Kind);
2183
2184 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2185 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2186 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2187 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2188 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2189 // Returns true if the function declaration is a redeclaration
2190 bool CheckFunctionDeclaration(Scope *S,
2191 FunctionDecl *NewFD, LookupResult &Previous,
2192 bool IsMemberSpecialization);
2193 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2194 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2195 QualType NewT, QualType OldT);
2196 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2197 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2198 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2199 bool IsDefinition);
2200 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2201 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2202 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2203 SourceLocation Loc,
2204 QualType T);
2205 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2206 SourceLocation NameLoc, IdentifierInfo *Name,
2207 QualType T, TypeSourceInfo *TSInfo,
2208 StorageClass SC);
2209 void ActOnParamDefaultArgument(Decl *param,
2210 SourceLocation EqualLoc,
2211 Expr *defarg);
2212 void ActOnParamUnparsedDefaultArgument(Decl *param,
2213 SourceLocation EqualLoc,
2214 SourceLocation ArgLoc);
2215 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2216 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2217 SourceLocation EqualLoc);
2218
2219 // Contexts where using non-trivial C union types can be disallowed. This is
2220 // passed to err_non_trivial_c_union_in_invalid_context.
2221 enum NonTrivialCUnionContext {
2222 // Function parameter.
2223 NTCUC_FunctionParam,
2224 // Function return.
2225 NTCUC_FunctionReturn,
2226 // Default-initialized object.
2227 NTCUC_DefaultInitializedObject,
2228 // Variable with automatic storage duration.
2229 NTCUC_AutoVar,
2230 // Initializer expression that might copy from another object.
2231 NTCUC_CopyInit,
2232 // Assignment.
2233 NTCUC_Assignment,
2234 // Compound literal.
2235 NTCUC_CompoundLiteral,
2236 // Block capture.
2237 NTCUC_BlockCapture,
2238 // lvalue-to-rvalue conversion of volatile type.
2239 NTCUC_LValueToRValueVolatile,
2240 };
2241
2242 /// Emit diagnostics if the initializer or any of its explicit or
2243 /// implicitly-generated subexpressions require copying or
2244 /// default-initializing a type that is or contains a C union type that is
2245 /// non-trivial to copy or default-initialize.
2246 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2247
2248 // These flags are passed to checkNonTrivialCUnion.
2249 enum NonTrivialCUnionKind {
2250 NTCUK_Init = 0x1,
2251 NTCUK_Destruct = 0x2,
2252 NTCUK_Copy = 0x4,
2253 };
2254
2255 /// Emit diagnostics if a non-trivial C union type or a struct that contains
2256 /// a non-trivial C union is used in an invalid context.
2257 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2258 NonTrivialCUnionContext UseContext,
2259 unsigned NonTrivialKind);
2260
2261 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2262 void ActOnUninitializedDecl(Decl *dcl);
2263 void ActOnInitializerError(Decl *Dcl);
2264
2265 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2266 void ActOnCXXForRangeDecl(Decl *D);
2267 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2268 IdentifierInfo *Ident,
2269 ParsedAttributes &Attrs,
2270 SourceLocation AttrEnd);
2271 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2272 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2273 void CheckStaticLocalForDllExport(VarDecl *VD);
2274 void FinalizeDeclaration(Decl *D);
2275 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2276 ArrayRef<Decl *> Group);
2277 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2278
2279 /// Should be called on all declarations that might have attached
2280 /// documentation comments.
2281 void ActOnDocumentableDecl(Decl *D);
2282 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2283
2284 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2285 SourceLocation LocAfterDecls);
2286 void CheckForFunctionRedefinition(
2287 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2288 SkipBodyInfo *SkipBody = nullptr);
2289 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2290 MultiTemplateParamsArg TemplateParamLists,
2291 SkipBodyInfo *SkipBody = nullptr);
2292 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2293 SkipBodyInfo *SkipBody = nullptr);
2294 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2295 bool isObjCMethodDecl(Decl *D) {
2296 return D && isa<ObjCMethodDecl>(D);
2297 }
2298
2299 /// Determine whether we can delay parsing the body of a function or
2300 /// function template until it is used, assuming we don't care about emitting
2301 /// code for that function.
2302 ///
2303 /// This will be \c false if we may need the body of the function in the
2304 /// middle of parsing an expression (where it's impractical to switch to
2305 /// parsing a different function), for instance, if it's constexpr in C++11
2306 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2307 bool canDelayFunctionBody(const Declarator &D);
2308
2309 /// Determine whether we can skip parsing the body of a function
2310 /// definition, assuming we don't care about analyzing its body or emitting
2311 /// code for that function.
2312 ///
2313 /// This will be \c false only if we may need the body of the function in
2314 /// order to parse the rest of the program (for instance, if it is
2315 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2316 bool canSkipFunctionBody(Decl *D);
2317
2318 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2319 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2320 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2321 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2322 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2323
2324 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2325 /// attribute for which parsing is delayed.
2326 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2327
2328 /// Diagnose any unused parameters in the given sequence of
2329 /// ParmVarDecl pointers.
2330 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2331
2332 /// Diagnose whether the size of parameters or return value of a
2333 /// function or obj-c method definition is pass-by-value and larger than a
2334 /// specified threshold.
2335 void
2336 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2337 QualType ReturnTy, NamedDecl *D);
2338
2339 void DiagnoseInvalidJumps(Stmt *Body);
2340 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2341 SourceLocation AsmLoc,
2342 SourceLocation RParenLoc);
2343
2344 /// Handle a C++11 empty-declaration and attribute-declaration.
2345 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2346 SourceLocation SemiLoc);
2347
2348 enum class ModuleDeclKind {
2349 Interface, ///< 'export module X;'
2350 Implementation, ///< 'module X;'
2351 };
2352
2353 /// The parser has processed a module-declaration that begins the definition
2354 /// of a module interface or implementation.
2355 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2356 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2357 ModuleIdPath Path, bool IsFirstDecl);
2358
2359 /// The parser has processed a global-module-fragment declaration that begins
2360 /// the definition of the global module fragment of the current module unit.
2361 /// \param ModuleLoc The location of the 'module' keyword.
2362 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2363
2364 /// The parser has processed a private-module-fragment declaration that begins
2365 /// the definition of the private module fragment of the current module unit.
2366 /// \param ModuleLoc The location of the 'module' keyword.
2367 /// \param PrivateLoc The location of the 'private' keyword.
2368 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2369 SourceLocation PrivateLoc);
2370
2371 /// The parser has processed a module import declaration.
2372 ///
2373 /// \param StartLoc The location of the first token in the declaration. This
2374 /// could be the location of an '@', 'export', or 'import'.
2375 /// \param ExportLoc The location of the 'export' keyword, if any.
2376 /// \param ImportLoc The location of the 'import' keyword.
2377 /// \param Path The module access path.
2378 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2379 SourceLocation ExportLoc,
2380 SourceLocation ImportLoc, ModuleIdPath Path);
2381 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2382 SourceLocation ExportLoc,
2383 SourceLocation ImportLoc, Module *M,
2384 ModuleIdPath Path = {});
2385
2386 /// The parser has processed a module import translated from a
2387 /// #include or similar preprocessing directive.
2388 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2389 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2390
2391 /// The parsed has entered a submodule.
2392 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2393 /// The parser has left a submodule.
2394 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2395
2396 /// Create an implicit import of the given module at the given
2397 /// source location, for error recovery, if possible.
2398 ///
2399 /// This routine is typically used when an entity found by name lookup
2400 /// is actually hidden within a module that we know about but the user
2401 /// has forgotten to import.
2402 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2403 Module *Mod);
2404
2405 /// Kinds of missing import. Note, the values of these enumerators correspond
2406 /// to %select values in diagnostics.
2407 enum class MissingImportKind {
2408 Declaration,
2409 Definition,
2410 DefaultArgument,
2411 ExplicitSpecialization,
2412 PartialSpecialization
2413 };
2414
2415 /// Diagnose that the specified declaration needs to be visible but
2416 /// isn't, and suggest a module import that would resolve the problem.
2417 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2418 MissingImportKind MIK, bool Recover = true);
2419 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2420 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2421 MissingImportKind MIK, bool Recover);
2422
2423 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2424 SourceLocation LBraceLoc);
2425 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2426 SourceLocation RBraceLoc);
2427
2428 /// We've found a use of a templated declaration that would trigger an
2429 /// implicit instantiation. Check that any relevant explicit specializations
2430 /// and partial specializations are visible, and diagnose if not.
2431 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2432
2433 /// We've found a use of a template specialization that would select a
2434 /// partial specialization. Check that the partial specialization is visible,
2435 /// and diagnose if not.
2436 void checkPartialSpecializationVisibility(SourceLocation Loc,
2437 NamedDecl *Spec);
2438
2439 /// Retrieve a suitable printing policy for diagnostics.
2440 PrintingPolicy getPrintingPolicy() const {
2441 return getPrintingPolicy(Context, PP);
2442 }
2443
2444 /// Retrieve a suitable printing policy for diagnostics.
2445 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2446 const Preprocessor &PP);
2447
2448 /// Scope actions.
2449 void ActOnPopScope(SourceLocation Loc, Scope *S);
2450 void ActOnTranslationUnitScope(Scope *S);
2451
2452 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2453 RecordDecl *&AnonRecord);
2454 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2455 MultiTemplateParamsArg TemplateParams,
2456 bool IsExplicitInstantiation,
2457 RecordDecl *&AnonRecord);
2458
2459 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2460 AccessSpecifier AS,
2461 RecordDecl *Record,
2462 const PrintingPolicy &Policy);
2463
2464 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2465 RecordDecl *Record);
2466
2467 /// Common ways to introduce type names without a tag for use in diagnostics.
2468 /// Keep in sync with err_tag_reference_non_tag.
2469 enum NonTagKind {
2470 NTK_NonStruct,
2471 NTK_NonClass,
2472 NTK_NonUnion,
2473 NTK_NonEnum,
2474 NTK_Typedef,
2475 NTK_TypeAlias,
2476 NTK_Template,
2477 NTK_TypeAliasTemplate,
2478 NTK_TemplateTemplateArgument,
2479 };
2480
2481 /// Given a non-tag type declaration, returns an enum useful for indicating
2482 /// what kind of non-tag type this is.
2483 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2484
2485 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2486 TagTypeKind NewTag, bool isDefinition,
2487 SourceLocation NewTagLoc,
2488 const IdentifierInfo *Name);
2489
2490 enum TagUseKind {
2491 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2492 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2493 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2494 TUK_Friend // Friend declaration: 'friend struct foo;'
2495 };
2496
2497 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2498 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2499 SourceLocation NameLoc, const ParsedAttributesView &Attr,
2500 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2501 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2502 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2503 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2504 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2505 SkipBodyInfo *SkipBody = nullptr);
2506
2507 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2508 unsigned TagSpec, SourceLocation TagLoc,
2509 CXXScopeSpec &SS, IdentifierInfo *Name,
2510 SourceLocation NameLoc,
2511 const ParsedAttributesView &Attr,
2512 MultiTemplateParamsArg TempParamLists);
2513
2514 TypeResult ActOnDependentTag(Scope *S,
2515 unsigned TagSpec,
2516 TagUseKind TUK,
2517 const CXXScopeSpec &SS,
2518 IdentifierInfo *Name,
2519 SourceLocation TagLoc,
2520 SourceLocation NameLoc);
2521
2522 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2523 IdentifierInfo *ClassName,
2524 SmallVectorImpl<Decl *> &Decls);
2525 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2526 Declarator &D, Expr *BitfieldWidth);
2527
2528 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2529 Declarator &D, Expr *BitfieldWidth,
2530 InClassInitStyle InitStyle,
2531 AccessSpecifier AS);
2532 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2533 SourceLocation DeclStart, Declarator &D,
2534 Expr *BitfieldWidth,
2535 InClassInitStyle InitStyle,
2536 AccessSpecifier AS,
2537 const ParsedAttr &MSPropertyAttr);
2538
2539 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2540 TypeSourceInfo *TInfo,
2541 RecordDecl *Record, SourceLocation Loc,
2542 bool Mutable, Expr *BitfieldWidth,
2543 InClassInitStyle InitStyle,
2544 SourceLocation TSSL,
2545 AccessSpecifier AS, NamedDecl *PrevDecl,
2546 Declarator *D = nullptr);
2547
2548 bool CheckNontrivialField(FieldDecl *FD);
2549 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2550
2551 enum TrivialABIHandling {
2552 /// The triviality of a method unaffected by "trivial_abi".
2553 TAH_IgnoreTrivialABI,
2554
2555 /// The triviality of a method affected by "trivial_abi".
2556 TAH_ConsiderTrivialABI
2557 };
2558
2559 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2560 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2561 bool Diagnose = false);
2562
2563 /// For a defaulted function, the kind of defaulted function that it is.
2564 class DefaultedFunctionKind {
2565 CXXSpecialMember SpecialMember : 8;
2566 DefaultedComparisonKind Comparison : 8;
2567
2568 public:
2569 DefaultedFunctionKind()
2570 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
2571 }
2572 DefaultedFunctionKind(CXXSpecialMember CSM)
2573 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
2574 DefaultedFunctionKind(DefaultedComparisonKind Comp)
2575 : SpecialMember(CXXInvalid), Comparison(Comp) {}
2576
2577 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
2578 bool isComparison() const {
2579 return Comparison != DefaultedComparisonKind::None;
2580 }
2581
2582 explicit operator bool() const {
2583 return isSpecialMember() || isComparison();
2584 }
2585
2586 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
2587 DefaultedComparisonKind asComparison() const { return Comparison; }
2588
2589 /// Get the index of this function kind for use in diagnostics.
2590 unsigned getDiagnosticIndex() const {
2591 static_assert(CXXInvalid > CXXDestructor,
2592 "invalid should have highest index");
2593 static_assert((unsigned)DefaultedComparisonKind::None == 0,
2594 "none should be equal to zero");
2595 return SpecialMember + (unsigned)Comparison;
2596 }
2597 };
2598
2599 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
2600
2601 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
2602 return getDefaultedFunctionKind(MD).asSpecialMember();
2603 }
2604 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
2605 return getDefaultedFunctionKind(FD).asComparison();
2606 }
2607
2608 void ActOnLastBitfield(SourceLocation DeclStart,
2609 SmallVectorImpl<Decl *> &AllIvarDecls);
2610 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2611 Declarator &D, Expr *BitfieldWidth,
2612 tok::ObjCKeywordKind visibility);
2613
2614 // This is used for both record definitions and ObjC interface declarations.
2615 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
2616 ArrayRef<Decl *> Fields, SourceLocation LBrac,
2617 SourceLocation RBrac, const ParsedAttributesView &AttrList);
2618
2619 /// ActOnTagStartDefinition - Invoked when we have entered the
2620 /// scope of a tag's definition (e.g., for an enumeration, class,
2621 /// struct, or union).
2622 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2623
2624 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2625 /// Differently from C++, actually parse the body and reject / error out
2626 /// in case of a structural mismatch.
2627 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2628 SkipBodyInfo &SkipBody);
2629
2630 typedef void *SkippedDefinitionContext;
2631
2632 /// Invoked when we enter a tag definition that we're skipping.
2633 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2634
2635 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2636
2637 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2638 /// C++ record definition's base-specifiers clause and are starting its
2639 /// member declarations.
2640 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2641 SourceLocation FinalLoc,
2642 bool IsFinalSpelledSealed,
2643 SourceLocation LBraceLoc);
2644
2645 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2646 /// the definition of a tag (enumeration, class, struct, or union).
2647 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2648 SourceRange BraceRange);
2649
2650 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2651
2652 void ActOnObjCContainerFinishDefinition();
2653
2654 /// Invoked when we must temporarily exit the objective-c container
2655 /// scope for parsing/looking-up C constructs.
2656 ///
2657 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2658 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2659 void ActOnObjCReenterContainerContext(DeclContext *DC);
2660
2661 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2662 /// error parsing the definition of a tag.
2663 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2664
2665 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2666 EnumConstantDecl *LastEnumConst,
2667 SourceLocation IdLoc,
2668 IdentifierInfo *Id,
2669 Expr *val);
2670 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2671 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2672 QualType EnumUnderlyingTy, bool IsFixed,
2673 const EnumDecl *Prev);
2674
2675 /// Determine whether the body of an anonymous enumeration should be skipped.
2676 /// \param II The name of the first enumerator.
2677 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2678 SourceLocation IILoc);
2679
2680 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2681 SourceLocation IdLoc, IdentifierInfo *Id,
2682 const ParsedAttributesView &Attrs,
2683 SourceLocation EqualLoc, Expr *Val);
2684 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2685 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
2686 const ParsedAttributesView &Attr);
2687
2688 DeclContext *getContainingDC(DeclContext *DC);
2689
2690 /// Set the current declaration context until it gets popped.
2691 void PushDeclContext(Scope *S, DeclContext *DC);
2692 void PopDeclContext();
2693
2694 /// EnterDeclaratorContext - Used when we must lookup names in the context
2695 /// of a declarator's nested name specifier.
2696 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2697 void ExitDeclaratorContext(Scope *S);
2698
2699 /// Push the parameters of D, which must be a function, into scope.
2700 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2701 void ActOnExitFunctionContext();
2702
2703 DeclContext *getFunctionLevelDeclContext();
2704
2705 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2706 /// to the function decl for the function being parsed. If we're currently
2707 /// in a 'block', this returns the containing context.
2708 FunctionDecl *getCurFunctionDecl();
2709
2710 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2711 /// the method decl for the method being parsed. If we're currently
2712 /// in a 'block', this returns the containing context.
2713 ObjCMethodDecl *getCurMethodDecl();
2714
2715 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2716 /// or C function we're in, otherwise return null. If we're currently
2717 /// in a 'block', this returns the containing context.
2718 NamedDecl *getCurFunctionOrMethodDecl();
2719
2720 /// Add this decl to the scope shadowed decl chains.
2721 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2722
2723 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2724 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2725 /// true if 'D' belongs to the given declaration context.
2726 ///
2727 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2728 /// enclosing namespace set of the context, rather than contained
2729 /// directly within it.
2730 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2731 bool AllowInlineNamespace = false);
2732
2733 /// Finds the scope corresponding to the given decl context, if it
2734 /// happens to be an enclosing scope. Otherwise return NULL.
2735 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2736
2737 /// Subroutines of ActOnDeclarator().
2738 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2739 TypeSourceInfo *TInfo);
2740 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2741
2742 /// Describes the kind of merge to perform for availability
2743 /// attributes (including "deprecated", "unavailable", and "availability").
2744 enum AvailabilityMergeKind {
2745 /// Don't merge availability attributes at all.
2746 AMK_None,
2747 /// Merge availability attributes for a redeclaration, which requires
2748 /// an exact match.
2749 AMK_Redeclaration,
2750 /// Merge availability attributes for an override, which requires
2751 /// an exact match or a weakening of constraints.
2752 AMK_Override,
2753 /// Merge availability attributes for an implementation of
2754 /// a protocol requirement.
2755 AMK_ProtocolImplementation,
2756 };
2757
2758 /// Describes the kind of priority given to an availability attribute.
2759 ///
2760 /// The sum of priorities deteremines the final priority of the attribute.
2761 /// The final priority determines how the attribute will be merged.
2762 /// An attribute with a lower priority will always remove higher priority
2763 /// attributes for the specified platform when it is being applied. An
2764 /// attribute with a higher priority will not be applied if the declaration
2765 /// already has an availability attribute with a lower priority for the
2766 /// specified platform. The final prirority values are not expected to match
2767 /// the values in this enumeration, but instead should be treated as a plain
2768 /// integer value. This enumeration just names the priority weights that are
2769 /// used to calculate that final vaue.
2770 enum AvailabilityPriority : int {
2771 /// The availability attribute was specified explicitly next to the
2772 /// declaration.
2773 AP_Explicit = 0,
2774
2775 /// The availability attribute was applied using '#pragma clang attribute'.
2776 AP_PragmaClangAttribute = 1,
2777
2778 /// The availability attribute for a specific platform was inferred from
2779 /// an availability attribute for another platform.
2780 AP_InferredFromOtherPlatform = 2
2781 };
2782
2783 /// Attribute merging methods. Return true if a new attribute was added.
2784 AvailabilityAttr *
2785 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
2786 IdentifierInfo *Platform, bool Implicit,
2787 VersionTuple Introduced, VersionTuple Deprecated,
2788 VersionTuple Obsoleted, bool IsUnavailable,
2789 StringRef Message, bool IsStrict, StringRef Replacement,
2790 AvailabilityMergeKind AMK, int Priority);
2791 TypeVisibilityAttr *
2792 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2793 TypeVisibilityAttr::VisibilityType Vis);
2794 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2795 VisibilityAttr::VisibilityType Vis);
2796 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
2797 StringRef Uuid);
2798 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
2799 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
2800 MSInheritanceAttr *
2801 mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase,
2802 MSInheritanceAttr::Spelling SemanticSpelling);
2803 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
2804 IdentifierInfo *Format, int FormatIdx,
2805 int FirstArg);
2806 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
2807 StringRef Name);
2808 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
2809 StringRef Name);
2810 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
2811 const AttributeCommonInfo &CI,
2812 const IdentifierInfo *Ident);
2813 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
2814 NoSpeculativeLoadHardeningAttr *
2815 mergeNoSpeculativeLoadHardeningAttr(Decl *D,
2816 const NoSpeculativeLoadHardeningAttr &AL);
2817 SpeculativeLoadHardeningAttr *
2818 mergeSpeculativeLoadHardeningAttr(Decl *D,
2819 const SpeculativeLoadHardeningAttr &AL);
2820 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
2821 const AttributeCommonInfo &CI);
2822 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
2823 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
2824 const InternalLinkageAttr &AL);
2825 CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
2826 CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
2827
2828 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2829 AvailabilityMergeKind AMK = AMK_Redeclaration);
2830 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2831 LookupResult &OldDecls);
2832 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2833 bool MergeTypeWithOld);
2834 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2835 Scope *S, bool MergeTypeWithOld);
2836 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2837 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2838 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2839 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2840 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2841 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2842 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2843
2844 // AssignmentAction - This is used by all the assignment diagnostic functions
2845 // to represent what is actually causing the operation
2846 enum AssignmentAction {
2847 AA_Assigning,
2848 AA_Passing,
2849 AA_Returning,
2850 AA_Converting,
2851 AA_Initializing,
2852 AA_Sending,
2853 AA_Casting,
2854 AA_Passing_CFAudited
2855 };
2856
2857 /// C++ Overloading.
2858 enum OverloadKind {
2859 /// This is a legitimate overload: the existing declarations are
2860 /// functions or function templates with different signatures.
2861 Ovl_Overload,
2862
2863 /// This is not an overload because the signature exactly matches
2864 /// an existing declaration.
2865 Ovl_Match,
2866
2867 /// This is not an overload because the lookup results contain a
2868 /// non-function.
2869 Ovl_NonFunction
2870 };
2871 OverloadKind CheckOverload(Scope *S,
2872 FunctionDecl *New,
2873 const LookupResult &OldDecls,
2874 NamedDecl *&OldDecl,
2875 bool IsForUsingDecl);
2876 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2877 bool ConsiderCudaAttrs = true);
2878
2879 ImplicitConversionSequence
2880 TryImplicitConversion(Expr *From, QualType ToType,
2881 bool SuppressUserConversions,
2882 bool AllowExplicit,
2883 bool InOverloadResolution,
2884 bool CStyle,
2885 bool AllowObjCWritebackConversion);
2886
2887 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2888 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2889 bool IsComplexPromotion(QualType FromType, QualType ToType);
2890 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2891 bool InOverloadResolution,
2892 QualType& ConvertedType, bool &IncompatibleObjC);
2893 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2894 QualType& ConvertedType, bool &IncompatibleObjC);
2895 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2896 QualType &ConvertedType);
2897 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2898 QualType& ConvertedType);
2899 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2900 const FunctionProtoType *NewType,
2901 unsigned *ArgPos = nullptr);
2902 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2903 QualType FromType, QualType ToType);
2904
2905 void maybeExtendBlockObject(ExprResult &E);
2906 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2907 bool CheckPointerConversion(Expr *From, QualType ToType,
2908 CastKind &Kind,
2909 CXXCastPath& BasePath,
2910 bool IgnoreBaseAccess,
2911 bool Diagnose = true);
2912 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2913 bool InOverloadResolution,
2914 QualType &ConvertedType);
2915 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2916 CastKind &Kind,
2917 CXXCastPath &BasePath,
2918 bool IgnoreBaseAccess);
2919 bool IsQualificationConversion(QualType FromType, QualType ToType,
2920 bool CStyle, bool &ObjCLifetimeConversion);
2921 bool IsFunctionConversion(QualType FromType, QualType ToType,
2922 QualType &ResultTy);
2923 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2924 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2925
2926 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2927 const VarDecl *NRVOCandidate,
2928 QualType ResultType,
2929 Expr *Value,
2930 bool AllowNRVO = true);
2931
2932 bool CanPerformAggregateInitializationForOverloadResolution(
2933 const InitializedEntity &Entity, InitListExpr *From);
2934
2935 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2936 ExprResult Init);
2937 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2938 SourceLocation EqualLoc,
2939 ExprResult Init,
2940 bool TopLevelOfInitList = false,
2941 bool AllowExplicit = false);
2942 ExprResult PerformObjectArgumentInitialization(Expr *From,
2943 NestedNameSpecifier *Qualifier,
2944 NamedDecl *FoundDecl,
2945 CXXMethodDecl *Method);
2946
2947 /// Check that the lifetime of the initializer (and its subobjects) is
2948 /// sufficient for initializing the entity, and perform lifetime extension
2949 /// (when permitted) if not.
2950 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
2951
2952 ExprResult PerformContextuallyConvertToBool(Expr *From);
2953 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2954
2955 /// Contexts in which a converted constant expression is required.
2956 enum CCEKind {
2957 CCEK_CaseValue, ///< Expression in a case label.
2958 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2959 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2960 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2961 CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
2962 CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
2963 };
2964 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2965 llvm::APSInt &Value, CCEKind CCE);
2966 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2967 APValue &Value, CCEKind CCE);
2968
2969 /// Abstract base class used to perform a contextual implicit
2970 /// conversion from an expression to any type passing a filter.
2971 class ContextualImplicitConverter {
2972 public:
2973 bool Suppress;
2974 bool SuppressConversion;
2975
2976 ContextualImplicitConverter(bool Suppress = false,
2977 bool SuppressConversion = false)
2978 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2979
2980 /// Determine whether the specified type is a valid destination type
2981 /// for this conversion.
2982 virtual bool match(QualType T) = 0;
2983
2984 /// Emits a diagnostic complaining that the expression does not have
2985 /// integral or enumeration type.
2986 virtual SemaDiagnosticBuilder
2987 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2988
2989 /// Emits a diagnostic when the expression has incomplete class type.
2990 virtual SemaDiagnosticBuilder
2991 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2992
2993 /// Emits a diagnostic when the only matching conversion function
2994 /// is explicit.
2995 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2996 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2997
2998 /// Emits a note for the explicit conversion function.
2999 virtual SemaDiagnosticBuilder
3000 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3001
3002 /// Emits a diagnostic when there are multiple possible conversion
3003 /// functions.
3004 virtual SemaDiagnosticBuilder
3005 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3006
3007 /// Emits a note for one of the candidate conversions.
3008 virtual SemaDiagnosticBuilder
3009 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3010
3011 /// Emits a diagnostic when we picked a conversion function
3012 /// (for cases when we are not allowed to pick a conversion function).
3013 virtual SemaDiagnosticBuilder diagnoseConversion(
3014 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3015
3016 virtual ~ContextualImplicitConverter() {}
3017 };
3018
3019 class ICEConvertDiagnoser : public ContextualImplicitConverter {
3020 bool AllowScopedEnumerations;
3021
3022 public:
3023 ICEConvertDiagnoser(bool AllowScopedEnumerations,
3024 bool Suppress, bool SuppressConversion)
3025 : ContextualImplicitConverter(Suppress, SuppressConversion),
3026 AllowScopedEnumerations(AllowScopedEnumerations) {}
3027
3028 /// Match an integral or (possibly scoped) enumeration type.
3029 bool match(QualType T) override;
3030
3031 SemaDiagnosticBuilder
3032 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3033 return diagnoseNotInt(S, Loc, T);
3034 }
3035
3036 /// Emits a diagnostic complaining that the expression does not have
3037 /// integral or enumeration type.
3038 virtual SemaDiagnosticBuilder
3039 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3040 };
3041
3042 /// Perform a contextual implicit conversion.
3043 ExprResult PerformContextualImplicitConversion(
3044 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3045
3046
3047 enum ObjCSubscriptKind {
3048 OS_Array,
3049 OS_Dictionary,
3050 OS_Error
3051 };
3052 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3053
3054 // Note that LK_String is intentionally after the other literals, as
3055 // this is used for diagnostics logic.
3056 enum ObjCLiteralKind {
3057 LK_Array,
3058 LK_Dictionary,
3059 LK_Numeric,
3060 LK_Boxed,
3061 LK_String,
3062 LK_Block,
3063 LK_None
3064 };
3065 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3066
3067 ExprResult PerformObjectMemberConversion(Expr *From,
3068 NestedNameSpecifier *Qualifier,
3069 NamedDecl *FoundDecl,
3070 NamedDecl *Member);
3071
3072 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3073 // TODO: make this is a typesafe union.
3074 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
3075 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3076
3077 using ADLCallKind = CallExpr::ADLCallKind;
3078
3079 void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3080 ArrayRef<Expr *> Args,
3081 OverloadCandidateSet &CandidateSet,
3082 bool SuppressUserConversions = false,
3083 bool PartialOverloading = false,
3084 bool AllowExplicit = true,
3085 bool AllowExplicitConversion = false,
3086 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3087 ConversionSequenceList EarlyConversions = None,
3088 OverloadCandidateParamOrder PO = {});
3089 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3090 ArrayRef<Expr *> Args,
3091 OverloadCandidateSet &CandidateSet,
3092 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3093 bool SuppressUserConversions = false,
3094 bool PartialOverloading = false,
3095 bool FirstArgumentIsBase = false);
3096 void AddMethodCandidate(DeclAccessPair FoundDecl,
3097 QualType ObjectType,
3098 Expr::Classification ObjectClassification,
3099 ArrayRef<Expr *> Args,
3100 OverloadCandidateSet& CandidateSet,
3101 bool SuppressUserConversion = false,
3102 OverloadCandidateParamOrder PO = {});
3103 void AddMethodCandidate(CXXMethodDecl *Method,
3104 DeclAccessPair FoundDecl,
3105 CXXRecordDecl *ActingContext, QualType ObjectType,
3106 Expr::Classification ObjectClassification,
3107 ArrayRef<Expr *> Args,
3108 OverloadCandidateSet& CandidateSet,
3109 bool SuppressUserConversions = false,
3110 bool PartialOverloading = false,
3111 ConversionSequenceList EarlyConversions = None,
3112 OverloadCandidateParamOrder PO = {});
3113 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3114 DeclAccessPair FoundDecl,
3115 CXXRecordDecl *ActingContext,
3116 TemplateArgumentListInfo *ExplicitTemplateArgs,
3117 QualType ObjectType,
3118 Expr::Classification ObjectClassification,
3119 ArrayRef<Expr *> Args,
3120 OverloadCandidateSet& CandidateSet,
3121 bool SuppressUserConversions = false,
3122 bool PartialOverloading = false,
3123 OverloadCandidateParamOrder PO = {});
3124 void AddTemplateOverloadCandidate(
3125 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3126 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3127 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3128 bool PartialOverloading = false, bool AllowExplicit = true,
3129 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3130 OverloadCandidateParamOrder PO = {});
3131 bool CheckNonDependentConversions(
3132 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3133 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3134 ConversionSequenceList &Conversions, bool SuppressUserConversions,
3135 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3136 Expr::Classification ObjectClassification = {},
3137 OverloadCandidateParamOrder PO = {});
3138 void AddConversionCandidate(
3139 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3140 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3141 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3142 bool AllowExplicit, bool AllowResultConversion = true);
3143 void AddTemplateConversionCandidate(
3144 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3145 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3146 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3147 bool AllowExplicit, bool AllowResultConversion = true);
3148 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3149 DeclAccessPair FoundDecl,
3150 CXXRecordDecl *ActingContext,
3151 const FunctionProtoType *Proto,
3152 Expr *Object, ArrayRef<Expr *> Args,
3153 OverloadCandidateSet& CandidateSet);
3154 void AddNonMemberOperatorCandidates(
3155 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3156 OverloadCandidateSet &CandidateSet,
3157 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3158 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3159 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3160 OverloadCandidateSet &CandidateSet,
3161 OverloadCandidateParamOrder PO = {});
3162 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3163 OverloadCandidateSet& CandidateSet,
3164 bool IsAssignmentOperator = false,
3165 unsigned NumContextualBoolArguments = 0);
3166 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3167 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3168 OverloadCandidateSet& CandidateSet);
3169 void AddArgumentDependentLookupCandidates(DeclarationName Name,
3170 SourceLocation Loc,
3171 ArrayRef<Expr *> Args,
3172 TemplateArgumentListInfo *ExplicitTemplateArgs,
3173 OverloadCandidateSet& CandidateSet,
3174 bool PartialOverloading = false);
3175
3176 // Emit as a 'note' the specific overload candidate
3177 void NoteOverloadCandidate(
3178 NamedDecl *Found, FunctionDecl *Fn,
3179 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3180 QualType DestType = QualType(), bool TakingAddress = false);
3181
3182 // Emit as a series of 'note's all template and non-templates identified by
3183 // the expression Expr
3184 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3185 bool TakingAddress = false);
3186
3187 /// Check the enable_if expressions on the given function. Returns the first
3188 /// failing attribute, or NULL if they were all successful.
3189 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
3190 bool MissingImplicitThis = false);
3191
3192 /// Find the failed Boolean condition within a given Boolean
3193 /// constant expression, and describe it with a string.
3194 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3195
3196 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3197 /// non-ArgDependent DiagnoseIfAttrs.
3198 ///
3199 /// Argument-dependent diagnose_if attributes should be checked each time a
3200 /// function is used as a direct callee of a function call.
3201 ///
3202 /// Returns true if any errors were emitted.
3203 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3204 const Expr *ThisArg,
3205 ArrayRef<const Expr *> Args,
3206 SourceLocation Loc);
3207
3208 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3209 /// ArgDependent DiagnoseIfAttrs.
3210 ///
3211 /// Argument-independent diagnose_if attributes should be checked on every use
3212 /// of a function.
3213 ///
3214 /// Returns true if any errors were emitted.
3215 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3216 SourceLocation Loc);
3217
3218 /// Returns whether the given function's address can be taken or not,
3219 /// optionally emitting a diagnostic if the address can't be taken.
3220 ///
3221 /// Returns false if taking the address of the function is illegal.
3222 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3223 bool Complain = false,
3224 SourceLocation Loc = SourceLocation());
3225
3226 // [PossiblyAFunctionType] --> [Return]
3227 // NonFunctionType --> NonFunctionType
3228 // R (A) --> R(A)
3229 // R (*)(A) --> R (A)
3230 // R (&)(A) --> R (A)
3231 // R (S::*)(A) --> R (A)
3232 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3233
3234 FunctionDecl *
3235 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3236 QualType TargetType,
3237 bool Complain,
3238 DeclAccessPair &Found,
3239 bool *pHadMultipleCandidates = nullptr);
3240
3241 FunctionDecl *
3242 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
3243 DeclAccessPair &FoundResult);
3244
3245 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
3246 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3247
3248 FunctionDecl *
3249 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3250 bool Complain = false,
3251 DeclAccessPair *Found = nullptr);
3252
3253 bool ResolveAndFixSingleFunctionTemplateSpecialization(
3254 ExprResult &SrcExpr,
3255 bool DoFunctionPointerConverion = false,
3256 bool Complain = false,
3257 SourceRange OpRangeForComplaining = SourceRange(),
3258 QualType DestTypeForComplaining = QualType(),
3259 unsigned DiagIDForComplaining = 0);
3260
3261
3262 Expr *FixOverloadedFunctionReference(Expr *E,
3263 DeclAccessPair FoundDecl,
3264 FunctionDecl *Fn);
3265 ExprResult FixOverloadedFunctionReference(ExprResult,
3266 DeclAccessPair FoundDecl,
3267 FunctionDecl *Fn);
3268
3269 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3270 ArrayRef<Expr *> Args,
3271 OverloadCandidateSet &CandidateSet,
3272 bool PartialOverloading = false);
3273
3274 // An enum used to represent the different possible results of building a
3275 // range-based for loop.
3276 enum ForRangeStatus {
3277 FRS_Success,
3278 FRS_NoViableFunction,
3279 FRS_DiagnosticIssued
3280 };
3281
3282 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3283 SourceLocation RangeLoc,
3284 const DeclarationNameInfo &NameInfo,
3285 LookupResult &MemberLookup,
3286 OverloadCandidateSet *CandidateSet,
3287 Expr *Range, ExprResult *CallExpr);
3288
3289 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3290 UnresolvedLookupExpr *ULE,
3291 SourceLocation LParenLoc,
3292 MultiExprArg Args,
3293 SourceLocation RParenLoc,
3294 Expr *ExecConfig,
3295 bool AllowTypoCorrection=true,
3296 bool CalleesAddressIsTaken=false);
3297
3298 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3299 MultiExprArg Args, SourceLocation RParenLoc,
3300 OverloadCandidateSet *CandidateSet,
3301 ExprResult *Result);
3302
3303 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3304 UnaryOperatorKind Opc,
3305 const UnresolvedSetImpl &Fns,
3306 Expr *input, bool RequiresADL = true);
3307
3308 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3309 BinaryOperatorKind Opc,
3310 const UnresolvedSetImpl &Fns,
3311 Expr *LHS, Expr *RHS,
3312 bool RequiresADL = true,
3313 bool AllowRewrittenCandidates = true);
3314
3315 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3316 SourceLocation RLoc,
3317 Expr *Base,Expr *Idx);
3318
3319 ExprResult
3320 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3321 SourceLocation LParenLoc,
3322 MultiExprArg Args,
3323 SourceLocation RParenLoc);
3324 ExprResult
3325 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3326 MultiExprArg Args,
3327 SourceLocation RParenLoc);
3328
3329 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3330 SourceLocation OpLoc,
3331 bool *NoArrowOperatorFound = nullptr);
3332
3333 /// CheckCallReturnType - Checks that a call expression's return type is
3334 /// complete. Returns true on failure. The location passed in is the location
3335 /// that best represents the call.
3336 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3337 CallExpr *CE, FunctionDecl *FD);
3338
3339 /// Helpers for dealing with blocks and functions.
3340 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3341 bool CheckParameterNames);
3342 void CheckCXXDefaultArguments(FunctionDecl *FD);
3343 void CheckExtraCXXDefaultArguments(Declarator &D);
3344 Scope *getNonFieldDeclScope(Scope *S);
3345
3346 /// \name Name lookup
3347 ///
3348 /// These routines provide name lookup that is used during semantic
3349 /// analysis to resolve the various kinds of names (identifiers,
3350 /// overloaded operator names, constructor names, etc.) into zero or
3351 /// more declarations within a particular scope. The major entry
3352 /// points are LookupName, which performs unqualified name lookup,
3353 /// and LookupQualifiedName, which performs qualified name lookup.
3354 ///
3355 /// All name lookup is performed based on some specific criteria,
3356 /// which specify what names will be visible to name lookup and how
3357 /// far name lookup should work. These criteria are important both
3358 /// for capturing language semantics (certain lookups will ignore
3359 /// certain names, for example) and for performance, since name
3360 /// lookup is often a bottleneck in the compilation of C++. Name
3361 /// lookup criteria is specified via the LookupCriteria enumeration.
3362 ///
3363 /// The results of name lookup can vary based on the kind of name
3364 /// lookup performed, the current language, and the translation
3365 /// unit. In C, for example, name lookup will either return nothing
3366 /// (no entity found) or a single declaration. In C++, name lookup
3367 /// can additionally refer to a set of overloaded functions or
3368 /// result in an ambiguity. All of the possible results of name
3369 /// lookup are captured by the LookupResult class, which provides
3370 /// the ability to distinguish among them.
3371 //@{
3372
3373 /// Describes the kind of name lookup to perform.
3374 enum LookupNameKind {
3375 /// Ordinary name lookup, which finds ordinary names (functions,
3376 /// variables, typedefs, etc.) in C and most kinds of names
3377 /// (functions, variables, members, types, etc.) in C++.
3378 LookupOrdinaryName = 0,
3379 /// Tag name lookup, which finds the names of enums, classes,
3380 /// structs, and unions.
3381 LookupTagName,
3382 /// Label name lookup.
3383 LookupLabel,
3384 /// Member name lookup, which finds the names of
3385 /// class/struct/union members.
3386 LookupMemberName,
3387 /// Look up of an operator name (e.g., operator+) for use with
3388 /// operator overloading. This lookup is similar to ordinary name
3389 /// lookup, but will ignore any declarations that are class members.
3390 LookupOperatorName,
3391 /// Look up of a name that precedes the '::' scope resolution
3392 /// operator in C++. This lookup completely ignores operator, object,
3393 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3394 LookupNestedNameSpecifierName,
3395 /// Look up a namespace name within a C++ using directive or
3396 /// namespace alias definition, ignoring non-namespace names (C++
3397 /// [basic.lookup.udir]p1).
3398 LookupNamespaceName,
3399 /// Look up all declarations in a scope with the given name,
3400 /// including resolved using declarations. This is appropriate
3401 /// for checking redeclarations for a using declaration.
3402 LookupUsingDeclName,
3403 /// Look up an ordinary name that is going to be redeclared as a
3404 /// name with linkage. This lookup ignores any declarations that
3405 /// are outside of the current scope unless they have linkage. See
3406 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3407 LookupRedeclarationWithLinkage,
3408 /// Look up a friend of a local class. This lookup does not look
3409 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3410 LookupLocalFriendName,
3411 /// Look up the name of an Objective-C protocol.
3412 LookupObjCProtocolName,
3413 /// Look up implicit 'self' parameter of an objective-c method.
3414 LookupObjCImplicitSelfParam,
3415 /// Look up the name of an OpenMP user-defined reduction operation.
3416 LookupOMPReductionName,
3417 /// Look up the name of an OpenMP user-defined mapper.
3418 LookupOMPMapperName,
3419 /// Look up any declaration with any name.
3420 LookupAnyName
3421 };
3422
3423 /// Specifies whether (or how) name lookup is being performed for a
3424 /// redeclaration (vs. a reference).
3425 enum RedeclarationKind {
3426 /// The lookup is a reference to this name that is not for the
3427 /// purpose of redeclaring the name.
3428 NotForRedeclaration = 0,
3429 /// The lookup results will be used for redeclaration of a name,
3430 /// if an entity by that name already exists and is visible.
3431 ForVisibleRedeclaration,
3432 /// The lookup results will be used for redeclaration of a name
3433 /// with external linkage; non-visible lookup results with external linkage
3434 /// may also be found.
3435 ForExternalRedeclaration
3436 };
3437
3438 RedeclarationKind forRedeclarationInCurContext() {
3439 // A declaration with an owning module for linkage can never link against
3440 // anything that is not visible. We don't need to check linkage here; if
3441 // the context has internal linkage, redeclaration lookup won't find things
3442 // from other TUs, and we can't safely compute linkage yet in general.
3443 if (cast<Decl>(CurContext)
3444 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3445 return ForVisibleRedeclaration;
3446 return ForExternalRedeclaration;
3447 }
3448
3449 /// The possible outcomes of name lookup for a literal operator.
3450 enum LiteralOperatorLookupResult {
3451 /// The lookup resulted in an error.
3452 LOLR_Error,
3453 /// The lookup found no match but no diagnostic was issued.
3454 LOLR_ErrorNoDiagnostic,
3455 /// The lookup found a single 'cooked' literal operator, which
3456 /// expects a normal literal to be built and passed to it.
3457 LOLR_Cooked,
3458 /// The lookup found a single 'raw' literal operator, which expects
3459 /// a string literal containing the spelling of the literal token.
3460 LOLR_Raw,
3461 /// The lookup found an overload set of literal operator templates,
3462 /// which expect the characters of the spelling of the literal token to be
3463 /// passed as a non-type template argument pack.
3464 LOLR_Template,
3465 /// The lookup found an overload set of literal operator templates,
3466 /// which expect the character type and characters of the spelling of the
3467 /// string literal token to be passed as template arguments.
3468 LOLR_StringTemplate
3469 };
3470
3471 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3472 CXXSpecialMember SM,
3473 bool ConstArg,
3474 bool VolatileArg,
3475 bool RValueThis,
3476 bool ConstThis,
3477 bool VolatileThis);
3478
3479 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3480 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3481 TypoRecoveryCallback;
3482
3483private:
3484 bool CppLookupName(LookupResult &R, Scope *S);
3485
3486 struct TypoExprState {
3487 std::unique_ptr<TypoCorrectionConsumer> Consumer;
3488 TypoDiagnosticGenerator DiagHandler;
3489 TypoRecoveryCallback RecoveryHandler;
3490 TypoExprState();
3491 TypoExprState(TypoExprState &&other) noexcept;
3492 TypoExprState &operator=(TypoExprState &&other) noexcept;
3493 };
3494
3495 /// The set of unhandled TypoExprs and their associated state.
3496 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3497
3498 /// Creates a new TypoExpr AST node.
3499 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3500 TypoDiagnosticGenerator TDG,
3501 TypoRecoveryCallback TRC);
3502
3503 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
3504 //
3505 // The boolean value will be true to indicate that the namespace was loaded
3506 // from an AST/PCH file, or false otherwise.
3507 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3508
3509 /// Whether we have already loaded known namespaces from an extenal
3510 /// source.
3511 bool LoadedExternalKnownNamespaces;
3512
3513 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
3514 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3515 /// should be skipped entirely.
3516 std::unique_ptr<TypoCorrectionConsumer>
3517 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3518 Sema::LookupNameKind LookupKind, Scope *S,
3519 CXXScopeSpec *SS,
3520 CorrectionCandidateCallback &CCC,
3521 DeclContext *MemberContext, bool EnteringContext,
3522 const ObjCObjectPointerType *OPT,
3523 bool ErrorRecovery);
3524
3525public:
3526 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3527
3528 /// Clears the state of the given TypoExpr.
3529 void clearDelayedTypo(TypoExpr *TE);
3530
3531 /// Look up a name, looking for a single declaration. Return
3532 /// null if the results were absent, ambiguous, or overloaded.
3533 ///
3534 /// It is preferable to use the elaborated form and explicitly handle
3535 /// ambiguity and overloaded.
3536 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3537 SourceLocation Loc,
3538 LookupNameKind NameKind,
3539 RedeclarationKind Redecl
3540 = NotForRedeclaration);
3541 bool LookupBuiltin(LookupResult &R);
3542 bool LookupName(LookupResult &R, Scope *S,
3543 bool AllowBuiltinCreation = false);
3544 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3545 bool InUnqualifiedLookup = false);
3546 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3547 CXXScopeSpec &SS);
3548 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3549 bool AllowBuiltinCreation = false,
3550 bool EnteringContext = false);
3551 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3552 RedeclarationKind Redecl
3553 = NotForRedeclaration);
3554 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3555
3556 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3557 QualType T1, QualType T2,
3558 UnresolvedSetImpl &Functions);
3559
3560 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3561 SourceLocation GnuLabelLoc = SourceLocation());
3562
3563 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3564 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3565 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3566 unsigned Quals);
3567 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3568 bool RValueThis, unsigned ThisQuals);
3569 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3570 unsigned Quals);
3571 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3572 bool RValueThis, unsigned ThisQuals);
3573 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3574
3575 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3576 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3577 ArrayRef<QualType> ArgTys,
3578 bool AllowRaw,
3579 bool AllowTemplate,
3580 bool AllowStringTemplate,
3581 bool DiagnoseMissing);
3582 bool isKnownName(StringRef name);
3583
3584 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
3585 enum class FunctionEmissionStatus {
3586 Emitted,
3587 CUDADiscarded, // Discarded due to CUDA/HIP hostness
3588 OMPDiscarded, // Discarded due to OpenMP hostness
3589 TemplateDiscarded, // Discarded due to uninstantiated templates
3590 Unknown,
3591 };
3592 FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl);
3593
3594 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
3595 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
3596
3597 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3598 ArrayRef<Expr *> Args, ADLResult &Functions);
3599
3600 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3601 VisibleDeclConsumer &Consumer,
3602 bool IncludeGlobalScope = true,
3603 bool LoadExternal = true);
3604 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3605 VisibleDeclConsumer &Consumer,
3606 bool IncludeGlobalScope = true,
3607 bool IncludeDependentBases = false,
3608 bool LoadExternal = true);
3609
3610 enum CorrectTypoKind {
3611 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3612 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3613 };
3614
3615 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3616 Sema::LookupNameKind LookupKind,
3617 Scope *S, CXXScopeSpec *SS,
3618 CorrectionCandidateCallback &CCC,
3619 CorrectTypoKind Mode,
3620 DeclContext *MemberContext = nullptr,
3621 bool EnteringContext = false,
3622 const ObjCObjectPointerType *OPT = nullptr,
3623 bool RecordFailure = true);
3624
3625 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3626 Sema::LookupNameKind LookupKind, Scope *S,
3627 CXXScopeSpec *SS,
3628 CorrectionCandidateCallback &CCC,
3629 TypoDiagnosticGenerator TDG,
3630 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3631 DeclContext *MemberContext = nullptr,
3632 bool EnteringContext = false,
3633 const ObjCObjectPointerType *OPT = nullptr);
3634
3635 /// Process any TypoExprs in the given Expr and its children,
3636 /// generating diagnostics as appropriate and returning a new Expr if there
3637 /// were typos that were all successfully corrected and ExprError if one or
3638 /// more typos could not be corrected.
3639 ///
3640 /// \param E The Expr to check for TypoExprs.
3641 ///
3642 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3643 /// initializer.
3644 ///
3645 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3646 /// it is an acceptable/usable result from a single combination of typo
3647 /// corrections. As long as the filter returns ExprError, different
3648 /// combinations of corrections will be tried until all are exhausted.
3649 ExprResult
3650 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3651 llvm::function_ref<ExprResult(Expr *)> Filter =
3652 [](Expr *E) -> ExprResult { return E; });
3653
3654 ExprResult
3655 CorrectDelayedTyposInExpr(Expr *E,
3656 llvm::function_ref<ExprResult(Expr *)> Filter) {
3657 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3658 }
3659
3660 ExprResult
3661 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3662 llvm::function_ref<ExprResult(Expr *)> Filter =
3663 [](Expr *E) -> ExprResult { return E; }) {
3664 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3665 }
3666
3667 ExprResult
3668 CorrectDelayedTyposInExpr(ExprResult ER,
3669 llvm::function_ref<ExprResult(Expr *)> Filter) {
3670 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3671 }
3672
3673 void diagnoseTypo(const TypoCorrection &Correction,
3674 const PartialDiagnostic &TypoDiag,
3675 bool ErrorRecovery = true);
3676
3677 void diagnoseTypo(const TypoCorrection &Correction,
3678 const PartialDiagnostic &TypoDiag,
3679 const PartialDiagnostic &PrevNote,
3680 bool ErrorRecovery = true);
3681
3682 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3683
3684 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3685 ArrayRef<Expr *> Args,
3686 AssociatedNamespaceSet &AssociatedNamespaces,
3687 AssociatedClassSet &AssociatedClasses);
3688
3689 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3690 bool ConsiderLinkage, bool AllowInlineNamespace);
3691
3692 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3693
3694 void DiagnoseAmbiguousLookup(LookupResult &Result);
3695 //@}
3696
3697 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3698 SourceLocation IdLoc,
3699 bool TypoCorrection = false);
3700 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3701 Scope *S, bool ForRedeclaration,
3702 SourceLocation Loc);
3703 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3704 Scope *S);
3705 void AddKnownFunctionAttributes(FunctionDecl *FD);
3706
3707 // More parsing and symbol table subroutines.
3708
3709 void ProcessPragmaWeak(Scope *S, Decl *D);
3710 // Decl attributes - this routine is the top level dispatcher.
3711 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3712 // Helper for delayed processing of attributes.
3713 void ProcessDeclAttributeDelayed(Decl *D,
3714 const ParsedAttributesView &AttrList);
3715 void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
3716 bool IncludeCXX11Attributes = true);
3717 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3718 const ParsedAttributesView &AttrList);
3719
3720 void checkUnusedDeclAttributes(Declarator &D);
3721
3722 /// Determine if type T is a valid subject for a nonnull and similar
3723 /// attributes. By default, we look through references (the behavior used by
3724 /// nonnull), but if the second parameter is true, then we treat a reference
3725 /// type as valid.
3726 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3727
3728 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
3729 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
3730 const FunctionDecl *FD = nullptr);
3731 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
3732 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
3733 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
3734 StringRef &Str,
3735 SourceLocation *ArgLocation = nullptr);
3736 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3737 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3738 bool checkMSInheritanceAttrOnDefinition(
3739 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3740 MSInheritanceAttr::Spelling SemanticSpelling);
3741
3742 void CheckAlignasUnderalignment(Decl *D);
3743
3744 /// Adjust the calling convention of a method to be the ABI default if it
3745 /// wasn't specified explicitly. This handles method types formed from
3746 /// function type typedefs and typename template arguments.
3747 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3748 SourceLocation Loc);
3749
3750 // Check if there is an explicit attribute, but only look through parens.
3751 // The intent is to look for an attribute on the current declarator, but not
3752 // one that came from a typedef.
3753 bool hasExplicitCallingConv(QualType T);
3754
3755 /// Get the outermost AttributedType node that sets a calling convention.
3756 /// Valid types should not have multiple attributes with different CCs.
3757 const AttributedType *getCallingConvAttributedType(QualType T) const;
3758
3759 /// Stmt attributes - this routine is the top level dispatcher.
3760 StmtResult ProcessStmtAttributes(Stmt *Stmt,
3761 const ParsedAttributesView &Attrs,
3762 SourceRange Range);
3763
3764 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3765 ObjCMethodDecl *MethodDecl,
3766 bool IsProtocolMethodDecl);
3767
3768 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3769 ObjCMethodDecl *Overridden,
3770 bool IsProtocolMethodDecl);
3771
3772 /// WarnExactTypedMethods - This routine issues a warning if method
3773 /// implementation declaration matches exactly that of its declaration.
3774 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3775 ObjCMethodDecl *MethodDecl,
3776 bool IsProtocolMethodDecl);
3777
3778 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3779
3780 /// CheckImplementationIvars - This routine checks if the instance variables
3781 /// listed in the implelementation match those listed in the interface.
3782 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3783 ObjCIvarDecl **Fields, unsigned nIvars,
3784 SourceLocation Loc);
3785
3786 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3787 /// remains unimplemented in the class or category \@implementation.
3788 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3789 ObjCContainerDecl* IDecl,
3790 bool IncompleteImpl = false);
3791
3792 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3793 /// which must be implemented by this implementation.
3794 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3795 ObjCContainerDecl *CDecl,
3796 bool SynthesizeProperties);
3797
3798 /// Diagnose any null-resettable synthesized setters.
3799 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3800
3801 /// DefaultSynthesizeProperties - This routine default synthesizes all
3802 /// properties which must be synthesized in the class's \@implementation.
3803 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3804 ObjCInterfaceDecl *IDecl,
3805 SourceLocation AtEnd);
3806 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3807
3808 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3809 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3810 /// declared in class 'IFace'.
3811 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3812 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3813
3814 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3815 /// backs the property is not used in the property's accessor.
3816 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3817 const ObjCImplementationDecl *ImplD);
3818
3819 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3820 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3821 /// It also returns ivar's property on success.
3822 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3823 const ObjCPropertyDecl *&PDecl) const;
3824
3825 /// Called by ActOnProperty to handle \@property declarations in
3826 /// class extensions.
3827 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3828 SourceLocation AtLoc,
3829 SourceLocation LParenLoc,
3830 FieldDeclarator &FD,
3831 Selector GetterSel,
3832 SourceLocation GetterNameLoc,
3833 Selector SetterSel,
3834 SourceLocation SetterNameLoc,
3835 const bool isReadWrite,
3836 unsigned &Attributes,
3837 const unsigned AttributesAsWritten,
3838 QualType T,
3839 TypeSourceInfo *TSI,
3840 tok::ObjCKeywordKind MethodImplKind);
3841
3842 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3843 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3844 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3845 ObjCContainerDecl *CDecl,
3846 SourceLocation AtLoc,
3847 SourceLocation LParenLoc,
3848 FieldDeclarator &FD,
3849 Selector GetterSel,
3850 SourceLocation GetterNameLoc,
3851 Selector SetterSel,
3852 SourceLocation SetterNameLoc,
3853 const bool isReadWrite,
3854 const unsigned Attributes,
3855 const unsigned AttributesAsWritten,
3856 QualType T,
3857 TypeSourceInfo *TSI,
3858 tok::ObjCKeywordKind MethodImplKind,
3859 DeclContext *lexicalDC = nullptr);
3860
3861 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3862 /// warning) when atomic property has one but not the other user-declared
3863 /// setter or getter.
3864 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3865 ObjCInterfaceDecl* IDecl);
3866
3867 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3868
3869 void DiagnoseMissingDesignatedInitOverrides(
3870 const ObjCImplementationDecl *ImplD,
3871 const ObjCInterfaceDecl *IFD);
3872
3873 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3874
3875 enum MethodMatchStrategy {
3876 MMS_loose,
3877 MMS_strict
3878 };
3879
3880 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3881 /// true, or false, accordingly.
3882 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3883 const ObjCMethodDecl *PrevMethod,
3884 MethodMatchStrategy strategy = MMS_strict);
3885
3886 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3887 /// or protocol against those declared in their implementations.
3888 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3889 const SelectorSet &ClsMap,
3890 SelectorSet &InsMapSeen,
3891 SelectorSet &ClsMapSeen,
3892 ObjCImplDecl* IMPDecl,
3893 ObjCContainerDecl* IDecl,
3894 bool &IncompleteImpl,
3895 bool ImmediateClass,
3896 bool WarnCategoryMethodImpl=false);
3897
3898 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3899 /// category matches with those implemented in its primary class and
3900 /// warns each time an exact match is found.
3901 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3902
3903 /// Add the given method to the list of globally-known methods.
3904 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3905
3906private:
3907 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3908 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3909 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3910
3911 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3912 /// optionally warns if there are multiple signatures.
3913 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3914 bool receiverIdOrClass,
3915 bool instance);
3916
3917public:
3918 /// - Returns instance or factory methods in global method pool for
3919 /// given selector. It checks the desired kind first, if none is found, and
3920 /// parameter checkTheOther is set, it then checks the other kind. If no such
3921 /// method or only one method is found, function returns false; otherwise, it
3922 /// returns true.
3923 bool
3924 CollectMultipleMethodsInGlobalPool(Selector Sel,
3925 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3926 bool InstanceFirst, bool CheckTheOther,
3927 const ObjCObjectType *TypeBound = nullptr);
3928
3929 bool
3930 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3931 SourceRange R, bool receiverIdOrClass,
3932 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3933
3934 void
3935 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3936 Selector Sel, SourceRange R,
3937 bool receiverIdOrClass);
3938
3939private:
3940 /// - Returns a selector which best matches given argument list or
3941 /// nullptr if none could be found
3942 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3943 bool IsInstance,
3944 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3945
3946
3947 /// Record the typo correction failure and return an empty correction.
3948 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3949 bool RecordFailure = true) {
3950 if (RecordFailure)
3951 TypoCorrectionFailures[Typo].insert(TypoLoc);
3952 return TypoCorrection();
3953 }
3954
3955public:
3956 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3957 /// unit are added to a global pool. This allows us to efficiently associate
3958 /// a selector with a method declaraation for purposes of typechecking
3959 /// messages sent to "id" (where the class of the object is unknown).
3960 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3961 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3962 }
3963
3964 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3965 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3966 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3967 }
3968
3969 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3970 /// pool.
3971 void AddAnyMethodToGlobalPool(Decl *D);
3972
3973 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3974 /// there are multiple signatures.
3975 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3976 bool receiverIdOrClass=false) {
3977 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3978 /*instance*/true);
3979 }
3980
3981 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3982 /// there are multiple signatures.
3983 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3984 bool receiverIdOrClass=false) {
3985 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3986 /*instance*/false);
3987 }
3988
3989 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3990 QualType ObjectType=QualType());
3991 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3992 /// implementation.
3993 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3994
3995 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3996 /// initialization.
3997 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3998 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3999
4000 //===--------------------------------------------------------------------===//
4001 // Statement Parsing Callbacks: SemaStmt.cpp.
4002public:
4003 class FullExprArg {
4004 public:
4005 FullExprArg() : E(nullptr) { }
4006 FullExprArg(Sema &actions) : E(nullptr) { }
4007
4008 ExprResult release() {
4009 return E;
4010 }
4011
4012 Expr *get() const { return E; }
4013
4014 Expr *operator->() {
4015 return E;
4016 }
4017
4018 private:
4019 // FIXME: No need to make the entire Sema class a friend when it's just
4020 // Sema::MakeFullExpr that needs access to the constructor below.
4021 friend class Sema;
4022
4023 explicit FullExprArg(Expr *expr) : E(expr) {}
4024
4025 Expr *E;
4026 };
4027
4028 FullExprArg MakeFullExpr(Expr *Arg) {
4029 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4030 }
4031 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
4032 return FullExprArg(
4033 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4034 }
4035 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
4036 ExprResult FE =
4037 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4038 /*DiscardedValue*/ true);
4039 return FullExprArg(FE.get());
4040 }
4041
4042 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4043 StmtResult ActOnExprStmtError();
4044
4045 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
4046 bool HasLeadingEmptyMacro = false);
4047
4048 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4049 void ActOnFinishOfCompoundStmt();
4050 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4051 ArrayRef<Stmt *> Elts, bool isStmtExpr);
4052
4053 /// A RAII object to enter scope of a compound statement.
4054 class CompoundScopeRAII {
4055 public:
4056 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
4057 S.ActOnStartOfCompoundStmt(IsStmtExpr);
4058 }
4059
4060 ~CompoundScopeRAII() {
4061 S.ActOnFinishOfCompoundStmt();
4062 }
4063
4064 private:
4065 Sema &S;
4066 };
4067
4068 /// An RAII helper that pops function a function scope on exit.
4069 struct FunctionScopeRAII {
4070 Sema &S;
4071 bool Active;
4072 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
4073 ~FunctionScopeRAII() {
4074 if (Active)
4075 S.PopFunctionScopeInfo();
4076 }
4077 void disable() { Active = false; }
4078 };
4079
4080 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4081 SourceLocation StartLoc,
4082 SourceLocation EndLoc);
4083 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4084 StmtResult ActOnForEachLValueExpr(Expr *E);
4085 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4086 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4087 SourceLocation DotDotDotLoc, ExprResult RHS,
4088 SourceLocation ColonLoc);
4089 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4090
4091 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4092 SourceLocation ColonLoc,
4093 Stmt *SubStmt, Scope *CurScope);
4094 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4095 SourceLocation ColonLoc, Stmt *SubStmt);
4096
4097 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
4098 ArrayRef<const Attr*> Attrs,
4099 Stmt *SubStmt);
4100
4101 class ConditionResult;
4102 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4103 Stmt *InitStmt,
4104 ConditionResult Cond, Stmt *ThenVal,
4105 SourceLocation ElseLoc, Stmt *ElseVal);
4106 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4107 Stmt *InitStmt,
4108 ConditionResult Cond, Stmt *ThenVal,
4109 SourceLocation ElseLoc, Stmt *ElseVal);
4110 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4111 Stmt *InitStmt,
4112 ConditionResult Cond);
4113 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4114 Stmt *Switch, Stmt *Body);
4115 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
4116 Stmt *Body);
4117 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4118 SourceLocation WhileLoc, SourceLocation CondLParen,
4119 Expr *Cond, SourceLocation CondRParen);
4120
4121 StmtResult ActOnForStmt(SourceLocation ForLoc,
4122 SourceLocation LParenLoc,
4123 Stmt *First,
4124 ConditionResult Second,
4125 FullExprArg Third,
4126 SourceLocation RParenLoc,
4127 Stmt *Body);
4128 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4129 Expr *collection);
4130 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4131 Stmt *First, Expr *collection,
4132 SourceLocation RParenLoc);
4133 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4134
4135 enum BuildForRangeKind {
4136 /// Initial building of a for-range statement.
4137 BFRK_Build,
4138 /// Instantiation or recovery rebuild of a for-range statement. Don't
4139 /// attempt any typo-correction.
4140 BFRK_Rebuild,
4141 /// Determining whether a for-range statement could be built. Avoid any
4142 /// unnecessary or irreversible actions.
4143 BFRK_Check
4144 };
4145
4146 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4147 SourceLocation CoawaitLoc,
4148 Stmt *InitStmt,
4149 Stmt *LoopVar,
4150 SourceLocation ColonLoc, Expr *Collection,
4151 SourceLocation RParenLoc,
4152 BuildForRangeKind Kind);
4153 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4154 SourceLocation CoawaitLoc,
4155 Stmt *InitStmt,
4156 SourceLocation ColonLoc,
4157 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4158 Expr *Cond, Expr *Inc,
4159 Stmt *LoopVarDecl,
4160 SourceLocation RParenLoc,
4161 BuildForRangeKind Kind);
4162 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
4163
4164 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
4165 SourceLocation LabelLoc,
4166 LabelDecl *TheDecl);
4167 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
4168 SourceLocation StarLoc,
4169 Expr *DestExp);
4170 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
4171 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
4172
4173 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4174 CapturedRegionKind Kind, unsigned NumParams);
4175 typedef std::pair<StringRef, QualType> CapturedParamNameType;
4176 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4177 CapturedRegionKind Kind,
4178 ArrayRef<CapturedParamNameType> Params,
4179 unsigned OpenMPCaptureLevel = 0);
4180 StmtResult ActOnCapturedRegionEnd(Stmt *S);
4181 void ActOnCapturedRegionError();
4182 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
4183 SourceLocation Loc,
4184 unsigned NumParams);
4185
4186 enum CopyElisionSemanticsKind {
4187 CES_Strict = 0,
4188 CES_AllowParameters = 1,
4189 CES_AllowDifferentTypes = 2,
4190 CES_AllowExceptionVariables = 4,
4191 CES_FormerDefault = (CES_AllowParameters),
4192 CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
4193 CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
4194 CES_AllowExceptionVariables),
4195 };
4196
4197 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
4198 CopyElisionSemanticsKind CESK);
4199 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
4200 CopyElisionSemanticsKind CESK);
4201
4202 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4203 Scope *CurScope);
4204 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4205 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4206
4207 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4208 bool IsVolatile, unsigned NumOutputs,
4209 unsigned NumInputs, IdentifierInfo **Names,
4210 MultiExprArg Constraints, MultiExprArg Exprs,
4211 Expr *AsmString, MultiExprArg Clobbers,
4212 unsigned NumLabels,
4213 SourceLocation RParenLoc);
4214
4215 void FillInlineAsmIdentifierInfo(Expr *Res,
4216 llvm::InlineAsmIdentifierInfo &Info);
4217 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4218 SourceLocation TemplateKWLoc,
4219 UnqualifiedId &Id,
4220 bool IsUnevaluatedContext);
4221 bool LookupInlineAsmField(StringRef Base, StringRef Member,
4222 unsigned &Offset, SourceLocation AsmLoc);
4223 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4224 SourceLocation AsmLoc);
4225 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4226 ArrayRef<Token> AsmToks,
4227 StringRef AsmString,
4228 unsigned NumOutputs, unsigned NumInputs,
4229 ArrayRef<StringRef> Constraints,
4230 ArrayRef<StringRef> Clobbers,
4231 ArrayRef<Expr*> Exprs,
4232 SourceLocation EndLoc);
4233 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4234 SourceLocation Location,
4235 bool AlwaysCreate);
4236
4237 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4238 SourceLocation StartLoc,
4239 SourceLocation IdLoc, IdentifierInfo *Id,
4240 bool Invalid = false);
4241
4242 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4243
4244 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4245 Decl *Parm, Stmt *Body);
4246
4247 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
4248
4249 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4250 MultiStmtArg Catch, Stmt *Finally);
4251
4252 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
4253 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4254 Scope *CurScope);
4255 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
4256 Expr *operand);
4257 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
4258 Expr *SynchExpr,
4259 Stmt *SynchBody);
4260
4261 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
4262
4263 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
4264 SourceLocation StartLoc,
4265 SourceLocation IdLoc,
4266 IdentifierInfo *Id);
4267
4268 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
4269
4270 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
4271 Decl *ExDecl, Stmt *HandlerBlock);
4272 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4273 ArrayRef<Stmt *> Handlers);
4274
4275 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
4276 SourceLocation TryLoc, Stmt *TryBlock,
4277 Stmt *Handler);
4278 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
4279 Expr *FilterExpr,
4280 Stmt *Block);
4281 void ActOnStartSEHFinallyBlock();
4282 void ActOnAbortSEHFinallyBlock();
4283 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
4284 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
4285
4286 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
4287
4288 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4289
4290 /// If it's a file scoped decl that must warn if not used, keep track
4291 /// of it.
4292 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4293
4294 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
4295 /// whose result is unused, warn.
4296 void DiagnoseUnusedExprResult(const Stmt *S);
4297 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4298 void DiagnoseUnusedDecl(const NamedDecl *ND);
4299
4300 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
4301 /// statement as a \p Body, and it is located on the same line.
4302 ///
4303 /// This helps prevent bugs due to typos, such as:
4304 /// if (condition);
4305 /// do_stuff();
4306 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4307 const Stmt *Body,
4308 unsigned DiagID);
4309
4310 /// Warn if a for/while loop statement \p S, which is followed by
4311 /// \p PossibleBody, has a suspicious null statement as a body.
4312 void DiagnoseEmptyLoopBody(const Stmt *S,
4313 const Stmt *PossibleBody);
4314
4315 /// Warn if a value is moved to itself.
4316 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
4317 SourceLocation OpLoc);
4318
4319 /// Warn if we're implicitly casting from a _Nullable pointer type to a
4320 /// _Nonnull one.
4321 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
4322 SourceLocation Loc);
4323
4324 /// Warn when implicitly casting 0 to nullptr.
4325 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
4326
4327 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
4328 return DelayedDiagnostics.push(pool);
4329 }
4330 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
4331
4332 typedef ProcessingContextState ParsingClassState;
4333 ParsingClassState PushParsingClass() {
4334 return DelayedDiagnostics.pushUndelayed();
4335 }
4336 void PopParsingClass(ParsingClassState state) {
4337 DelayedDiagnostics.popUndelayed(state);
4338 }
4339
4340 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
4341
4342 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4343 const ObjCInterfaceDecl *UnknownObjCClass,
4344 bool ObjCPropertyAccess,
4345 bool AvoidPartialAvailabilityChecks = false,
4346 ObjCInterfaceDecl *ClassReceiver = nullptr);
4347
4348 bool makeUnavailableInSystemHeader(SourceLocation loc,
4349 UnavailableAttr::ImplicitReason reason);
4350
4351 /// Issue any -Wunguarded-availability warnings in \c FD
4352 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
4353
4354 //===--------------------------------------------------------------------===//
4355 // Expression Parsing Callbacks: SemaExpr.cpp.
4356
4357 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4358 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4359 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4360 bool ObjCPropertyAccess = false,
4361 bool AvoidPartialAvailabilityChecks = false,
4362 ObjCInterfaceDecl *ClassReciever = nullptr);
4363 void NoteDeletedFunction(FunctionDecl *FD);
4364 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
4365 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
4366 ObjCMethodDecl *Getter,
4367 SourceLocation Loc);
4368 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
4369 ArrayRef<Expr *> Args);
4370
4371 void PushExpressionEvaluationContext(
4372 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
4373 ExpressionEvaluationContextRecord::ExpressionKind Type =
4374 ExpressionEvaluationContextRecord::EK_Other);
4375 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
4376 void PushExpressionEvaluationContext(
4377 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
4378 ExpressionEvaluationContextRecord::ExpressionKind Type =
4379 ExpressionEvaluationContextRecord::EK_Other);
4380 void PopExpressionEvaluationContext();
4381
4382 void DiscardCleanupsInEvaluationContext();
4383
4384 ExprResult TransformToPotentiallyEvaluated(Expr *E);
4385 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
4386
4387 ExprResult CheckUnevaluatedOperand(Expr *E);
4388 void CheckUnusedVolatileAssignment(Expr *E);
4389
4390 ExprResult ActOnConstantExpression(ExprResult Res);
4391
4392 // Functions for marking a declaration referenced. These functions also
4393 // contain the relevant logic for marking if a reference to a function or
4394 // variable is an odr-use (in the C++11 sense). There are separate variants
4395 // for expressions referring to a decl; these exist because odr-use marking
4396 // needs to be delayed for some constant variables when we build one of the
4397 // named expressions.
4398 //
4399 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4400 // should usually be true. This only needs to be set to false if the lack of
4401 // odr-use cannot be determined from the current context (for instance,
4402 // because the name denotes a virtual function and was written without an
4403 // explicit nested-name-specifier).
4404 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4405 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4406 bool MightBeOdrUse = true);
4407 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4408 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4409 void MarkMemberReferenced(MemberExpr *E);
4410 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
4411 void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
4412 unsigned CapturingScopeIndex);
4413
4414 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
4415 void CleanupVarDeclMarking();
4416
4417 enum TryCaptureKind {
4418 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4419 };
4420
4421 /// Try to capture the given variable.
4422 ///
4423 /// \param Var The variable to capture.
4424 ///
4425 /// \param Loc The location at which the capture occurs.
4426 ///
4427 /// \param Kind The kind of capture, which may be implicit (for either a
4428 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4429 ///
4430 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4431 /// an explicit lambda capture.
4432 ///
4433 /// \param BuildAndDiagnose Whether we are actually supposed to add the
4434 /// captures or diagnose errors. If false, this routine merely check whether
4435 /// the capture can occur without performing the capture itself or complaining
4436 /// if the variable cannot be captured.
4437 ///
4438 /// \param CaptureType Will be set to the type of the field used to capture
4439 /// this variable in the innermost block or lambda. Only valid when the
4440 /// variable can be captured.
4441 ///
4442 /// \param DeclRefType Will be set to the type of a reference to the capture
4443 /// from within the current scope. Only valid when the variable can be
4444 /// captured.
4445 ///
4446 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4447 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4448 /// This is useful when enclosing lambdas must speculatively capture
4449 /// variables that may or may not be used in certain specializations of
4450 /// a nested generic lambda.
4451 ///
4452 /// \returns true if an error occurred (i.e., the variable cannot be
4453 /// captured) and false if the capture succeeded.
4454 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4455 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4456 QualType &CaptureType,
4457 QualType &DeclRefType,
4458 const unsigned *const FunctionScopeIndexToStopAt);
4459
4460 /// Try to capture the given variable.
4461 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4462 TryCaptureKind Kind = TryCapture_Implicit,
4463 SourceLocation EllipsisLoc = SourceLocation());
4464
4465 /// Checks if the variable must be captured.
4466 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4467
4468 /// Given a variable, determine the type that a reference to that
4469 /// variable will have in the given scope.
4470 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4471
4472 /// Mark all of the declarations referenced within a particular AST node as
4473 /// referenced. Used when template instantiation instantiates a non-dependent
4474 /// type -- entities referenced by the type are now referenced.
4475 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4476 void MarkDeclarationsReferencedInExpr(Expr *E,
4477 bool SkipLocalVariables = false);
4478
4479 /// Try to recover by turning the given expression into a
4480 /// call. Returns true if recovery was attempted or an error was
4481 /// emitted; this may also leave the ExprResult invalid.
4482 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4483 bool ForceComplain = false,
4484 bool (*IsPlausibleResult)(QualType) = nullptr);
4485
4486 /// Figure out if an expression could be turned into a call.
4487 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4488 UnresolvedSetImpl &NonTemplateOverloads);
4489
4490 /// Conditionally issue a diagnostic based on the current
4491 /// evaluation context.
4492 ///
4493 /// \param Statement If Statement is non-null, delay reporting the
4494 /// diagnostic until the function body is parsed, and then do a basic
4495 /// reachability analysis to determine if the statement is reachable.
4496 /// If it is unreachable, the diagnostic will not be emitted.
4497 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4498 const PartialDiagnostic &PD);
4499 /// Similar, but diagnostic is only produced if all the specified statements
4500 /// are reachable.
4501 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
4502 const PartialDiagnostic &PD);
4503
4504 // Primary Expressions.
4505 SourceRange getExprRange(Expr *E) const;
4506
4507 ExprResult ActOnIdExpression(
4508 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4509 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4510 CorrectionCandidateCallback *CCC = nullptr,
4511 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4512
4513 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4514 TemplateArgumentListInfo &Buffer,
4515 DeclarationNameInfo &NameInfo,
4516 const TemplateArgumentListInfo *&TemplateArgs);
4517
4518 bool
4519 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4520 CorrectionCandidateCallback &CCC,
4521 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4522 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4523
4524 DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
4525 IdentifierInfo *II);
4526 ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
4527
4528 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4529 IdentifierInfo *II,
4530 bool AllowBuiltinCreation=false);
4531
4532 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4533 SourceLocation TemplateKWLoc,
4534 const DeclarationNameInfo &NameInfo,
4535 bool isAddressOfOperand,
4536 const TemplateArgumentListInfo *TemplateArgs);
4537
4538 /// If \p D cannot be odr-used in the current expression evaluation context,
4539 /// return a reason explaining why. Otherwise, return NOUR_None.
4540 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
4541
4542 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4543 SourceLocation Loc,
4544 const CXXScopeSpec *SS = nullptr);
4545 DeclRefExpr *
4546 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4547 const DeclarationNameInfo &NameInfo,
4548 const CXXScopeSpec *SS = nullptr,
4549 NamedDecl *FoundD = nullptr,
4550 SourceLocation TemplateKWLoc = SourceLocation(),
4551 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4552 DeclRefExpr *
4553 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4554 const DeclarationNameInfo &NameInfo,
4555 NestedNameSpecifierLoc NNS,
4556 NamedDecl *FoundD = nullptr,
4557 SourceLocation TemplateKWLoc = SourceLocation(),
4558 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4559
4560 ExprResult
4561 BuildAnonymousStructUnionMemberReference(
4562 const CXXScopeSpec &SS,
4563 SourceLocation nameLoc,
4564 IndirectFieldDecl *indirectField,
4565 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4566 Expr *baseObjectExpr = nullptr,
4567 SourceLocation opLoc = SourceLocation());
4568
4569 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4570 SourceLocation TemplateKWLoc,
4571 LookupResult &R,
4572 const TemplateArgumentListInfo *TemplateArgs,
4573 const Scope *S);
4574 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4575 SourceLocation TemplateKWLoc,
4576 LookupResult &R,
4577 const TemplateArgumentListInfo *TemplateArgs,
4578 bool IsDefiniteInstance,
4579 const Scope *S);
4580 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4581 const LookupResult &R,
4582 bool HasTrailingLParen);
4583
4584 ExprResult
4585 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4586 const DeclarationNameInfo &NameInfo,
4587 bool IsAddressOfOperand, const Scope *S,
4588 TypeSourceInfo **RecoveryTSI = nullptr);
4589
4590 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4591 SourceLocation TemplateKWLoc,
4592 const DeclarationNameInfo &NameInfo,
4593 const TemplateArgumentListInfo *TemplateArgs);
4594
4595 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4596 LookupResult &R,
4597 bool NeedsADL,
4598 bool AcceptInvalidDecl = false);
4599 ExprResult BuildDeclarationNameExpr(
4600 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4601 NamedDecl *FoundD = nullptr,
4602 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4603 bool AcceptInvalidDecl = false);
4604
4605 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4606 DeclarationNameInfo &SuffixInfo,
4607 ArrayRef<Expr *> Args,
4608 SourceLocation LitEndLoc,
4609 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4610
4611 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4612 PredefinedExpr::IdentKind IK);
4613 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4614 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4615
4616 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4617
4618 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4619 ExprResult ActOnCharacterConstant(const Token &Tok,
4620 Scope *UDLScope = nullptr);
4621 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4622 ExprResult ActOnParenListExpr(SourceLocation L,
4623 SourceLocation R,
4624 MultiExprArg Val);
4625
4626 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4627 /// fragments (e.g. "foo" "bar" L"baz").
4628 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4629 Scope *UDLScope = nullptr);
4630
4631 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4632 SourceLocation DefaultLoc,
4633 SourceLocation RParenLoc,
4634 Expr *ControllingExpr,
4635 ArrayRef<ParsedType> ArgTypes,
4636 ArrayRef<Expr *> ArgExprs);
4637 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4638 SourceLocation DefaultLoc,
4639 SourceLocation RParenLoc,
4640 Expr *ControllingExpr,
4641 ArrayRef<TypeSourceInfo *> Types,
4642 ArrayRef<Expr *> Exprs);
4643
4644 // Binary/Unary Operators. 'Tok' is the token for the operator.
4645 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4646 Expr *InputExpr);
4647 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4648 UnaryOperatorKind Opc, Expr *Input);
4649 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4650 tok::TokenKind Op, Expr *Input);
4651
4652 bool isQualifiedMemberAccess(Expr *E);
4653 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4654
4655 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4656 SourceLocation OpLoc,
4657 UnaryExprOrTypeTrait ExprKind,
4658 SourceRange R);
4659 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4660 UnaryExprOrTypeTrait ExprKind);
4661 ExprResult
4662 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4663 UnaryExprOrTypeTrait ExprKind,
4664 bool IsType, void *TyOrEx,
4665 SourceRange ArgRange);
4666
4667 ExprResult CheckPlaceholderExpr(Expr *E);
4668 bool CheckVecStepExpr(Expr *E);
4669
4670 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4671 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4672 SourceRange ExprRange,
4673 UnaryExprOrTypeTrait ExprKind);
4674 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4675 SourceLocation OpLoc,
4676 IdentifierInfo &Name,
4677 SourceLocation NameLoc,
4678 SourceLocation RParenLoc);
4679 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4680 tok::TokenKind Kind, Expr *Input);
4681
4682 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4683 Expr *Idx, SourceLocation RLoc);
4684 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4685 Expr *Idx, SourceLocation RLoc);
4686 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4687 Expr *LowerBound, SourceLocation ColonLoc,
4688 Expr *Length, SourceLocation RBLoc);
4689
4690 // This struct is for use by ActOnMemberAccess to allow
4691 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4692 // changing the access operator from a '.' to a '->' (to see if that is the
4693 // change needed to fix an error about an unknown member, e.g. when the class
4694 // defines a custom operator->).
4695 struct ActOnMemberAccessExtraArgs {
4696 Scope *S;
4697 UnqualifiedId &Id;
4698 Decl *ObjCImpDecl;
4699 };
4700
4701 ExprResult BuildMemberReferenceExpr(
4702 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4703 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4704 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4705 const TemplateArgumentListInfo *TemplateArgs,
4706 const Scope *S,
4707 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4708
4709 ExprResult
4710 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4711 bool IsArrow, const CXXScopeSpec &SS,
4712 SourceLocation TemplateKWLoc,
4713 NamedDecl *FirstQualifierInScope, LookupResult &R,
4714 const TemplateArgumentListInfo *TemplateArgs,
4715 const Scope *S,
4716 bool SuppressQualifierCheck = false,
4717 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4718
4719 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4720 SourceLocation OpLoc,
4721 const CXXScopeSpec &SS, FieldDecl *Field,
4722 DeclAccessPair FoundDecl,
4723 const DeclarationNameInfo &MemberNameInfo);
4724
4725 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4726
4727 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4728 const CXXScopeSpec &SS,
4729 const LookupResult &R);
4730
4731 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4732 bool IsArrow, SourceLocation OpLoc,
4733 const CXXScopeSpec &SS,
4734 SourceLocation TemplateKWLoc,
4735 NamedDecl *FirstQualifierInScope,
4736 const DeclarationNameInfo &NameInfo,
4737 const TemplateArgumentListInfo *TemplateArgs);
4738
4739 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4740 SourceLocation OpLoc,
4741 tok::TokenKind OpKind,
4742 CXXScopeSpec &SS,
4743 SourceLocation TemplateKWLoc,
4744 UnqualifiedId &Member,
4745 Decl *ObjCImpDecl);
4746
4747 MemberExpr *
4748 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4749 const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
4750 ValueDecl *Member, DeclAccessPair FoundDecl,
4751 bool HadMultipleCandidates,
4752 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4753 ExprValueKind VK, ExprObjectKind OK,
4754 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4755 MemberExpr *
4756 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4757 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
4758 ValueDecl *Member, DeclAccessPair FoundDecl,
4759 bool HadMultipleCandidates,
4760 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4761 ExprValueKind VK, ExprObjectKind OK,
4762 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4763
4764 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4765 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4766 FunctionDecl *FDecl,
4767 const FunctionProtoType *Proto,
4768 ArrayRef<Expr *> Args,
4769 SourceLocation RParenLoc,
4770 bool ExecConfig = false);
4771 void CheckStaticArrayArgument(SourceLocation CallLoc,
4772 ParmVarDecl *Param,
4773 const Expr *ArgExpr);
4774
4775 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4776 /// This provides the location of the left/right parens and a list of comma
4777 /// locations.
4778 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4779 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4780 Expr *ExecConfig = nullptr);
4781 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4782 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4783 Expr *ExecConfig = nullptr,
4784 bool IsExecConfig = false);
4785 enum class AtomicArgumentOrder { API, AST };
4786 ExprResult
4787 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4788 SourceLocation RParenLoc, MultiExprArg Args,
4789 AtomicExpr::AtomicOp Op,
4790 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
4791 ExprResult
4792 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
4793 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
4794 Expr *Config = nullptr, bool IsExecConfig = false,
4795 ADLCallKind UsesADL = ADLCallKind::NotADL);
4796
4797 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4798 MultiExprArg ExecConfig,
4799 SourceLocation GGGLoc);
4800
4801 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4802 Declarator &D, ParsedType &Ty,
4803 SourceLocation RParenLoc, Expr *CastExpr);
4804 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4805 TypeSourceInfo *Ty,
4806 SourceLocation RParenLoc,
4807 Expr *Op);
4808 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4809
4810 /// Build an altivec or OpenCL literal.
4811 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4812 SourceLocation RParenLoc, Expr *E,
4813 TypeSourceInfo *TInfo);
4814
4815 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4816
4817 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4818 ParsedType Ty,
4819 SourceLocation RParenLoc,
4820 Expr *InitExpr);
4821
4822 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4823 TypeSourceInfo *TInfo,
4824 SourceLocation RParenLoc,
4825 Expr *LiteralExpr);
4826
4827 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4828 MultiExprArg InitArgList,
4829 SourceLocation RBraceLoc);
4830
4831 ExprResult BuildInitList(SourceLocation LBraceLoc,
4832 MultiExprArg InitArgList,
4833 SourceLocation RBraceLoc);
4834
4835 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4836 SourceLocation EqualOrColonLoc,
4837 bool GNUSyntax,
4838 ExprResult Init);
4839
4840private:
4841 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4842
4843public:
4844 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4845 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4846 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4847 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4848 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4849 Expr *LHSExpr, Expr *RHSExpr);
4850
4851 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4852
4853 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4854 /// in the case of a the GNU conditional expr extension.
4855 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4856 SourceLocation ColonLoc,
4857 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4858
4859 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4860 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4861 LabelDecl *TheDecl);
4862
4863 void ActOnStartStmtExpr();
4864 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4865 SourceLocation RPLoc); // "({..})"
4866 // Handle the final expression in a statement expression.
4867 ExprResult ActOnStmtExprResult(ExprResult E);
4868 void ActOnStmtExprError();
4869
4870 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4871 struct OffsetOfComponent {
4872 SourceLocation LocStart, LocEnd;
4873 bool isBrackets; // true if [expr], false if .ident
4874 union {
4875 IdentifierInfo *IdentInfo;
4876 Expr *E;
4877 } U;
4878 };
4879
4880 /// __builtin_offsetof(type, a.b[123][456].c)
4881 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4882 TypeSourceInfo *TInfo,
4883 ArrayRef<OffsetOfComponent> Components,
4884 SourceLocation RParenLoc);
4885 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4886 SourceLocation BuiltinLoc,
4887 SourceLocation TypeLoc,
4888 ParsedType ParsedArgTy,
4889 ArrayRef<OffsetOfComponent> Components,
4890 SourceLocation RParenLoc);
4891
4892 // __builtin_choose_expr(constExpr, expr1, expr2)
4893 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4894 Expr *CondExpr, Expr *LHSExpr,
4895 Expr *RHSExpr, SourceLocation RPLoc);
4896
4897 // __builtin_va_arg(expr, type)
4898 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4899 SourceLocation RPLoc);
4900 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4901 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4902
4903 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
4904 // __builtin_COLUMN()
4905 ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
4906 SourceLocation BuiltinLoc,
4907 SourceLocation RPLoc);
4908
4909 // Build a potentially resolved SourceLocExpr.
4910 ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
4911 SourceLocation BuiltinLoc, SourceLocation RPLoc,
4912 DeclContext *ParentContext);
4913
4914 // __null
4915 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4916
4917 bool CheckCaseExpression(Expr *E);
4918
4919 /// Describes the result of an "if-exists" condition check.
4920 enum IfExistsResult {
4921 /// The symbol exists.
4922 IER_Exists,
4923
4924 /// The symbol does not exist.
4925 IER_DoesNotExist,
4926
4927 /// The name is a dependent name, so the results will differ
4928 /// from one instantiation to the next.
4929 IER_Dependent,
4930
4931 /// An error occurred.
4932 IER_Error
4933 };
4934
4935 IfExistsResult
4936 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4937 const DeclarationNameInfo &TargetNameInfo);
4938
4939 IfExistsResult
4940 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4941 bool IsIfExists, CXXScopeSpec &SS,
4942 UnqualifiedId &Name);
4943
4944 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4945 bool IsIfExists,
4946 NestedNameSpecifierLoc QualifierLoc,
4947 DeclarationNameInfo NameInfo,
4948 Stmt *Nested);
4949 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4950 bool IsIfExists,
4951 CXXScopeSpec &SS, UnqualifiedId &Name,
4952 Stmt *Nested);
4953
4954 //===------------------------- "Block" Extension ------------------------===//
4955
4956 /// ActOnBlockStart - This callback is invoked when a block literal is
4957 /// started.
4958 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4959
4960 /// ActOnBlockArguments - This callback allows processing of block arguments.
4961 /// If there are no arguments, this is still invoked.
4962 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4963 Scope *CurScope);
4964
4965 /// ActOnBlockError - If there is an error parsing a block, this callback
4966 /// is invoked to pop the information about the block from the action impl.
4967 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4968
4969 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4970 /// literal was successfully completed. ^(int x){...}
4971 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4972 Scope *CurScope);
4973
4974 //===---------------------------- Clang Extensions ----------------------===//
4975
4976 /// __builtin_convertvector(...)
4977 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4978 SourceLocation BuiltinLoc,
4979 SourceLocation RParenLoc);
4980
4981 //===---------------------------- OpenCL Features -----------------------===//
4982
4983 /// __builtin_astype(...)
4984 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4985 SourceLocation BuiltinLoc,
4986 SourceLocation RParenLoc);
4987
4988 //===---------------------------- C++ Features --------------------------===//
4989
4990 // Act on C++ namespaces
4991 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4992 SourceLocation NamespaceLoc,
4993 SourceLocation IdentLoc, IdentifierInfo *Ident,
4994 SourceLocation LBrace,
4995 const ParsedAttributesView &AttrList,
4996 UsingDirectiveDecl *&UsingDecl);
4997 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4998
4999 NamespaceDecl *getStdNamespace() const;
5000 NamespaceDecl *getOrCreateStdNamespace();
5001
5002 NamespaceDecl *lookupStdExperimentalNamespace();
5003
5004 CXXRecordDecl *getStdBadAlloc() const;
5005 EnumDecl *getStdAlignValT() const;
5006
5007private:
5008 // A cache representing if we've fully checked the various comparison category
5009 // types stored in ASTContext. The bit-index corresponds to the integer value
5010 // of a ComparisonCategoryType enumerator.
5011 llvm::SmallBitVector FullyCheckedComparisonCategories;
5012
5013 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
5014 CXXScopeSpec &SS,
5015 ParsedType TemplateTypeTy,
5016 IdentifierInfo *MemberOrBase);
5017
5018public:
5019 /// Lookup the specified comparison category types in the standard
5020 /// library, an check the VarDecls possibly returned by the operator<=>
5021 /// builtins for that type.
5022 ///
5023 /// \return The type of the comparison category type corresponding to the
5024 /// specified Kind, or a null type if an error occurs
5025 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5026 SourceLocation Loc);
5027
5028 /// Tests whether Ty is an instance of std::initializer_list and, if
5029 /// it is and Element is not NULL, assigns the element type to Element.
5030 bool isStdInitializerList(QualType Ty, QualType *Element);
5031
5032 /// Looks for the std::initializer_list template and instantiates it
5033 /// with Element, or emits an error if it's not found.
5034 ///
5035 /// \returns The instantiated template, or null on error.
5036 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5037
5038 /// Determine whether Ctor is an initializer-list constructor, as
5039 /// defined in [dcl.init.list]p2.
5040 bool isInitListConstructor(const FunctionDecl *Ctor);
5041
5042 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5043 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5044 SourceLocation IdentLoc,
5045 IdentifierInfo *NamespcName,
5046 const ParsedAttributesView &AttrList);
5047
5048 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5049
5050 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
5051 SourceLocation NamespaceLoc,
5052 SourceLocation AliasLoc,
5053 IdentifierInfo *Alias,
5054 CXXScopeSpec &SS,
5055 SourceLocation IdentLoc,
5056 IdentifierInfo *Ident);
5057
5058 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5059 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
5060 const LookupResult &PreviousDecls,
5061 UsingShadowDecl *&PrevShadow);
5062 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
5063 NamedDecl *Target,
5064 UsingShadowDecl *PrevDecl);
5065
5066 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5067 bool HasTypenameKeyword,
5068 const CXXScopeSpec &SS,
5069 SourceLocation NameLoc,
5070 const LookupResult &Previous);
5071 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
5072 bool HasTypename,
5073 const CXXScopeSpec &SS,
5074 const DeclarationNameInfo &NameInfo,
5075 SourceLocation NameLoc);
5076
5077 NamedDecl *BuildUsingDeclaration(
5078 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
5079 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
5080 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
5081 const ParsedAttributesView &AttrList, bool IsInstantiation);
5082 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5083 ArrayRef<NamedDecl *> Expansions);
5084
5085 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5086
5087 /// Given a derived-class using shadow declaration for a constructor and the
5088 /// correspnding base class constructor, find or create the implicit
5089 /// synthesized derived class constructor to use for this initialization.
5090 CXXConstructorDecl *
5091 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5092 ConstructorUsingShadowDecl *DerivedShadow);
5093
5094 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5095 SourceLocation UsingLoc,
5096 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5097 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5098 const ParsedAttributesView &AttrList);
5099 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5100 MultiTemplateParamsArg TemplateParams,
5101 SourceLocation UsingLoc, UnqualifiedId &Name,
5102 const ParsedAttributesView &AttrList,
5103 TypeResult Type, Decl *DeclFromDeclSpec);
5104
5105 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5106 /// including handling of its default argument expressions.
5107 ///
5108 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5109 ExprResult
5110 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5111 NamedDecl *FoundDecl,
5112 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5113 bool HadMultipleCandidates, bool IsListInitialization,
5114 bool IsStdInitListInitialization,
5115 bool RequiresZeroInit, unsigned ConstructKind,
5116 SourceRange ParenRange);
5117
5118 /// Build a CXXConstructExpr whose constructor has already been resolved if
5119 /// it denotes an inherited constructor.
5120 ExprResult
5121 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5122 CXXConstructorDecl *Constructor, bool Elidable,
5123 MultiExprArg Exprs,
5124 bool HadMultipleCandidates, bool IsListInitialization,
5125 bool IsStdInitListInitialization,
5126 bool RequiresZeroInit, unsigned ConstructKind,
5127 SourceRange ParenRange);
5128
5129 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5130 // the constructor can be elidable?
5131 ExprResult
5132 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5133 NamedDecl *FoundDecl,
5134 CXXConstructorDecl *Constructor, bool Elidable,
5135 MultiExprArg Exprs, bool HadMultipleCandidates,
5136 bool IsListInitialization,
5137 bool IsStdInitListInitialization, bool RequiresZeroInit,
5138 unsigned ConstructKind, SourceRange ParenRange);
5139
5140 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
5141
5142
5143 /// Instantiate or parse a C++ default argument expression as necessary.
5144 /// Return true on error.
5145 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5146 ParmVarDecl *Param);
5147
5148 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
5149 /// the default expr if needed.
5150 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5151 FunctionDecl *FD,
5152 ParmVarDecl *Param);
5153
5154 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5155 /// constructed variable.
5156 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
5157
5158 /// Helper class that collects exception specifications for
5159 /// implicitly-declared special member functions.
5160 class ImplicitExceptionSpecification {
5161 // Pointer to allow copying
5162 Sema *Self;
5163 // We order exception specifications thus:
5164 // noexcept is the most restrictive, but is only used in C++11.
5165 // throw() comes next.
5166 // Then a throw(collected exceptions)
5167 // Finally no specification, which is expressed as noexcept(false).
5168 // throw(...) is used instead if any called function uses it.
5169 ExceptionSpecificationType ComputedEST;
5170 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5171 SmallVector<QualType, 4> Exceptions;
5172
5173 void ClearExceptions() {
5174 ExceptionsSeen.clear();
5175 Exceptions.clear();
5176 }
5177
5178 public:
5179 explicit ImplicitExceptionSpecification(Sema &Self)
5180 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5181 if (!Self.getLangOpts().CPlusPlus11)
5182 ComputedEST = EST_DynamicNone;
5183 }
5184
5185 /// Get the computed exception specification type.
5186 ExceptionSpecificationType getExceptionSpecType() const {
5187 assert(!isComputedNoexcept(ComputedEST) &&((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 5188, __PRETTY_FUNCTION__))
5188 "noexcept(expr) should not be a possible result")((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 5188, __PRETTY_FUNCTION__))
;
5189 return ComputedEST;
5190 }
5191
5192 /// The number of exceptions in the exception specification.
5193 unsigned size() const { return Exceptions.size(); }
5194
5195 /// The set of exceptions in the exception specification.
5196 const QualType *data() const { return Exceptions.data(); }
5197
5198 /// Integrate another called method into the collected data.
5199 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5200
5201 /// Integrate an invoked expression into the collected data.
5202 void CalledExpr(Expr *E);
5203
5204 /// Overwrite an EPI's exception specification with this
5205 /// computed exception specification.
5206 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5207 FunctionProtoType::ExceptionSpecInfo ESI;
5208 ESI.Type = getExceptionSpecType();
5209 if (ESI.Type == EST_Dynamic) {
5210 ESI.Exceptions = Exceptions;
5211 } else if (ESI.Type == EST_None) {
5212 /// C++11 [except.spec]p14:
5213 /// The exception-specification is noexcept(false) if the set of
5214 /// potential exceptions of the special member function contains "any"
5215 ESI.Type = EST_NoexceptFalse;
5216 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
5217 tok::kw_false).get();
5218 }
5219 return ESI;
5220 }
5221 };
5222
5223 /// Determine what sort of exception specification a defaulted
5224 /// copy constructor of a class will have.
5225 ImplicitExceptionSpecification
5226 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
5227 CXXMethodDecl *MD);
5228
5229 /// Determine what sort of exception specification a defaulted
5230 /// default constructor of a class will have, and whether the parameter
5231 /// will be const.
5232 ImplicitExceptionSpecification
5233 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
5234
5235 /// Determine what sort of exception specification a defaulted
5236 /// copy assignment operator of a class will have, and whether the
5237 /// parameter will be const.
5238 ImplicitExceptionSpecification
5239 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
5240
5241 /// Determine what sort of exception specification a defaulted move
5242 /// constructor of a class will have.
5243 ImplicitExceptionSpecification
5244 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
5245
5246 /// Determine what sort of exception specification a defaulted move
5247 /// assignment operator of a class will have.
5248 ImplicitExceptionSpecification
5249 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
5250
5251 /// Determine what sort of exception specification a defaulted
5252 /// destructor of a class will have.
5253 ImplicitExceptionSpecification
5254 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
5255
5256 /// Determine what sort of exception specification an inheriting
5257 /// constructor of a class will have.
5258 ImplicitExceptionSpecification
5259 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
5260 CXXConstructorDecl *CD);
5261
5262 /// Evaluate the implicit exception specification for a defaulted
5263 /// special member function.
5264 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
5265
5266 /// Check the given noexcept-specifier, convert its expression, and compute
5267 /// the appropriate ExceptionSpecificationType.
5268 ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
5269 ExceptionSpecificationType &EST);
5270
5271 /// Check the given exception-specification and update the
5272 /// exception specification information with the results.
5273 void checkExceptionSpecification(bool IsTopLevel,
5274 ExceptionSpecificationType EST,
5275 ArrayRef<ParsedType> DynamicExceptions,
5276 ArrayRef<SourceRange> DynamicExceptionRanges,
5277 Expr *NoexceptExpr,
5278 SmallVectorImpl<QualType> &Exceptions,
5279 FunctionProtoType::ExceptionSpecInfo &ESI);
5280
5281 /// Determine if we're in a case where we need to (incorrectly) eagerly
5282 /// parse an exception specification to work around a libstdc++ bug.
5283 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
5284
5285 /// Add an exception-specification to the given member function
5286 /// (or member function template). The exception-specification was parsed
5287 /// after the method itself was declared.
5288 void actOnDelayedExceptionSpecification(Decl *Method,
5289 ExceptionSpecificationType EST,
5290 SourceRange SpecificationRange,
5291 ArrayRef<ParsedType> DynamicExceptions,
5292 ArrayRef<SourceRange> DynamicExceptionRanges,
5293 Expr *NoexceptExpr);
5294
5295 class InheritedConstructorInfo;
5296
5297 /// Determine if a special member function should have a deleted
5298 /// definition when it is defaulted.
5299 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5300 InheritedConstructorInfo *ICI = nullptr,
5301 bool Diagnose = false);
5302
5303 /// Declare the implicit default constructor for the given class.
5304 ///
5305 /// \param ClassDecl The class declaration into which the implicit
5306 /// default constructor will be added.
5307 ///
5308 /// \returns The implicitly-declared default constructor.
5309 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
5310 CXXRecordDecl *ClassDecl);
5311
5312 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5313 /// defining this constructor as the default constructor.
5314 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5315 CXXConstructorDecl *Constructor);
5316
5317 /// Declare the implicit destructor for the given class.
5318 ///
5319 /// \param ClassDecl The class declaration into which the implicit
5320 /// destructor will be added.
5321 ///
5322 /// \returns The implicitly-declared destructor.
5323 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5324
5325 /// DefineImplicitDestructor - Checks for feasibility of
5326 /// defining this destructor as the default destructor.
5327 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5328 CXXDestructorDecl *Destructor);
5329
5330 /// Build an exception spec for destructors that don't have one.
5331 ///
5332 /// C++11 says that user-defined destructors with no exception spec get one
5333 /// that looks as if the destructor was implicitly declared.
5334 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5335
5336 /// Define the specified inheriting constructor.
5337 void DefineInheritingConstructor(SourceLocation UseLoc,
5338 CXXConstructorDecl *Constructor);
5339
5340 /// Declare the implicit copy constructor for the given class.
5341 ///
5342 /// \param ClassDecl The class declaration into which the implicit
5343 /// copy constructor will be added.
5344 ///
5345 /// \returns The implicitly-declared copy constructor.
5346 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5347
5348 /// DefineImplicitCopyConstructor - Checks for feasibility of
5349 /// defining this constructor as the copy constructor.
5350 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5351 CXXConstructorDecl *Constructor);
5352
5353 /// Declare the implicit move constructor for the given class.
5354 ///
5355 /// \param ClassDecl The Class declaration into which the implicit
5356 /// move constructor will be added.
5357 ///
5358 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5359 /// declared.
5360 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5361
5362 /// DefineImplicitMoveConstructor - Checks for feasibility of
5363 /// defining this constructor as the move constructor.
5364 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5365 CXXConstructorDecl *Constructor);
5366
5367 /// Declare the implicit copy assignment operator for the given class.
5368 ///
5369 /// \param ClassDecl The class declaration into which the implicit
5370 /// copy assignment operator will be added.
5371 ///
5372 /// \returns The implicitly-declared copy assignment operator.
5373 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5374
5375 /// Defines an implicitly-declared copy assignment operator.
5376 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5377 CXXMethodDecl *MethodDecl);
5378
5379 /// Declare the implicit move assignment operator for the given class.
5380 ///
5381 /// \param ClassDecl The Class declaration into which the implicit
5382 /// move assignment operator will be added.
5383 ///
5384 /// \returns The implicitly-declared move assignment operator, or NULL if it
5385 /// wasn't declared.
5386 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5387
5388 /// Defines an implicitly-declared move assignment operator.
5389 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5390 CXXMethodDecl *MethodDecl);
5391
5392 /// Force the declaration of any implicitly-declared members of this
5393 /// class.
5394 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
5395
5396 /// Check a completed declaration of an implicit special member.
5397 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5398
5399 /// Determine whether the given function is an implicitly-deleted
5400 /// special member function.
5401 bool isImplicitlyDeleted(FunctionDecl *FD);
5402
5403 /// Check whether 'this' shows up in the type of a static member
5404 /// function after the (naturally empty) cv-qualifier-seq would be.
5405 ///
5406 /// \returns true if an error occurred.
5407 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5408
5409 /// Whether this' shows up in the exception specification of a static
5410 /// member function.
5411 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5412
5413 /// Check whether 'this' shows up in the attributes of the given
5414 /// static member function.
5415 ///
5416 /// \returns true if an error occurred.
5417 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5418
5419 /// MaybeBindToTemporary - If the passed in expression has a record type with
5420 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
5421 /// it simply returns the passed in expression.
5422 ExprResult MaybeBindToTemporary(Expr *E);
5423
5424 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5425 MultiExprArg ArgsPtr,
5426 SourceLocation Loc,
5427 SmallVectorImpl<Expr*> &ConvertedArgs,
5428 bool AllowExplicit = false,
5429 bool IsListInitialization = false);
5430
5431 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
5432 SourceLocation NameLoc,
5433 IdentifierInfo &Name);
5434
5435 ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
5436 Scope *S, CXXScopeSpec &SS,
5437 bool EnteringContext);
5438 ParsedType getDestructorName(SourceLocation TildeLoc,
5439 IdentifierInfo &II, SourceLocation NameLoc,
5440 Scope *S, CXXScopeSpec &SS,
5441 ParsedType ObjectType,
5442 bool EnteringContext);
5443
5444 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
5445 ParsedType ObjectType);
5446
5447 // Checks that reinterpret casts don't have undefined behavior.
5448 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
5449 bool IsDereference, SourceRange Range);
5450
5451 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
5452 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
5453 tok::TokenKind Kind,
5454 SourceLocation LAngleBracketLoc,
5455 Declarator &D,
5456 SourceLocation RAngleBracketLoc,
5457 SourceLocation LParenLoc,
5458 Expr *E,
5459 SourceLocation RParenLoc);
5460
5461 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
5462 tok::TokenKind Kind,
5463 TypeSourceInfo *Ty,
5464 Expr *E,
5465 SourceRange AngleBrackets,
5466 SourceRange Parens);
5467
5468 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
5469 ExprResult Operand,
5470 SourceLocation RParenLoc);
5471
5472 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
5473 Expr *Operand, SourceLocation RParenLoc);
5474
5475 ExprResult BuildCXXTypeId(QualType TypeInfoType,
5476 SourceLocation TypeidLoc,
5477 TypeSourceInfo *Operand,
5478 SourceLocation RParenLoc);
5479 ExprResult BuildCXXTypeId(QualType TypeInfoType,
5480 SourceLocation TypeidLoc,
5481 Expr *Operand,
5482 SourceLocation RParenLoc);
5483
5484 /// ActOnCXXTypeid - Parse typeid( something ).
5485 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
5486 SourceLocation LParenLoc, bool isType,
5487 void *TyOrExpr,
5488 SourceLocation RParenLoc);
5489
5490 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5491 SourceLocation TypeidLoc,
5492 TypeSourceInfo *Operand,
5493 SourceLocation RParenLoc);
5494 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5495 SourceLocation TypeidLoc,
5496 Expr *Operand,
5497 SourceLocation RParenLoc);
5498
5499 /// ActOnCXXUuidof - Parse __uuidof( something ).
5500 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
5501 SourceLocation LParenLoc, bool isType,
5502 void *TyOrExpr,
5503 SourceLocation RParenLoc);
5504
5505 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
5506 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5507 tok::TokenKind Operator,
5508 SourceLocation EllipsisLoc, Expr *RHS,
5509 SourceLocation RParenLoc);
5510 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5511 BinaryOperatorKind Operator,
5512 SourceLocation EllipsisLoc, Expr *RHS,
5513 SourceLocation RParenLoc,
5514 Optional<unsigned> NumExpansions);
5515 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
5516 BinaryOperatorKind Operator);
5517
5518 //// ActOnCXXThis - Parse 'this' pointer.
5519 ExprResult ActOnCXXThis(SourceLocation loc);
5520
5521 /// Build a CXXThisExpr and mark it referenced in the current context.
5522 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
5523 void MarkThisReferenced(CXXThisExpr *This);
5524
5525 /// Try to retrieve the type of the 'this' pointer.
5526 ///
5527 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
5528 QualType getCurrentThisType();
5529
5530 /// When non-NULL, the C++ 'this' expression is allowed despite the
5531 /// current context not being a non-static member function. In such cases,
5532 /// this provides the type used for 'this'.
5533 QualType CXXThisTypeOverride;
5534
5535 /// RAII object used to temporarily allow the C++ 'this' expression
5536 /// to be used, with the given qualifiers on the current class type.
5537 class CXXThisScopeRAII {
5538 Sema &S;
5539 QualType OldCXXThisTypeOverride;
5540 bool Enabled;
5541
5542 public:
5543 /// Introduce a new scope where 'this' may be allowed (when enabled),
5544 /// using the given declaration (which is either a class template or a
5545 /// class) along with the given qualifiers.
5546 /// along with the qualifiers placed on '*this'.
5547 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
5548 bool Enabled = true);
5549
5550 ~CXXThisScopeRAII();
5551 };
5552
5553 /// Make sure the value of 'this' is actually available in the current
5554 /// context, if it is a potentially evaluated context.
5555 ///
5556 /// \param Loc The location at which the capture of 'this' occurs.
5557 ///
5558 /// \param Explicit Whether 'this' is explicitly captured in a lambda
5559 /// capture list.
5560 ///
5561 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5562 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5563 /// This is useful when enclosing lambdas must speculatively capture
5564 /// 'this' that may or may not be used in certain specializations of
5565 /// a nested generic lambda (depending on whether the name resolves to
5566 /// a non-static member function or a static function).
5567 /// \return returns 'true' if failed, 'false' if success.
5568 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
5569 bool BuildAndDiagnose = true,
5570 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
5571 bool ByCopy = false);
5572
5573 /// Determine whether the given type is the type of *this that is used
5574 /// outside of the body of a member function for a type that is currently
5575 /// being defined.
5576 bool isThisOutsideMemberFunctionBody(QualType BaseType);
5577
5578 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5579 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5580
5581
5582 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5583 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5584
5585 ExprResult
5586 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5587 SourceLocation AtLoc, SourceLocation RParen);
5588
5589 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5590 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5591
5592 //// ActOnCXXThrow - Parse throw expressions.
5593 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5594 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5595 bool IsThrownVarInScope);
5596 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5597
5598 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5599 /// Can be interpreted either as function-style casting ("int(x)")
5600 /// or class type construction ("ClassType(x,y,z)")
5601 /// or creation of a value-initialized type ("int()").
5602 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5603 SourceLocation LParenOrBraceLoc,
5604 MultiExprArg Exprs,
5605 SourceLocation RParenOrBraceLoc,
5606 bool ListInitialization);
5607
5608 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5609 SourceLocation LParenLoc,
5610 MultiExprArg Exprs,
5611 SourceLocation RParenLoc,
5612 bool ListInitialization);
5613
5614 /// ActOnCXXNew - Parsed a C++ 'new' expression.
5615 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5616 SourceLocation PlacementLParen,
5617 MultiExprArg PlacementArgs,
5618 SourceLocation PlacementRParen,
5619 SourceRange TypeIdParens, Declarator &D,
5620 Expr *Initializer);
5621 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5622 SourceLocation PlacementLParen,
5623 MultiExprArg PlacementArgs,
5624 SourceLocation PlacementRParen,
5625 SourceRange TypeIdParens,
5626 QualType AllocType,
5627 TypeSourceInfo *AllocTypeInfo,
5628 Optional<Expr *> ArraySize,
5629 SourceRange DirectInitRange,
5630 Expr *Initializer);
5631
5632 /// Determine whether \p FD is an aligned allocation or deallocation
5633 /// function that is unavailable.
5634 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
5635
5636 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
5637 /// function that is unavailable.
5638 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
5639 SourceLocation Loc);
5640
5641 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5642 SourceRange R);
5643
5644 /// The scope in which to find allocation functions.
5645 enum AllocationFunctionScope {
5646 /// Only look for allocation functions in the global scope.
5647 AFS_Global,
5648 /// Only look for allocation functions in the scope of the
5649 /// allocated class.
5650 AFS_Class,
5651 /// Look for allocation functions in both the global scope
5652 /// and in the scope of the allocated class.
5653 AFS_Both
5654 };
5655
5656 /// Finds the overloads of operator new and delete that are appropriate
5657 /// for the allocation.
5658 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5659 AllocationFunctionScope NewScope,
5660 AllocationFunctionScope DeleteScope,
5661 QualType AllocType, bool IsArray,
5662 bool &PassAlignment, MultiExprArg PlaceArgs,
5663 FunctionDecl *&OperatorNew,
5664 FunctionDecl *&OperatorDelete,
5665 bool Diagnose = true);
5666 void DeclareGlobalNewDelete();
5667 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5668 ArrayRef<QualType> Params);
5669
5670 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5671 DeclarationName Name, FunctionDecl* &Operator,
5672 bool Diagnose = true);
5673 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5674 bool CanProvideSize,
5675 bool Overaligned,
5676 DeclarationName Name);
5677 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5678 CXXRecordDecl *RD);
5679
5680 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5681 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5682 bool UseGlobal, bool ArrayForm,
5683 Expr *Operand);
5684 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5685 bool IsDelete, bool CallCanBeVirtual,
5686 bool WarnOnNonAbstractTypes,
5687 SourceLocation DtorLoc);
5688
5689 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5690 Expr *Operand, SourceLocation RParen);
5691 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5692 SourceLocation RParen);
5693
5694 /// Parsed one of the type trait support pseudo-functions.
5695 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5696 ArrayRef<ParsedType> Args,
5697 SourceLocation RParenLoc);
5698 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5699 ArrayRef<TypeSourceInfo *> Args,
5700 SourceLocation RParenLoc);
5701
5702 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5703 /// pseudo-functions.
5704 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5705 SourceLocation KWLoc,
5706 ParsedType LhsTy,
5707 Expr *DimExpr,
5708 SourceLocation RParen);
5709
5710 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5711 SourceLocation KWLoc,
5712 TypeSourceInfo *TSInfo,
5713 Expr *DimExpr,
5714 SourceLocation RParen);
5715
5716 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5717 /// pseudo-functions.
5718 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5719 SourceLocation KWLoc,
5720 Expr *Queried,
5721 SourceLocation RParen);
5722
5723 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5724 SourceLocation KWLoc,
5725 Expr *Queried,
5726 SourceLocation RParen);
5727
5728 ExprResult ActOnStartCXXMemberReference(Scope *S,
5729 Expr *Base,
5730 SourceLocation OpLoc,
5731 tok::TokenKind OpKind,
5732 ParsedType &ObjectType,
5733 bool &MayBePseudoDestructor);
5734
5735 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5736 SourceLocation OpLoc,
5737 tok::TokenKind OpKind,
5738 const CXXScopeSpec &SS,
5739 TypeSourceInfo *ScopeType,
5740 SourceLocation CCLoc,
5741 SourceLocation TildeLoc,
5742 PseudoDestructorTypeStorage DestroyedType);
5743
5744 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5745 SourceLocation OpLoc,
5746 tok::TokenKind OpKind,
5747 CXXScopeSpec &SS,
5748 UnqualifiedId &FirstTypeName,
5749 SourceLocation CCLoc,
5750 SourceLocation TildeLoc,
5751 UnqualifiedId &SecondTypeName);
5752
5753 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5754 SourceLocation OpLoc,
5755 tok::TokenKind OpKind,
5756 SourceLocation TildeLoc,
5757 const DeclSpec& DS);
5758
5759 /// MaybeCreateExprWithCleanups - If the current full-expression
5760 /// requires any cleanups, surround it with a ExprWithCleanups node.
5761 /// Otherwise, just returns the passed-in expression.
5762 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5763 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5764 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5765
5766 MaterializeTemporaryExpr *
5767 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5768 bool BoundToLvalueReference);
5769
5770 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
5771 return ActOnFinishFullExpr(
5772 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
5773 }
5774 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5775 bool DiscardedValue, bool IsConstexpr = false);
5776 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5777
5778 // Marks SS invalid if it represents an incomplete type.
5779 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5780
5781 DeclContext *computeDeclContext(QualType T);
5782 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5783 bool EnteringContext = false);
5784 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5785 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5786
5787 /// The parser has parsed a global nested-name-specifier '::'.
5788 ///
5789 /// \param CCLoc The location of the '::'.
5790 ///
5791 /// \param SS The nested-name-specifier, which will be updated in-place
5792 /// to reflect the parsed nested-name-specifier.
5793 ///
5794 /// \returns true if an error occurred, false otherwise.
5795 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5796
5797 /// The parser has parsed a '__super' nested-name-specifier.
5798 ///
5799 /// \param SuperLoc The location of the '__super' keyword.
5800 ///
5801 /// \param ColonColonLoc The location of the '::'.
5802 ///
5803 /// \param SS The nested-name-specifier, which will be updated in-place
5804 /// to reflect the parsed nested-name-specifier.
5805 ///
5806 /// \returns true if an error occurred, false otherwise.
5807 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5808 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5809
5810 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5811 bool *CanCorrect = nullptr);
5812 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5813
5814 /// Keeps information about an identifier in a nested-name-spec.
5815 ///
5816 struct NestedNameSpecInfo {
5817 /// The type of the object, if we're parsing nested-name-specifier in
5818 /// a member access expression.
5819 ParsedType ObjectType;
5820
5821 /// The identifier preceding the '::'.
5822 IdentifierInfo *Identifier;
5823
5824 /// The location of the identifier.
5825 SourceLocation IdentifierLoc;
5826
5827 /// The location of the '::'.
5828 SourceLocation CCLoc;
5829
5830 /// Creates info object for the most typical case.
5831 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5832 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5833 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5834 CCLoc(ColonColonLoc) {
5835 }
5836
5837 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5838 SourceLocation ColonColonLoc, QualType ObjectType)
5839 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5840 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5841 }
5842 };
5843
5844 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5845 NestedNameSpecInfo &IdInfo);
5846
5847 bool BuildCXXNestedNameSpecifier(Scope *S,
5848 NestedNameSpecInfo &IdInfo,
5849 bool EnteringContext,
5850 CXXScopeSpec &SS,
5851 NamedDecl *ScopeLookupResult,
5852 bool ErrorRecoveryLookup,
5853 bool *IsCorrectedToColon = nullptr,
5854 bool OnlyNamespace = false);
5855
5856 /// The parser has parsed a nested-name-specifier 'identifier::'.
5857 ///
5858 /// \param S The scope in which this nested-name-specifier occurs.
5859 ///
5860 /// \param IdInfo Parser information about an identifier in the
5861 /// nested-name-spec.
5862 ///
5863 /// \param EnteringContext Whether we're entering the context nominated by
5864 /// this nested-name-specifier.
5865 ///
5866 /// \param SS The nested-name-specifier, which is both an input
5867 /// parameter (the nested-name-specifier before this type) and an
5868 /// output parameter (containing the full nested-name-specifier,
5869 /// including this new type).
5870 ///
5871 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5872 /// error recovery. In this case do not emit error message.
5873 ///
5874 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5875 /// are allowed. The bool value pointed by this parameter is set to 'true'
5876 /// if the identifier is treated as if it was followed by ':', not '::'.
5877 ///
5878 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5879 ///
5880 /// \returns true if an error occurred, false otherwise.
5881 bool ActOnCXXNestedNameSpecifier(Scope *S,
5882 NestedNameSpecInfo &IdInfo,
5883 bool EnteringContext,
5884 CXXScopeSpec &SS,
5885 bool ErrorRecoveryLookup = false,
5886 bool *IsCorrectedToColon = nullptr,
5887 bool OnlyNamespace = false);
5888
5889 ExprResult ActOnDecltypeExpression(Expr *E);
5890
5891 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5892 const DeclSpec &DS,
5893 SourceLocation ColonColonLoc);
5894
5895 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5896 NestedNameSpecInfo &IdInfo,
5897 bool EnteringContext);
5898
5899 /// The parser has parsed a nested-name-specifier
5900 /// 'template[opt] template-name < template-args >::'.
5901 ///
5902 /// \param S The scope in which this nested-name-specifier occurs.
5903 ///
5904 /// \param SS The nested-name-specifier, which is both an input
5905 /// parameter (the nested-name-specifier before this type) and an
5906 /// output parameter (containing the full nested-name-specifier,
5907 /// including this new type).
5908 ///
5909 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5910 /// \param TemplateName the template name.
5911 /// \param TemplateNameLoc The location of the template name.
5912 /// \param LAngleLoc The location of the opening angle bracket ('<').
5913 /// \param TemplateArgs The template arguments.
5914 /// \param RAngleLoc The location of the closing angle bracket ('>').
5915 /// \param CCLoc The location of the '::'.
5916 ///
5917 /// \param EnteringContext Whether we're entering the context of the
5918 /// nested-name-specifier.
5919 ///
5920 ///
5921 /// \returns true if an error occurred, false otherwise.
5922 bool ActOnCXXNestedNameSpecifier(Scope *S,
5923 CXXScopeSpec &SS,
5924 SourceLocation TemplateKWLoc,
5925 TemplateTy TemplateName,
5926 SourceLocation TemplateNameLoc,
5927 SourceLocation LAngleLoc,
5928 ASTTemplateArgsPtr TemplateArgs,
5929 SourceLocation RAngleLoc,
5930 SourceLocation CCLoc,
5931 bool EnteringContext);
5932
5933 /// Given a C++ nested-name-specifier, produce an annotation value
5934 /// that the parser can use later to reconstruct the given
5935 /// nested-name-specifier.
5936 ///
5937 /// \param SS A nested-name-specifier.
5938 ///
5939 /// \returns A pointer containing all of the information in the
5940 /// nested-name-specifier \p SS.
5941 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5942
5943 /// Given an annotation pointer for a nested-name-specifier, restore
5944 /// the nested-name-specifier structure.
5945 ///
5946 /// \param Annotation The annotation pointer, produced by
5947 /// \c SaveNestedNameSpecifierAnnotation().
5948 ///
5949 /// \param AnnotationRange The source range corresponding to the annotation.
5950 ///
5951 /// \param SS The nested-name-specifier that will be updated with the contents
5952 /// of the annotation pointer.
5953 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5954 SourceRange AnnotationRange,
5955 CXXScopeSpec &SS);
5956
5957 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5958
5959 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5960 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5961 /// After this method is called, according to [C++ 3.4.3p3], names should be
5962 /// looked up in the declarator-id's scope, until the declarator is parsed and
5963 /// ActOnCXXExitDeclaratorScope is called.
5964 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5965 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5966
5967 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5968 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5969 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5970 /// Used to indicate that names should revert to being looked up in the
5971 /// defining scope.
5972 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5973
5974 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5975 /// initializer for the declaration 'Dcl'.
5976 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5977 /// static data member of class X, names should be looked up in the scope of
5978 /// class X.
5979 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5980
5981 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5982 /// initializer for the declaration 'Dcl'.
5983 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5984
5985 /// Create a new lambda closure type.
5986 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5987 TypeSourceInfo *Info,
5988 bool KnownDependent,
5989 LambdaCaptureDefault CaptureDefault);
5990
5991 /// Start the definition of a lambda expression.
5992 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5993 SourceRange IntroducerRange,
5994 TypeSourceInfo *MethodType,
5995 SourceLocation EndLoc,
5996 ArrayRef<ParmVarDecl *> Params,
5997 ConstexprSpecKind ConstexprKind);
5998
5999 /// Number lambda for linkage purposes if necessary.
6000 void handleLambdaNumbering(
6001 CXXRecordDecl *Class, CXXMethodDecl *Method,
6002 Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None);
6003
6004 /// Endow the lambda scope info with the relevant properties.
6005 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
6006 CXXMethodDecl *CallOperator,
6007 SourceRange IntroducerRange,
6008 LambdaCaptureDefault CaptureDefault,
6009 SourceLocation CaptureDefaultLoc,
6010 bool ExplicitParams,
6011 bool ExplicitResultType,
6012 bool Mutable);
6013
6014 /// Perform initialization analysis of the init-capture and perform
6015 /// any implicit conversions such as an lvalue-to-rvalue conversion if
6016 /// not being used to initialize a reference.
6017 ParsedType actOnLambdaInitCaptureInitialization(
6018 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6019 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
6020 return ParsedType::make(buildLambdaInitCaptureInitialization(
6021 Loc, ByRef, EllipsisLoc, None, Id,
6022 InitKind != LambdaCaptureInitKind::CopyInit, Init));
6023 }
6024 QualType buildLambdaInitCaptureInitialization(
6025 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6026 Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
6027 Expr *&Init);
6028
6029 /// Create a dummy variable within the declcontext of the lambda's
6030 /// call operator, for name lookup purposes for a lambda init capture.
6031 ///
6032 /// CodeGen handles emission of lambda captures, ignoring these dummy
6033 /// variables appropriately.
6034 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
6035 QualType InitCaptureType,
6036 SourceLocation EllipsisLoc,
6037 IdentifierInfo *Id,
6038 unsigned InitStyle, Expr *Init);
6039
6040 /// Add an init-capture to a lambda scope.
6041 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
6042
6043 /// Note that we have finished the explicit captures for the
6044 /// given lambda.
6045 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
6046
6047 /// \brief This is called after parsing the explicit template parameter list
6048 /// on a lambda (if it exists) in C++2a.
6049 void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
6050 ArrayRef<NamedDecl *> TParams,
6051 SourceLocation RAngleLoc);
6052
6053 /// Introduce the lambda parameters into scope.
6054 void addLambdaParameters(
6055 ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
6056 CXXMethodDecl *CallOperator, Scope *CurScope);
6057
6058 /// Deduce a block or lambda's return type based on the return
6059 /// statements present in the body.
6060 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
6061
6062 /// ActOnStartOfLambdaDefinition - This is called just before we start
6063 /// parsing the body of a lambda; it analyzes the explicit captures and
6064 /// arguments, and sets up various data-structures for the body of the
6065 /// lambda.
6066 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
6067 Declarator &ParamInfo, Scope *CurScope);
6068
6069 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
6070 /// is invoked to pop the information about the lambda.
6071 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
6072 bool IsInstantiation = false);
6073
6074 /// ActOnLambdaExpr - This is called when the body of a lambda expression
6075 /// was successfully completed.
6076 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
6077 Scope *CurScope);
6078
6079 /// Does copying/destroying the captured variable have side effects?
6080 bool CaptureHasSideEffects(const sema::Capture &From);
6081
6082 /// Diagnose if an explicit lambda capture is unused. Returns true if a
6083 /// diagnostic is emitted.
6084 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
6085 const sema::Capture &From);
6086
6087 /// Build a FieldDecl suitable to hold the given capture.
6088 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
6089
6090 /// Initialize the given capture with a suitable expression.
6091 ExprResult BuildCaptureInit(const sema::Capture &Capture,
6092 SourceLocation ImplicitCaptureLoc,
6093 bool IsOpenMPMapping = false);
6094
6095 /// Complete a lambda-expression having processed and attached the
6096 /// lambda body.
6097 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
6098 sema::LambdaScopeInfo *LSI);
6099
6100 /// Get the return type to use for a lambda's conversion function(s) to
6101 /// function pointer type, given the type of the call operator.
6102 QualType
6103 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
6104
6105 /// Define the "body" of the conversion from a lambda object to a
6106 /// function pointer.
6107 ///
6108 /// This routine doesn't actually define a sensible body; rather, it fills
6109 /// in the initialization expression needed to copy the lambda object into
6110 /// the block, and IR generation actually generates the real body of the
6111 /// block pointer conversion.
6112 void DefineImplicitLambdaToFunctionPointerConversion(
6113 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
6114
6115 /// Define the "body" of the conversion from a lambda object to a
6116 /// block pointer.
6117 ///
6118 /// This routine doesn't actually define a sensible body; rather, it fills
6119 /// in the initialization expression needed to copy the lambda object into
6120 /// the block, and IR generation actually generates the real body of the
6121 /// block pointer conversion.
6122 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
6123 CXXConversionDecl *Conv);
6124
6125 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
6126 SourceLocation ConvLocation,
6127 CXXConversionDecl *Conv,
6128 Expr *Src);
6129
6130 /// Check whether the given expression is a valid constraint expression.
6131 /// A diagnostic is emitted if it is not, and false is returned.
6132 bool CheckConstraintExpression(Expr *CE);
6133
6134 bool CalculateConstraintSatisfaction(ConceptDecl *NamedConcept,
6135 MultiLevelTemplateArgumentList &MLTAL,
6136 Expr *ConstraintExpr,
6137 bool &IsSatisfied);
6138
6139 /// Check that the associated constraints of a template declaration match the
6140 /// associated constraints of an older declaration of which it is a
6141 /// redeclaration.
6142 bool CheckRedeclarationConstraintMatch(TemplateParameterList *Old,
6143 TemplateParameterList *New);
6144
6145 // ParseObjCStringLiteral - Parse Objective-C string literals.
6146 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
6147 ArrayRef<Expr *> Strings);
6148
6149 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
6150
6151 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
6152 /// numeric literal expression. Type of the expression will be "NSNumber *"
6153 /// or "id" if NSNumber is unavailable.
6154 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
6155 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
6156 bool Value);
6157 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
6158
6159 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
6160 /// '@' prefixed parenthesized expression. The type of the expression will
6161 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
6162 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
6163 /// "const char *" or C structure with attribute 'objc_boxable'.
6164 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
6165
6166 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
6167 Expr *IndexExpr,
6168 ObjCMethodDecl *getterMethod,
6169 ObjCMethodDecl *setterMethod);
6170
6171 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
6172 MutableArrayRef<ObjCDictionaryElement> Elements);
6173
6174 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
6175 TypeSourceInfo *EncodedTypeInfo,
6176 SourceLocation RParenLoc);
6177 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
6178 CXXConversionDecl *Method,
6179 bool HadMultipleCandidates);
6180
6181 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
6182 SourceLocation EncodeLoc,
6183 SourceLocation LParenLoc,
6184 ParsedType Ty,
6185 SourceLocation RParenLoc);
6186
6187 /// ParseObjCSelectorExpression - Build selector expression for \@selector
6188 ExprResult ParseObjCSelectorExpression(Selector Sel,
6189 SourceLocation AtLoc,
6190 SourceLocation SelLoc,
6191 SourceLocation LParenLoc,
6192 SourceLocation RParenLoc,
6193 bool WarnMultipleSelectors);
6194
6195 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
6196 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
6197 SourceLocation AtLoc,
6198 SourceLocation ProtoLoc,
6199 SourceLocation LParenLoc,
6200 SourceLocation ProtoIdLoc,
6201 SourceLocation RParenLoc);
6202
6203 //===--------------------------------------------------------------------===//
6204 // C++ Declarations
6205 //
6206 Decl *ActOnStartLinkageSpecification(Scope *S,
6207 SourceLocation ExternLoc,
6208 Expr *LangStr,
6209 SourceLocation LBraceLoc);
6210 Decl *ActOnFinishLinkageSpecification(Scope *S,
6211 Decl *LinkageSpec,
6212 SourceLocation RBraceLoc);
6213
6214
6215 //===--------------------------------------------------------------------===//
6216 // C++ Classes
6217 //
6218 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
6219 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
6220 const CXXScopeSpec *SS = nullptr);
6221 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
6222
6223 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
6224 SourceLocation ColonLoc,
6225 const ParsedAttributesView &Attrs);
6226
6227 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
6228 Declarator &D,
6229 MultiTemplateParamsArg TemplateParameterLists,
6230 Expr *BitfieldWidth, const VirtSpecifiers &VS,
6231 InClassInitStyle InitStyle);
6232
6233 void ActOnStartCXXInClassMemberInitializer();
6234 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
6235 SourceLocation EqualLoc,
6236 Expr *Init);
6237
6238 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6239 Scope *S,
6240 CXXScopeSpec &SS,
6241 IdentifierInfo *MemberOrBase,
6242 ParsedType TemplateTypeTy,
6243 const DeclSpec &DS,
6244 SourceLocation IdLoc,
6245 SourceLocation LParenLoc,
6246 ArrayRef<Expr *> Args,
6247 SourceLocation RParenLoc,
6248 SourceLocation EllipsisLoc);
6249
6250 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6251 Scope *S,
6252 CXXScopeSpec &SS,
6253 IdentifierInfo *MemberOrBase,
6254 ParsedType TemplateTypeTy,
6255 const DeclSpec &DS,
6256 SourceLocation IdLoc,
6257 Expr *InitList,
6258 SourceLocation EllipsisLoc);
6259
6260 MemInitResult BuildMemInitializer(Decl *ConstructorD,
6261 Scope *S,
6262 CXXScopeSpec &SS,
6263 IdentifierInfo *MemberOrBase,
6264 ParsedType TemplateTypeTy,
6265 const DeclSpec &DS,
6266 SourceLocation IdLoc,
6267 Expr *Init,
6268 SourceLocation EllipsisLoc);
6269
6270 MemInitResult BuildMemberInitializer(ValueDecl *Member,
6271 Expr *Init,
6272 SourceLocation IdLoc);
6273
6274 MemInitResult BuildBaseInitializer(QualType BaseType,
6275 TypeSourceInfo *BaseTInfo,
6276 Expr *Init,
6277 CXXRecordDecl *ClassDecl,
6278 SourceLocation EllipsisLoc);
6279
6280 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
6281 Expr *Init,
6282 CXXRecordDecl *ClassDecl);
6283
6284 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
6285 CXXCtorInitializer *Initializer);
6286
6287 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
6288 ArrayRef<CXXCtorInitializer *> Initializers = None);
6289
6290 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
6291
6292
6293 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
6294 /// mark all the non-trivial destructors of its members and bases as
6295 /// referenced.
6296 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
6297 CXXRecordDecl *Record);
6298
6299 /// The list of classes whose vtables have been used within
6300 /// this translation unit, and the source locations at which the
6301 /// first use occurred.
6302 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
6303
6304 /// The list of vtables that are required but have not yet been
6305 /// materialized.
6306 SmallVector<VTableUse, 16> VTableUses;
6307
6308 /// The set of classes whose vtables have been used within
6309 /// this translation unit, and a bit that will be true if the vtable is
6310 /// required to be emitted (otherwise, it should be emitted only if needed
6311 /// by code generation).
6312 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
6313
6314 /// Load any externally-stored vtable uses.
6315 void LoadExternalVTableUses();
6316
6317 /// Note that the vtable for the given class was used at the
6318 /// given location.
6319 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6320 bool DefinitionRequired = false);
6321
6322 /// Mark the exception specifications of all virtual member functions
6323 /// in the given class as needed.
6324 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
6325 const CXXRecordDecl *RD);
6326
6327 /// MarkVirtualMembersReferenced - Will mark all members of the given
6328 /// CXXRecordDecl referenced.
6329 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
6330 bool ConstexprOnly = false);
6331
6332 /// Define all of the vtables that have been used in this
6333 /// translation unit and reference any virtual members used by those
6334 /// vtables.
6335 ///
6336 /// \returns true if any work was done, false otherwise.
6337 bool DefineUsedVTables();
6338
6339 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
6340
6341 void ActOnMemInitializers(Decl *ConstructorDecl,
6342 SourceLocation ColonLoc,
6343 ArrayRef<CXXCtorInitializer*> MemInits,
6344 bool AnyErrors);
6345
6346 /// Check class-level dllimport/dllexport attribute. The caller must
6347 /// ensure that referenceDLLExportedClassMethods is called some point later
6348 /// when all outer classes of Class are complete.
6349 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
6350 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
6351
6352 void referenceDLLExportedClassMethods();
6353
6354 void propagateDLLAttrToBaseClassTemplate(
6355 CXXRecordDecl *Class, Attr *ClassAttr,
6356 ClassTemplateSpecializationDecl *BaseTemplateSpec,
6357 SourceLocation BaseLoc);
6358
6359 /// Add gsl::Pointer attribute to std::container::iterator
6360 /// \param ND The declaration that introduces the name
6361 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
6362 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
6363
6364 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
6365 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
6366
6367 /// Add [[gsl::Pointer]] attributes for std:: types.
6368 void inferGslPointerAttribute(TypedefNameDecl *TD);
6369
6370 void CheckCompletedCXXClass(CXXRecordDecl *Record);
6371
6372 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6373 /// conditions that are needed for the attribute to have an effect.
6374 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
6375
6376 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
6377 Decl *TagDecl, SourceLocation LBrac,
6378 SourceLocation RBrac,
6379 const ParsedAttributesView &AttrList);
6380 void ActOnFinishCXXMemberDecls();
6381 void ActOnFinishCXXNonNestedClass(Decl *D);
6382
6383 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
6384 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
6385 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6386 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6387 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6388 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6389 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6390 void ActOnFinishDelayedMemberInitializers(Decl *Record);
6391 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
6392 CachedTokens &Toks);
6393 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
6394 bool IsInsideALocalClassWithinATemplateFunction();
6395
6396 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6397 Expr *AssertExpr,
6398 Expr *AssertMessageExpr,
6399 SourceLocation RParenLoc);
6400 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6401 Expr *AssertExpr,
6402 StringLiteral *AssertMessageExpr,
6403 SourceLocation RParenLoc,
6404 bool Failed);
6405
6406 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
6407 SourceLocation FriendLoc,
6408 TypeSourceInfo *TSInfo);
6409 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6410 MultiTemplateParamsArg TemplateParams);
6411 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6412 MultiTemplateParamsArg TemplateParams);
6413
6414 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6415 StorageClass& SC);
6416 void CheckConstructor(CXXConstructorDecl *Constructor);
6417 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6418 StorageClass& SC);
6419 bool CheckDestructor(CXXDestructorDecl *Destructor);
6420 void CheckConversionDeclarator(Declarator &D, QualType &R,
6421 StorageClass& SC);
6422 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6423 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6424 StorageClass &SC);
6425 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
6426
6427 void CheckExplicitlyDefaultedFunction(FunctionDecl *MD);
6428
6429 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
6430 CXXSpecialMember CSM);
6431 void CheckDelayedMemberExceptionSpecs();
6432
6433 bool CheckExplicitlyDefaultedComparison(FunctionDecl *MD,
6434 DefaultedComparisonKind DCK);
6435
6436 //===--------------------------------------------------------------------===//
6437 // C++ Derived Classes
6438 //
6439
6440 /// ActOnBaseSpecifier - Parsed a base specifier
6441 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6442 SourceRange SpecifierRange,
6443 bool Virtual, AccessSpecifier Access,
6444 TypeSourceInfo *TInfo,
6445 SourceLocation EllipsisLoc);
6446
6447 BaseResult ActOnBaseSpecifier(Decl *classdecl,
6448 SourceRange SpecifierRange,
6449 ParsedAttributes &Attrs,
6450 bool Virtual, AccessSpecifier Access,
6451 ParsedType basetype,
6452 SourceLocation BaseLoc,
6453 SourceLocation EllipsisLoc);
6454
6455 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6456 MutableArrayRef<CXXBaseSpecifier *> Bases);
6457 void ActOnBaseSpecifiers(Decl *ClassDecl,
6458 MutableArrayRef<CXXBaseSpecifier *> Bases);
6459
6460 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6461 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6462 CXXBasePaths &Paths);
6463
6464 // FIXME: I don't like this name.
6465 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6466
6467 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6468 SourceLocation Loc, SourceRange Range,
6469 CXXCastPath *BasePath = nullptr,
6470 bool IgnoreAccess = false);
6471 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6472 unsigned InaccessibleBaseID,
6473 unsigned AmbigiousBaseConvID,
6474 SourceLocation Loc, SourceRange Range,
6475 DeclarationName Name,
6476 CXXCastPath *BasePath,
6477 bool IgnoreAccess = false);
6478
6479 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6480
6481 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6482 const CXXMethodDecl *Old);
6483
6484 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6485 /// covariant, according to C++ [class.virtual]p5.
6486 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6487 const CXXMethodDecl *Old);
6488
6489 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6490 /// spec is a subset of base spec.
6491 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6492 const CXXMethodDecl *Old);
6493
6494 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6495
6496 /// CheckOverrideControl - Check C++11 override control semantics.
6497 void CheckOverrideControl(NamedDecl *D);
6498
6499 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6500 /// not used in the declaration of an overriding method.
6501 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
6502
6503 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
6504 /// overrides a virtual member function marked 'final', according to
6505 /// C++11 [class.virtual]p4.
6506 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6507 const CXXMethodDecl *Old);
6508
6509
6510 //===--------------------------------------------------------------------===//
6511 // C++ Access Control
6512 //
6513
6514 enum AccessResult {
6515 AR_accessible,
6516 AR_inaccessible,
6517 AR_dependent,
6518 AR_delayed
6519 };
6520
6521 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
6522 NamedDecl *PrevMemberDecl,
6523 AccessSpecifier LexicalAS);
6524
6525 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
6526 DeclAccessPair FoundDecl);
6527 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
6528 DeclAccessPair FoundDecl);
6529 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
6530 SourceRange PlacementRange,
6531 CXXRecordDecl *NamingClass,
6532 DeclAccessPair FoundDecl,
6533 bool Diagnose = true);
6534 AccessResult CheckConstructorAccess(SourceLocation Loc,
6535 CXXConstructorDecl *D,
6536 DeclAccessPair FoundDecl,
6537 const InitializedEntity &Entity,
6538 bool IsCopyBindingRefToTemp = false);
6539 AccessResult CheckConstructorAccess(SourceLocation Loc,
6540 CXXConstructorDecl *D,
6541 DeclAccessPair FoundDecl,
6542 const InitializedEntity &Entity,
6543 const PartialDiagnostic &PDiag);
6544 AccessResult CheckDestructorAccess(SourceLocation Loc,
6545 CXXDestructorDecl *Dtor,
6546 const PartialDiagnostic &PDiag,
6547 QualType objectType = QualType());
6548 AccessResult CheckFriendAccess(NamedDecl *D);
6549 AccessResult CheckMemberAccess(SourceLocation UseLoc,
6550 CXXRecordDecl *NamingClass,
6551 DeclAccessPair Found);
6552 AccessResult
6553 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
6554 CXXRecordDecl *DecomposedClass,
6555 DeclAccessPair Field);
6556 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
6557 Expr *ObjectExpr,
6558 Expr *ArgExpr,
6559 DeclAccessPair FoundDecl);
6560 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
6561 DeclAccessPair FoundDecl);
6562 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
6563 QualType Base, QualType Derived,
6564 const CXXBasePath &Path,
6565 unsigned DiagID,
6566 bool ForceCheck = false,
6567 bool ForceUnprivileged = false);
6568 void CheckLookupAccess(const LookupResult &R);
6569 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
6570 QualType BaseType);
6571 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
6572 AccessSpecifier access,
6573 QualType objectType);
6574
6575 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
6576 const MultiLevelTemplateArgumentList &TemplateArgs);
6577 void PerformDependentDiagnostics(const DeclContext *Pattern,
6578 const MultiLevelTemplateArgumentList &TemplateArgs);
6579
6580 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
6581
6582 /// When true, access checking violations are treated as SFINAE
6583 /// failures rather than hard errors.
6584 bool AccessCheckingSFINAE;
6585
6586 enum AbstractDiagSelID {
6587 AbstractNone = -1,
6588 AbstractReturnType,
6589 AbstractParamType,
6590 AbstractVariableType,
6591 AbstractFieldType,
6592 AbstractIvarType,
6593 AbstractSynthesizedIvarType,
6594 AbstractArrayType
6595 };
6596
6597 bool isAbstractType(SourceLocation Loc, QualType T);
6598 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6599 TypeDiagnoser &Diagnoser);
6600 template <typename... Ts>
6601 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6602 const Ts &...Args) {
6603 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6604 return RequireNonAbstractType(Loc, T, Diagnoser);
6605 }
6606
6607 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6608
6609 //===--------------------------------------------------------------------===//
6610 // C++ Overloaded Operators [C++ 13.5]
6611 //
6612
6613 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6614
6615 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6616
6617 //===--------------------------------------------------------------------===//
6618 // C++ Templates [C++ 14]
6619 //
6620 void FilterAcceptableTemplateNames(LookupResult &R,
6621 bool AllowFunctionTemplates = true,
6622 bool AllowDependent = true);
6623 bool hasAnyAcceptableTemplateNames(LookupResult &R,
6624 bool AllowFunctionTemplates = true,
6625 bool AllowDependent = true,
6626 bool AllowNonTemplateFunctions = false);
6627 /// Try to interpret the lookup result D as a template-name.
6628 ///
6629 /// \param D A declaration found by name lookup.
6630 /// \param AllowFunctionTemplates Whether function templates should be
6631 /// considered valid results.
6632 /// \param AllowDependent Whether unresolved using declarations (that might
6633 /// name templates) should be considered valid results.
6634 NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
6635 bool AllowFunctionTemplates = true,
6636 bool AllowDependent = true);
6637
6638 enum class AssumedTemplateKind {
6639 /// This is not assumed to be a template name.
6640 None,
6641 /// This is assumed to be a template name because lookup found nothing.
6642 FoundNothing,
6643 /// This is assumed to be a template name because lookup found one or more
6644 /// functions (but no function templates).
6645 FoundFunctions,
6646 };
6647 bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
6648 QualType ObjectType, bool EnteringContext,
6649 bool &MemberOfUnknownSpecialization,
6650 SourceLocation TemplateKWLoc = SourceLocation(),
6651 AssumedTemplateKind *ATK = nullptr);
6652
6653 TemplateNameKind isTemplateName(Scope *S,
6654 CXXScopeSpec &SS,
6655 bool hasTemplateKeyword,
6656 const UnqualifiedId &Name,
6657 ParsedType ObjectType,
6658 bool EnteringContext,
6659 TemplateTy &Template,
6660 bool &MemberOfUnknownSpecialization);
6661
6662 /// Try to resolve an undeclared template name as a type template.
6663 ///
6664 /// Sets II to the identifier corresponding to the template name, and updates
6665 /// Name to a corresponding (typo-corrected) type template name and TNK to
6666 /// the corresponding kind, if possible.
6667 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
6668 TemplateNameKind &TNK,
6669 SourceLocation NameLoc,
6670 IdentifierInfo *&II);
6671
6672 bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
6673 SourceLocation NameLoc,
6674 bool Diagnose = true);
6675
6676 /// Determine whether a particular identifier might be the name in a C++1z
6677 /// deduction-guide declaration.
6678 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
6679 SourceLocation NameLoc,
6680 ParsedTemplateTy *Template = nullptr);
6681
6682 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
6683 SourceLocation IILoc,
6684 Scope *S,
6685 const CXXScopeSpec *SS,
6686 TemplateTy &SuggestedTemplate,
6687 TemplateNameKind &SuggestedKind);
6688
6689 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
6690 NamedDecl *Instantiation,
6691 bool InstantiatedFromMember,
6692 const NamedDecl *Pattern,
6693 const NamedDecl *PatternDef,
6694 TemplateSpecializationKind TSK,
6695 bool Complain = true);
6696
6697 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
6698 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
6699
6700 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
6701 SourceLocation EllipsisLoc,
6702 SourceLocation KeyLoc,
6703 IdentifierInfo *ParamName,
6704 SourceLocation ParamNameLoc,
6705 unsigned Depth, unsigned Position,
6706 SourceLocation EqualLoc,
6707 ParsedType DefaultArg);
6708
6709 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
6710 SourceLocation Loc);
6711 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
6712
6713 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
6714 unsigned Depth,
6715 unsigned Position,
6716 SourceLocation EqualLoc,
6717 Expr *DefaultArg);
6718 NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
6719 SourceLocation TmpLoc,
6720 TemplateParameterList *Params,
6721 SourceLocation EllipsisLoc,
6722 IdentifierInfo *ParamName,
6723 SourceLocation ParamNameLoc,
6724 unsigned Depth,
6725 unsigned Position,
6726 SourceLocation EqualLoc,
6727 ParsedTemplateArgument DefaultArg);
6728
6729 TemplateParameterList *
6730 ActOnTemplateParameterList(unsigned Depth,
6731 SourceLocation ExportLoc,
6732 SourceLocation TemplateLoc,
6733 SourceLocation LAngleLoc,
6734 ArrayRef<NamedDecl *> Params,
6735 SourceLocation RAngleLoc,
6736 Expr *RequiresClause);
6737
6738 /// The context in which we are checking a template parameter list.
6739 enum TemplateParamListContext {
6740 TPC_ClassTemplate,
6741 TPC_VarTemplate,
6742 TPC_FunctionTemplate,
6743 TPC_ClassTemplateMember,
6744 TPC_FriendClassTemplate,
6745 TPC_FriendFunctionTemplate,
6746 TPC_FriendFunctionTemplateDefinition,
6747 TPC_TypeAliasTemplate
6748 };
6749
6750 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
6751 TemplateParameterList *OldParams,
6752 TemplateParamListContext TPC,
6753 SkipBodyInfo *SkipBody = nullptr);
6754 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
6755 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
6756 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
6757 ArrayRef<TemplateParameterList *> ParamLists,
6758 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
6759
6760 DeclResult CheckClassTemplate(
6761 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
6762 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
6763 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
6764 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
6765 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
6766 TemplateParameterList **OuterTemplateParamLists,
6767 SkipBodyInfo *SkipBody = nullptr);
6768
6769 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
6770 QualType NTTPType,
6771 SourceLocation Loc);
6772
6773 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
6774 TemplateArgumentListInfo &Out);
6775
6776 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
6777
6778 void NoteAllFoundTemplates(TemplateName Name);
6779
6780 QualType CheckTemplateIdType(TemplateName Template,
6781 SourceLocation TemplateLoc,
6782 TemplateArgumentListInfo &TemplateArgs);
6783
6784 TypeResult
6785 ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6786 TemplateTy Template, IdentifierInfo *TemplateII,
6787 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
6788 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
6789 bool IsCtorOrDtorName = false, bool IsClassName = false);
6790
6791 /// Parsed an elaborated-type-specifier that refers to a template-id,
6792 /// such as \c class T::template apply<U>.
6793 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6794 TypeSpecifierType TagSpec,
6795 SourceLocation TagLoc,
6796 CXXScopeSpec &SS,
6797 SourceLocation TemplateKWLoc,
6798 TemplateTy TemplateD,
6799 SourceLocation TemplateLoc,
6800 SourceLocation LAngleLoc,
6801 ASTTemplateArgsPtr TemplateArgsIn,
6802 SourceLocation RAngleLoc);
6803
6804 DeclResult ActOnVarTemplateSpecialization(
6805 Scope *S, Declarator &D, TypeSourceInfo *DI,
6806 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6807 StorageClass SC, bool IsPartialSpecialization);
6808
6809 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6810 SourceLocation TemplateLoc,
6811 SourceLocation TemplateNameLoc,
6812 const TemplateArgumentListInfo &TemplateArgs);
6813
6814 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6815 const DeclarationNameInfo &NameInfo,
6816 VarTemplateDecl *Template,
6817 SourceLocation TemplateLoc,
6818 const TemplateArgumentListInfo *TemplateArgs);
6819
6820 ExprResult
6821 CheckConceptTemplateId(const CXXScopeSpec &SS,
6822 SourceLocation TemplateKWLoc,
6823 SourceLocation ConceptNameLoc, NamedDecl *FoundDecl,
6824 ConceptDecl *NamedConcept,
6825 const TemplateArgumentListInfo *TemplateArgs);
6826
6827 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
6828
6829 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6830 SourceLocation TemplateKWLoc,
6831 LookupResult &R,
6832 bool RequiresADL,
6833 const TemplateArgumentListInfo *TemplateArgs);
6834
6835 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6836 SourceLocation TemplateKWLoc,
6837 const DeclarationNameInfo &NameInfo,
6838 const TemplateArgumentListInfo *TemplateArgs);
6839
6840 TemplateNameKind ActOnDependentTemplateName(
6841 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6842 const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6843 TemplateTy &Template, bool AllowInjectedClassName = false);
6844
6845 DeclResult ActOnClassTemplateSpecialization(
6846 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
6847 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
6848 const ParsedAttributesView &Attr,
6849 MultiTemplateParamsArg TemplateParameterLists,
6850 SkipBodyInfo *SkipBody = nullptr);
6851
6852 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6853 TemplateDecl *PrimaryTemplate,
6854 unsigned NumExplicitArgs,
6855 ArrayRef<TemplateArgument> Args);
6856 void CheckTemplatePartialSpecialization(
6857 ClassTemplatePartialSpecializationDecl *Partial);
6858 void CheckTemplatePartialSpecialization(
6859 VarTemplatePartialSpecializationDecl *Partial);
6860
6861 Decl *ActOnTemplateDeclarator(Scope *S,
6862 MultiTemplateParamsArg TemplateParameterLists,
6863 Declarator &D);
6864
6865 bool
6866 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6867 TemplateSpecializationKind NewTSK,
6868 NamedDecl *PrevDecl,
6869 TemplateSpecializationKind PrevTSK,
6870 SourceLocation PrevPtOfInstantiation,
6871 bool &SuppressNew);
6872
6873 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6874 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6875 LookupResult &Previous);
6876
6877 bool CheckFunctionTemplateSpecialization(
6878 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6879 LookupResult &Previous, bool QualifiedFriend = false);
6880 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6881 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6882
6883 DeclResult ActOnExplicitInstantiation(
6884 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
6885 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
6886 TemplateTy Template, SourceLocation TemplateNameLoc,
6887 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
6888 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
6889
6890 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
6891 SourceLocation TemplateLoc,
6892 unsigned TagSpec, SourceLocation KWLoc,
6893 CXXScopeSpec &SS, IdentifierInfo *Name,
6894 SourceLocation NameLoc,
6895 const ParsedAttributesView &Attr);
6896
6897 DeclResult ActOnExplicitInstantiation(Scope *S,
6898 SourceLocation ExternLoc,
6899 SourceLocation TemplateLoc,
6900 Declarator &D);
6901
6902 TemplateArgumentLoc
6903 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6904 SourceLocation TemplateLoc,
6905 SourceLocation RAngleLoc,
6906 Decl *Param,
6907 SmallVectorImpl<TemplateArgument>
6908 &Converted,
6909 bool &HasDefaultArg);
6910
6911 /// Specifies the context in which a particular template
6912 /// argument is being checked.
6913 enum CheckTemplateArgumentKind {
6914 /// The template argument was specified in the code or was
6915 /// instantiated with some deduced template arguments.
6916 CTAK_Specified,
6917
6918 /// The template argument was deduced via template argument
6919 /// deduction.
6920 CTAK_Deduced,
6921
6922 /// The template argument was deduced from an array bound
6923 /// via template argument deduction.
6924 CTAK_DeducedFromArrayBound
6925 };
6926
6927 bool CheckTemplateArgument(NamedDecl *Param,
6928 TemplateArgumentLoc &Arg,
6929 NamedDecl *Template,
6930 SourceLocation TemplateLoc,
6931 SourceLocation RAngleLoc,
6932 unsigned ArgumentPackIndex,
6933 SmallVectorImpl<TemplateArgument> &Converted,
6934 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6935
6936 /// Check that the given template arguments can be be provided to
6937 /// the given template, converting the arguments along the way.
6938 ///
6939 /// \param Template The template to which the template arguments are being
6940 /// provided.
6941 ///
6942 /// \param TemplateLoc The location of the template name in the source.
6943 ///
6944 /// \param TemplateArgs The list of template arguments. If the template is
6945 /// a template template parameter, this function may extend the set of
6946 /// template arguments to also include substituted, defaulted template
6947 /// arguments.
6948 ///
6949 /// \param PartialTemplateArgs True if the list of template arguments is
6950 /// intentionally partial, e.g., because we're checking just the initial
6951 /// set of template arguments.
6952 ///
6953 /// \param Converted Will receive the converted, canonicalized template
6954 /// arguments.
6955 ///
6956 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6957 /// contain the converted forms of the template arguments as written.
6958 /// Otherwise, \p TemplateArgs will not be modified.
6959 ///
6960 /// \returns true if an error occurred, false otherwise.
6961 bool CheckTemplateArgumentList(TemplateDecl *Template,
6962 SourceLocation TemplateLoc,
6963 TemplateArgumentListInfo &TemplateArgs,
6964 bool PartialTemplateArgs,
6965 SmallVectorImpl<TemplateArgument> &Converted,
6966 bool UpdateArgsWithConversions = true);
6967
6968 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6969 TemplateArgumentLoc &Arg,
6970 SmallVectorImpl<TemplateArgument> &Converted);
6971
6972 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6973 TypeSourceInfo *Arg);
6974 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6975 QualType InstantiatedParamType, Expr *Arg,
6976 TemplateArgument &Converted,
6977 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6978 bool CheckTemplateTemplateArgument(TemplateParameterList *Params,
6979 TemplateArgumentLoc &Arg);
6980
6981 ExprResult
6982 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6983 QualType ParamType,
6984 SourceLocation Loc);
6985 ExprResult
6986 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6987 SourceLocation Loc);
6988
6989 /// Enumeration describing how template parameter lists are compared
6990 /// for equality.
6991 enum TemplateParameterListEqualKind {
6992 /// We are matching the template parameter lists of two templates
6993 /// that might be redeclarations.
6994 ///
6995 /// \code
6996 /// template<typename T> struct X;
6997 /// template<typename T> struct X;
6998 /// \endcode
6999 TPL_TemplateMatch,
7000
7001 /// We are matching the template parameter lists of two template
7002 /// template parameters as part of matching the template parameter lists
7003 /// of two templates that might be redeclarations.
7004 ///
7005 /// \code
7006 /// template<template<int I> class TT> struct X;
7007 /// template<template<int Value> class Other> struct X;
7008 /// \endcode
7009 TPL_TemplateTemplateParmMatch,
7010
7011 /// We are matching the template parameter lists of a template
7012 /// template argument against the template parameter lists of a template
7013 /// template parameter.
7014 ///
7015 /// \code
7016 /// template<template<int Value> class Metafun> struct X;
7017 /// template<int Value> struct integer_c;
7018 /// X<integer_c> xic;
7019 /// \endcode
7020 TPL_TemplateTemplateArgumentMatch
7021 };
7022
7023 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
7024 TemplateParameterList *Old,
7025 bool Complain,
7026 TemplateParameterListEqualKind Kind,
7027 SourceLocation TemplateArgLoc
7028 = SourceLocation());
7029
7030 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
7031
7032 /// Called when the parser has parsed a C++ typename
7033 /// specifier, e.g., "typename T::type".
7034 ///
7035 /// \param S The scope in which this typename type occurs.
7036 /// \param TypenameLoc the location of the 'typename' keyword
7037 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7038 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
7039 /// \param IdLoc the location of the identifier.
7040 TypeResult
7041 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7042 const CXXScopeSpec &SS, const IdentifierInfo &II,
7043 SourceLocation IdLoc);
7044
7045 /// Called when the parser has parsed a C++ typename
7046 /// specifier that ends in a template-id, e.g.,
7047 /// "typename MetaFun::template apply<T1, T2>".
7048 ///
7049 /// \param S The scope in which this typename type occurs.
7050 /// \param TypenameLoc the location of the 'typename' keyword
7051 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7052 /// \param TemplateLoc the location of the 'template' keyword, if any.
7053 /// \param TemplateName The template name.
7054 /// \param TemplateII The identifier used to name the template.
7055 /// \param TemplateIILoc The location of the template name.
7056 /// \param LAngleLoc The location of the opening angle bracket ('<').
7057 /// \param TemplateArgs The template arguments.
7058 /// \param RAngleLoc The location of the closing angle bracket ('>').
7059 TypeResult
7060 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7061 const CXXScopeSpec &SS,
7062 SourceLocation TemplateLoc,
7063 TemplateTy TemplateName,
7064 IdentifierInfo *TemplateII,
7065 SourceLocation TemplateIILoc,
7066 SourceLocation LAngleLoc,
7067 ASTTemplateArgsPtr TemplateArgs,
7068 SourceLocation RAngleLoc);
7069
7070 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7071 SourceLocation KeywordLoc,
7072 NestedNameSpecifierLoc QualifierLoc,
7073 const IdentifierInfo &II,
7074 SourceLocation IILoc);
7075
7076 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
7077 SourceLocation Loc,
7078 DeclarationName Name);
7079 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
7080
7081 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
7082 bool RebuildTemplateParamsInCurrentInstantiation(
7083 TemplateParameterList *Params);
7084
7085 std::string
7086 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7087 const TemplateArgumentList &Args);
7088
7089 std::string
7090 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7091 const TemplateArgument *Args,
7092 unsigned NumArgs);
7093
7094 // Concepts
7095 Decl *ActOnConceptDefinition(
7096 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
7097 IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
7098
7099 //===--------------------------------------------------------------------===//
7100 // C++ Variadic Templates (C++0x [temp.variadic])
7101 //===--------------------------------------------------------------------===//
7102
7103 /// Determine whether an unexpanded parameter pack might be permitted in this
7104 /// location. Useful for error recovery.
7105 bool isUnexpandedParameterPackPermitted();
7106
7107 /// The context in which an unexpanded parameter pack is
7108 /// being diagnosed.
7109 ///
7110 /// Note that the values of this enumeration line up with the first
7111 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
7112 enum UnexpandedParameterPackContext {
7113 /// An arbitrary expression.
7114 UPPC_Expression = 0,
7115
7116 /// The base type of a class type.
7117 UPPC_BaseType,
7118
7119 /// The type of an arbitrary declaration.
7120 UPPC_DeclarationType,
7121
7122 /// The type of a data member.
7123 UPPC_DataMemberType,
7124
7125 /// The size of a bit-field.
7126 UPPC_BitFieldWidth,
7127
7128 /// The expression in a static assertion.
7129 UPPC_StaticAssertExpression,
7130
7131 /// The fixed underlying type of an enumeration.
7132 UPPC_FixedUnderlyingType,
7133
7134 /// The enumerator value.
7135 UPPC_EnumeratorValue,
7136
7137 /// A using declaration.
7138 UPPC_UsingDeclaration,
7139
7140 /// A friend declaration.
7141 UPPC_FriendDeclaration,
7142
7143 /// A declaration qualifier.
7144 UPPC_DeclarationQualifier,
7145
7146 /// An initializer.
7147 UPPC_Initializer,
7148
7149 /// A default argument.
7150 UPPC_DefaultArgument,
7151
7152 /// The type of a non-type template parameter.
7153 UPPC_NonTypeTemplateParameterType,
7154
7155 /// The type of an exception.
7156 UPPC_ExceptionType,
7157
7158 /// Partial specialization.
7159 UPPC_PartialSpecialization,
7160
7161 /// Microsoft __if_exists.
7162 UPPC_IfExists,
7163
7164 /// Microsoft __if_not_exists.
7165 UPPC_IfNotExists,
7166
7167 /// Lambda expression.
7168 UPPC_Lambda,
7169
7170 /// Block expression,
7171 UPPC_Block
7172 };
7173
7174 /// Diagnose unexpanded parameter packs.
7175 ///
7176 /// \param Loc The location at which we should emit the diagnostic.
7177 ///
7178 /// \param UPPC The context in which we are diagnosing unexpanded
7179 /// parameter packs.
7180 ///
7181 /// \param Unexpanded the set of unexpanded parameter packs.
7182 ///
7183 /// \returns true if an error occurred, false otherwise.
7184 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
7185 UnexpandedParameterPackContext UPPC,
7186 ArrayRef<UnexpandedParameterPack> Unexpanded);
7187
7188 /// If the given type contains an unexpanded parameter pack,
7189 /// diagnose the error.
7190 ///
7191 /// \param Loc The source location where a diagnostc should be emitted.
7192 ///
7193 /// \param T The type that is being checked for unexpanded parameter
7194 /// packs.
7195 ///
7196 /// \returns true if an error occurred, false otherwise.
7197 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
7198 UnexpandedParameterPackContext UPPC);
7199
7200 /// If the given expression contains an unexpanded parameter
7201 /// pack, diagnose the error.
7202 ///
7203 /// \param E The expression that is being checked for unexpanded
7204 /// parameter packs.
7205 ///
7206 /// \returns true if an error occurred, false otherwise.
7207 bool DiagnoseUnexpandedParameterPack(Expr *E,
7208 UnexpandedParameterPackContext UPPC = UPPC_Expression);
7209
7210 /// If the given nested-name-specifier contains an unexpanded
7211 /// parameter pack, diagnose the error.
7212 ///
7213 /// \param SS The nested-name-specifier that is being checked for
7214 /// unexpanded parameter packs.
7215 ///
7216 /// \returns true if an error occurred, false otherwise.
7217 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
7218 UnexpandedParameterPackContext UPPC);
7219
7220 /// If the given name contains an unexpanded parameter pack,
7221 /// diagnose the error.
7222 ///
7223 /// \param NameInfo The name (with source location information) that
7224 /// is being checked for unexpanded parameter packs.
7225 ///
7226 /// \returns true if an error occurred, false otherwise.
7227 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
7228 UnexpandedParameterPackContext UPPC);
7229
7230 /// If the given template name contains an unexpanded parameter pack,
7231 /// diagnose the error.
7232 ///
7233 /// \param Loc The location of the template name.
7234 ///
7235 /// \param Template The template name that is being checked for unexpanded
7236 /// parameter packs.
7237 ///
7238 /// \returns true if an error occurred, false otherwise.
7239 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
7240 TemplateName Template,
7241 UnexpandedParameterPackContext UPPC);
7242
7243 /// If the given template argument contains an unexpanded parameter
7244 /// pack, diagnose the error.
7245 ///
7246 /// \param Arg The template argument that is being checked for unexpanded
7247 /// parameter packs.
7248 ///
7249 /// \returns true if an error occurred, false otherwise.
7250 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
7251 UnexpandedParameterPackContext UPPC);
7252
7253 /// Collect the set of unexpanded parameter packs within the given
7254 /// template argument.
7255 ///
7256 /// \param Arg The template argument that will be traversed to find
7257 /// unexpanded parameter packs.
7258 void collectUnexpandedParameterPacks(TemplateArgument Arg,
7259 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7260
7261 /// Collect the set of unexpanded parameter packs within the given
7262 /// template argument.
7263 ///
7264 /// \param Arg The template argument that will be traversed to find
7265 /// unexpanded parameter packs.
7266 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
7267 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7268
7269 /// Collect the set of unexpanded parameter packs within the given
7270 /// type.
7271 ///
7272 /// \param T The type that will be traversed to find
7273 /// unexpanded parameter packs.
7274 void collectUnexpandedParameterPacks(QualType T,
7275 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7276
7277 /// Collect the set of unexpanded parameter packs within the given
7278 /// type.
7279 ///
7280 /// \param TL The type that will be traversed to find
7281 /// unexpanded parameter packs.
7282 void collectUnexpandedParameterPacks(TypeLoc TL,
7283 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7284
7285 /// Collect the set of unexpanded parameter packs within the given
7286 /// nested-name-specifier.
7287 ///
7288 /// \param NNS The nested-name-specifier that will be traversed to find
7289 /// unexpanded parameter packs.
7290 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
7291 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7292
7293 /// Collect the set of unexpanded parameter packs within the given
7294 /// name.
7295 ///
7296 /// \param NameInfo The name that will be traversed to find
7297 /// unexpanded parameter packs.
7298 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
7299 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7300
7301 /// Invoked when parsing a template argument followed by an
7302 /// ellipsis, which creates a pack expansion.
7303 ///
7304 /// \param Arg The template argument preceding the ellipsis, which
7305 /// may already be invalid.
7306 ///
7307 /// \param EllipsisLoc The location of the ellipsis.
7308 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
7309 SourceLocation EllipsisLoc);
7310
7311 /// Invoked when parsing a type followed by an ellipsis, which
7312 /// creates a pack expansion.
7313 ///
7314 /// \param Type The type preceding the ellipsis, which will become
7315 /// the pattern of the pack expansion.
7316 ///
7317 /// \param EllipsisLoc The location of the ellipsis.
7318 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
7319
7320 /// Construct a pack expansion type from the pattern of the pack
7321 /// expansion.
7322 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
7323 SourceLocation EllipsisLoc,
7324 Optional<unsigned> NumExpansions);
7325
7326 /// Construct a pack expansion type from the pattern of the pack
7327 /// expansion.
7328 QualType CheckPackExpansion(QualType Pattern,
7329 SourceRange PatternRange,
7330 SourceLocation EllipsisLoc,
7331 Optional<unsigned> NumExpansions);
7332
7333 /// Invoked when parsing an expression followed by an ellipsis, which
7334 /// creates a pack expansion.
7335 ///
7336 /// \param Pattern The expression preceding the ellipsis, which will become
7337 /// the pattern of the pack expansion.
7338 ///
7339 /// \param EllipsisLoc The location of the ellipsis.
7340 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
7341
7342 /// Invoked when parsing an expression followed by an ellipsis, which
7343 /// creates a pack expansion.
7344 ///
7345 /// \param Pattern The expression preceding the ellipsis, which will become
7346 /// the pattern of the pack expansion.
7347 ///
7348 /// \param EllipsisLoc The location of the ellipsis.
7349 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
7350 Optional<unsigned> NumExpansions);
7351
7352 /// Determine whether we could expand a pack expansion with the
7353 /// given set of parameter packs into separate arguments by repeatedly
7354 /// transforming the pattern.
7355 ///
7356 /// \param EllipsisLoc The location of the ellipsis that identifies the
7357 /// pack expansion.
7358 ///
7359 /// \param PatternRange The source range that covers the entire pattern of
7360 /// the pack expansion.
7361 ///
7362 /// \param Unexpanded The set of unexpanded parameter packs within the
7363 /// pattern.
7364 ///
7365 /// \param ShouldExpand Will be set to \c true if the transformer should
7366 /// expand the corresponding pack expansions into separate arguments. When
7367 /// set, \c NumExpansions must also be set.
7368 ///
7369 /// \param RetainExpansion Whether the caller should add an unexpanded
7370 /// pack expansion after all of the expanded arguments. This is used
7371 /// when extending explicitly-specified template argument packs per
7372 /// C++0x [temp.arg.explicit]p9.
7373 ///
7374 /// \param NumExpansions The number of separate arguments that will be in
7375 /// the expanded form of the corresponding pack expansion. This is both an
7376 /// input and an output parameter, which can be set by the caller if the
7377 /// number of expansions is known a priori (e.g., due to a prior substitution)
7378 /// and will be set by the callee when the number of expansions is known.
7379 /// The callee must set this value when \c ShouldExpand is \c true; it may
7380 /// set this value in other cases.
7381 ///
7382 /// \returns true if an error occurred (e.g., because the parameter packs
7383 /// are to be instantiated with arguments of different lengths), false
7384 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
7385 /// must be set.
7386 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
7387 SourceRange PatternRange,
7388 ArrayRef<UnexpandedParameterPack> Unexpanded,
7389 const MultiLevelTemplateArgumentList &TemplateArgs,
7390 bool &ShouldExpand,
7391 bool &RetainExpansion,
7392 Optional<unsigned> &NumExpansions);
7393
7394 /// Determine the number of arguments in the given pack expansion
7395 /// type.
7396 ///
7397 /// This routine assumes that the number of arguments in the expansion is
7398 /// consistent across all of the unexpanded parameter packs in its pattern.
7399 ///
7400 /// Returns an empty Optional if the type can't be expanded.
7401 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
7402 const MultiLevelTemplateArgumentList &TemplateArgs);
7403
7404 /// Determine whether the given declarator contains any unexpanded
7405 /// parameter packs.
7406 ///
7407 /// This routine is used by the parser to disambiguate function declarators
7408 /// with an ellipsis prior to the ')', e.g.,
7409 ///
7410 /// \code
7411 /// void f(T...);
7412 /// \endcode
7413 ///
7414 /// To determine whether we have an (unnamed) function parameter pack or
7415 /// a variadic function.
7416 ///
7417 /// \returns true if the declarator contains any unexpanded parameter packs,
7418 /// false otherwise.
7419 bool containsUnexpandedParameterPacks(Declarator &D);
7420
7421 /// Returns the pattern of the pack expansion for a template argument.
7422 ///
7423 /// \param OrigLoc The template argument to expand.
7424 ///
7425 /// \param Ellipsis Will be set to the location of the ellipsis.
7426 ///
7427 /// \param NumExpansions Will be set to the number of expansions that will
7428 /// be generated from this pack expansion, if known a priori.
7429 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
7430 TemplateArgumentLoc OrigLoc,
7431 SourceLocation &Ellipsis,
7432 Optional<unsigned> &NumExpansions) const;
7433
7434 /// Given a template argument that contains an unexpanded parameter pack, but
7435 /// which has already been substituted, attempt to determine the number of
7436 /// elements that will be produced once this argument is fully-expanded.
7437 ///
7438 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
7439 /// avoid actually expanding the pack where possible.
7440 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
7441
7442 //===--------------------------------------------------------------------===//
7443 // C++ Template Argument Deduction (C++ [temp.deduct])
7444 //===--------------------------------------------------------------------===//
7445
7446 /// Adjust the type \p ArgFunctionType to match the calling convention,
7447 /// noreturn, and optionally the exception specification of \p FunctionType.
7448 /// Deduction often wants to ignore these properties when matching function
7449 /// types.
7450 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
7451 bool AdjustExceptionSpec = false);
7452
7453 /// Describes the result of template argument deduction.
7454 ///
7455 /// The TemplateDeductionResult enumeration describes the result of
7456 /// template argument deduction, as returned from
7457 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
7458 /// structure provides additional information about the results of
7459 /// template argument deduction, e.g., the deduced template argument
7460 /// list (if successful) or the specific template parameters or
7461 /// deduced arguments that were involved in the failure.
7462 enum TemplateDeductionResult {
7463 /// Template argument deduction was successful.
7464 TDK_Success = 0,
7465 /// The declaration was invalid; do nothing.
7466 TDK_Invalid,
7467 /// Template argument deduction exceeded the maximum template
7468 /// instantiation depth (which has already been diagnosed).
7469 TDK_InstantiationDepth,
7470 /// Template argument deduction did not deduce a value
7471 /// for every template parameter.
7472 TDK_Incomplete,
7473 /// Template argument deduction did not deduce a value for every
7474 /// expansion of an expanded template parameter pack.
7475 TDK_IncompletePack,
7476 /// Template argument deduction produced inconsistent
7477 /// deduced values for the given template parameter.
7478 TDK_Inconsistent,
7479 /// Template argument deduction failed due to inconsistent
7480 /// cv-qualifiers on a template parameter type that would
7481 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
7482 /// but were given a non-const "X".
7483 TDK_Underqualified,
7484 /// Substitution of the deduced template argument values
7485 /// resulted in an error.
7486 TDK_SubstitutionFailure,
7487 /// After substituting deduced template arguments, a dependent
7488 /// parameter type did not match the corresponding argument.
7489 TDK_DeducedMismatch,
7490 /// After substituting deduced template arguments, an element of
7491 /// a dependent parameter type did not match the corresponding element
7492 /// of the corresponding argument (when deducing from an initializer list).
7493 TDK_DeducedMismatchNested,
7494 /// A non-depnedent component of the parameter did not match the
7495 /// corresponding component of the argument.
7496 TDK_NonDeducedMismatch,
7497 /// When performing template argument deduction for a function
7498 /// template, there were too many call arguments.
7499 TDK_TooManyArguments,
7500 /// When performing template argument deduction for a function
7501 /// template, there were too few call arguments.
7502 TDK_TooFewArguments,
7503 /// The explicitly-specified template arguments were not valid
7504 /// template arguments for the given template.
7505 TDK_InvalidExplicitArguments,
7506 /// Checking non-dependent argument conversions failed.
7507 TDK_NonDependentConversionFailure,
7508 /// Deduction failed; that's all we know.
7509 TDK_MiscellaneousDeductionFailure,
7510 /// CUDA Target attributes do not match.
7511 TDK_CUDATargetMismatch
7512 };
7513
7514 TemplateDeductionResult
7515 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
7516 const TemplateArgumentList &TemplateArgs,
7517 sema::TemplateDeductionInfo &Info);
7518
7519 TemplateDeductionResult
7520 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
7521 const TemplateArgumentList &TemplateArgs,
7522 sema::TemplateDeductionInfo &Info);
7523
7524 TemplateDeductionResult SubstituteExplicitTemplateArguments(
7525 FunctionTemplateDecl *FunctionTemplate,
7526 TemplateArgumentListInfo &ExplicitTemplateArgs,
7527 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
7528 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
7529 sema::TemplateDeductionInfo &Info);
7530
7531 /// brief A function argument from which we performed template argument
7532 // deduction for a call.
7533 struct OriginalCallArg {
7534 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
7535 unsigned ArgIdx, QualType OriginalArgType)
7536 : OriginalParamType(OriginalParamType),
7537 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
7538 OriginalArgType(OriginalArgType) {}
7539
7540 QualType OriginalParamType;
7541 bool DecomposedParam;
7542 unsigned ArgIdx;
7543 QualType OriginalArgType;
7544 };
7545
7546 TemplateDeductionResult FinishTemplateArgumentDeduction(
7547 FunctionTemplateDecl *FunctionTemplate,
7548 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
7549 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
7550 sema::TemplateDeductionInfo &Info,
7551 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
7552 bool PartialOverloading = false,
7553 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
7554
7555 TemplateDeductionResult DeduceTemplateArguments(
7556 FunctionTemplateDecl *FunctionTemplate,
7557 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7558 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
7559 bool PartialOverloading,
7560 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
7561
7562 TemplateDeductionResult
7563 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7564 TemplateArgumentListInfo *ExplicitTemplateArgs,
7565 QualType ArgFunctionType,
7566 FunctionDecl *&Specialization,
7567 sema::TemplateDeductionInfo &Info,
7568 bool IsAddressOfFunction = false);
7569
7570 TemplateDeductionResult
7571 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7572 QualType ToType,
7573 CXXConversionDecl *&Specialization,
7574 sema::TemplateDeductionInfo &Info);
7575
7576 TemplateDeductionResult
7577 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7578 TemplateArgumentListInfo *ExplicitTemplateArgs,
7579 FunctionDecl *&Specialization,
7580 sema::TemplateDeductionInfo &Info,
7581 bool IsAddressOfFunction = false);
7582
7583 /// Substitute Replacement for \p auto in \p TypeWithAuto
7584 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
7585 /// Substitute Replacement for auto in TypeWithAuto
7586 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
7587 QualType Replacement);
7588 /// Completely replace the \c auto in \p TypeWithAuto by
7589 /// \p Replacement. This does not retain any \c auto type sugar.
7590 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
7591
7592 /// Result type of DeduceAutoType.
7593 enum DeduceAutoResult {
7594 DAR_Succeeded,
7595 DAR_Failed,
7596 DAR_FailedAlreadyDiagnosed
7597 };
7598
7599 DeduceAutoResult
7600 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
7601 Optional<unsigned> DependentDeductionDepth = None);
7602 DeduceAutoResult
7603 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
7604 Optional<unsigned> DependentDeductionDepth = None);
7605 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
7606 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
7607 bool Diagnose = true);
7608
7609 /// Declare implicit deduction guides for a class template if we've
7610 /// not already done so.
7611 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
7612 SourceLocation Loc);
7613
7614 QualType DeduceTemplateSpecializationFromInitializer(
7615 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
7616 const InitializationKind &Kind, MultiExprArg Init);
7617
7618 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
7619 QualType Type, TypeSourceInfo *TSI,
7620 SourceRange Range, bool DirectInit,
7621 Expr *Init);
7622
7623 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
7624
7625 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
7626 SourceLocation ReturnLoc,
7627 Expr *&RetExpr, AutoType *AT);
7628
7629 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
7630 FunctionTemplateDecl *FT2,
7631 SourceLocation Loc,
7632 TemplatePartialOrderingContext TPOC,
7633 unsigned NumCallArguments1,
7634 unsigned NumCallArguments2);
7635 UnresolvedSetIterator
7636 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
7637 TemplateSpecCandidateSet &FailedCandidates,
7638 SourceLocation Loc,
7639 const PartialDiagnostic &NoneDiag,
7640 const PartialDiagnostic &AmbigDiag,
7641 const PartialDiagnostic &CandidateDiag,
7642 bool Complain = true, QualType TargetType = QualType());
7643
7644 ClassTemplatePartialSpecializationDecl *
7645 getMoreSpecializedPartialSpecialization(
7646 ClassTemplatePartialSpecializationDecl *PS1,
7647 ClassTemplatePartialSpecializationDecl *PS2,
7648 SourceLocation Loc);
7649
7650 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
7651 sema::TemplateDeductionInfo &Info);
7652
7653 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
7654 VarTemplatePartialSpecializationDecl *PS1,
7655 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
7656
7657 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
7658 sema::TemplateDeductionInfo &Info);
7659
7660 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
7661 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
7662
7663 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
7664 bool OnlyDeduced,
7665 unsigned Depth,
7666 llvm::SmallBitVector &Used);
7667 void MarkDeducedTemplateParameters(
7668 const FunctionTemplateDecl *FunctionTemplate,
7669 llvm::SmallBitVector &Deduced) {
7670 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
7671 }
7672 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
7673 const FunctionTemplateDecl *FunctionTemplate,
7674 llvm::SmallBitVector &Deduced);
7675
7676 //===--------------------------------------------------------------------===//
7677 // C++ Template Instantiation
7678 //
7679
7680 MultiLevelTemplateArgumentList
7681 getTemplateInstantiationArgs(NamedDecl *D,
7682 const TemplateArgumentList *Innermost = nullptr,
7683 bool RelativeToPrimary = false,
7684 const FunctionDecl *Pattern = nullptr);
7685
7686 /// A context in which code is being synthesized (where a source location
7687 /// alone is not sufficient to identify the context). This covers template
7688 /// instantiation and various forms of implicitly-generated functions.
7689 struct CodeSynthesisContext {
7690 /// The kind of template instantiation we are performing
7691 enum SynthesisKind {
7692 /// We are instantiating a template declaration. The entity is
7693 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
7694 TemplateInstantiation,
7695
7696 /// We are instantiating a default argument for a template
7697 /// parameter. The Entity is the template parameter whose argument is
7698 /// being instantiated, the Template is the template, and the
7699 /// TemplateArgs/NumTemplateArguments provide the template arguments as
7700 /// specified.
7701 DefaultTemplateArgumentInstantiation,
7702
7703 /// We are instantiating a default argument for a function.
7704 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
7705 /// provides the template arguments as specified.
7706 DefaultFunctionArgumentInstantiation,
7707
7708 /// We are substituting explicit template arguments provided for
7709 /// a function template. The entity is a FunctionTemplateDecl.
7710 ExplicitTemplateArgumentSubstitution,
7711
7712 /// We are substituting template argument determined as part of
7713 /// template argument deduction for either a class template
7714 /// partial specialization or a function template. The
7715 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
7716 /// a TemplateDecl.
7717 DeducedTemplateArgumentSubstitution,
7718
7719 /// We are substituting prior template arguments into a new
7720 /// template parameter. The template parameter itself is either a
7721 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
7722 PriorTemplateArgumentSubstitution,
7723
7724 /// We are checking the validity of a default template argument that
7725 /// has been used when naming a template-id.
7726 DefaultTemplateArgumentChecking,
7727
7728 /// We are computing the exception specification for a defaulted special
7729 /// member function.
7730 ExceptionSpecEvaluation,
7731
7732 /// We are instantiating the exception specification for a function
7733 /// template which was deferred until it was needed.
7734 ExceptionSpecInstantiation,
7735
7736 /// We are declaring an implicit special member function.
7737 DeclaringSpecialMember,
7738
7739 /// We are defining a synthesized function (such as a defaulted special
7740 /// member).
7741 DefiningSynthesizedFunction,
7742
7743 // We are checking the constraints associated with a constrained entity or
7744 // the constraint expression of a concept. This includes the checks that
7745 // atomic constraints have the type 'bool' and that they can be constant
7746 // evaluated.
7747 ConstraintsCheck,
7748
7749 // We are substituting template arguments into a constraint expression.
7750 ConstraintSubstitution,
7751
7752 /// We are rewriting a comparison operator in terms of an operator<=>.
7753 RewritingOperatorAsSpaceship,
7754
7755 /// Added for Template instantiation observation.
7756 /// Memoization means we are _not_ instantiating a template because
7757 /// it is already instantiated (but we entered a context where we
7758 /// would have had to if it was not already instantiated).
7759 Memoization
7760 } Kind;
7761
7762 /// Was the enclosing context a non-instantiation SFINAE context?
7763 bool SavedInNonInstantiationSFINAEContext;
7764
7765 /// The point of instantiation or synthesis within the source code.
7766 SourceLocation PointOfInstantiation;
7767
7768 /// The entity that is being synthesized.
7769 Decl *Entity;
7770
7771 /// The template (or partial specialization) in which we are
7772 /// performing the instantiation, for substitutions of prior template
7773 /// arguments.
7774 NamedDecl *Template;
7775
7776 /// The list of template arguments we are substituting, if they
7777 /// are not part of the entity.
7778 const TemplateArgument *TemplateArgs;
7779
7780 // FIXME: Wrap this union around more members, or perhaps store the
7781 // kind-specific members in the RAII object owning the context.
7782 union {
7783 /// The number of template arguments in TemplateArgs.
7784 unsigned NumTemplateArgs;
7785
7786 /// The special member being declared or defined.
7787 CXXSpecialMember SpecialMember;
7788 };
7789
7790 ArrayRef<TemplateArgument> template_arguments() const {
7791 assert(Kind != DeclaringSpecialMember)((Kind != DeclaringSpecialMember) ? static_cast<void> (
0) : __assert_fail ("Kind != DeclaringSpecialMember", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 7791, __PRETTY_FUNCTION__))
;
7792 return {TemplateArgs, NumTemplateArgs};
7793 }
7794
7795 /// The template deduction info object associated with the
7796 /// substitution or checking of explicit or deduced template arguments.
7797 sema::TemplateDeductionInfo *DeductionInfo;
7798
7799 /// The source range that covers the construct that cause
7800 /// the instantiation, e.g., the template-id that causes a class
7801 /// template instantiation.
7802 SourceRange InstantiationRange;
7803
7804 CodeSynthesisContext()
7805 : Kind(TemplateInstantiation),
7806 SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
7807 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
7808 DeductionInfo(nullptr) {}
7809
7810 /// Determines whether this template is an actual instantiation
7811 /// that should be counted toward the maximum instantiation depth.
7812 bool isInstantiationRecord() const;
7813 };
7814
7815 /// List of active code synthesis contexts.
7816 ///
7817 /// This vector is treated as a stack. As synthesis of one entity requires
7818 /// synthesis of another, additional contexts are pushed onto the stack.
7819 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
7820
7821 /// Specializations whose definitions are currently being instantiated.
7822 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
7823
7824 /// Non-dependent types used in templates that have already been instantiated
7825 /// by some template instantiation.
7826 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
7827
7828 /// Extra modules inspected when performing a lookup during a template
7829 /// instantiation. Computed lazily.
7830 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7831
7832 /// Cache of additional modules that should be used for name lookup
7833 /// within the current template instantiation. Computed lazily; use
7834 /// getLookupModules() to get a complete set.
7835 llvm::DenseSet<Module*> LookupModulesCache;
7836
7837 /// Get the set of additional modules that should be checked during
7838 /// name lookup. A module and its imports become visible when instanting a
7839 /// template defined within it.
7840 llvm::DenseSet<Module*> &getLookupModules();
7841
7842 /// Map from the most recent declaration of a namespace to the most
7843 /// recent visible declaration of that namespace.
7844 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7845
7846 /// Whether we are in a SFINAE context that is not associated with
7847 /// template instantiation.
7848 ///
7849 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7850 /// of a template instantiation or template argument deduction.
7851 bool InNonInstantiationSFINAEContext;
7852
7853 /// The number of \p CodeSynthesisContexts that are not template
7854 /// instantiations and, therefore, should not be counted as part of the
7855 /// instantiation depth.
7856 ///
7857 /// When the instantiation depth reaches the user-configurable limit
7858 /// \p LangOptions::InstantiationDepth we will abort instantiation.
7859 // FIXME: Should we have a similar limit for other forms of synthesis?
7860 unsigned NonInstantiationEntries;
7861
7862 /// The depth of the context stack at the point when the most recent
7863 /// error or warning was produced.
7864 ///
7865 /// This value is used to suppress printing of redundant context stacks
7866 /// when there are multiple errors or warnings in the same instantiation.
7867 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7868 unsigned LastEmittedCodeSynthesisContextDepth = 0;
7869
7870 /// The template instantiation callbacks to trace or track
7871 /// instantiations (objects can be chained).
7872 ///
7873 /// This callbacks is used to print, trace or track template
7874 /// instantiations as they are being constructed.
7875 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
7876 TemplateInstCallbacks;
7877
7878 /// The current index into pack expansion arguments that will be
7879 /// used for substitution of parameter packs.
7880 ///
7881 /// The pack expansion index will be -1 to indicate that parameter packs
7882 /// should be instantiated as themselves. Otherwise, the index specifies
7883 /// which argument within the parameter pack will be used for substitution.
7884 int ArgumentPackSubstitutionIndex;
7885
7886 /// RAII object used to change the argument pack substitution index
7887 /// within a \c Sema object.
7888 ///
7889 /// See \c ArgumentPackSubstitutionIndex for more information.
7890 class ArgumentPackSubstitutionIndexRAII {
7891 Sema &Self;
7892 int OldSubstitutionIndex;
7893
7894 public:
7895 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7896 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7897 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7898 }
7899
7900 ~ArgumentPackSubstitutionIndexRAII() {
7901 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7902 }
7903 };
7904
7905 friend class ArgumentPackSubstitutionRAII;
7906
7907 /// For each declaration that involved template argument deduction, the
7908 /// set of diagnostics that were suppressed during that template argument
7909 /// deduction.
7910 ///
7911 /// FIXME: Serialize this structure to the AST file.
7912 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7913 SuppressedDiagnosticsMap;
7914 SuppressedDiagnosticsMap SuppressedDiagnostics;
7915
7916 /// A stack object to be created when performing template
7917 /// instantiation.
7918 ///
7919 /// Construction of an object of type \c InstantiatingTemplate
7920 /// pushes the current instantiation onto the stack of active
7921 /// instantiations. If the size of this stack exceeds the maximum
7922 /// number of recursive template instantiations, construction
7923 /// produces an error and evaluates true.
7924 ///
7925 /// Destruction of this object will pop the named instantiation off
7926 /// the stack.
7927 struct InstantiatingTemplate {
7928 /// Note that we are instantiating a class template,
7929 /// function template, variable template, alias template,
7930 /// or a member thereof.
7931 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7932 Decl *Entity,
7933 SourceRange InstantiationRange = SourceRange());
7934
7935 struct ExceptionSpecification {};
7936 /// Note that we are instantiating an exception specification
7937 /// of a function template.
7938 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7939 FunctionDecl *Entity, ExceptionSpecification,
7940 SourceRange InstantiationRange = SourceRange());
7941
7942 /// Note that we are instantiating a default argument in a
7943 /// template-id.
7944 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7945 TemplateParameter Param, TemplateDecl *Template,
7946 ArrayRef<TemplateArgument> TemplateArgs,
7947 SourceRange InstantiationRange = SourceRange());
7948
7949 /// Note that we are substituting either explicitly-specified or
7950 /// deduced template arguments during function template argument deduction.
7951 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7952 FunctionTemplateDecl *FunctionTemplate,
7953 ArrayRef<TemplateArgument> TemplateArgs,
7954 CodeSynthesisContext::SynthesisKind Kind,
7955 sema::TemplateDeductionInfo &DeductionInfo,
7956 SourceRange InstantiationRange = SourceRange());
7957
7958 /// Note that we are instantiating as part of template
7959 /// argument deduction for a class template declaration.
7960 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7961 TemplateDecl *Template,
7962 ArrayRef<TemplateArgument> TemplateArgs,
7963 sema::TemplateDeductionInfo &DeductionInfo,
7964 SourceRange InstantiationRange = SourceRange());
7965
7966 /// Note that we are instantiating as part of template
7967 /// argument deduction for a class template partial
7968 /// specialization.
7969 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7970 ClassTemplatePartialSpecializationDecl *PartialSpec,
7971 ArrayRef<TemplateArgument> TemplateArgs,
7972 sema::TemplateDeductionInfo &DeductionInfo,
7973 SourceRange InstantiationRange = SourceRange());
7974
7975 /// Note that we are instantiating as part of template
7976 /// argument deduction for a variable template partial
7977 /// specialization.
7978 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7979 VarTemplatePartialSpecializationDecl *PartialSpec,
7980 ArrayRef<TemplateArgument> TemplateArgs,
7981 sema::TemplateDeductionInfo &DeductionInfo,
7982 SourceRange InstantiationRange = SourceRange());
7983
7984 /// Note that we are instantiating a default argument for a function
7985 /// parameter.
7986 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7987 ParmVarDecl *Param,
7988 ArrayRef<TemplateArgument> TemplateArgs,
7989 SourceRange InstantiationRange = SourceRange());
7990
7991 /// Note that we are substituting prior template arguments into a
7992 /// non-type parameter.
7993 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7994 NamedDecl *Template,
7995 NonTypeTemplateParmDecl *Param,
7996 ArrayRef<TemplateArgument> TemplateArgs,
7997 SourceRange InstantiationRange);
7998
7999 /// Note that we are substituting prior template arguments into a
8000 /// template template parameter.
8001 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8002 NamedDecl *Template,
8003 TemplateTemplateParmDecl *Param,
8004 ArrayRef<TemplateArgument> TemplateArgs,
8005 SourceRange InstantiationRange);
8006
8007 /// Note that we are checking the default template argument
8008 /// against the template parameter for a given template-id.
8009 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8010 TemplateDecl *Template,
8011 NamedDecl *Param,
8012 ArrayRef<TemplateArgument> TemplateArgs,
8013 SourceRange InstantiationRange);
8014
8015 struct ConstraintsCheck {};
8016 /// \brief Note that we are checking the constraints associated with some
8017 /// constrained entity (a concept declaration or a template with associated
8018 /// constraints).
8019 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8020 ConstraintsCheck, TemplateDecl *Template,
8021 ArrayRef<TemplateArgument> TemplateArgs,
8022 SourceRange InstantiationRange);
8023
8024 struct ConstraintSubstitution {};
8025 /// \brief Note that we are checking a constraint expression associated
8026 /// with a template declaration or as part of the satisfaction check of a
8027 /// concept.
8028 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8029 ConstraintSubstitution, TemplateDecl *Template,
8030 sema::TemplateDeductionInfo &DeductionInfo,
8031 SourceRange InstantiationRange);
8032
8033 /// Note that we have finished instantiating this template.
8034 void Clear();
8035
8036 ~InstantiatingTemplate() { Clear(); }
8037
8038 /// Determines whether we have exceeded the maximum
8039 /// recursive template instantiations.
8040 bool isInvalid() const { return Invalid; }
49
Returning zero, which participates in a condition later
8041
8042 /// Determine whether we are already instantiating this
8043 /// specialization in some surrounding active instantiation.
8044 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
8045
8046 private:
8047 Sema &SemaRef;
8048 bool Invalid;
8049 bool AlreadyInstantiating;
8050 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
8051 SourceRange InstantiationRange);
8052
8053 InstantiatingTemplate(
8054 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
8055 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
8056 Decl *Entity, NamedDecl *Template = nullptr,
8057 ArrayRef<TemplateArgument> TemplateArgs = None,
8058 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
8059
8060 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
8061
8062 InstantiatingTemplate&
8063 operator=(const InstantiatingTemplate&) = delete;
8064 };
8065
8066 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
8067 void popCodeSynthesisContext();
8068
8069 /// Determine whether we are currently performing template instantiation.
8070 bool inTemplateInstantiation() const {
8071 return CodeSynthesisContexts.size() > NonInstantiationEntries;
8072 }
8073
8074 void PrintContextStack() {
8075 if (!CodeSynthesisContexts.empty() &&
8076 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
8077 PrintInstantiationStack();
8078 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
8079 }
8080 if (PragmaAttributeCurrentTargetDecl)
8081 PrintPragmaAttributeInstantiationPoint();
8082 }
8083 void PrintInstantiationStack();
8084
8085 void PrintPragmaAttributeInstantiationPoint();
8086
8087 /// Determines whether we are currently in a context where
8088 /// template argument substitution failures are not considered
8089 /// errors.
8090 ///
8091 /// \returns An empty \c Optional if we're not in a SFINAE context.
8092 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
8093 /// template-deduction context object, which can be used to capture
8094 /// diagnostics that will be suppressed.
8095 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
8096
8097 /// Determines whether we are currently in a context that
8098 /// is not evaluated as per C++ [expr] p5.
8099 bool isUnevaluatedContext() const {
8100 assert(!ExprEvalContexts.empty() &&((!ExprEvalContexts.empty() && "Must be in an expression evaluation context"
) ? static_cast<void> (0) : __assert_fail ("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 8101, __PRETTY_FUNCTION__))
8101 "Must be in an expression evaluation context")((!ExprEvalContexts.empty() && "Must be in an expression evaluation context"
) ? static_cast<void> (0) : __assert_fail ("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 8101, __PRETTY_FUNCTION__))
;
8102 return ExprEvalContexts.back().isUnevaluated();
8103 }
8104
8105 /// RAII class used to determine whether SFINAE has
8106 /// trapped any errors that occur during template argument
8107 /// deduction.
8108 class SFINAETrap {
8109 Sema &SemaRef;
8110 unsigned PrevSFINAEErrors;
8111 bool PrevInNonInstantiationSFINAEContext;
8112 bool PrevAccessCheckingSFINAE;
8113 bool PrevLastDiagnosticIgnored;
8114
8115 public:
8116 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
8117 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
8118 PrevInNonInstantiationSFINAEContext(
8119 SemaRef.InNonInstantiationSFINAEContext),
8120 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
8121 PrevLastDiagnosticIgnored(
8122 SemaRef.getDiagnostics().isLastDiagnosticIgnored())
8123 {
8124 if (!SemaRef.isSFINAEContext())
8125 SemaRef.InNonInstantiationSFINAEContext = true;
8126 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
8127 }
8128
8129 ~SFINAETrap() {
8130 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
8131 SemaRef.InNonInstantiationSFINAEContext
8132 = PrevInNonInstantiationSFINAEContext;
8133 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
8134 SemaRef.getDiagnostics().setLastDiagnosticIgnored(
8135 PrevLastDiagnosticIgnored);
8136 }
8137
8138 /// Determine whether any SFINAE errors have been trapped.
8139 bool hasErrorOccurred() const {
8140 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
8141 }
8142 };
8143
8144 /// RAII class used to indicate that we are performing provisional
8145 /// semantic analysis to determine the validity of a construct, so
8146 /// typo-correction and diagnostics in the immediate context (not within
8147 /// implicitly-instantiated templates) should be suppressed.
8148 class TentativeAnalysisScope {
8149 Sema &SemaRef;
8150 // FIXME: Using a SFINAETrap for this is a hack.
8151 SFINAETrap Trap;
8152 bool PrevDisableTypoCorrection;
8153 public:
8154 explicit TentativeAnalysisScope(Sema &SemaRef)
8155 : SemaRef(SemaRef), Trap(SemaRef, true),
8156 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
8157 SemaRef.DisableTypoCorrection = true;
8158 }
8159 ~TentativeAnalysisScope() {
8160 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
8161 }
8162 };
8163
8164 /// The current instantiation scope used to store local
8165 /// variables.
8166 LocalInstantiationScope *CurrentInstantiationScope;
8167
8168 /// Tracks whether we are in a context where typo correction is
8169 /// disabled.
8170 bool DisableTypoCorrection;
8171
8172 /// The number of typos corrected by CorrectTypo.
8173 unsigned TyposCorrected;
8174
8175 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
8176 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
8177
8178 /// A cache containing identifiers for which typo correction failed and
8179 /// their locations, so that repeated attempts to correct an identifier in a
8180 /// given location are ignored if typo correction already failed for it.
8181 IdentifierSourceLocations TypoCorrectionFailures;
8182
8183 /// Worker object for performing CFG-based warnings.
8184 sema::AnalysisBasedWarnings AnalysisWarnings;
8185 threadSafety::BeforeSet *ThreadSafetyDeclCache;
8186
8187 /// An entity for which implicit template instantiation is required.
8188 ///
8189 /// The source location associated with the declaration is the first place in
8190 /// the source code where the declaration was "used". It is not necessarily
8191 /// the point of instantiation (which will be either before or after the
8192 /// namespace-scope declaration that triggered this implicit instantiation),
8193 /// However, it is the location that diagnostics should generally refer to,
8194 /// because users will need to know what code triggered the instantiation.
8195 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
8196
8197 /// The queue of implicit template instantiations that are required
8198 /// but have not yet been performed.
8199 std::deque<PendingImplicitInstantiation> PendingInstantiations;
8200
8201 /// Queue of implicit template instantiations that cannot be performed
8202 /// eagerly.
8203 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
8204
8205 class GlobalEagerInstantiationScope {
8206 public:
8207 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
8208 : S(S), Enabled(Enabled) {
8209 if (!Enabled) return;
8210
8211 SavedPendingInstantiations.swap(S.PendingInstantiations);
8212 SavedVTableUses.swap(S.VTableUses);
8213 }
8214
8215 void perform() {
8216 if (Enabled) {
8217 S.DefineUsedVTables();
8218 S.PerformPendingInstantiations();
8219 }
8220 }
8221
8222 ~GlobalEagerInstantiationScope() {
8223 if (!Enabled) return;
8224
8225 // Restore the set of pending vtables.
8226 assert(S.VTableUses.empty() &&((S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 8227, __PRETTY_FUNCTION__))
8227 "VTableUses should be empty before it is discarded.")((S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 8227, __PRETTY_FUNCTION__))
;
8228 S.VTableUses.swap(SavedVTableUses);
8229
8230 // Restore the set of pending implicit instantiations.
8231 assert(S.PendingInstantiations.empty() &&((S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 8232, __PRETTY_FUNCTION__))
8232 "PendingInstantiations should be empty before it is discarded.")((S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 8232, __PRETTY_FUNCTION__))
;
8233 S.PendingInstantiations.swap(SavedPendingInstantiations);
8234 }
8235
8236 private:
8237 Sema &S;
8238 SmallVector<VTableUse, 16> SavedVTableUses;
8239 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
8240 bool Enabled;
8241 };
8242
8243 /// The queue of implicit template instantiations that are required
8244 /// and must be performed within the current local scope.
8245 ///
8246 /// This queue is only used for member functions of local classes in
8247 /// templates, which must be instantiated in the same scope as their
8248 /// enclosing function, so that they can reference function-local
8249 /// types, static variables, enumerators, etc.
8250 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
8251
8252 class LocalEagerInstantiationScope {
8253 public:
8254 LocalEagerInstantiationScope(Sema &S) : S(S) {
8255 SavedPendingLocalImplicitInstantiations.swap(
8256 S.PendingLocalImplicitInstantiations);
8257 }
8258
8259 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
8260
8261 ~LocalEagerInstantiationScope() {
8262 assert(S.PendingLocalImplicitInstantiations.empty() &&((S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"
) ? static_cast<void> (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 8263, __PRETTY_FUNCTION__))
8263 "there shouldn't be any pending local implicit instantiations")((S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"
) ? static_cast<void> (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 8263, __PRETTY_FUNCTION__))
;
8264 SavedPendingLocalImplicitInstantiations.swap(
8265 S.PendingLocalImplicitInstantiations);
8266 }
8267
8268 private:
8269 Sema &S;
8270 std::deque<PendingImplicitInstantiation>
8271 SavedPendingLocalImplicitInstantiations;
8272 };
8273
8274 /// A helper class for building up ExtParameterInfos.
8275 class ExtParameterInfoBuilder {
8276 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
8277 bool HasInteresting = false;
8278
8279 public:
8280 /// Set the ExtParameterInfo for the parameter at the given index,
8281 ///
8282 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
8283 assert(Infos.size() <= index)((Infos.size() <= index) ? static_cast<void> (0) : __assert_fail
("Infos.size() <= index", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 8283, __PRETTY_FUNCTION__))
;
8284 Infos.resize(index);
8285 Infos.push_back(info);
8286
8287 if (!HasInteresting)
8288 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
8289 }
8290
8291 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
8292 /// ExtParameterInfo array we've built up.
8293 const FunctionProtoType::ExtParameterInfo *
8294 getPointerOrNull(unsigned numParams) {
8295 if (!HasInteresting) return nullptr;
8296 Infos.resize(numParams);
8297 return Infos.data();
8298 }
8299 };
8300
8301 void PerformPendingInstantiations(bool LocalOnly = false);
8302
8303 TypeSourceInfo *SubstType(TypeSourceInfo *T,
8304 const MultiLevelTemplateArgumentList &TemplateArgs,
8305 SourceLocation Loc, DeclarationName Entity,
8306 bool AllowDeducedTST = false);
8307
8308 QualType SubstType(QualType T,
8309 const MultiLevelTemplateArgumentList &TemplateArgs,
8310 SourceLocation Loc, DeclarationName Entity);
8311
8312 TypeSourceInfo *SubstType(TypeLoc TL,
8313 const MultiLevelTemplateArgumentList &TemplateArgs,
8314 SourceLocation Loc, DeclarationName Entity);
8315
8316 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
8317 const MultiLevelTemplateArgumentList &TemplateArgs,
8318 SourceLocation Loc,
8319 DeclarationName Entity,
8320 CXXRecordDecl *ThisContext,
8321 Qualifiers ThisTypeQuals);
8322 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
8323 const MultiLevelTemplateArgumentList &Args);
8324 bool SubstExceptionSpec(SourceLocation Loc,
8325 FunctionProtoType::ExceptionSpecInfo &ESI,
8326 SmallVectorImpl<QualType> &ExceptionStorage,
8327 const MultiLevelTemplateArgumentList &Args);
8328 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
8329 const MultiLevelTemplateArgumentList &TemplateArgs,
8330 int indexAdjustment,
8331 Optional<unsigned> NumExpansions,
8332 bool ExpectParameterPack);
8333 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
8334 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
8335 const MultiLevelTemplateArgumentList &TemplateArgs,
8336 SmallVectorImpl<QualType> &ParamTypes,
8337 SmallVectorImpl<ParmVarDecl *> *OutParams,
8338 ExtParameterInfoBuilder &ParamInfos);
8339 ExprResult SubstExpr(Expr *E,
8340 const MultiLevelTemplateArgumentList &TemplateArgs);
8341
8342 /// Substitute the given template arguments into a list of
8343 /// expressions, expanding pack expansions if required.
8344 ///
8345 /// \param Exprs The list of expressions to substitute into.
8346 ///
8347 /// \param IsCall Whether this is some form of call, in which case
8348 /// default arguments will be dropped.
8349 ///
8350 /// \param TemplateArgs The set of template arguments to substitute.
8351 ///
8352 /// \param Outputs Will receive all of the substituted arguments.
8353 ///
8354 /// \returns true if an error occurred, false otherwise.
8355 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
8356 const MultiLevelTemplateArgumentList &TemplateArgs,
8357 SmallVectorImpl<Expr *> &Outputs);
8358
8359 StmtResult SubstStmt(Stmt *S,
8360 const MultiLevelTemplateArgumentList &TemplateArgs);
8361
8362 TemplateParameterList *
8363 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
8364 const MultiLevelTemplateArgumentList &TemplateArgs);
8365
8366 Decl *SubstDecl(Decl *D, DeclContext *Owner,
8367 const MultiLevelTemplateArgumentList &TemplateArgs);
8368
8369 ExprResult SubstInitializer(Expr *E,
8370 const MultiLevelTemplateArgumentList &TemplateArgs,
8371 bool CXXDirectInit);
8372
8373 bool
8374 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
8375 CXXRecordDecl *Pattern,
8376 const MultiLevelTemplateArgumentList &TemplateArgs);
8377
8378 bool
8379 InstantiateClass(SourceLocation PointOfInstantiation,
8380 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
8381 const MultiLevelTemplateArgumentList &TemplateArgs,
8382 TemplateSpecializationKind TSK,
8383 bool Complain = true);
8384
8385 bool InstantiateEnum(SourceLocation PointOfInstantiation,
8386 EnumDecl *Instantiation, EnumDecl *Pattern,
8387 const MultiLevelTemplateArgumentList &TemplateArgs,
8388 TemplateSpecializationKind TSK);
8389
8390 bool InstantiateInClassInitializer(
8391 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
8392 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
8393
8394 struct LateInstantiatedAttribute {
8395 const Attr *TmplAttr;
8396 LocalInstantiationScope *Scope;
8397 Decl *NewDecl;
8398
8399 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
8400 Decl *D)
8401 : TmplAttr(A), Scope(S), NewDecl(D)
8402 { }
8403 };
8404 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
8405
8406 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
8407 const Decl *Pattern, Decl *Inst,
8408 LateInstantiatedAttrVec *LateAttrs = nullptr,
8409 LocalInstantiationScope *OuterMostScope = nullptr);
8410
8411 void
8412 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
8413 const Decl *Pattern, Decl *Inst,
8414 LateInstantiatedAttrVec *LateAttrs = nullptr,
8415 LocalInstantiationScope *OuterMostScope = nullptr);
8416
8417 bool usesPartialOrExplicitSpecialization(
8418 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
8419
8420 bool
8421 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
8422 ClassTemplateSpecializationDecl *ClassTemplateSpec,
8423 TemplateSpecializationKind TSK,
8424 bool Complain = true);
8425
8426 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
8427 CXXRecordDecl *Instantiation,
8428 const MultiLevelTemplateArgumentList &TemplateArgs,
8429 TemplateSpecializationKind TSK);
8430
8431 void InstantiateClassTemplateSpecializationMembers(
8432 SourceLocation PointOfInstantiation,
8433 ClassTemplateSpecializationDecl *ClassTemplateSpec,
8434 TemplateSpecializationKind TSK);
8435
8436 NestedNameSpecifierLoc
8437 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
8438 const MultiLevelTemplateArgumentList &TemplateArgs);
8439
8440 DeclarationNameInfo
8441 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
8442 const MultiLevelTemplateArgumentList &TemplateArgs);
8443 TemplateName
8444 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
8445 SourceLocation Loc,
8446 const MultiLevelTemplateArgumentList &TemplateArgs);
8447 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
8448 TemplateArgumentListInfo &Result,
8449 const MultiLevelTemplateArgumentList &TemplateArgs);
8450
8451 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
8452 FunctionDecl *Function);
8453 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
8454 const TemplateArgumentList *Args,
8455 SourceLocation Loc);
8456 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
8457 FunctionDecl *Function,
8458 bool Recursive = false,
8459 bool DefinitionRequired = false,
8460 bool AtEndOfTU = false);
8461 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
8462 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
8463 const TemplateArgumentList &TemplateArgList,
8464 const TemplateArgumentListInfo &TemplateArgsInfo,
8465 SmallVectorImpl<TemplateArgument> &Converted,
8466 SourceLocation PointOfInstantiation, void *InsertPos,
8467 LateInstantiatedAttrVec *LateAttrs = nullptr,
8468 LocalInstantiationScope *StartingScope = nullptr);
8469 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
8470 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
8471 const MultiLevelTemplateArgumentList &TemplateArgs);
8472 void
8473 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
8474 const MultiLevelTemplateArgumentList &TemplateArgs,
8475 LateInstantiatedAttrVec *LateAttrs,
8476 DeclContext *Owner,
8477 LocalInstantiationScope *StartingScope,
8478 bool InstantiatingVarTemplate = false,
8479 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
8480
8481 VarDecl *getVarTemplateSpecialization(
8482 VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs,
8483 const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc);
8484
8485 void InstantiateVariableInitializer(
8486 VarDecl *Var, VarDecl *OldVar,
8487 const MultiLevelTemplateArgumentList &TemplateArgs);
8488 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
8489 VarDecl *Var, bool Recursive = false,
8490 bool DefinitionRequired = false,
8491 bool AtEndOfTU = false);
8492
8493 void InstantiateMemInitializers(CXXConstructorDecl *New,
8494 const CXXConstructorDecl *Tmpl,
8495 const MultiLevelTemplateArgumentList &TemplateArgs);
8496
8497 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
8498 const MultiLevelTemplateArgumentList &TemplateArgs,
8499 bool FindingInstantiatedContext = false);
8500 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
8501 const MultiLevelTemplateArgumentList &TemplateArgs);
8502
8503 // Objective-C declarations.
8504 enum ObjCContainerKind {
8505 OCK_None = -1,
8506 OCK_Interface = 0,
8507 OCK_Protocol,
8508 OCK_Category,
8509 OCK_ClassExtension,
8510 OCK_Implementation,
8511 OCK_CategoryImplementation
8512 };
8513 ObjCContainerKind getObjCContainerKind() const;
8514
8515 DeclResult actOnObjCTypeParam(Scope *S,
8516 ObjCTypeParamVariance variance,
8517 SourceLocation varianceLoc,
8518 unsigned index,
8519 IdentifierInfo *paramName,
8520 SourceLocation paramLoc,
8521 SourceLocation colonLoc,
8522 ParsedType typeBound);
8523
8524 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
8525 ArrayRef<Decl *> typeParams,
8526 SourceLocation rAngleLoc);
8527 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
8528
8529 Decl *ActOnStartClassInterface(
8530 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
8531 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
8532 IdentifierInfo *SuperName, SourceLocation SuperLoc,
8533 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
8534 Decl *const *ProtoRefs, unsigned NumProtoRefs,
8535 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
8536 const ParsedAttributesView &AttrList);
8537
8538 void ActOnSuperClassOfClassInterface(Scope *S,
8539 SourceLocation AtInterfaceLoc,
8540 ObjCInterfaceDecl *IDecl,
8541 IdentifierInfo *ClassName,
8542 SourceLocation ClassLoc,
8543 IdentifierInfo *SuperName,
8544 SourceLocation SuperLoc,
8545 ArrayRef<ParsedType> SuperTypeArgs,
8546 SourceRange SuperTypeArgsRange);
8547
8548 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
8549 SmallVectorImpl<SourceLocation> &ProtocolLocs,
8550 IdentifierInfo *SuperName,
8551 SourceLocation SuperLoc);
8552
8553 Decl *ActOnCompatibilityAlias(
8554 SourceLocation AtCompatibilityAliasLoc,
8555 IdentifierInfo *AliasName, SourceLocation AliasLocation,
8556 IdentifierInfo *ClassName, SourceLocation ClassLocation);
8557
8558 bool CheckForwardProtocolDeclarationForCircularDependency(
8559 IdentifierInfo *PName,
8560 SourceLocation &PLoc, SourceLocation PrevLoc,
8561 const ObjCList<ObjCProtocolDecl> &PList);
8562
8563 Decl *ActOnStartProtocolInterface(
8564 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
8565 SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
8566 unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
8567 SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
8568
8569 Decl *ActOnStartCategoryInterface(
8570 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
8571 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
8572 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
8573 Decl *const *ProtoRefs, unsigned NumProtoRefs,
8574 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
8575 const ParsedAttributesView &AttrList);
8576
8577 Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
8578 IdentifierInfo *ClassName,
8579 SourceLocation ClassLoc,
8580 IdentifierInfo *SuperClassname,
8581 SourceLocation SuperClassLoc,
8582 const ParsedAttributesView &AttrList);
8583
8584 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
8585 IdentifierInfo *ClassName,
8586 SourceLocation ClassLoc,
8587 IdentifierInfo *CatName,
8588 SourceLocation CatLoc,
8589 const ParsedAttributesView &AttrList);
8590
8591 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
8592 ArrayRef<Decl *> Decls);
8593
8594 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
8595 IdentifierInfo **IdentList,
8596 SourceLocation *IdentLocs,
8597 ArrayRef<ObjCTypeParamList *> TypeParamLists,
8598 unsigned NumElts);
8599
8600 DeclGroupPtrTy
8601 ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
8602 ArrayRef<IdentifierLocPair> IdentList,
8603 const ParsedAttributesView &attrList);
8604
8605 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
8606 ArrayRef<IdentifierLocPair> ProtocolId,
8607 SmallVectorImpl<Decl *> &Protocols);
8608
8609 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
8610 SourceLocation ProtocolLoc,
8611 IdentifierInfo *TypeArgId,
8612 SourceLocation TypeArgLoc,
8613 bool SelectProtocolFirst = false);
8614
8615 /// Given a list of identifiers (and their locations), resolve the
8616 /// names to either Objective-C protocol qualifiers or type
8617 /// arguments, as appropriate.
8618 void actOnObjCTypeArgsOrProtocolQualifiers(
8619 Scope *S,
8620 ParsedType baseType,
8621 SourceLocation lAngleLoc,
8622 ArrayRef<IdentifierInfo *> identifiers,
8623 ArrayRef<SourceLocation> identifierLocs,
8624 SourceLocation rAngleLoc,
8625 SourceLocation &typeArgsLAngleLoc,
8626 SmallVectorImpl<ParsedType> &typeArgs,
8627 SourceLocation &typeArgsRAngleLoc,
8628 SourceLocation &protocolLAngleLoc,
8629 SmallVectorImpl<Decl *> &protocols,
8630 SourceLocation &protocolRAngleLoc,
8631 bool warnOnIncompleteProtocols);
8632
8633 /// Build a an Objective-C protocol-qualified 'id' type where no
8634 /// base type was specified.
8635 TypeResult actOnObjCProtocolQualifierType(
8636 SourceLocation lAngleLoc,
8637 ArrayRef<Decl *> protocols,
8638 ArrayRef<SourceLocation> protocolLocs,
8639 SourceLocation rAngleLoc);
8640
8641 /// Build a specialized and/or protocol-qualified Objective-C type.
8642 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
8643 Scope *S,
8644 SourceLocation Loc,
8645 ParsedType BaseType,
8646 SourceLocation TypeArgsLAngleLoc,
8647 ArrayRef<ParsedType> TypeArgs,
8648 SourceLocation TypeArgsRAngleLoc,
8649 SourceLocation ProtocolLAngleLoc,
8650 ArrayRef<Decl *> Protocols,
8651 ArrayRef<SourceLocation> ProtocolLocs,
8652 SourceLocation ProtocolRAngleLoc);
8653
8654 /// Build an Objective-C type parameter type.
8655 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
8656 SourceLocation ProtocolLAngleLoc,
8657 ArrayRef<ObjCProtocolDecl *> Protocols,
8658 ArrayRef<SourceLocation> ProtocolLocs,
8659 SourceLocation ProtocolRAngleLoc,
8660 bool FailOnError = false);
8661
8662 /// Build an Objective-C object pointer type.
8663 QualType BuildObjCObjectType(QualType BaseType,
8664 SourceLocation Loc,
8665 SourceLocation TypeArgsLAngleLoc,
8666 ArrayRef<TypeSourceInfo *> TypeArgs,
8667 SourceLocation TypeArgsRAngleLoc,
8668 SourceLocation ProtocolLAngleLoc,
8669 ArrayRef<ObjCProtocolDecl *> Protocols,
8670 ArrayRef<SourceLocation> ProtocolLocs,
8671 SourceLocation ProtocolRAngleLoc,
8672 bool FailOnError = false);
8673
8674 /// Ensure attributes are consistent with type.
8675 /// \param [in, out] Attributes The attributes to check; they will
8676 /// be modified to be consistent with \p PropertyTy.
8677 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
8678 SourceLocation Loc,
8679 unsigned &Attributes,
8680 bool propertyInPrimaryClass);
8681
8682 /// Process the specified property declaration and create decls for the
8683 /// setters and getters as needed.
8684 /// \param property The property declaration being processed
8685 void ProcessPropertyDecl(ObjCPropertyDecl *property);
8686
8687
8688 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
8689 ObjCPropertyDecl *SuperProperty,
8690 const IdentifierInfo *Name,
8691 bool OverridingProtocolProperty);
8692
8693 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
8694 ObjCInterfaceDecl *ID);
8695
8696 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
8697 ArrayRef<Decl *> allMethods = None,
8698 ArrayRef<DeclGroupPtrTy> allTUVars = None);
8699
8700 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
8701 SourceLocation LParenLoc,
8702 FieldDeclarator &FD, ObjCDeclSpec &ODS,
8703 Selector GetterSel, Selector SetterSel,
8704 tok::ObjCKeywordKind MethodImplKind,
8705 DeclContext *lexicalDC = nullptr);
8706
8707 Decl *ActOnPropertyImplDecl(Scope *S,
8708 SourceLocation AtLoc,
8709 SourceLocation PropertyLoc,
8710 bool ImplKind,
8711 IdentifierInfo *PropertyId,
8712 IdentifierInfo *PropertyIvar,
8713 SourceLocation PropertyIvarLoc,
8714 ObjCPropertyQueryKind QueryKind);
8715
8716 enum ObjCSpecialMethodKind {
8717 OSMK_None,
8718 OSMK_Alloc,
8719 OSMK_New,
8720 OSMK_Copy,
8721 OSMK_RetainingInit,
8722 OSMK_NonRetainingInit
8723 };
8724
8725 struct ObjCArgInfo {
8726 IdentifierInfo *Name;
8727 SourceLocation NameLoc;
8728 // The Type is null if no type was specified, and the DeclSpec is invalid
8729 // in this case.
8730 ParsedType Type;
8731 ObjCDeclSpec DeclSpec;
8732
8733 /// ArgAttrs - Attribute list for this argument.
8734 ParsedAttributesView ArgAttrs;
8735 };
8736
8737 Decl *ActOnMethodDeclaration(
8738 Scope *S,
8739 SourceLocation BeginLoc, // location of the + or -.
8740 SourceLocation EndLoc, // location of the ; or {.
8741 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
8742 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
8743 // optional arguments. The number of types/arguments is obtained
8744 // from the Sel.getNumArgs().
8745 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
8746 unsigned CNumArgs, // c-style args
8747 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
8748 bool isVariadic, bool MethodDefinition);
8749
8750 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
8751 const ObjCObjectPointerType *OPT,
8752 bool IsInstance);
8753 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
8754 bool IsInstance);
8755
8756 bool CheckARCMethodDecl(ObjCMethodDecl *method);
8757 bool inferObjCARCLifetime(ValueDecl *decl);
8758
8759 ExprResult
8760 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
8761 Expr *BaseExpr,
8762 SourceLocation OpLoc,
8763 DeclarationName MemberName,
8764 SourceLocation MemberLoc,
8765 SourceLocation SuperLoc, QualType SuperType,
8766 bool Super);
8767
8768 ExprResult
8769 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
8770 IdentifierInfo &propertyName,
8771 SourceLocation receiverNameLoc,
8772 SourceLocation propertyNameLoc);
8773
8774 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
8775
8776 /// Describes the kind of message expression indicated by a message
8777 /// send that starts with an identifier.
8778 enum ObjCMessageKind {
8779 /// The message is sent to 'super'.
8780 ObjCSuperMessage,
8781 /// The message is an instance message.
8782 ObjCInstanceMessage,
8783 /// The message is a class message, and the identifier is a type
8784 /// name.
8785 ObjCClassMessage
8786 };
8787
8788 ObjCMessageKind getObjCMessageKind(Scope *S,
8789 IdentifierInfo *Name,
8790 SourceLocation NameLoc,
8791 bool IsSuper,
8792 bool HasTrailingDot,
8793 ParsedType &ReceiverType);
8794
8795 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
8796 Selector Sel,
8797 SourceLocation LBracLoc,
8798 ArrayRef<SourceLocation> SelectorLocs,
8799 SourceLocation RBracLoc,
8800 MultiExprArg Args);
8801
8802 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
8803 QualType ReceiverType,
8804 SourceLocation SuperLoc,
8805 Selector Sel,
8806 ObjCMethodDecl *Method,
8807 SourceLocation LBracLoc,
8808 ArrayRef<SourceLocation> SelectorLocs,
8809 SourceLocation RBracLoc,
8810 MultiExprArg Args,
8811 bool isImplicit = false);
8812
8813 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
8814 bool isSuperReceiver,
8815 SourceLocation Loc,
8816 Selector Sel,
8817 ObjCMethodDecl *Method,
8818 MultiExprArg Args);
8819
8820 ExprResult ActOnClassMessage(Scope *S,
8821 ParsedType Receiver,
8822 Selector Sel,
8823 SourceLocation LBracLoc,
8824 ArrayRef<SourceLocation> SelectorLocs,
8825 SourceLocation RBracLoc,
8826 MultiExprArg Args);
8827
8828 ExprResult BuildInstanceMessage(Expr *Receiver,
8829 QualType ReceiverType,
8830 SourceLocation SuperLoc,
8831 Selector Sel,
8832 ObjCMethodDecl *Method,
8833 SourceLocation LBracLoc,
8834 ArrayRef<SourceLocation> SelectorLocs,
8835 SourceLocation RBracLoc,
8836 MultiExprArg Args,
8837 bool isImplicit = false);
8838
8839 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
8840 QualType ReceiverType,
8841 SourceLocation Loc,
8842 Selector Sel,
8843 ObjCMethodDecl *Method,
8844 MultiExprArg Args);
8845
8846 ExprResult ActOnInstanceMessage(Scope *S,
8847 Expr *Receiver,
8848 Selector Sel,
8849 SourceLocation LBracLoc,
8850 ArrayRef<SourceLocation> SelectorLocs,
8851 SourceLocation RBracLoc,
8852 MultiExprArg Args);
8853
8854 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
8855 ObjCBridgeCastKind Kind,
8856 SourceLocation BridgeKeywordLoc,
8857 TypeSourceInfo *TSInfo,
8858 Expr *SubExpr);
8859
8860 ExprResult ActOnObjCBridgedCast(Scope *S,
8861 SourceLocation LParenLoc,
8862 ObjCBridgeCastKind Kind,
8863 SourceLocation BridgeKeywordLoc,
8864 ParsedType Type,
8865 SourceLocation RParenLoc,
8866 Expr *SubExpr);
8867
8868 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
8869
8870 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
8871
8872 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
8873 CastKind &Kind);
8874
8875 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
8876 QualType DestType, QualType SrcType,
8877 ObjCInterfaceDecl *&RelatedClass,
8878 ObjCMethodDecl *&ClassMethod,
8879 ObjCMethodDecl *&InstanceMethod,
8880 TypedefNameDecl *&TDNDecl,
8881 bool CfToNs, bool Diagnose = true);
8882
8883 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8884 QualType DestType, QualType SrcType,
8885 Expr *&SrcExpr, bool Diagnose = true);
8886
8887 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8888 bool Diagnose = true);
8889
8890 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8891
8892 /// Check whether the given new method is a valid override of the
8893 /// given overridden method, and set any properties that should be inherited.
8894 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8895 const ObjCMethodDecl *Overridden);
8896
8897 /// Describes the compatibility of a result type with its method.
8898 enum ResultTypeCompatibilityKind {
8899 RTC_Compatible,
8900 RTC_Incompatible,
8901 RTC_Unknown
8902 };
8903
8904 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8905 ObjCInterfaceDecl *CurrentClass,
8906 ResultTypeCompatibilityKind RTC);
8907
8908 enum PragmaOptionsAlignKind {
8909 POAK_Native, // #pragma options align=native
8910 POAK_Natural, // #pragma options align=natural
8911 POAK_Packed, // #pragma options align=packed
8912 POAK_Power, // #pragma options align=power
8913 POAK_Mac68k, // #pragma options align=mac68k
8914 POAK_Reset // #pragma options align=reset
8915 };
8916
8917 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
8918 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
8919 PragmaClangSectionAction Action,
8920 PragmaClangSectionKind SecKind, StringRef SecName);
8921
8922 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8923 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8924 SourceLocation PragmaLoc);
8925
8926 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8927 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8928 StringRef SlotLabel, Expr *Alignment);
8929
8930 enum class PragmaPackDiagnoseKind {
8931 NonDefaultStateAtInclude,
8932 ChangedStateAtExit
8933 };
8934
8935 void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
8936 SourceLocation IncludeLoc);
8937 void DiagnoseUnterminatedPragmaPack();
8938
8939 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8940 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8941
8942 /// ActOnPragmaMSComment - Called on well formed
8943 /// \#pragma comment(kind, "arg").
8944 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8945 StringRef Arg);
8946
8947 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8948 /// pointers_to_members(representation method[, general purpose
8949 /// representation]).
8950 void ActOnPragmaMSPointersToMembers(
8951 LangOptions::PragmaMSPointersToMembersKind Kind,
8952 SourceLocation PragmaLoc);
8953
8954 /// Called on well formed \#pragma vtordisp().
8955 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8956 SourceLocation PragmaLoc,
8957 MSVtorDispAttr::Mode Value);
8958
8959 enum PragmaSectionKind {
8960 PSK_DataSeg,
8961 PSK_BSSSeg,
8962 PSK_ConstSeg,
8963 PSK_CodeSeg,
8964 };
8965
8966 bool UnifySection(StringRef SectionName,
8967 int SectionFlags,
8968 DeclaratorDecl *TheDecl);
8969 bool UnifySection(StringRef SectionName,
8970 int SectionFlags,
8971 SourceLocation PragmaSectionLocation);
8972
8973 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8974 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8975 PragmaMsStackAction Action,
8976 llvm::StringRef StackSlotLabel,
8977 StringLiteral *SegmentName,
8978 llvm::StringRef PragmaName);
8979
8980 /// Called on well formed \#pragma section().
8981 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8982 int SectionFlags, StringLiteral *SegmentName);
8983
8984 /// Called on well-formed \#pragma init_seg().
8985 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8986 StringLiteral *SegmentName);
8987
8988 /// Called on #pragma clang __debug dump II
8989 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8990
8991 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8992 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8993 StringRef Value);
8994
8995 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8996 void ActOnPragmaUnused(const Token &Identifier,
8997 Scope *curScope,
8998 SourceLocation PragmaLoc);
8999
9000 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
9001 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
9002 SourceLocation PragmaLoc);
9003
9004 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
9005 SourceLocation Loc);
9006 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
9007
9008 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
9009 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
9010 SourceLocation PragmaLoc,
9011 SourceLocation WeakNameLoc);
9012
9013 /// ActOnPragmaRedefineExtname - Called on well formed
9014 /// \#pragma redefine_extname oldname newname.
9015 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
9016 IdentifierInfo* AliasName,
9017 SourceLocation PragmaLoc,
9018 SourceLocation WeakNameLoc,
9019 SourceLocation AliasNameLoc);
9020
9021 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
9022 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
9023 IdentifierInfo* AliasName,
9024 SourceLocation PragmaLoc,
9025 SourceLocation WeakNameLoc,
9026 SourceLocation AliasNameLoc);
9027
9028 /// ActOnPragmaFPContract - Called on well formed
9029 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
9030 /// \#pragma clang fp contract
9031 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
9032
9033 /// ActOnPragmaFenvAccess - Called on well formed
9034 /// \#pragma STDC FENV_ACCESS
9035 void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC);
9036
9037 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
9038 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
9039 void AddAlignmentAttributesForRecord(RecordDecl *RD);
9040
9041 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
9042 void AddMsStructLayoutForRecord(RecordDecl *RD);
9043
9044 /// FreePackedContext - Deallocate and null out PackContext.
9045 void FreePackedContext();
9046
9047 /// PushNamespaceVisibilityAttr - Note that we've entered a
9048 /// namespace with a visibility attribute.
9049 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
9050 SourceLocation Loc);
9051
9052 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
9053 /// add an appropriate visibility attribute.
9054 void AddPushedVisibilityAttribute(Decl *RD);
9055
9056 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
9057 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
9058 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
9059
9060 /// FreeVisContext - Deallocate and null out VisContext.
9061 void FreeVisContext();
9062
9063 /// AddCFAuditedAttribute - Check whether we're currently within
9064 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
9065 /// the appropriate attribute.
9066 void AddCFAuditedAttribute(Decl *D);
9067
9068 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
9069 SourceLocation PragmaLoc,
9070 attr::ParsedSubjectMatchRuleSet Rules);
9071 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
9072 const IdentifierInfo *Namespace);
9073
9074 /// Called on well-formed '\#pragma clang attribute pop'.
9075 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
9076 const IdentifierInfo *Namespace);
9077
9078 /// Adds the attributes that have been specified using the
9079 /// '\#pragma clang attribute push' directives to the given declaration.
9080 void AddPragmaAttributes(Scope *S, Decl *D);
9081
9082 void DiagnoseUnterminatedPragmaAttribute();
9083
9084 /// Called on well formed \#pragma clang optimize.
9085 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
9086
9087 /// Get the location for the currently active "\#pragma clang optimize
9088 /// off". If this location is invalid, then the state of the pragma is "on".
9089 SourceLocation getOptimizeOffPragmaLocation() const {
9090 return OptimizeOffPragmaLocation;
9091 }
9092
9093 /// Only called on function definitions; if there is a pragma in scope
9094 /// with the effect of a range-based optnone, consider marking the function
9095 /// with attribute optnone.
9096 void AddRangeBasedOptnone(FunctionDecl *FD);
9097
9098 /// Adds the 'optnone' attribute to the function declaration if there
9099 /// are no conflicts; Loc represents the location causing the 'optnone'
9100 /// attribute to be added (usually because of a pragma).
9101 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
9102
9103 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
9104 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
9105 bool IsPackExpansion);
9106 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
9107 bool IsPackExpansion);
9108
9109 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
9110 /// declaration.
9111 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
9112 Expr *OE);
9113
9114 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
9115 /// declaration.
9116 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
9117 Expr *ParamExpr);
9118
9119 /// AddAlignValueAttr - Adds an align_value attribute to a particular
9120 /// declaration.
9121 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
9122
9123 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
9124 /// declaration.
9125 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
9126 Expr *MaxThreads, Expr *MinBlocks);
9127
9128 /// AddModeAttr - Adds a mode attribute to a particular declaration.
9129 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
9130 bool InInstantiation = false);
9131
9132 void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
9133 ParameterABI ABI);
9134
9135 enum class RetainOwnershipKind {NS, CF, OS};
9136 void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
9137 RetainOwnershipKind K, bool IsTemplateInstantiation);
9138
9139 /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
9140 /// attribute to a particular declaration.
9141 void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
9142 Expr *Min, Expr *Max);
9143
9144 /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
9145 /// particular declaration.
9146 void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
9147 Expr *Min, Expr *Max);
9148
9149 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
9150
9151 //===--------------------------------------------------------------------===//
9152 // C++ Coroutines TS
9153 //
9154 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
9155 StringRef Keyword);
9156 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
9157 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
9158 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
9159
9160 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
9161 bool IsImplicit = false);
9162 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
9163 UnresolvedLookupExpr* Lookup);
9164 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
9165 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
9166 bool IsImplicit = false);
9167 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
9168 bool buildCoroutineParameterMoves(SourceLocation Loc);
9169 VarDecl *buildCoroutinePromise(SourceLocation Loc);
9170 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
9171 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
9172 SourceLocation FuncLoc);
9173
9174 //===--------------------------------------------------------------------===//
9175 // OpenCL extensions.
9176 //
9177private:
9178 std::string CurrOpenCLExtension;
9179 /// Extensions required by an OpenCL type.
9180 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
9181 /// Extensions required by an OpenCL declaration.
9182 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
9183public:
9184 llvm::StringRef getCurrentOpenCLExtension() const {
9185 return CurrOpenCLExtension;
9186 }
9187
9188 /// Check if a function declaration \p FD associates with any
9189 /// extensions present in OpenCLDeclExtMap and if so return the
9190 /// extension(s) name(s).
9191 std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD);
9192
9193 /// Check if a function type \p FT associates with any
9194 /// extensions present in OpenCLTypeExtMap and if so return the
9195 /// extension(s) name(s).
9196 std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT);
9197
9198 /// Find an extension in an appropriate extension map and return its name
9199 template<typename T, typename MapT>
9200 std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map);
9201
9202 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
9203 CurrOpenCLExtension = Ext;
9204 }
9205
9206 /// Set OpenCL extensions for a type which can only be used when these
9207 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
9208 /// \param Exts A space separated list of OpenCL extensions.
9209 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
9210
9211 /// Set OpenCL extensions for a declaration which can only be
9212 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
9213 /// nothing.
9214 /// \param Exts A space separated list of OpenCL extensions.
9215 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
9216
9217 /// Set current OpenCL extensions for a type which can only be used
9218 /// when these OpenCL extensions are enabled. If current OpenCL extension is
9219 /// empty, do nothing.
9220 void setCurrentOpenCLExtensionForType(QualType T);
9221
9222 /// Set current OpenCL extensions for a declaration which
9223 /// can only be used when these OpenCL extensions are enabled. If current
9224 /// OpenCL extension is empty, do nothing.
9225 void setCurrentOpenCLExtensionForDecl(Decl *FD);
9226
9227 bool isOpenCLDisabledDecl(Decl *FD);
9228
9229 /// Check if type \p T corresponding to declaration specifier \p DS
9230 /// is disabled due to required OpenCL extensions being disabled. If so,
9231 /// emit diagnostics.
9232 /// \return true if type is disabled.
9233 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
9234
9235 /// Check if declaration \p D used by expression \p E
9236 /// is disabled due to required OpenCL extensions being disabled. If so,
9237 /// emit diagnostics.
9238 /// \return true if type is disabled.
9239 bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
9240
9241 //===--------------------------------------------------------------------===//
9242 // OpenMP directives and clauses.
9243 //
9244private:
9245 void *VarDataSharingAttributesStack;
9246 /// Number of nested '#pragma omp declare target' directives.
9247 unsigned DeclareTargetNestingLevel = 0;
9248 /// Initialization of data-sharing attributes stack.
9249 void InitDataSharingAttributesStack();
9250 void DestroyDataSharingAttributesStack();
9251 ExprResult
9252 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
9253 bool StrictlyPositive = true);
9254 /// Returns OpenMP nesting level for current directive.
9255 unsigned getOpenMPNestingLevel() const;
9256
9257 /// Adjusts the function scopes index for the target-based regions.
9258 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
9259 unsigned Level) const;
9260
9261 /// Returns the number of scopes associated with the construct on the given
9262 /// OpenMP level.
9263 int getNumberOfConstructScopes(unsigned Level) const;
9264
9265 /// Push new OpenMP function region for non-capturing function.
9266 void pushOpenMPFunctionRegion();
9267
9268 /// Pop OpenMP function region for non-capturing function.
9269 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
9270
9271 /// Check whether we're allowed to call Callee from the current function.
9272 void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
9273 bool CheckForDelayedContext = true);
9274
9275 /// Check whether we're allowed to call Callee from the current function.
9276 void checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
9277 bool CheckCaller = true);
9278
9279 /// Check if the expression is allowed to be used in expressions for the
9280 /// OpenMP devices.
9281 void checkOpenMPDeviceExpr(const Expr *E);
9282
9283 /// Finishes analysis of the deferred functions calls that may be declared as
9284 /// host/nohost during device/host compilation.
9285 void finalizeOpenMPDelayedAnalysis();
9286
9287 /// Checks if a type or a declaration is disabled due to the owning extension
9288 /// being disabled, and emits diagnostic messages if it is disabled.
9289 /// \param D type or declaration to be checked.
9290 /// \param DiagLoc source location for the diagnostic message.
9291 /// \param DiagInfo information to be emitted for the diagnostic message.
9292 /// \param SrcRange source range of the declaration.
9293 /// \param Map maps type or declaration to the extensions.
9294 /// \param Selector selects diagnostic message: 0 for type and 1 for
9295 /// declaration.
9296 /// \return true if the type or declaration is disabled.
9297 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
9298 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
9299 MapT &Map, unsigned Selector = 0,
9300 SourceRange SrcRange = SourceRange());
9301
9302 /// Marks all the functions that might be required for the currently active
9303 /// OpenMP context.
9304 void markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
9305 FunctionDecl *Func,
9306 bool MightBeOdrUse);
9307
9308public:
9309 /// Struct to store the context selectors info for declare variant directive.
9310 using OMPCtxStringType = SmallString<8>;
9311 using OMPCtxSelectorData =
9312 OpenMPCtxSelectorData<OMPCtxStringType, SmallVector<OMPCtxStringType, 4>,
9313 ExprResult>;
9314
9315 /// Checks if the variant/multiversion functions are compatible.
9316 bool areMultiversionVariantFunctionsCompatible(
9317 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9318 const PartialDiagnostic &NoProtoDiagID,
9319 const PartialDiagnosticAt &NoteCausedDiagIDAt,
9320 const PartialDiagnosticAt &NoSupportDiagIDAt,
9321 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9322 bool ConstexprSupported, bool CLinkageMayDiffer);
9323
9324 /// Function tries to capture lambda's captured variables in the OpenMP region
9325 /// before the original lambda is captured.
9326 void tryCaptureOpenMPLambdas(ValueDecl *V);
9327
9328 /// Return true if the provided declaration \a VD should be captured by
9329 /// reference.
9330 /// \param Level Relative level of nested OpenMP construct for that the check
9331 /// is performed.
9332 /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
9333 bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
9334 unsigned OpenMPCaptureLevel) const;
9335
9336 /// Check if the specified variable is used in one of the private
9337 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
9338 /// constructs.
9339 VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
9340 unsigned StopAt = 0);
9341 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
9342 ExprObjectKind OK, SourceLocation Loc);
9343
9344 /// If the current region is a loop-based region, mark the start of the loop
9345 /// construct.
9346 void startOpenMPLoop();
9347
9348 /// If the current region is a range loop-based region, mark the start of the
9349 /// loop construct.
9350 void startOpenMPCXXRangeFor();
9351
9352 /// Check if the specified variable is used in 'private' clause.
9353 /// \param Level Relative level of nested OpenMP construct for that the check
9354 /// is performed.
9355 bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const;
9356
9357 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
9358 /// for \p FD based on DSA for the provided corresponding captured declaration
9359 /// \p D.
9360 void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
9361
9362 /// Check if the specified variable is captured by 'target' directive.
9363 /// \param Level Relative level of nested OpenMP construct for that the check
9364 /// is performed.
9365 bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const;
9366
9367 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
9368 Expr *Op);
9369 /// Called on start of new data sharing attribute block.
9370 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
9371 const DeclarationNameInfo &DirName, Scope *CurScope,
9372 SourceLocation Loc);
9373 /// Start analysis of clauses.
9374 void StartOpenMPClause(OpenMPClauseKind K);
9375 /// End analysis of clauses.
9376 void EndOpenMPClause();
9377 /// Called on end of data sharing attribute block.
9378 void EndOpenMPDSABlock(Stmt *CurDirective);
9379
9380 /// Check if the current region is an OpenMP loop region and if it is,
9381 /// mark loop control variable, used in \p Init for loop initialization, as
9382 /// private by default.
9383 /// \param Init First part of the for loop.
9384 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
9385
9386 // OpenMP directives and clauses.
9387 /// Called on correct id-expression from the '#pragma omp
9388 /// threadprivate'.
9389 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
9390 const DeclarationNameInfo &Id,
9391 OpenMPDirectiveKind Kind);
9392 /// Called on well-formed '#pragma omp threadprivate'.
9393 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
9394 SourceLocation Loc,
9395 ArrayRef<Expr *> VarList);
9396 /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
9397 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
9398 ArrayRef<Expr *> VarList);
9399 /// Called on well-formed '#pragma omp allocate'.
9400 DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
9401 ArrayRef<Expr *> VarList,
9402 ArrayRef<OMPClause *> Clauses,
9403 DeclContext *Owner = nullptr);
9404 /// Called on well-formed '#pragma omp requires'.
9405 DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
9406 ArrayRef<OMPClause *> ClauseList);
9407 /// Check restrictions on Requires directive
9408 OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
9409 ArrayRef<OMPClause *> Clauses);
9410 /// Check if the specified type is allowed to be used in 'omp declare
9411 /// reduction' construct.
9412 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
9413 TypeResult ParsedType);
9414 /// Called on start of '#pragma omp declare reduction'.
9415 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
9416 Scope *S, DeclContext *DC, DeclarationName Name,
9417 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
9418 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
9419 /// Initialize declare reduction construct initializer.
9420 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
9421 /// Finish current declare reduction construct initializer.
9422 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
9423 /// Initialize declare reduction construct initializer.
9424 /// \return omp_priv variable.
9425 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
9426 /// Finish current declare reduction construct initializer.
9427 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
9428 VarDecl *OmpPrivParm);
9429 /// Called at the end of '#pragma omp declare reduction'.
9430 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
9431 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
9432
9433 /// Check variable declaration in 'omp declare mapper' construct.
9434 TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
9435 /// Check if the specified type is allowed to be used in 'omp declare
9436 /// mapper' construct.
9437 QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
9438 TypeResult ParsedType);
9439 /// Called on start of '#pragma omp declare mapper'.
9440 OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart(
9441 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
9442 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
9443 Decl *PrevDeclInScope = nullptr);
9444 /// Build the mapper variable of '#pragma omp declare mapper'.
9445 void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
9446 Scope *S, QualType MapperType,
9447 SourceLocation StartLoc,
9448 DeclarationName VN);
9449 /// Called at the end of '#pragma omp declare mapper'.
9450 DeclGroupPtrTy
9451 ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
9452 ArrayRef<OMPClause *> ClauseList);
9453
9454 /// Called on the start of target region i.e. '#pragma omp declare target'.
9455 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
9456 /// Called at the end of target region i.e. '#pragme omp end declare target'.
9457 void ActOnFinishOpenMPDeclareTargetDirective();
9458 /// Searches for the provided declaration name for OpenMP declare target
9459 /// directive.
9460 NamedDecl *
9461 lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
9462 const DeclarationNameInfo &Id,
9463 NamedDeclSetType &SameDirectiveDecls);
9464 /// Called on correct id-expression from the '#pragma omp declare target'.
9465 void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
9466 OMPDeclareTargetDeclAttr::MapTypeTy MT,
9467 OMPDeclareTargetDeclAttr::DevTypeTy DT);
9468 /// Check declaration inside target region.
9469 void
9470 checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
9471 SourceLocation IdLoc = SourceLocation());
9472 /// Return true inside OpenMP declare target region.
9473 bool isInOpenMPDeclareTargetContext() const {
9474 return DeclareTargetNestingLevel > 0;
9475 }
9476 /// Return true inside OpenMP target region.
9477 bool isInOpenMPTargetExecutionDirective() const;
9478
9479 /// Return the number of captured regions created for an OpenMP directive.
9480 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
9481
9482 /// Initialization of captured region for OpenMP region.
9483 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
9484 /// End of OpenMP region.
9485 ///
9486 /// \param S Statement associated with the current OpenMP region.
9487 /// \param Clauses List of clauses for the current OpenMP region.
9488 ///
9489 /// \returns Statement for finished OpenMP region.
9490 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
9491 StmtResult ActOnOpenMPExecutableDirective(
9492 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
9493 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
9494 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
9495 /// Called on well-formed '\#pragma omp parallel' after parsing
9496 /// of the associated statement.
9497 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
9498 Stmt *AStmt,
9499 SourceLocation StartLoc,
9500 SourceLocation EndLoc);
9501 using VarsWithInheritedDSAType =
9502 llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
9503 /// Called on well-formed '\#pragma omp simd' after parsing
9504 /// of the associated statement.
9505 StmtResult
9506 ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9507 SourceLocation StartLoc, SourceLocation EndLoc,
9508 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9509 /// Called on well-formed '\#pragma omp for' after parsing
9510 /// of the associated statement.
9511 StmtResult
9512 ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9513 SourceLocation StartLoc, SourceLocation EndLoc,
9514 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9515 /// Called on well-formed '\#pragma omp for simd' after parsing
9516 /// of the associated statement.
9517 StmtResult
9518 ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9519 SourceLocation StartLoc, SourceLocation EndLoc,
9520 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9521 /// Called on well-formed '\#pragma omp sections' after parsing
9522 /// of the associated statement.
9523 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
9524 Stmt *AStmt, SourceLocation StartLoc,
9525 SourceLocation EndLoc);
9526 /// Called on well-formed '\#pragma omp section' after parsing of the
9527 /// associated statement.
9528 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
9529 SourceLocation EndLoc);
9530 /// Called on well-formed '\#pragma omp single' after parsing of the
9531 /// associated statement.
9532 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
9533 Stmt *AStmt, SourceLocation StartLoc,
9534 SourceLocation EndLoc);
9535 /// Called on well-formed '\#pragma omp master' after parsing of the
9536 /// associated statement.
9537 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
9538 SourceLocation EndLoc);
9539 /// Called on well-formed '\#pragma omp critical' after parsing of the
9540 /// associated statement.
9541 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
9542 ArrayRef<OMPClause *> Clauses,
9543 Stmt *AStmt, SourceLocation StartLoc,
9544 SourceLocation EndLoc);
9545 /// Called on well-formed '\#pragma omp parallel for' after parsing
9546 /// of the associated statement.
9547 StmtResult ActOnOpenMPParallelForDirective(
9548 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9549 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9550 /// Called on well-formed '\#pragma omp parallel for simd' after
9551 /// parsing of the associated statement.
9552 StmtResult ActOnOpenMPParallelForSimdDirective(
9553 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9554 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9555 /// Called on well-formed '\#pragma omp parallel sections' after
9556 /// parsing of the associated statement.
9557 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
9558 Stmt *AStmt,
9559 SourceLocation StartLoc,
9560 SourceLocation EndLoc);
9561 /// Called on well-formed '\#pragma omp task' after parsing of the
9562 /// associated statement.
9563 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
9564 Stmt *AStmt, SourceLocation StartLoc,
9565 SourceLocation EndLoc);
9566 /// Called on well-formed '\#pragma omp taskyield'.
9567 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
9568 SourceLocation EndLoc);
9569 /// Called on well-formed '\#pragma omp barrier'.
9570 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
9571 SourceLocation EndLoc);
9572 /// Called on well-formed '\#pragma omp taskwait'.
9573 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
9574 SourceLocation EndLoc);
9575 /// Called on well-formed '\#pragma omp taskgroup'.
9576 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
9577 Stmt *AStmt, SourceLocation StartLoc,
9578 SourceLocation EndLoc);
9579 /// Called on well-formed '\#pragma omp flush'.
9580 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
9581 SourceLocation StartLoc,
9582 SourceLocation EndLoc);
9583 /// Called on well-formed '\#pragma omp ordered' after parsing of the
9584 /// associated statement.
9585 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
9586 Stmt *AStmt, SourceLocation StartLoc,
9587 SourceLocation EndLoc);
9588 /// Called on well-formed '\#pragma omp atomic' after parsing of the
9589 /// associated statement.
9590 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
9591 Stmt *AStmt, SourceLocation StartLoc,
9592 SourceLocation EndLoc);
9593 /// Called on well-formed '\#pragma omp target' after parsing of the
9594 /// associated statement.
9595 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9596 Stmt *AStmt, SourceLocation StartLoc,
9597 SourceLocation EndLoc);
9598 /// Called on well-formed '\#pragma omp target data' after parsing of
9599 /// the associated statement.
9600 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9601 Stmt *AStmt, SourceLocation StartLoc,
9602 SourceLocation EndLoc);
9603 /// Called on well-formed '\#pragma omp target enter data' after
9604 /// parsing of the associated statement.
9605 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9606 SourceLocation StartLoc,
9607 SourceLocation EndLoc,
9608 Stmt *AStmt);
9609 /// Called on well-formed '\#pragma omp target exit data' after
9610 /// parsing of the associated statement.
9611 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9612 SourceLocation StartLoc,
9613 SourceLocation EndLoc,
9614 Stmt *AStmt);
9615 /// Called on well-formed '\#pragma omp target parallel' after
9616 /// parsing of the associated statement.
9617 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
9618 Stmt *AStmt,
9619 SourceLocation StartLoc,
9620 SourceLocation EndLoc);
9621 /// Called on well-formed '\#pragma omp target parallel for' after
9622 /// parsing of the associated statement.
9623 StmtResult ActOnOpenMPTargetParallelForDirective(
9624 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9625 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9626 /// Called on well-formed '\#pragma omp teams' after parsing of the
9627 /// associated statement.
9628 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9629 Stmt *AStmt, SourceLocation StartLoc,
9630 SourceLocation EndLoc);
9631 /// Called on well-formed '\#pragma omp cancellation point'.
9632 StmtResult
9633 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9634 SourceLocation EndLoc,
9635 OpenMPDirectiveKind CancelRegion);
9636 /// Called on well-formed '\#pragma omp cancel'.
9637 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9638 SourceLocation StartLoc,
9639 SourceLocation EndLoc,
9640 OpenMPDirectiveKind CancelRegion);
9641 /// Called on well-formed '\#pragma omp taskloop' after parsing of the
9642 /// associated statement.
9643 StmtResult
9644 ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9645 SourceLocation StartLoc, SourceLocation EndLoc,
9646 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9647 /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
9648 /// the associated statement.
9649 StmtResult ActOnOpenMPTaskLoopSimdDirective(
9650 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9651 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9652 /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
9653 /// associated statement.
9654 StmtResult ActOnOpenMPMasterTaskLoopDirective(
9655 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9656 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9657 /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
9658 /// the associated statement.
9659 StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
9660 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9661 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9662 /// Called on well-formed '\#pragma omp parallel master taskloop' after
9663 /// parsing of the associated statement.
9664 StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
9665 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9666 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9667 /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
9668 /// parsing of the associated statement.
9669 StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
9670 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9671 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9672 /// Called on well-formed '\#pragma omp distribute' after parsing
9673 /// of the associated statement.
9674 StmtResult
9675 ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9676 SourceLocation StartLoc, SourceLocation EndLoc,
9677 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9678 /// Called on well-formed '\#pragma omp target update'.
9679 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9680 SourceLocation StartLoc,
9681 SourceLocation EndLoc,
9682 Stmt *AStmt);
9683 /// Called on well-formed '\#pragma omp distribute parallel for' after
9684 /// parsing of the associated statement.
9685 StmtResult ActOnOpenMPDistributeParallelForDirective(
9686 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9687 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9688 /// Called on well-formed '\#pragma omp distribute parallel for simd'
9689 /// after parsing of the associated statement.
9690 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
9691 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9692 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9693 /// Called on well-formed '\#pragma omp distribute simd' after
9694 /// parsing of the associated statement.
9695 StmtResult ActOnOpenMPDistributeSimdDirective(
9696 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9697 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9698 /// Called on well-formed '\#pragma omp target parallel for simd' after
9699 /// parsing of the associated statement.
9700 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
9701 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9702 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9703 /// Called on well-formed '\#pragma omp target simd' after parsing of
9704 /// the associated statement.
9705 StmtResult
9706 ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9707 SourceLocation StartLoc, SourceLocation EndLoc,
9708 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9709 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
9710 /// the associated statement.
9711 StmtResult ActOnOpenMPTeamsDistributeDirective(
9712 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9713 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9714 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
9715 /// of the associated statement.
9716 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
9717 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9718 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9719 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
9720 /// after parsing of the associated statement.
9721 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
9722 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9723 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9724 /// Called on well-formed '\#pragma omp teams distribute parallel for'
9725 /// after parsing of the associated statement.
9726 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
9727 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9728 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9729 /// Called on well-formed '\#pragma omp target teams' after parsing of the
9730 /// associated statement.
9731 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
9732 Stmt *AStmt,
9733 SourceLocation StartLoc,
9734 SourceLocation EndLoc);
9735 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
9736 /// of the associated statement.
9737 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
9738 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9739 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9740 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
9741 /// after parsing of the associated statement.
9742 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
9743 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9744 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9745 /// Called on well-formed '\#pragma omp target teams distribute parallel for
9746 /// simd' after parsing of the associated statement.
9747 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
9748 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9749 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9750 /// Called on well-formed '\#pragma omp target teams distribute simd' after
9751 /// parsing of the associated statement.
9752 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
9753 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9754 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9755
9756 /// Checks correctness of linear modifiers.
9757 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9758 SourceLocation LinLoc);
9759 /// Checks that the specified declaration matches requirements for the linear
9760 /// decls.
9761 bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
9762 OpenMPLinearClauseKind LinKind, QualType Type);
9763
9764 /// Called on well-formed '\#pragma omp declare simd' after parsing of
9765 /// the associated method/function.
9766 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
9767 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
9768 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
9769 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
9770 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
9771
9772 /// Checks '\#pragma omp declare variant' variant function and original
9773 /// functions after parsing of the associated method/function.
9774 /// \param DG Function declaration to which declare variant directive is
9775 /// applied to.
9776 /// \param VariantRef Expression that references the variant function, which
9777 /// must be used instead of the original one, specified in \p DG.
9778 /// \returns None, if the function/variant function are not compatible with
9779 /// the pragma, pair of original function/variant ref expression otherwise.
9780 Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(
9781 DeclGroupPtrTy DG, Expr *VariantRef, SourceRange SR);
9782
9783 /// Called on well-formed '\#pragma omp declare variant' after parsing of
9784 /// the associated method/function.
9785 /// \param FD Function declaration to which declare variant directive is
9786 /// applied to.
9787 /// \param VariantRef Expression that references the variant function, which
9788 /// must be used instead of the original one, specified in \p DG.
9789 /// \param Data Set of context-specific data for the specified context
9790 /// selector.
9791 void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef,
9792 SourceRange SR,
9793 ArrayRef<OMPCtxSelectorData> Data);
9794
9795 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
9796 Expr *Expr,
9797 SourceLocation StartLoc,
9798 SourceLocation LParenLoc,
9799 SourceLocation EndLoc);
9800 /// Called on well-formed 'allocator' clause.
9801 OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
9802 SourceLocation StartLoc,
9803 SourceLocation LParenLoc,
9804 SourceLocation EndLoc);
9805 /// Called on well-formed 'if' clause.
9806 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9807 Expr *Condition, SourceLocation StartLoc,
9808 SourceLocation LParenLoc,
9809 SourceLocation NameModifierLoc,
9810 SourceLocation ColonLoc,
9811 SourceLocation EndLoc);
9812 /// Called on well-formed 'final' clause.
9813 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
9814 SourceLocation LParenLoc,
9815 SourceLocation EndLoc);
9816 /// Called on well-formed 'num_threads' clause.
9817 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9818 SourceLocation StartLoc,
9819 SourceLocation LParenLoc,
9820 SourceLocation EndLoc);
9821 /// Called on well-formed 'safelen' clause.
9822 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
9823 SourceLocation StartLoc,
9824 SourceLocation LParenLoc,
9825 SourceLocation EndLoc);
9826 /// Called on well-formed 'simdlen' clause.
9827 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
9828 SourceLocation LParenLoc,
9829 SourceLocation EndLoc);
9830 /// Called on well-formed 'collapse' clause.
9831 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
9832 SourceLocation StartLoc,
9833 SourceLocation LParenLoc,
9834 SourceLocation EndLoc);
9835 /// Called on well-formed 'ordered' clause.
9836 OMPClause *
9837 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
9838 SourceLocation LParenLoc = SourceLocation(),
9839 Expr *NumForLoops = nullptr);
9840 /// Called on well-formed 'grainsize' clause.
9841 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
9842 SourceLocation LParenLoc,
9843 SourceLocation EndLoc);
9844 /// Called on well-formed 'num_tasks' clause.
9845 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
9846 SourceLocation LParenLoc,
9847 SourceLocation EndLoc);
9848 /// Called on well-formed 'hint' clause.
9849 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
9850 SourceLocation LParenLoc,
9851 SourceLocation EndLoc);
9852
9853 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
9854 unsigned Argument,
9855 SourceLocation ArgumentLoc,
9856 SourceLocation StartLoc,
9857 SourceLocation LParenLoc,
9858 SourceLocation EndLoc);
9859 /// Called on well-formed 'default' clause.
9860 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9861 SourceLocation KindLoc,
9862 SourceLocation StartLoc,
9863 SourceLocation LParenLoc,
9864 SourceLocation EndLoc);
9865 /// Called on well-formed 'proc_bind' clause.
9866 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9867 SourceLocation KindLoc,
9868 SourceLocation StartLoc,
9869 SourceLocation LParenLoc,
9870 SourceLocation EndLoc);
9871
9872 OMPClause *ActOnOpenMPSingleExprWithArgClause(
9873 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
9874 SourceLocation StartLoc, SourceLocation LParenLoc,
9875 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
9876 SourceLocation EndLoc);
9877 /// Called on well-formed 'schedule' clause.
9878 OMPClause *ActOnOpenMPScheduleClause(
9879 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
9880 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
9881 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9882 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
9883
9884 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
9885 SourceLocation EndLoc);
9886 /// Called on well-formed 'nowait' clause.
9887 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9888 SourceLocation EndLoc);
9889 /// Called on well-formed 'untied' clause.
9890 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9891 SourceLocation EndLoc);
9892 /// Called on well-formed 'mergeable' clause.
9893 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9894 SourceLocation EndLoc);
9895 /// Called on well-formed 'read' clause.
9896 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
9897 SourceLocation EndLoc);
9898 /// Called on well-formed 'write' clause.
9899 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
9900 SourceLocation EndLoc);
9901 /// Called on well-formed 'update' clause.
9902 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9903 SourceLocation EndLoc);
9904 /// Called on well-formed 'capture' clause.
9905 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9906 SourceLocation EndLoc);
9907 /// Called on well-formed 'seq_cst' clause.
9908 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9909 SourceLocation EndLoc);
9910 /// Called on well-formed 'threads' clause.
9911 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9912 SourceLocation EndLoc);
9913 /// Called on well-formed 'simd' clause.
9914 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9915 SourceLocation EndLoc);
9916 /// Called on well-formed 'nogroup' clause.
9917 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9918 SourceLocation EndLoc);
9919 /// Called on well-formed 'unified_address' clause.
9920 OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
9921 SourceLocation EndLoc);
9922
9923 /// Called on well-formed 'unified_address' clause.
9924 OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
9925 SourceLocation EndLoc);
9926
9927 /// Called on well-formed 'reverse_offload' clause.
9928 OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
9929 SourceLocation EndLoc);
9930
9931 /// Called on well-formed 'dynamic_allocators' clause.
9932 OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
9933 SourceLocation EndLoc);
9934
9935 /// Called on well-formed 'atomic_default_mem_order' clause.
9936 OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
9937 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
9938 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
9939
9940 OMPClause *ActOnOpenMPVarListClause(
9941 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
9942 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
9943 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
9944 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
9945 OpenMPLinearClauseKind LinKind,
9946 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
9947 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
9948 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc);
9949 /// Called on well-formed 'allocate' clause.
9950 OMPClause *
9951 ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
9952 SourceLocation StartLoc, SourceLocation ColonLoc,
9953 SourceLocation LParenLoc, SourceLocation EndLoc);
9954 /// Called on well-formed 'private' clause.
9955 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9956 SourceLocation StartLoc,
9957 SourceLocation LParenLoc,
9958 SourceLocation EndLoc);
9959 /// Called on well-formed 'firstprivate' clause.
9960 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9961 SourceLocation StartLoc,
9962 SourceLocation LParenLoc,
9963 SourceLocation EndLoc);
9964 /// Called on well-formed 'lastprivate' clause.
9965 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9966 SourceLocation StartLoc,
9967 SourceLocation LParenLoc,
9968 SourceLocation EndLoc);
9969 /// Called on well-formed 'shared' clause.
9970 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9971 SourceLocation StartLoc,
9972 SourceLocation LParenLoc,
9973 SourceLocation EndLoc);
9974 /// Called on well-formed 'reduction' clause.
9975 OMPClause *ActOnOpenMPReductionClause(
9976 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9977 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9978 CXXScopeSpec &ReductionIdScopeSpec,
9979 const DeclarationNameInfo &ReductionId,
9980 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9981 /// Called on well-formed 'task_reduction' clause.
9982 OMPClause *ActOnOpenMPTaskReductionClause(
9983 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9984 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9985 CXXScopeSpec &ReductionIdScopeSpec,
9986 const DeclarationNameInfo &ReductionId,
9987 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9988 /// Called on well-formed 'in_reduction' clause.
9989 OMPClause *ActOnOpenMPInReductionClause(
9990 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9991 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9992 CXXScopeSpec &ReductionIdScopeSpec,
9993 const DeclarationNameInfo &ReductionId,
9994 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9995 /// Called on well-formed 'linear' clause.
9996 OMPClause *
9997 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
9998 SourceLocation StartLoc, SourceLocation LParenLoc,
9999 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
10000 SourceLocation ColonLoc, SourceLocation EndLoc);
10001 /// Called on well-formed 'aligned' clause.
10002 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
10003 Expr *Alignment,
10004 SourceLocation StartLoc,
10005 SourceLocation LParenLoc,
10006 SourceLocation ColonLoc,
10007 SourceLocation EndLoc);
10008 /// Called on well-formed 'copyin' clause.
10009 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10010 SourceLocation StartLoc,
10011 SourceLocation LParenLoc,
10012 SourceLocation EndLoc);
10013 /// Called on well-formed 'copyprivate' clause.
10014 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10015 SourceLocation StartLoc,
10016 SourceLocation LParenLoc,
10017 SourceLocation EndLoc);
10018 /// Called on well-formed 'flush' pseudo clause.
10019 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10020 SourceLocation StartLoc,
10021 SourceLocation LParenLoc,
10022 SourceLocation EndLoc);
10023 /// Called on well-formed 'depend' clause.
10024 OMPClause *
10025 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
10026 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
10027 SourceLocation StartLoc, SourceLocation LParenLoc,
10028 SourceLocation EndLoc);
10029 /// Called on well-formed 'device' clause.
10030 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10031 SourceLocation LParenLoc,
10032 SourceLocation EndLoc);
10033 /// Called on well-formed 'map' clause.
10034 OMPClause *
10035 ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
10036 ArrayRef<SourceLocation> MapTypeModifiersLoc,
10037 CXXScopeSpec &MapperIdScopeSpec,
10038 DeclarationNameInfo &MapperId,
10039 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10040 SourceLocation MapLoc, SourceLocation ColonLoc,
10041 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
10042 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10043 /// Called on well-formed 'num_teams' clause.
10044 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
10045 SourceLocation LParenLoc,
10046 SourceLocation EndLoc);
10047 /// Called on well-formed 'thread_limit' clause.
10048 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10049 SourceLocation StartLoc,
10050 SourceLocation LParenLoc,
10051 SourceLocation EndLoc);
10052 /// Called on well-formed 'priority' clause.
10053 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
10054 SourceLocation LParenLoc,
10055 SourceLocation EndLoc);
10056 /// Called on well-formed 'dist_schedule' clause.
10057 OMPClause *ActOnOpenMPDistScheduleClause(
10058 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
10059 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
10060 SourceLocation CommaLoc, SourceLocation EndLoc);
10061 /// Called on well-formed 'defaultmap' clause.
10062 OMPClause *ActOnOpenMPDefaultmapClause(
10063 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10064 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10065 SourceLocation KindLoc, SourceLocation EndLoc);
10066 /// Called on well-formed 'to' clause.
10067 OMPClause *
10068 ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
10069 DeclarationNameInfo &MapperId,
10070 const OMPVarListLocTy &Locs,
10071 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10072 /// Called on well-formed 'from' clause.
10073 OMPClause *ActOnOpenMPFromClause(
10074 ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
10075 DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs,
10076 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10077 /// Called on well-formed 'use_device_ptr' clause.
10078 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10079 const OMPVarListLocTy &Locs);
10080 /// Called on well-formed 'is_device_ptr' clause.
10081 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10082 const OMPVarListLocTy &Locs);
10083
10084 /// The kind of conversion being performed.
10085 enum CheckedConversionKind {
10086 /// An implicit conversion.
10087 CCK_ImplicitConversion,
10088 /// A C-style cast.
10089 CCK_CStyleCast,
10090 /// A functional-style cast.
10091 CCK_FunctionalCast,
10092 /// A cast other than a C-style cast.
10093 CCK_OtherCast,
10094 /// A conversion for an operand of a builtin overloaded operator.
10095 CCK_ForBuiltinOverloadedOp
10096 };
10097
10098 static bool isCast(CheckedConversionKind CCK) {
10099 return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
10100 CCK == CCK_OtherCast;
10101 }
10102
10103 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
10104 /// cast. If there is already an implicit cast, merge into the existing one.
10105 /// If isLvalue, the result of the cast is an lvalue.
10106 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
10107 ExprValueKind VK = VK_RValue,
10108 const CXXCastPath *BasePath = nullptr,
10109 CheckedConversionKind CCK
10110 = CCK_ImplicitConversion);
10111
10112 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
10113 /// to the conversion from scalar type ScalarTy to the Boolean type.
10114 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
10115
10116 /// IgnoredValueConversions - Given that an expression's result is
10117 /// syntactically ignored, perform any conversions that are
10118 /// required.
10119 ExprResult IgnoredValueConversions(Expr *E);
10120
10121 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
10122 // functions and arrays to their respective pointers (C99 6.3.2.1).
10123 ExprResult UsualUnaryConversions(Expr *E);
10124
10125 /// CallExprUnaryConversions - a special case of an unary conversion
10126 /// performed on a function designator of a call expression.
10127 ExprResult CallExprUnaryConversions(Expr *E);
10128
10129 // DefaultFunctionArrayConversion - converts functions and arrays
10130 // to their respective pointers (C99 6.3.2.1).
10131 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
10132
10133 // DefaultFunctionArrayLvalueConversion - converts functions and
10134 // arrays to their respective pointers and performs the
10135 // lvalue-to-rvalue conversion.
10136 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
10137 bool Diagnose = true);
10138
10139 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
10140 // the operand. This is DefaultFunctionArrayLvalueConversion,
10141 // except that it assumes the operand isn't of function or array
10142 // type.
10143 ExprResult DefaultLvalueConversion(Expr *E);
10144
10145 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
10146 // do not have a prototype. Integer promotions are performed on each
10147 // argument, and arguments that have type float are promoted to double.
10148 ExprResult DefaultArgumentPromotion(Expr *E);
10149
10150 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
10151 /// it as an xvalue. In C++98, the result will still be a prvalue, because
10152 /// we don't have xvalues there.
10153 ExprResult TemporaryMaterializationConversion(Expr *E);
10154
10155 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
10156 enum VariadicCallType {
10157 VariadicFunction,
10158 VariadicBlock,
10159 VariadicMethod,
10160 VariadicConstructor,
10161 VariadicDoesNotApply
10162 };
10163
10164 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
10165 const FunctionProtoType *Proto,
10166 Expr *Fn);
10167
10168 // Used for determining in which context a type is allowed to be passed to a
10169 // vararg function.
10170 enum VarArgKind {
10171 VAK_Valid,
10172 VAK_ValidInCXX11,
10173 VAK_Undefined,
10174 VAK_MSVCUndefined,
10175 VAK_Invalid
10176 };
10177
10178 // Determines which VarArgKind fits an expression.
10179 VarArgKind isValidVarArgType(const QualType &Ty);
10180
10181 /// Check to see if the given expression is a valid argument to a variadic
10182 /// function, issuing a diagnostic if not.
10183 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
10184
10185 /// Check to see if a given expression could have '.c_str()' called on it.
10186 bool hasCStrMethod(const Expr *E);
10187
10188 /// GatherArgumentsForCall - Collector argument expressions for various
10189 /// form of call prototypes.
10190 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
10191 const FunctionProtoType *Proto,
10192 unsigned FirstParam, ArrayRef<Expr *> Args,
10193 SmallVectorImpl<Expr *> &AllArgs,
10194 VariadicCallType CallType = VariadicDoesNotApply,
10195 bool AllowExplicit = false,
10196 bool IsListInitialization = false);
10197
10198 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
10199 // will create a runtime trap if the resulting type is not a POD type.
10200 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
10201 FunctionDecl *FDecl);
10202
10203 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
10204 // operands and then handles various conversions that are common to binary
10205 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
10206 // routine returns the first non-arithmetic type found. The client is
10207 // responsible for emitting appropriate error diagnostics.
10208 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
10209 bool IsCompAssign = false);
10210
10211 /// AssignConvertType - All of the 'assignment' semantic checks return this
10212 /// enum to indicate whether the assignment was allowed. These checks are
10213 /// done for simple assignments, as well as initialization, return from
10214 /// function, argument passing, etc. The query is phrased in terms of a
10215 /// source and destination type.
10216 enum AssignConvertType {
10217 /// Compatible - the types are compatible according to the standard.
10218 Compatible,
10219
10220 /// PointerToInt - The assignment converts a pointer to an int, which we
10221 /// accept as an extension.
10222 PointerToInt,
10223
10224 /// IntToPointer - The assignment converts an int to a pointer, which we
10225 /// accept as an extension.
10226 IntToPointer,
10227
10228 /// FunctionVoidPointer - The assignment is between a function pointer and
10229 /// void*, which the standard doesn't allow, but we accept as an extension.
10230 FunctionVoidPointer,
10231
10232 /// IncompatiblePointer - The assignment is between two pointers types that
10233 /// are not compatible, but we accept them as an extension.
10234 IncompatiblePointer,
10235
10236 /// IncompatiblePointerSign - The assignment is between two pointers types
10237 /// which point to integers which have a different sign, but are otherwise
10238 /// identical. This is a subset of the above, but broken out because it's by
10239 /// far the most common case of incompatible pointers.
10240 IncompatiblePointerSign,
10241
10242 /// CompatiblePointerDiscardsQualifiers - The assignment discards
10243 /// c/v/r qualifiers, which we accept as an extension.
10244 CompatiblePointerDiscardsQualifiers,
10245
10246 /// IncompatiblePointerDiscardsQualifiers - The assignment
10247 /// discards qualifiers that we don't permit to be discarded,
10248 /// like address spaces.
10249 IncompatiblePointerDiscardsQualifiers,
10250
10251 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
10252 /// changes address spaces in nested pointer types which is not allowed.
10253 /// For instance, converting __private int ** to __generic int ** is
10254 /// illegal even though __private could be converted to __generic.
10255 IncompatibleNestedPointerAddressSpaceMismatch,
10256
10257 /// IncompatibleNestedPointerQualifiers - The assignment is between two
10258 /// nested pointer types, and the qualifiers other than the first two
10259 /// levels differ e.g. char ** -> const char **, but we accept them as an
10260 /// extension.
10261 IncompatibleNestedPointerQualifiers,
10262
10263 /// IncompatibleVectors - The assignment is between two vector types that
10264 /// have the same size, which we accept as an extension.
10265 IncompatibleVectors,
10266
10267 /// IntToBlockPointer - The assignment converts an int to a block
10268 /// pointer. We disallow this.
10269 IntToBlockPointer,
10270
10271 /// IncompatibleBlockPointer - The assignment is between two block
10272 /// pointers types that are not compatible.
10273 IncompatibleBlockPointer,
10274
10275 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
10276 /// id type and something else (that is incompatible with it). For example,
10277 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
10278 IncompatibleObjCQualifiedId,
10279
10280 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
10281 /// object with __weak qualifier.
10282 IncompatibleObjCWeakRef,
10283
10284 /// Incompatible - We reject this conversion outright, it is invalid to
10285 /// represent it in the AST.
10286 Incompatible
10287 };
10288
10289 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
10290 /// assignment conversion type specified by ConvTy. This returns true if the
10291 /// conversion was invalid or false if the conversion was accepted.
10292 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
10293 SourceLocation Loc,
10294 QualType DstType, QualType SrcType,
10295 Expr *SrcExpr, AssignmentAction Action,
10296 bool *Complained = nullptr);
10297
10298 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
10299 /// enum. If AllowMask is true, then we also allow the complement of a valid
10300 /// value, to be used as a mask.
10301 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
10302 bool AllowMask) const;
10303
10304 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
10305 /// integer not in the range of enum values.
10306 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
10307 Expr *SrcExpr);
10308
10309 /// CheckAssignmentConstraints - Perform type checking for assignment,
10310 /// argument passing, variable initialization, and function return values.
10311 /// C99 6.5.16.
10312 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
10313 QualType LHSType,
10314 QualType RHSType);
10315
10316 /// Check assignment constraints and optionally prepare for a conversion of
10317 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
10318 /// is true.
10319 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
10320 ExprResult &RHS,
10321 CastKind &Kind,
10322 bool ConvertRHS = true);
10323
10324 /// Check assignment constraints for an assignment of RHS to LHSType.
10325 ///
10326 /// \param LHSType The destination type for the assignment.
10327 /// \param RHS The source expression for the assignment.
10328 /// \param Diagnose If \c true, diagnostics may be produced when checking
10329 /// for assignability. If a diagnostic is produced, \p RHS will be
10330 /// set to ExprError(). Note that this function may still return
10331 /// without producing a diagnostic, even for an invalid assignment.
10332 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
10333 /// in an audited Core Foundation API and does not need to be checked
10334 /// for ARC retain issues.
10335 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
10336 /// conversions necessary to perform the assignment. If \c false,
10337 /// \p Diagnose must also be \c false.
10338 AssignConvertType CheckSingleAssignmentConstraints(
10339 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
10340 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
10341
10342 // If the lhs type is a transparent union, check whether we
10343 // can initialize the transparent union with the given expression.
10344 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
10345 ExprResult &RHS);
10346
10347 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
10348
10349 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
10350
10351 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10352 AssignmentAction Action,
10353 bool AllowExplicit = false);
10354 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10355 AssignmentAction Action,
10356 bool AllowExplicit,
10357 ImplicitConversionSequence& ICS);
10358 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10359 const ImplicitConversionSequence& ICS,
10360 AssignmentAction Action,
10361 CheckedConversionKind CCK
10362 = CCK_ImplicitConversion);
10363 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10364 const StandardConversionSequence& SCS,
10365 AssignmentAction Action,
10366 CheckedConversionKind CCK);
10367
10368 ExprResult PerformQualificationConversion(
10369 Expr *E, QualType Ty, ExprValueKind VK = VK_RValue,
10370 CheckedConversionKind CCK = CCK_ImplicitConversion);
10371
10372 /// the following "Check" methods will return a valid/converted QualType
10373 /// or a null QualType (indicating an error diagnostic was issued).
10374
10375 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
10376 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10377 ExprResult &RHS);
10378 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10379 ExprResult &RHS);
10380 QualType CheckPointerToMemberOperands( // C++ 5.5
10381 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
10382 SourceLocation OpLoc, bool isIndirect);
10383 QualType CheckMultiplyDivideOperands( // C99 6.5.5
10384 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
10385 bool IsDivide);
10386 QualType CheckRemainderOperands( // C99 6.5.5
10387 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10388 bool IsCompAssign = false);
10389 QualType CheckAdditionOperands( // C99 6.5.6
10390 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10391 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
10392 QualType CheckSubtractionOperands( // C99 6.5.6
10393 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10394 QualType* CompLHSTy = nullptr);
10395 QualType CheckShiftOperands( // C99 6.5.7
10396 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10397 BinaryOperatorKind Opc, bool IsCompAssign = false);
10398 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
10399 QualType CheckCompareOperands( // C99 6.5.8/9
10400 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10401 BinaryOperatorKind Opc);
10402 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
10403 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10404 BinaryOperatorKind Opc);
10405 QualType CheckLogicalOperands( // C99 6.5.[13,14]
10406 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10407 BinaryOperatorKind Opc);
10408 // CheckAssignmentOperands is used for both simple and compound assignment.
10409 // For simple assignment, pass both expressions and a null converted type.
10410 // For compound assignment, pass both expressions and the converted type.
10411 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
10412 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
10413
10414 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
10415 UnaryOperatorKind Opcode, Expr *Op);
10416 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
10417 BinaryOperatorKind Opcode,
10418 Expr *LHS, Expr *RHS);
10419 ExprResult checkPseudoObjectRValue(Expr *E);
10420 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
10421
10422 QualType CheckConditionalOperands( // C99 6.5.15
10423 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
10424 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
10425 QualType CXXCheckConditionalOperands( // C++ 5.16
10426 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
10427 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
10428 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
10429 bool ConvertArgs = true);
10430 QualType FindCompositePointerType(SourceLocation Loc,
10431 ExprResult &E1, ExprResult &E2,
10432 bool ConvertArgs = true) {
10433 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
10434 QualType Composite =
10435 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
10436 E1 = E1Tmp;
10437 E2 = E2Tmp;
10438 return Composite;
10439 }
10440
10441 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
10442 SourceLocation QuestionLoc);
10443
10444 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
10445 SourceLocation QuestionLoc);
10446
10447 void DiagnoseAlwaysNonNullPointer(Expr *E,
10448 Expr::NullPointerConstantKind NullType,
10449 bool IsEqual, SourceRange Range);
10450
10451 /// type checking for vector binary operators.
10452 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10453 SourceLocation Loc, bool IsCompAssign,
10454 bool AllowBothBool, bool AllowBoolConversion);
10455 QualType GetSignedVectorType(QualType V);
10456 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10457 SourceLocation Loc,
10458 BinaryOperatorKind Opc);
10459 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10460 SourceLocation Loc);
10461
10462 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
10463 bool isLaxVectorConversion(QualType srcType, QualType destType);
10464
10465 /// type checking declaration initializers (C99 6.7.8)
10466 bool CheckForConstantInitializer(Expr *e, QualType t);
10467
10468 // type checking C++ declaration initializers (C++ [dcl.init]).
10469
10470 /// ReferenceCompareResult - Expresses the result of comparing two
10471 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10472 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10473 enum ReferenceCompareResult {
10474 /// Ref_Incompatible - The two types are incompatible, so direct
10475 /// reference binding is not possible.
10476 Ref_Incompatible = 0,
10477 /// Ref_Related - The two types are reference-related, which means
10478 /// that their unqualified forms (T1 and T2) are either the same
10479 /// or T1 is a base class of T2.
10480 Ref_Related,
10481 /// Ref_Compatible - The two types are reference-compatible.
10482 Ref_Compatible
10483 };
10484
10485 ReferenceCompareResult
10486 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
10487 bool &DerivedToBase, bool &ObjCConversion,
10488 bool &ObjCLifetimeConversion,
10489 bool &FunctionConversion);
10490
10491 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10492 Expr *CastExpr, CastKind &CastKind,
10493 ExprValueKind &VK, CXXCastPath &Path);
10494
10495 /// Force an expression with unknown-type to an expression of the
10496 /// given type.
10497 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
10498
10499 /// Type-check an expression that's being passed to an
10500 /// __unknown_anytype parameter.
10501 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
10502 Expr *result, QualType &paramType);
10503
10504 // CheckVectorCast - check type constraints for vectors.
10505 // Since vectors are an extension, there are no C standard reference for this.
10506 // We allow casting between vectors and integer datatypes of the same size.
10507 // returns true if the cast is invalid
10508 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
10509 CastKind &Kind);
10510
10511 /// Prepare `SplattedExpr` for a vector splat operation, adding
10512 /// implicit casts if necessary.
10513 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
10514
10515 // CheckExtVectorCast - check type constraints for extended vectors.
10516 // Since vectors are an extension, there are no C standard reference for this.
10517 // We allow casting between vectors and integer datatypes of the same size,
10518 // or vectors and the element type of that vector.
10519 // returns the cast expr
10520 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
10521 CastKind &Kind);
10522
10523 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
10524 SourceLocation LParenLoc,
10525 Expr *CastExpr,
10526 SourceLocation RParenLoc);
10527
10528 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
10529
10530 /// Checks for invalid conversions and casts between
10531 /// retainable pointers and other pointer kinds for ARC and Weak.
10532 ARCConversionResult CheckObjCConversion(SourceRange castRange,
10533 QualType castType, Expr *&op,
10534 CheckedConversionKind CCK,
10535 bool Diagnose = true,
10536 bool DiagnoseCFAudited = false,
10537 BinaryOperatorKind Opc = BO_PtrMemD
10538 );
10539
10540 Expr *stripARCUnbridgedCast(Expr *e);
10541 void diagnoseARCUnbridgedCast(Expr *e);
10542
10543 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
10544 QualType ExprType);
10545
10546 /// checkRetainCycles - Check whether an Objective-C message send
10547 /// might create an obvious retain cycle.
10548 void checkRetainCycles(ObjCMessageExpr *msg);
10549 void checkRetainCycles(Expr *receiver, Expr *argument);
10550 void checkRetainCycles(VarDecl *Var, Expr *Init);
10551
10552 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
10553 /// to weak/__unsafe_unretained type.
10554 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
10555
10556 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
10557 /// to weak/__unsafe_unretained expression.
10558 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
10559
10560 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
10561 /// \param Method - May be null.
10562 /// \param [out] ReturnType - The return type of the send.
10563 /// \return true iff there were any incompatible types.
10564 bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
10565 MultiExprArg Args, Selector Sel,
10566 ArrayRef<SourceLocation> SelectorLocs,
10567 ObjCMethodDecl *Method, bool isClassMessage,
10568 bool isSuperMessage, SourceLocation lbrac,
10569 SourceLocation rbrac, SourceRange RecRange,
10570 QualType &ReturnType, ExprValueKind &VK);
10571
10572 /// Determine the result of a message send expression based on
10573 /// the type of the receiver, the method expected to receive the message,
10574 /// and the form of the message send.
10575 QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
10576 ObjCMethodDecl *Method, bool isClassMessage,
10577 bool isSuperMessage);
10578
10579 /// If the given expression involves a message send to a method
10580 /// with a related result type, emit a note describing what happened.
10581 void EmitRelatedResultTypeNote(const Expr *E);
10582
10583 /// Given that we had incompatible pointer types in a return
10584 /// statement, check whether we're in a method with a related result
10585 /// type, and if so, emit a note describing what happened.
10586 void EmitRelatedResultTypeNoteForReturn(QualType destType);
10587
10588 class ConditionResult {
10589 Decl *ConditionVar;
10590 FullExprArg Condition;
10591 bool Invalid;
10592 bool HasKnownValue;
10593 bool KnownValue;
10594
10595 friend class Sema;
10596 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
10597 bool IsConstexpr)
10598 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
10599 HasKnownValue(IsConstexpr && Condition.get() &&
10600 !Condition.get()->isValueDependent()),
10601 KnownValue(HasKnownValue &&
10602 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
10603 explicit ConditionResult(bool Invalid)
10604 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
10605 HasKnownValue(false), KnownValue(false) {}
10606
10607 public:
10608 ConditionResult() : ConditionResult(false) {}
10609 bool isInvalid() const { return Invalid; }
10610 std::pair<VarDecl *, Expr *> get() const {
10611 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
10612 Condition.get());
10613 }
10614 llvm::Optional<bool> getKnownValue() const {
10615 if (!HasKnownValue)
10616 return None;
10617 return KnownValue;
10618 }
10619 };
10620 static ConditionResult ConditionError() { return ConditionResult(true); }
10621
10622 enum class ConditionKind {
10623 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
10624 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
10625 Switch ///< An integral condition for a 'switch' statement.
10626 };
10627
10628 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
10629 Expr *SubExpr, ConditionKind CK);
10630
10631 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
10632 SourceLocation StmtLoc,
10633 ConditionKind CK);
10634
10635 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
10636
10637 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
10638 SourceLocation StmtLoc,
10639 ConditionKind CK);
10640 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
10641
10642 /// CheckBooleanCondition - Diagnose problems involving the use of
10643 /// the given expression as a boolean condition (e.g. in an if
10644 /// statement). Also performs the standard function and array
10645 /// decays, possibly changing the input variable.
10646 ///
10647 /// \param Loc - A location associated with the condition, e.g. the
10648 /// 'if' keyword.
10649 /// \return true iff there were any errors
10650 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
10651 bool IsConstexpr = false);
10652
10653 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
10654 /// found in an explicit(bool) specifier.
10655 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
10656
10657 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
10658 /// Returns true if the explicit specifier is now resolved.
10659 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
10660
10661 /// DiagnoseAssignmentAsCondition - Given that an expression is
10662 /// being used as a boolean condition, warn if it's an assignment.
10663 void DiagnoseAssignmentAsCondition(Expr *E);
10664
10665 /// Redundant parentheses over an equality comparison can indicate
10666 /// that the user intended an assignment used as condition.
10667 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
10668
10669 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
10670 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
10671
10672 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
10673 /// the specified width and sign. If an overflow occurs, detect it and emit
10674 /// the specified diagnostic.
10675 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
10676 unsigned NewWidth, bool NewSign,
10677 SourceLocation Loc, unsigned DiagID);
10678
10679 /// Checks that the Objective-C declaration is declared in the global scope.
10680 /// Emits an error and marks the declaration as invalid if it's not declared
10681 /// in the global scope.
10682 bool CheckObjCDeclScope(Decl *D);
10683
10684 /// Abstract base class used for diagnosing integer constant
10685 /// expression violations.
10686 class VerifyICEDiagnoser {
10687 public:
10688 bool Suppress;
10689
10690 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
10691
10692 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
10693 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
10694 virtual ~VerifyICEDiagnoser() { }
10695 };
10696
10697 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
10698 /// and reports the appropriate diagnostics. Returns false on success.
10699 /// Can optionally return the value of the expression.
10700 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10701 VerifyICEDiagnoser &Diagnoser,
10702 bool AllowFold = true);
10703 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10704 unsigned DiagID,
10705 bool AllowFold = true);
10706 ExprResult VerifyIntegerConstantExpression(Expr *E,
10707 llvm::APSInt *Result = nullptr);
10708
10709 /// VerifyBitField - verifies that a bit field expression is an ICE and has
10710 /// the correct width, and that the field type is valid.
10711 /// Returns false on success.
10712 /// Can optionally return whether the bit-field is of width 0
10713 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
10714 QualType FieldTy, bool IsMsStruct,
10715 Expr *BitWidth, bool *ZeroWidth = nullptr);
10716
10717private:
10718 unsigned ForceCUDAHostDeviceDepth = 0;
10719
10720public:
10721 /// Increments our count of the number of times we've seen a pragma forcing
10722 /// functions to be __host__ __device__. So long as this count is greater
10723 /// than zero, all functions encountered will be __host__ __device__.
10724 void PushForceCUDAHostDevice();
10725
10726 /// Decrements our count of the number of times we've seen a pragma forcing
10727 /// functions to be __host__ __device__. Returns false if the count is 0
10728 /// before incrementing, so you can emit an error.
10729 bool PopForceCUDAHostDevice();
10730
10731 /// Diagnostics that are emitted only if we discover that the given function
10732 /// must be codegen'ed. Because handling these correctly adds overhead to
10733 /// compilation, this is currently only enabled for CUDA compilations.
10734 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
10735 std::vector<PartialDiagnosticAt>>
10736 DeviceDeferredDiags;
10737
10738 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
10739 /// key in a hashtable, both the FD and location are hashed.
10740 struct FunctionDeclAndLoc {
10741 CanonicalDeclPtr<FunctionDecl> FD;
10742 SourceLocation Loc;
10743 };
10744
10745 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
10746 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
10747 /// same deferred diag twice.
10748 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
10749
10750 /// An inverse call graph, mapping known-emitted functions to one of their
10751 /// known-emitted callers (plus the location of the call).
10752 ///
10753 /// Functions that we can tell a priori must be emitted aren't added to this
10754 /// map.
10755 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
10756 /* Caller = */ FunctionDeclAndLoc>
10757 DeviceKnownEmittedFns;
10758
10759 /// A partial call graph maintained during CUDA/OpenMP device code compilation
10760 /// to support deferred diagnostics.
10761 ///
10762 /// Functions are only added here if, at the time they're considered, they are
10763 /// not known-emitted. As soon as we discover that a function is
10764 /// known-emitted, we remove it and everything it transitively calls from this
10765 /// set and add those functions to DeviceKnownEmittedFns.
10766 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
10767 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
10768 SourceLocation>>
10769 DeviceCallGraph;
10770
10771 /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be
10772 /// deferred.
10773 ///
10774 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
10775 /// which are not allowed to appear inside __device__ functions and are
10776 /// allowed to appear in __host__ __device__ functions only if the host+device
10777 /// function is never codegen'ed.
10778 ///
10779 /// To handle this, we use the notion of "deferred diagnostics", where we
10780 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
10781 ///
10782 /// This class lets you emit either a regular diagnostic, a deferred
10783 /// diagnostic, or no diagnostic at all, according to an argument you pass to
10784 /// its constructor, thus simplifying the process of creating these "maybe
10785 /// deferred" diagnostics.
10786 class DeviceDiagBuilder {
10787 public:
10788 enum Kind {
10789 /// Emit no diagnostics.
10790 K_Nop,
10791 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
10792 K_Immediate,
10793 /// Emit the diagnostic immediately, and, if it's a warning or error, also
10794 /// emit a call stack showing how this function can be reached by an a
10795 /// priori known-emitted function.
10796 K_ImmediateWithCallStack,
10797 /// Create a deferred diagnostic, which is emitted only if the function
10798 /// it's attached to is codegen'ed. Also emit a call stack as with
10799 /// K_ImmediateWithCallStack.
10800 K_Deferred
10801 };
10802
10803 DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
10804 FunctionDecl *Fn, Sema &S);
10805 DeviceDiagBuilder(DeviceDiagBuilder &&D);
10806 DeviceDiagBuilder(const DeviceDiagBuilder &) = default;
10807 ~DeviceDiagBuilder();
10808
10809 /// Convertible to bool: True if we immediately emitted an error, false if
10810 /// we didn't emit an error or we created a deferred error.
10811 ///
10812 /// Example usage:
10813 ///
10814 /// if (DeviceDiagBuilder(...) << foo << bar)
10815 /// return ExprError();
10816 ///
10817 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
10818 /// want to use these instead of creating a DeviceDiagBuilder yourself.
10819 operator bool() const { return ImmediateDiag.hasValue(); }
10820
10821 template <typename T>
10822 friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag,
10823 const T &Value) {
10824 if (Diag.ImmediateDiag.hasValue())
10825 *Diag.ImmediateDiag << Value;
10826 else if (Diag.PartialDiagId.hasValue())
10827 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
10828 << Value;
10829 return Diag;
10830 }
10831
10832 private:
10833 Sema &S;
10834 SourceLocation Loc;
10835 unsigned DiagID;
10836 FunctionDecl *Fn;
10837 bool ShowCallStack;
10838
10839 // Invariant: At most one of these Optionals has a value.
10840 // FIXME: Switch these to a Variant once that exists.
10841 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
10842 llvm::Optional<unsigned> PartialDiagId;
10843 };
10844
10845 /// Indicate that this function (and thus everything it transtively calls)
10846 /// will be codegen'ed, and emit any deferred diagnostics on this function and
10847 /// its (transitive) callees.
10848 void markKnownEmitted(
10849 Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee,
10850 SourceLocation OrigLoc,
10851 const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted);
10852
10853 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
10854 /// is "used as device code".
10855 ///
10856 /// - If CurContext is a __host__ function, does not emit any diagnostics.
10857 /// - If CurContext is a __device__ or __global__ function, emits the
10858 /// diagnostics immediately.
10859 /// - If CurContext is a __host__ __device__ function and we are compiling for
10860 /// the device, creates a diagnostic which is emitted if and when we realize
10861 /// that the function will be codegen'ed.
10862 ///
10863 /// Example usage:
10864 ///
10865 /// // Variable-length arrays are not allowed in CUDA device code.
10866 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
10867 /// return ExprError();
10868 /// // Otherwise, continue parsing as normal.
10869 DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
10870
10871 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
10872 /// is "used as host code".
10873 ///
10874 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
10875 DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
10876
10877 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
10878 /// context is "used as device code".
10879 ///
10880 /// - If CurContext is a `declare target` function or it is known that the
10881 /// function is emitted for the device, emits the diagnostics immediately.
10882 /// - If CurContext is a non-`declare target` function and we are compiling
10883 /// for the device, creates a diagnostic which is emitted if and when we
10884 /// realize that the function will be codegen'ed.
10885 ///
10886 /// Example usage:
10887 ///
10888 /// // Variable-length arrays are not allowed in NVPTX device code.
10889 /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
10890 /// return ExprError();
10891 /// // Otherwise, continue parsing as normal.
10892 DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID);
10893
10894 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
10895 /// context is "used as host code".
10896 ///
10897 /// - If CurContext is a `declare target` function or it is known that the
10898 /// function is emitted for the host, emits the diagnostics immediately.
10899 /// - If CurContext is a non-host function, just ignore it.
10900 ///
10901 /// Example usage:
10902 ///
10903 /// // Variable-length arrays are not allowed in NVPTX device code.
10904 /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
10905 /// return ExprError();
10906 /// // Otherwise, continue parsing as normal.
10907 DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID);
10908
10909 DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID);
10910
10911 enum CUDAFunctionTarget {
10912 CFT_Device,
10913 CFT_Global,
10914 CFT_Host,
10915 CFT_HostDevice,
10916 CFT_InvalidTarget
10917 };
10918
10919 /// Determines whether the given function is a CUDA device/host/kernel/etc.
10920 /// function.
10921 ///
10922 /// Use this rather than examining the function's attributes yourself -- you
10923 /// will get it wrong. Returns CFT_Host if D is null.
10924 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
10925 bool IgnoreImplicitHDAttr = false);
10926 CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
10927
10928 /// Gets the CUDA target for the current context.
10929 CUDAFunctionTarget CurrentCUDATarget() {
10930 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
10931 }
10932
10933 // CUDA function call preference. Must be ordered numerically from
10934 // worst to best.
10935 enum CUDAFunctionPreference {
10936 CFP_Never, // Invalid caller/callee combination.
10937 CFP_WrongSide, // Calls from host-device to host or device
10938 // function that do not match current compilation
10939 // mode.
10940 CFP_HostDevice, // Any calls to host/device functions.
10941 CFP_SameSide, // Calls from host-device to host or device
10942 // function matching current compilation mode.
10943 CFP_Native, // host-to-host or device-to-device calls.
10944 };
10945
10946 /// Identifies relative preference of a given Caller/Callee
10947 /// combination, based on their host/device attributes.
10948 /// \param Caller function which needs address of \p Callee.
10949 /// nullptr in case of global context.
10950 /// \param Callee target function
10951 ///
10952 /// \returns preference value for particular Caller/Callee combination.
10953 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
10954 const FunctionDecl *Callee);
10955
10956 /// Determines whether Caller may invoke Callee, based on their CUDA
10957 /// host/device attributes. Returns false if the call is not allowed.
10958 ///
10959 /// Note: Will return true for CFP_WrongSide calls. These may appear in
10960 /// semantically correct CUDA programs, but only if they're never codegen'ed.
10961 bool IsAllowedCUDACall(const FunctionDecl *Caller,
10962 const FunctionDecl *Callee) {
10963 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
10964 }
10965
10966 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
10967 /// depending on FD and the current compilation settings.
10968 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
10969 const LookupResult &Previous);
10970
10971public:
10972 /// Check whether we're allowed to call Callee from the current context.
10973 ///
10974 /// - If the call is never allowed in a semantically-correct program
10975 /// (CFP_Never), emits an error and returns false.
10976 ///
10977 /// - If the call is allowed in semantically-correct programs, but only if
10978 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
10979 /// be emitted if and when the caller is codegen'ed, and returns true.
10980 ///
10981 /// Will only create deferred diagnostics for a given SourceLocation once,
10982 /// so you can safely call this multiple times without generating duplicate
10983 /// deferred errors.
10984 ///
10985 /// - Otherwise, returns true without emitting any diagnostics.
10986 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
10987
10988 /// Set __device__ or __host__ __device__ attributes on the given lambda
10989 /// operator() method.
10990 ///
10991 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
10992 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
10993 /// functions become __host__ __device__ themselves.
10994 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
10995
10996 /// Finds a function in \p Matches with highest calling priority
10997 /// from \p Caller context and erases all functions with lower
10998 /// calling priority.
10999 void EraseUnwantedCUDAMatches(
11000 const FunctionDecl *Caller,
11001 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
11002
11003 /// Given a implicit special member, infer its CUDA target from the
11004 /// calls it needs to make to underlying base/field special members.
11005 /// \param ClassDecl the class for which the member is being created.
11006 /// \param CSM the kind of special member.
11007 /// \param MemberDecl the special member itself.
11008 /// \param ConstRHS true if this is a copy operation with a const object on
11009 /// its RHS.
11010 /// \param Diagnose true if this call should emit diagnostics.
11011 /// \return true if there was an error inferring.
11012 /// The result of this call is implicit CUDA target attribute(s) attached to
11013 /// the member declaration.
11014 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
11015 CXXSpecialMember CSM,
11016 CXXMethodDecl *MemberDecl,
11017 bool ConstRHS,
11018 bool Diagnose);
11019
11020 /// \return true if \p CD can be considered empty according to CUDA
11021 /// (E.2.3.1 in CUDA 7.5 Programming guide).
11022 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
11023 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
11024
11025 // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
11026 // case of error emits appropriate diagnostic and invalidates \p Var.
11027 //
11028 // \details CUDA allows only empty constructors as initializers for global
11029 // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
11030 // __shared__ variables whether they are local or not (they all are implicitly
11031 // static in CUDA). One exception is that CUDA allows constant initializers
11032 // for __constant__ and __device__ variables.
11033 void checkAllowedCUDAInitializer(VarDecl *VD);
11034
11035 /// Check whether NewFD is a valid overload for CUDA. Emits
11036 /// diagnostics and invalidates NewFD if not.
11037 void checkCUDATargetOverload(FunctionDecl *NewFD,
11038 const LookupResult &Previous);
11039 /// Copies target attributes from the template TD to the function FD.
11040 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
11041
11042 /// Returns the name of the launch configuration function. This is the name
11043 /// of the function that will be called to configure kernel call, with the
11044 /// parameters specified via <<<>>>.
11045 std::string getCudaConfigureFuncName() const;
11046
11047 /// \name Code completion
11048 //@{
11049 /// Describes the context in which code completion occurs.
11050 enum ParserCompletionContext {
11051 /// Code completion occurs at top-level or namespace context.
11052 PCC_Namespace,
11053 /// Code completion occurs within a class, struct, or union.
11054 PCC_Class,
11055 /// Code completion occurs within an Objective-C interface, protocol,
11056 /// or category.
11057 PCC_ObjCInterface,
11058 /// Code completion occurs within an Objective-C implementation or
11059 /// category implementation
11060 PCC_ObjCImplementation,
11061 /// Code completion occurs within the list of instance variables
11062 /// in an Objective-C interface, protocol, category, or implementation.
11063 PCC_ObjCInstanceVariableList,
11064 /// Code completion occurs following one or more template
11065 /// headers.
11066 PCC_Template,
11067 /// Code completion occurs following one or more template
11068 /// headers within a class.
11069 PCC_MemberTemplate,
11070 /// Code completion occurs within an expression.
11071 PCC_Expression,
11072 /// Code completion occurs within a statement, which may
11073 /// also be an expression or a declaration.
11074 PCC_Statement,
11075 /// Code completion occurs at the beginning of the
11076 /// initialization statement (or expression) in a for loop.
11077 PCC_ForInit,
11078 /// Code completion occurs within the condition of an if,
11079 /// while, switch, or for statement.
11080 PCC_Condition,
11081 /// Code completion occurs within the body of a function on a
11082 /// recovery path, where we do not have a specific handle on our position
11083 /// in the grammar.
11084 PCC_RecoveryInFunction,
11085 /// Code completion occurs where only a type is permitted.
11086 PCC_Type,
11087 /// Code completion occurs in a parenthesized expression, which
11088 /// might also be a type cast.
11089 PCC_ParenthesizedExpression,
11090 /// Code completion occurs within a sequence of declaration
11091 /// specifiers within a function, method, or block.
11092 PCC_LocalDeclarationSpecifiers
11093 };
11094
11095 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
11096 void CodeCompleteOrdinaryName(Scope *S,
11097 ParserCompletionContext CompletionContext);
11098 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
11099 bool AllowNonIdentifiers,
11100 bool AllowNestedNameSpecifiers);
11101
11102 struct CodeCompleteExpressionData;
11103 void CodeCompleteExpression(Scope *S,
11104 const CodeCompleteExpressionData &Data);
11105 void CodeCompleteExpression(Scope *S, QualType PreferredType,
11106 bool IsParenthesized = false);
11107 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
11108 SourceLocation OpLoc, bool IsArrow,
11109 bool IsBaseExprStatement,
11110 QualType PreferredType);
11111 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
11112 QualType PreferredType);
11113 void CodeCompleteTag(Scope *S, unsigned TagSpec);
11114 void CodeCompleteTypeQualifiers(DeclSpec &DS);
11115 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
11116 const VirtSpecifiers *VS = nullptr);
11117 void CodeCompleteBracketDeclarator(Scope *S);
11118 void CodeCompleteCase(Scope *S);
11119 /// Reports signatures for a call to CodeCompleteConsumer and returns the
11120 /// preferred type for the current argument. Returned type can be null.
11121 QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
11122 SourceLocation OpenParLoc);
11123 QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
11124 SourceLocation Loc,
11125 ArrayRef<Expr *> Args,
11126 SourceLocation OpenParLoc);
11127 QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
11128 CXXScopeSpec SS,
11129 ParsedType TemplateTypeTy,
11130 ArrayRef<Expr *> ArgExprs,
11131 IdentifierInfo *II,
11132 SourceLocation OpenParLoc);
11133 void CodeCompleteInitializer(Scope *S, Decl *D);
11134 void CodeCompleteAfterIf(Scope *S);
11135
11136 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
11137 bool IsUsingDeclaration, QualType BaseType,
11138 QualType PreferredType);
11139 void CodeCompleteUsing(Scope *S);
11140 void CodeCompleteUsingDirective(Scope *S);
11141 void CodeCompleteNamespaceDecl(Scope *S);
11142 void CodeCompleteNamespaceAliasDecl(Scope *S);
11143 void CodeCompleteOperatorName(Scope *S);
11144 void CodeCompleteConstructorInitializer(
11145 Decl *Constructor,
11146 ArrayRef<CXXCtorInitializer *> Initializers);
11147
11148 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
11149 bool AfterAmpersand);
11150
11151 void CodeCompleteObjCAtDirective(Scope *S);
11152 void CodeCompleteObjCAtVisibility(Scope *S);
11153 void CodeCompleteObjCAtStatement(Scope *S);
11154 void CodeCompleteObjCAtExpression(Scope *S);
11155 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
11156 void CodeCompleteObjCPropertyGetter(Scope *S);
11157 void CodeCompleteObjCPropertySetter(Scope *S);
11158 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
11159 bool IsParameter);
11160 void CodeCompleteObjCMessageReceiver(Scope *S);
11161 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
11162 ArrayRef<IdentifierInfo *> SelIdents,
11163 bool AtArgumentExpression);
11164 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
11165 ArrayRef<IdentifierInfo *> SelIdents,
11166 bool AtArgumentExpression,
11167 bool IsSuper = false);
11168 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
11169 ArrayRef<IdentifierInfo *> SelIdents,
11170 bool AtArgumentExpression,
11171 ObjCInterfaceDecl *Super = nullptr);
11172 void CodeCompleteObjCForCollection(Scope *S,
11173 DeclGroupPtrTy IterationVar);
11174 void CodeCompleteObjCSelector(Scope *S,
11175 ArrayRef<IdentifierInfo *> SelIdents);
11176 void CodeCompleteObjCProtocolReferences(
11177 ArrayRef<IdentifierLocPair> Protocols);
11178 void CodeCompleteObjCProtocolDecl(Scope *S);
11179 void CodeCompleteObjCInterfaceDecl(Scope *S);
11180 void CodeCompleteObjCSuperclass(Scope *S,
11181 IdentifierInfo *ClassName,
11182 SourceLocation ClassNameLoc);
11183 void CodeCompleteObjCImplementationDecl(Scope *S);
11184 void CodeCompleteObjCInterfaceCategory(Scope *S,
11185 IdentifierInfo *ClassName,
11186 SourceLocation ClassNameLoc);
11187 void CodeCompleteObjCImplementationCategory(Scope *S,
11188 IdentifierInfo *ClassName,
11189 SourceLocation ClassNameLoc);
11190 void CodeCompleteObjCPropertyDefinition(Scope *S);
11191 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
11192 IdentifierInfo *PropertyName);
11193 void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
11194 ParsedType ReturnType);
11195 void CodeCompleteObjCMethodDeclSelector(Scope *S,
11196 bool IsInstanceMethod,
11197 bool AtParameterName,
11198 ParsedType ReturnType,
11199 ArrayRef<IdentifierInfo *> SelIdents);
11200 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
11201 SourceLocation ClassNameLoc,
11202 bool IsBaseExprStatement);
11203 void CodeCompletePreprocessorDirective(bool InConditional);
11204 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
11205 void CodeCompletePreprocessorMacroName(bool IsDefinition);
11206 void CodeCompletePreprocessorExpression();
11207 void CodeCompletePreprocessorMacroArgument(Scope *S,
11208 IdentifierInfo *Macro,
11209 MacroInfo *MacroInfo,
11210 unsigned Argument);
11211 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
11212 void CodeCompleteNaturalLanguage();
11213 void CodeCompleteAvailabilityPlatformName();
11214 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
11215 CodeCompletionTUInfo &CCTUInfo,
11216 SmallVectorImpl<CodeCompletionResult> &Results);
11217 //@}
11218
11219 //===--------------------------------------------------------------------===//
11220 // Extra semantic analysis beyond the C type system
11221
11222public:
11223 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
11224 unsigned ByteNo) const;
11225
11226private:
11227 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
11228 const ArraySubscriptExpr *ASE=nullptr,
11229 bool AllowOnePastEnd=true, bool IndexNegated=false);
11230 void CheckArrayAccess(const Expr *E);
11231 // Used to grab the relevant information from a FormatAttr and a
11232 // FunctionDeclaration.
11233 struct FormatStringInfo {
11234 unsigned FormatIdx;
11235 unsigned FirstDataArg;
11236 bool HasVAListArg;
11237 };
11238
11239 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
11240 FormatStringInfo *FSI);
11241 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
11242 const FunctionProtoType *Proto);
11243 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
11244 ArrayRef<const Expr *> Args);
11245 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
11246 const FunctionProtoType *Proto);
11247 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
11248 void CheckConstructorCall(FunctionDecl *FDecl,
11249 ArrayRef<const Expr *> Args,
11250 const FunctionProtoType *Proto,
11251 SourceLocation Loc);
11252
11253 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
11254 const Expr *ThisArg, ArrayRef<const Expr *> Args,
11255 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
11256 VariadicCallType CallType);
11257
11258 bool CheckObjCString(Expr *Arg);
11259 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
11260
11261 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
11262 unsigned BuiltinID, CallExpr *TheCall);
11263 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
11264
11265 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
11266 unsigned MaxWidth);
11267 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11268 bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11269 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11270
11271 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11272 bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11273 bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11274 bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
11275 bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
11276 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11277 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11278 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
11279 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
11280 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11281 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11282
11283 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
11284 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
11285 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
11286 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
11287 bool SemaBuiltinVSX(CallExpr *TheCall);
11288 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
11289
11290public:
11291 // Used by C++ template instantiation.
11292 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
11293 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
11294 SourceLocation BuiltinLoc,
11295 SourceLocation RParenLoc);
11296
11297private:
11298 bool SemaBuiltinPrefetch(CallExpr *TheCall);
11299 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
11300 bool SemaBuiltinAssume(CallExpr *TheCall);
11301 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
11302 bool SemaBuiltinLongjmp(CallExpr *TheCall);
11303 bool SemaBuiltinSetjmp(CallExpr *TheCall);
11304 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
11305 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
11306 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
11307 AtomicExpr::AtomicOp Op);
11308 ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
11309 bool IsDelete);
11310 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
11311 llvm::APSInt &Result);
11312 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
11313 int High, bool RangeIsError = true);
11314 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
11315 unsigned Multiple);
11316 bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
11317 bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum);
11318 bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum);
11319 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
11320 int ArgNum, unsigned ExpectedFieldNum,
11321 bool AllowName);
11322 bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
11323public:
11324 enum FormatStringType {
11325 FST_Scanf,
11326 FST_Printf,
11327 FST_NSString,
11328 FST_Strftime,
11329 FST_Strfmon,
11330 FST_Kprintf,
11331 FST_FreeBSDKPrintf,
11332 FST_OSTrace,
11333 FST_OSLog,
11334 FST_Unknown
11335 };
11336 static FormatStringType GetFormatStringType(const FormatAttr *Format);
11337
11338 bool FormatStringHasSArg(const StringLiteral *FExpr);
11339
11340 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
11341
11342private:
11343 bool CheckFormatArguments(const FormatAttr *Format,
11344 ArrayRef<const Expr *> Args,
11345 bool IsCXXMember,
11346 VariadicCallType CallType,
11347 SourceLocation Loc, SourceRange Range,
11348 llvm::SmallBitVector &CheckedVarArgs);
11349 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
11350 bool HasVAListArg, unsigned format_idx,
11351 unsigned firstDataArg, FormatStringType Type,
11352 VariadicCallType CallType,
11353 SourceLocation Loc, SourceRange range,
11354 llvm::SmallBitVector &CheckedVarArgs);
11355
11356 void CheckAbsoluteValueFunction(const CallExpr *Call,
11357 const FunctionDecl *FDecl);
11358
11359 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
11360
11361 void CheckMemaccessArguments(const CallExpr *Call,
11362 unsigned BId,
11363 IdentifierInfo *FnName);
11364
11365 void CheckStrlcpycatArguments(const CallExpr *Call,
11366 IdentifierInfo *FnName);
11367
11368 void CheckStrncatArguments(const CallExpr *Call,
11369 IdentifierInfo *FnName);
11370
11371 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11372 SourceLocation ReturnLoc,
11373 bool isObjCMethod = false,
11374 const AttrVec *Attrs = nullptr,
11375 const FunctionDecl *FD = nullptr);
11376
11377public:
11378 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
11379
11380private:
11381 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
11382 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
11383 void CheckForIntOverflow(Expr *E);
11384 void CheckUnsequencedOperations(Expr *E);
11385
11386 /// Perform semantic checks on a completed expression. This will either
11387 /// be a full-expression or a default argument expression.
11388 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
11389 bool IsConstexpr = false);
11390
11391 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
11392 Expr *Init);
11393
11394 /// Check if there is a field shadowing.
11395 void CheckShadowInheritedFields(const SourceLocation &Loc,
11396 DeclarationName FieldName,
11397 const CXXRecordDecl *RD,
11398 bool DeclIsField = true);
11399
11400 /// Check if the given expression contains 'break' or 'continue'
11401 /// statement that produces control flow different from GCC.
11402 void CheckBreakContinueBinding(Expr *E);
11403
11404 /// Check whether receiver is mutable ObjC container which
11405 /// attempts to add itself into the container
11406 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
11407
11408 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
11409 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
11410 bool DeleteWasArrayForm);
11411public:
11412 /// Register a magic integral constant to be used as a type tag.
11413 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11414 uint64_t MagicValue, QualType Type,
11415 bool LayoutCompatible, bool MustBeNull);
11416
11417 struct TypeTagData {
11418 TypeTagData() {}
11419
11420 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
11421 Type(Type), LayoutCompatible(LayoutCompatible),
11422 MustBeNull(MustBeNull)
11423 {}
11424
11425 QualType Type;
11426
11427 /// If true, \c Type should be compared with other expression's types for
11428 /// layout-compatibility.
11429 unsigned LayoutCompatible : 1;
11430 unsigned MustBeNull : 1;
11431 };
11432
11433 /// A pair of ArgumentKind identifier and magic value. This uniquely
11434 /// identifies the magic value.
11435 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
11436
11437private:
11438 /// A map from magic value to type information.
11439 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
11440 TypeTagForDatatypeMagicValues;
11441
11442 /// Peform checks on a call of a function with argument_with_type_tag
11443 /// or pointer_with_type_tag attributes.
11444 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11445 const ArrayRef<const Expr *> ExprArgs,
11446 SourceLocation CallSiteLoc);
11447
11448 /// Check if we are taking the address of a packed field
11449 /// as this may be a problem if the pointer value is dereferenced.
11450 void CheckAddressOfPackedMember(Expr *rhs);
11451
11452 /// The parser's current scope.
11453 ///
11454 /// The parser maintains this state here.
11455 Scope *CurScope;
11456
11457 mutable IdentifierInfo *Ident_super;
11458 mutable IdentifierInfo *Ident___float128;
11459
11460 /// Nullability type specifiers.
11461 IdentifierInfo *Ident__Nonnull = nullptr;
11462 IdentifierInfo *Ident__Nullable = nullptr;
11463 IdentifierInfo *Ident__Null_unspecified = nullptr;
11464
11465 IdentifierInfo *Ident_NSError = nullptr;
11466
11467 /// The handler for the FileChanged preprocessor events.
11468 ///
11469 /// Used for diagnostics that implement custom semantic analysis for #include
11470 /// directives, like -Wpragma-pack.
11471 sema::SemaPPCallbacks *SemaPPCallbackHandler;
11472
11473protected:
11474 friend class Parser;
11475 friend class InitializationSequence;
11476 friend class ASTReader;
11477 friend class ASTDeclReader;
11478 friend class ASTWriter;
11479
11480public:
11481 /// Retrieve the keyword associated
11482 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
11483
11484 /// The struct behind the CFErrorRef pointer.
11485 RecordDecl *CFError = nullptr;
11486
11487 /// Retrieve the identifier "NSError".
11488 IdentifierInfo *getNSErrorIdent();
11489
11490 /// Retrieve the parser's current scope.
11491 ///
11492 /// This routine must only be used when it is certain that semantic analysis
11493 /// and the parser are in precisely the same context, which is not the case
11494 /// when, e.g., we are performing any kind of template instantiation.
11495 /// Therefore, the only safe places to use this scope are in the parser
11496 /// itself and in routines directly invoked from the parser and *never* from
11497 /// template substitution or instantiation.
11498 Scope *getCurScope() const { return CurScope; }
11499
11500 void incrementMSManglingNumber() const {
11501 return CurScope->incrementMSManglingNumber();
11502 }
11503
11504 IdentifierInfo *getSuperIdentifier() const;
11505 IdentifierInfo *getFloat128Identifier() const;
11506
11507 Decl *getObjCDeclContext() const;
11508
11509 DeclContext *getCurLexicalContext() const {
11510 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
11511 }
11512
11513 const DeclContext *getCurObjCLexicalContext() const {
11514 const DeclContext *DC = getCurLexicalContext();
11515 // A category implicitly has the attribute of the interface.
11516 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
11517 DC = CatD->getClassInterface();
11518 return DC;
11519 }
11520
11521 /// To be used for checking whether the arguments being passed to
11522 /// function exceeds the number of parameters expected for it.
11523 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
11524 bool PartialOverloading = false) {
11525 // We check whether we're just after a comma in code-completion.
11526 if (NumArgs > 0 && PartialOverloading)
11527 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
11528 return NumArgs > NumParams;
11529 }
11530
11531 // Emitting members of dllexported classes is delayed until the class
11532 // (including field initializers) is fully parsed.
11533 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
11534 SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
11535
11536private:
11537 class SavePendingParsedClassStateRAII {
11538 public:
11539 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
11540
11541 ~SavePendingParsedClassStateRAII() {
11542 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&((S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 11543, __PRETTY_FUNCTION__))
11543 "there shouldn't be any pending delayed exception spec checks")((S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 11543, __PRETTY_FUNCTION__))
;
11544 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&((S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 11545, __PRETTY_FUNCTION__))
11545 "there shouldn't be any pending delayed exception spec checks")((S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 11545, __PRETTY_FUNCTION__))
;
11546 assert(S.DelayedDllExportClasses.empty() &&((S.DelayedDllExportClasses.empty() && "there shouldn't be any pending delayed DLL export classes"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 11547, __PRETTY_FUNCTION__))
11547 "there shouldn't be any pending delayed DLL export classes")((S.DelayedDllExportClasses.empty() && "there shouldn't be any pending delayed DLL export classes"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 11547, __PRETTY_FUNCTION__))
;
11548 swapSavedState();
11549 }
11550
11551 private:
11552 Sema &S;
11553 decltype(DelayedOverridingExceptionSpecChecks)
11554 SavedOverridingExceptionSpecChecks;
11555 decltype(DelayedEquivalentExceptionSpecChecks)
11556 SavedEquivalentExceptionSpecChecks;
11557 decltype(DelayedDllExportClasses) SavedDllExportClasses;
11558
11559 void swapSavedState() {
11560 SavedOverridingExceptionSpecChecks.swap(
11561 S.DelayedOverridingExceptionSpecChecks);
11562 SavedEquivalentExceptionSpecChecks.swap(
11563 S.DelayedEquivalentExceptionSpecChecks);
11564 SavedDllExportClasses.swap(S.DelayedDllExportClasses);
11565 }
11566 };
11567
11568 /// Helper class that collects misaligned member designations and
11569 /// their location info for delayed diagnostics.
11570 struct MisalignedMember {
11571 Expr *E;
11572 RecordDecl *RD;
11573 ValueDecl *MD;
11574 CharUnits Alignment;
11575
11576 MisalignedMember() : E(), RD(), MD(), Alignment() {}
11577 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
11578 CharUnits Alignment)
11579 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
11580 explicit MisalignedMember(Expr *E)
11581 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
11582
11583 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
11584 };
11585 /// Small set of gathered accesses to potentially misaligned members
11586 /// due to the packed attribute.
11587 SmallVector<MisalignedMember, 4> MisalignedMembers;
11588
11589 /// Adds an expression to the set of gathered misaligned members.
11590 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11591 CharUnits Alignment);
11592
11593public:
11594 /// Diagnoses the current set of gathered accesses. This typically
11595 /// happens at full expression level. The set is cleared after emitting the
11596 /// diagnostics.
11597 void DiagnoseMisalignedMembers();
11598
11599 /// This function checks if the expression is in the sef of potentially
11600 /// misaligned members and it is converted to some pointer type T with lower
11601 /// or equal alignment requirements. If so it removes it. This is used when
11602 /// we do not want to diagnose such misaligned access (e.g. in conversions to
11603 /// void*).
11604 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
11605
11606 /// This function calls Action when it determines that E designates a
11607 /// misaligned member due to the packed attribute. This is used to emit
11608 /// local diagnostics like in reference binding.
11609 void RefersToMemberWithReducedAlignment(
11610 Expr *E,
11611 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
11612 Action);
11613
11614 /// Describes the reason a calling convention specification was ignored, used
11615 /// for diagnostics.
11616 enum class CallingConventionIgnoredReason {
11617 ForThisTarget = 0,
11618 VariadicFunction,
11619 ConstructorDestructor,
11620 BuiltinFunction
11621 };
11622};
11623
11624/// RAII object that enters a new expression evaluation context.
11625class EnterExpressionEvaluationContext {
11626 Sema &Actions;
11627 bool Entered = true;
11628
11629public:
11630 EnterExpressionEvaluationContext(
11631 Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
11632 Decl *LambdaContextDecl = nullptr,
11633 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
11634 Sema::ExpressionEvaluationContextRecord::EK_Other,
11635 bool ShouldEnter = true)
11636 : Actions(Actions), Entered(ShouldEnter) {
11637 if (Entered)
11638 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
11639 ExprContext);
11640 }
11641 EnterExpressionEvaluationContext(
11642 Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
11643 Sema::ReuseLambdaContextDecl_t,
11644 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
11645 Sema::ExpressionEvaluationContextRecord::EK_Other)
11646 : Actions(Actions) {
11647 Actions.PushExpressionEvaluationContext(
11648 NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
11649 }
11650
11651 enum InitListTag { InitList };
11652 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
11653 bool ShouldEnter = true)
11654 : Actions(Actions), Entered(false) {
11655 // In C++11 onwards, narrowing checks are performed on the contents of
11656 // braced-init-lists, even when they occur within unevaluated operands.
11657 // Therefore we still need to instantiate constexpr functions used in such
11658 // a context.
11659 if (ShouldEnter && Actions.isUnevaluatedContext() &&
11660 Actions.getLangOpts().CPlusPlus11) {
11661 Actions.PushExpressionEvaluationContext(
11662 Sema::ExpressionEvaluationContext::UnevaluatedList);
11663 Entered = true;
11664 }
11665 }
11666
11667 ~EnterExpressionEvaluationContext() {
11668 if (Entered)
11669 Actions.PopExpressionEvaluationContext();
11670 }
11671};
11672
11673DeductionFailureInfo
11674MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
11675 sema::TemplateDeductionInfo &Info);
11676
11677/// Contains a late templated function.
11678/// Will be parsed at the end of the translation unit, used by Sema & Parser.
11679struct LateParsedTemplate {
11680 CachedTokens Toks;
11681 /// The template function declaration to be late parsed.
11682 Decl *D;
11683};
11684} // end namespace clang
11685
11686namespace llvm {
11687// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
11688// SourceLocation.
11689template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
11690 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
11691 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
11692
11693 static FunctionDeclAndLoc getEmptyKey() {
11694 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
11695 }
11696
11697 static FunctionDeclAndLoc getTombstoneKey() {
11698 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
11699 }
11700
11701 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
11702 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
11703 FDL.Loc.getRawEncoding());
11704 }
11705
11706 static bool isEqual(const FunctionDeclAndLoc &LHS,
11707 const FunctionDeclAndLoc &RHS) {
11708 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
11709 }
11710};
11711} // namespace llvm
11712
11713#endif