Bug Summary

File:tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
Warning:line 4763, column 7
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 SemaTemplateInstantiateDecl.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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.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-9~svn362543/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn362543/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/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.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++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn362543=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-06-05-060531-1271-1 -x c++ /build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp -faddrsig

/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

1//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl 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 for declarations.
9//
10//===----------------------------------------------------------------------===/
11#include "clang/Sema/SemaInternal.h"
12#include "clang/AST/ASTConsumer.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/ASTMutationListener.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/DeclVisitor.h"
17#include "clang/AST/DependentDiagnostic.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/PrettyDeclStackTrace.h"
21#include "clang/AST/TypeLoc.h"
22#include "clang/Sema/Initialization.h"
23#include "clang/Sema/Lookup.h"
24#include "clang/Sema/Template.h"
25#include "clang/Sema/TemplateInstCallback.h"
26#include "llvm/Support/TimeProfiler.h"
27
28using namespace clang;
29
30static bool isDeclWithinFunction(const Decl *D) {
31 const DeclContext *DC = D->getDeclContext();
32 if (DC->isFunctionOrMethod())
33 return true;
34
35 if (DC->isRecord())
36 return cast<CXXRecordDecl>(DC)->isLocalClass();
37
38 return false;
39}
40
41template<typename DeclT>
42static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
43 const MultiLevelTemplateArgumentList &TemplateArgs) {
44 if (!OldDecl->getQualifierLoc())
45 return false;
46
47 assert((NewDecl->getFriendObjectKind() ||(((NewDecl->getFriendObjectKind() || !OldDecl->getLexicalDeclContext
()->isDependentContext()) && "non-friend with qualified name defined in dependent context"
) ? static_cast<void> (0) : __assert_fail ("(NewDecl->getFriendObjectKind() || !OldDecl->getLexicalDeclContext()->isDependentContext()) && \"non-friend with qualified name defined in dependent context\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 49, __PRETTY_FUNCTION__))
48 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&(((NewDecl->getFriendObjectKind() || !OldDecl->getLexicalDeclContext
()->isDependentContext()) && "non-friend with qualified name defined in dependent context"
) ? static_cast<void> (0) : __assert_fail ("(NewDecl->getFriendObjectKind() || !OldDecl->getLexicalDeclContext()->isDependentContext()) && \"non-friend with qualified name defined in dependent context\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 49, __PRETTY_FUNCTION__))
49 "non-friend with qualified name defined in dependent context")(((NewDecl->getFriendObjectKind() || !OldDecl->getLexicalDeclContext
()->isDependentContext()) && "non-friend with qualified name defined in dependent context"
) ? static_cast<void> (0) : __assert_fail ("(NewDecl->getFriendObjectKind() || !OldDecl->getLexicalDeclContext()->isDependentContext()) && \"non-friend with qualified name defined in dependent context\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 49, __PRETTY_FUNCTION__))
;
50 Sema::ContextRAII SavedContext(
51 SemaRef,
52 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
53 ? NewDecl->getLexicalDeclContext()
54 : OldDecl->getLexicalDeclContext()));
55
56 NestedNameSpecifierLoc NewQualifierLoc
57 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
58 TemplateArgs);
59
60 if (!NewQualifierLoc)
61 return true;
62
63 NewDecl->setQualifierInfo(NewQualifierLoc);
64 return false;
65}
66
67bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
68 DeclaratorDecl *NewDecl) {
69 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
70}
71
72bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
73 TagDecl *NewDecl) {
74 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
75}
76
77// Include attribute instantiation code.
78#include "clang/Sema/AttrTemplateInstantiate.inc"
79
80static void instantiateDependentAlignedAttr(
81 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
82 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
83 if (Aligned->isAlignmentExpr()) {
84 // The alignment expression is a constant expression.
85 EnterExpressionEvaluationContext Unevaluated(
86 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
87 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
88 if (!Result.isInvalid())
89 S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
90 Aligned->getSpellingListIndex(), IsPackExpansion);
91 } else {
92 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
93 TemplateArgs, Aligned->getLocation(),
94 DeclarationName());
95 if (Result)
96 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
97 Aligned->getSpellingListIndex(), IsPackExpansion);
98 }
99}
100
101static void instantiateDependentAlignedAttr(
102 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
103 const AlignedAttr *Aligned, Decl *New) {
104 if (!Aligned->isPackExpansion()) {
105 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
106 return;
107 }
108
109 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
110 if (Aligned->isAlignmentExpr())
111 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
112 Unexpanded);
113 else
114 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
115 Unexpanded);
116 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")((!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? static_cast<void> (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 116, __PRETTY_FUNCTION__))
;
117
118 // Determine whether we can expand this attribute pack yet.
119 bool Expand = true, RetainExpansion = false;
120 Optional<unsigned> NumExpansions;
121 // FIXME: Use the actual location of the ellipsis.
122 SourceLocation EllipsisLoc = Aligned->getLocation();
123 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
124 Unexpanded, TemplateArgs, Expand,
125 RetainExpansion, NumExpansions))
126 return;
127
128 if (!Expand) {
129 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
130 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
131 } else {
132 for (unsigned I = 0; I != *NumExpansions; ++I) {
133 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
134 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
135 }
136 }
137}
138
139static void instantiateDependentAssumeAlignedAttr(
140 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
141 const AssumeAlignedAttr *Aligned, Decl *New) {
142 // The alignment expression is a constant expression.
143 EnterExpressionEvaluationContext Unevaluated(
144 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
145
146 Expr *E, *OE = nullptr;
147 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
148 if (Result.isInvalid())
149 return;
150 E = Result.getAs<Expr>();
151
152 if (Aligned->getOffset()) {
153 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
154 if (Result.isInvalid())
155 return;
156 OE = Result.getAs<Expr>();
157 }
158
159 S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
160 Aligned->getSpellingListIndex());
161}
162
163static void instantiateDependentAlignValueAttr(
164 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
165 const AlignValueAttr *Aligned, Decl *New) {
166 // The alignment expression is a constant expression.
167 EnterExpressionEvaluationContext Unevaluated(
168 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
169 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
170 if (!Result.isInvalid())
171 S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
172 Aligned->getSpellingListIndex());
173}
174
175static void instantiateDependentAllocAlignAttr(
176 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
177 const AllocAlignAttr *Align, Decl *New) {
178 Expr *Param = IntegerLiteral::Create(
179 S.getASTContext(),
180 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
181 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
182 S.AddAllocAlignAttr(Align->getLocation(), New, Param,
183 Align->getSpellingListIndex());
184}
185
186static Expr *instantiateDependentFunctionAttrCondition(
187 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
188 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
189 Expr *Cond = nullptr;
190 {
191 Sema::ContextRAII SwitchContext(S, New);
192 EnterExpressionEvaluationContext Unevaluated(
193 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
194 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
195 if (Result.isInvalid())
196 return nullptr;
197 Cond = Result.getAs<Expr>();
198 }
199 if (!Cond->isTypeDependent()) {
200 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
201 if (Converted.isInvalid())
202 return nullptr;
203 Cond = Converted.get();
204 }
205
206 SmallVector<PartialDiagnosticAt, 8> Diags;
207 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
208 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
209 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
210 for (const auto &P : Diags)
211 S.Diag(P.first, P.second);
212 return nullptr;
213 }
214 return Cond;
215}
216
217static void instantiateDependentEnableIfAttr(
218 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
219 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
220 Expr *Cond = instantiateDependentFunctionAttrCondition(
221 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
222
223 if (Cond)
224 New->addAttr(new (S.getASTContext()) EnableIfAttr(
225 EIA->getLocation(), S.getASTContext(), Cond, EIA->getMessage(),
226 EIA->getSpellingListIndex()));
227}
228
229static void instantiateDependentDiagnoseIfAttr(
230 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
231 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
232 Expr *Cond = instantiateDependentFunctionAttrCondition(
233 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
234
235 if (Cond)
236 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
237 DIA->getLocation(), S.getASTContext(), Cond, DIA->getMessage(),
238 DIA->getDiagnosticType(), DIA->getArgDependent(), New,
239 DIA->getSpellingListIndex()));
240}
241
242// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
243// template A as the base and arguments from TemplateArgs.
244static void instantiateDependentCUDALaunchBoundsAttr(
245 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
246 const CUDALaunchBoundsAttr &Attr, Decl *New) {
247 // The alignment expression is a constant expression.
248 EnterExpressionEvaluationContext Unevaluated(
249 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
250
251 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
252 if (Result.isInvalid())
253 return;
254 Expr *MaxThreads = Result.getAs<Expr>();
255
256 Expr *MinBlocks = nullptr;
257 if (Attr.getMinBlocks()) {
258 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
259 if (Result.isInvalid())
260 return;
261 MinBlocks = Result.getAs<Expr>();
262 }
263
264 S.AddLaunchBoundsAttr(Attr.getLocation(), New, MaxThreads, MinBlocks,
265 Attr.getSpellingListIndex());
266}
267
268static void
269instantiateDependentModeAttr(Sema &S,
270 const MultiLevelTemplateArgumentList &TemplateArgs,
271 const ModeAttr &Attr, Decl *New) {
272 S.AddModeAttr(Attr.getRange(), New, Attr.getMode(),
273 Attr.getSpellingListIndex(), /*InInstantiation=*/true);
274}
275
276/// Instantiation of 'declare simd' attribute and its arguments.
277static void instantiateOMPDeclareSimdDeclAttr(
278 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
279 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
280 // Allow 'this' in clauses with varlists.
281 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
282 New = FTD->getTemplatedDecl();
283 auto *FD = cast<FunctionDecl>(New);
284 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
285 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
286 SmallVector<unsigned, 4> LinModifiers;
287
288 auto &&Subst = [&](Expr *E) -> ExprResult {
289 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
290 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
291 Sema::ContextRAII SavedContext(S, FD);
292 LocalInstantiationScope Local(S);
293 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
294 Local.InstantiatedLocal(
295 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
296 return S.SubstExpr(E, TemplateArgs);
297 }
298 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
299 FD->isCXXInstanceMember());
300 return S.SubstExpr(E, TemplateArgs);
301 };
302
303 ExprResult Simdlen;
304 if (auto *E = Attr.getSimdlen())
305 Simdlen = Subst(E);
306
307 if (Attr.uniforms_size() > 0) {
308 for(auto *E : Attr.uniforms()) {
309 ExprResult Inst = Subst(E);
310 if (Inst.isInvalid())
311 continue;
312 Uniforms.push_back(Inst.get());
313 }
314 }
315
316 auto AI = Attr.alignments_begin();
317 for (auto *E : Attr.aligneds()) {
318 ExprResult Inst = Subst(E);
319 if (Inst.isInvalid())
320 continue;
321 Aligneds.push_back(Inst.get());
322 Inst = ExprEmpty();
323 if (*AI)
324 Inst = S.SubstExpr(*AI, TemplateArgs);
325 Alignments.push_back(Inst.get());
326 ++AI;
327 }
328
329 auto SI = Attr.steps_begin();
330 for (auto *E : Attr.linears()) {
331 ExprResult Inst = Subst(E);
332 if (Inst.isInvalid())
333 continue;
334 Linears.push_back(Inst.get());
335 Inst = ExprEmpty();
336 if (*SI)
337 Inst = S.SubstExpr(*SI, TemplateArgs);
338 Steps.push_back(Inst.get());
339 ++SI;
340 }
341 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
342 (void)S.ActOnOpenMPDeclareSimdDirective(
343 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
344 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
345 Attr.getRange());
346}
347
348static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
349 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
350 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
351 // Both min and max expression are constant expressions.
352 EnterExpressionEvaluationContext Unevaluated(
353 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
354
355 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
356 if (Result.isInvalid())
357 return;
358 Expr *MinExpr = Result.getAs<Expr>();
359
360 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
361 if (Result.isInvalid())
362 return;
363 Expr *MaxExpr = Result.getAs<Expr>();
364
365 S.addAMDGPUFlatWorkGroupSizeAttr(Attr.getLocation(), New, MinExpr, MaxExpr,
366 Attr.getSpellingListIndex());
367}
368
369static ExplicitSpecifier
370instantiateExplicitSpecifier(Sema &S,
371 const MultiLevelTemplateArgumentList &TemplateArgs,
372 ExplicitSpecifier ES, FunctionDecl *New) {
373 if (!ES.getExpr())
374 return ES;
375 Expr *OldCond = ES.getExpr();
376 Expr *Cond = nullptr;
377 {
378 EnterExpressionEvaluationContext Unevaluated(
379 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
380 ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
381 if (SubstResult.isInvalid()) {
382 return ExplicitSpecifier::Invalid();
383 }
384 Cond = SubstResult.get();
385 }
386 ExplicitSpecifier Result(Cond, ES.getKind());
387 if (!Cond->isTypeDependent())
388 S.tryResolveExplicitSpecifier(Result);
389 return Result;
390}
391
392static void instantiateDependentAMDGPUWavesPerEUAttr(
393 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
394 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
395 // Both min and max expression are constant expressions.
396 EnterExpressionEvaluationContext Unevaluated(
397 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
398
399 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
400 if (Result.isInvalid())
401 return;
402 Expr *MinExpr = Result.getAs<Expr>();
403
404 Expr *MaxExpr = nullptr;
405 if (auto Max = Attr.getMax()) {
406 Result = S.SubstExpr(Max, TemplateArgs);
407 if (Result.isInvalid())
408 return;
409 MaxExpr = Result.getAs<Expr>();
410 }
411
412 S.addAMDGPUWavesPerEUAttr(Attr.getLocation(), New, MinExpr, MaxExpr,
413 Attr.getSpellingListIndex());
414}
415
416void Sema::InstantiateAttrsForDecl(
417 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
418 Decl *New, LateInstantiatedAttrVec *LateAttrs,
419 LocalInstantiationScope *OuterMostScope) {
420 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
421 for (const auto *TmplAttr : Tmpl->attrs()) {
422 // FIXME: If any of the special case versions from InstantiateAttrs become
423 // applicable to template declaration, we'll need to add them here.
424 CXXThisScopeRAII ThisScope(
425 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
426 Qualifiers(), ND->isCXXInstanceMember());
427
428 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
429 TmplAttr, Context, *this, TemplateArgs);
430 if (NewAttr)
431 New->addAttr(NewAttr);
432 }
433 }
434}
435
436static Sema::RetainOwnershipKind
437attrToRetainOwnershipKind(const Attr *A) {
438 switch (A->getKind()) {
439 case clang::attr::CFConsumed:
440 return Sema::RetainOwnershipKind::CF;
441 case clang::attr::OSConsumed:
442 return Sema::RetainOwnershipKind::OS;
443 case clang::attr::NSConsumed:
444 return Sema::RetainOwnershipKind::NS;
445 default:
446 llvm_unreachable("Wrong argument supplied")::llvm::llvm_unreachable_internal("Wrong argument supplied", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 446)
;
447 }
448}
449
450void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
451 const Decl *Tmpl, Decl *New,
452 LateInstantiatedAttrVec *LateAttrs,
453 LocalInstantiationScope *OuterMostScope) {
454 for (const auto *TmplAttr : Tmpl->attrs()) {
455 // FIXME: This should be generalized to more than just the AlignedAttr.
456 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
457 if (Aligned && Aligned->isAlignmentDependent()) {
458 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
459 continue;
460 }
461
462 const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr);
463 if (AssumeAligned) {
464 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
465 continue;
466 }
467
468 const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr);
469 if (AlignValue) {
470 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
471 continue;
472 }
473
474 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
475 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
476 continue;
477 }
478
479
480 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
481 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
482 cast<FunctionDecl>(New));
483 continue;
484 }
485
486 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
487 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
488 cast<FunctionDecl>(New));
489 continue;
490 }
491
492 if (const CUDALaunchBoundsAttr *CUDALaunchBounds =
493 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
494 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
495 *CUDALaunchBounds, New);
496 continue;
497 }
498
499 if (const ModeAttr *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
500 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
501 continue;
502 }
503
504 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
505 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
506 continue;
507 }
508
509 if (const AMDGPUFlatWorkGroupSizeAttr *AMDGPUFlatWorkGroupSize =
510 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
511 instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
512 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
513 }
514
515 if (const AMDGPUWavesPerEUAttr *AMDGPUFlatWorkGroupSize =
516 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
517 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
518 *AMDGPUFlatWorkGroupSize, New);
519 }
520
521 // Existing DLL attribute on the instantiation takes precedence.
522 if (TmplAttr->getKind() == attr::DLLExport ||
523 TmplAttr->getKind() == attr::DLLImport) {
524 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
525 continue;
526 }
527 }
528
529 if (auto ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
530 AddParameterABIAttr(ABIAttr->getRange(), New, ABIAttr->getABI(),
531 ABIAttr->getSpellingListIndex());
532 continue;
533 }
534
535 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
536 isa<CFConsumedAttr>(TmplAttr)) {
537 AddXConsumedAttr(New, TmplAttr->getRange(),
538 TmplAttr->getSpellingListIndex(),
539 attrToRetainOwnershipKind(TmplAttr),
540 /*template instantiation=*/true);
541 continue;
542 }
543
544 assert(!TmplAttr->isPackExpansion())((!TmplAttr->isPackExpansion()) ? static_cast<void> (
0) : __assert_fail ("!TmplAttr->isPackExpansion()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 544, __PRETTY_FUNCTION__))
;
545 if (TmplAttr->isLateParsed() && LateAttrs) {
546 // Late parsed attributes must be instantiated and attached after the
547 // enclosing class has been instantiated. See Sema::InstantiateClass.
548 LocalInstantiationScope *Saved = nullptr;
549 if (CurrentInstantiationScope)
550 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
551 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
552 } else {
553 // Allow 'this' within late-parsed attributes.
554 NamedDecl *ND = dyn_cast<NamedDecl>(New);
555 CXXRecordDecl *ThisContext =
556 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
557 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
558 ND && ND->isCXXInstanceMember());
559
560 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
561 *this, TemplateArgs);
562 if (NewAttr)
563 New->addAttr(NewAttr);
564 }
565 }
566}
567
568/// Get the previous declaration of a declaration for the purposes of template
569/// instantiation. If this finds a previous declaration, then the previous
570/// declaration of the instantiation of D should be an instantiation of the
571/// result of this function.
572template<typename DeclT>
573static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
574 DeclT *Result = D->getPreviousDecl();
575
576 // If the declaration is within a class, and the previous declaration was
577 // merged from a different definition of that class, then we don't have a
578 // previous declaration for the purpose of template instantiation.
579 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
580 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
581 return nullptr;
582
583 return Result;
584}
585
586Decl *
587TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
588 llvm_unreachable("Translation units cannot be instantiated")::llvm::llvm_unreachable_internal("Translation units cannot be instantiated"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 588)
;
589}
590
591Decl *
592TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
593 llvm_unreachable("pragma comment cannot be instantiated")::llvm::llvm_unreachable_internal("pragma comment cannot be instantiated"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 593)
;
594}
595
596Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
597 PragmaDetectMismatchDecl *D) {
598 llvm_unreachable("pragma comment cannot be instantiated")::llvm::llvm_unreachable_internal("pragma comment cannot be instantiated"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 598)
;
599}
600
601Decl *
602TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
603 llvm_unreachable("extern \"C\" context cannot be instantiated")::llvm::llvm_unreachable_internal("extern \"C\" context cannot be instantiated"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 603)
;
604}
605
606Decl *
607TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
608 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
609 D->getIdentifier());
610 Owner->addDecl(Inst);
611 return Inst;
612}
613
614Decl *
615TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
616 llvm_unreachable("Namespaces cannot be instantiated")::llvm::llvm_unreachable_internal("Namespaces cannot be instantiated"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 616)
;
617}
618
619Decl *
620TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
621 NamespaceAliasDecl *Inst
622 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
623 D->getNamespaceLoc(),
624 D->getAliasLoc(),
625 D->getIdentifier(),
626 D->getQualifierLoc(),
627 D->getTargetNameLoc(),
628 D->getNamespace());
629 Owner->addDecl(Inst);
630 return Inst;
631}
632
633Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
634 bool IsTypeAlias) {
635 bool Invalid = false;
636 TypeSourceInfo *DI = D->getTypeSourceInfo();
637 if (DI->getType()->isInstantiationDependentType() ||
638 DI->getType()->isVariablyModifiedType()) {
639 DI = SemaRef.SubstType(DI, TemplateArgs,
640 D->getLocation(), D->getDeclName());
641 if (!DI) {
642 Invalid = true;
643 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
644 }
645 } else {
646 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
647 }
648
649 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
650 // libstdc++ relies upon this bug in its implementation of common_type.
651 // If we happen to be processing that implementation, fake up the g++ ?:
652 // semantics. See LWG issue 2141 for more information on the bug.
653 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
654 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
655 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
656 DT->isReferenceType() &&
657 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
658 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
659 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
660 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
661 // Fold it to the (non-reference) type which g++ would have produced.
662 DI = SemaRef.Context.getTrivialTypeSourceInfo(
663 DI->getType().getNonReferenceType());
664
665 // Create the new typedef
666 TypedefNameDecl *Typedef;
667 if (IsTypeAlias)
668 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
669 D->getLocation(), D->getIdentifier(), DI);
670 else
671 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
672 D->getLocation(), D->getIdentifier(), DI);
673 if (Invalid)
674 Typedef->setInvalidDecl();
675
676 // If the old typedef was the name for linkage purposes of an anonymous
677 // tag decl, re-establish that relationship for the new typedef.
678 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
679 TagDecl *oldTag = oldTagType->getDecl();
680 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
681 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
682 assert(!newTag->hasNameForLinkage())((!newTag->hasNameForLinkage()) ? static_cast<void> (
0) : __assert_fail ("!newTag->hasNameForLinkage()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 682, __PRETTY_FUNCTION__))
;
683 newTag->setTypedefNameForAnonDecl(Typedef);
684 }
685 }
686
687 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
688 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
689 TemplateArgs);
690 if (!InstPrev)
691 return nullptr;
692
693 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
694
695 // If the typedef types are not identical, reject them.
696 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
697
698 Typedef->setPreviousDecl(InstPrevTypedef);
699 }
700
701 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
702
703 Typedef->setAccess(D->getAccess());
704
705 return Typedef;
706}
707
708Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
709 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
710 if (Typedef)
711 Owner->addDecl(Typedef);
712 return Typedef;
713}
714
715Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
716 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
717 if (Typedef)
718 Owner->addDecl(Typedef);
719 return Typedef;
720}
721
722Decl *
723TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
724 // Create a local instantiation scope for this type alias template, which
725 // will contain the instantiations of the template parameters.
726 LocalInstantiationScope Scope(SemaRef);
727
728 TemplateParameterList *TempParams = D->getTemplateParameters();
729 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
730 if (!InstParams)
731 return nullptr;
732
733 TypeAliasDecl *Pattern = D->getTemplatedDecl();
734
735 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
736 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
737 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
738 if (!Found.empty()) {
739 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
740 }
741 }
742
743 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
744 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
745 if (!AliasInst)
746 return nullptr;
747
748 TypeAliasTemplateDecl *Inst
749 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
750 D->getDeclName(), InstParams, AliasInst);
751 AliasInst->setDescribedAliasTemplate(Inst);
752 if (PrevAliasTemplate)
753 Inst->setPreviousDecl(PrevAliasTemplate);
754
755 Inst->setAccess(D->getAccess());
756
757 if (!PrevAliasTemplate)
758 Inst->setInstantiatedFromMemberTemplate(D);
759
760 Owner->addDecl(Inst);
761
762 return Inst;
763}
764
765Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
766 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
767 D->getIdentifier());
768 NewBD->setReferenced(D->isReferenced());
769 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
770 return NewBD;
771}
772
773Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
774 // Transform the bindings first.
775 SmallVector<BindingDecl*, 16> NewBindings;
776 for (auto *OldBD : D->bindings())
777 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
778 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
779
780 auto *NewDD = cast_or_null<DecompositionDecl>(
781 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
782
783 if (!NewDD || NewDD->isInvalidDecl())
784 for (auto *NewBD : NewBindings)
785 NewBD->setInvalidDecl();
786
787 return NewDD;
788}
789
790Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
791 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
792}
793
794Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
795 bool InstantiatingVarTemplate,
796 ArrayRef<BindingDecl*> *Bindings) {
797
798 // Do substitution on the type of the declaration
799 TypeSourceInfo *DI = SemaRef.SubstType(
800 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
801 D->getDeclName(), /*AllowDeducedTST*/true);
802 if (!DI)
803 return nullptr;
804
805 if (DI->getType()->isFunctionType()) {
806 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
807 << D->isStaticDataMember() << DI->getType();
808 return nullptr;
809 }
810
811 DeclContext *DC = Owner;
812 if (D->isLocalExternDecl())
813 SemaRef.adjustContextForLocalExternDecl(DC);
814
815 // Build the instantiated declaration.
816 VarDecl *Var;
817 if (Bindings)
818 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
819 D->getLocation(), DI->getType(), DI,
820 D->getStorageClass(), *Bindings);
821 else
822 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
823 D->getLocation(), D->getIdentifier(), DI->getType(),
824 DI, D->getStorageClass());
825
826 // In ARC, infer 'retaining' for variables of retainable type.
827 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
828 SemaRef.inferObjCARCLifetime(Var))
829 Var->setInvalidDecl();
830
831 // Substitute the nested name specifier, if any.
832 if (SubstQualifier(D, Var))
833 return nullptr;
834
835 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
836 StartingScope, InstantiatingVarTemplate);
837
838 if (D->isNRVOVariable()) {
839 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
840 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, Sema::CES_Strict))
841 Var->setNRVOVariable(true);
842 }
843
844 Var->setImplicit(D->isImplicit());
845
846 if (Var->isStaticLocal())
847 SemaRef.CheckStaticLocalForDllExport(Var);
848
849 return Var;
850}
851
852Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
853 AccessSpecDecl* AD
854 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
855 D->getAccessSpecifierLoc(), D->getColonLoc());
856 Owner->addHiddenDecl(AD);
857 return AD;
858}
859
860Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
861 bool Invalid = false;
862 TypeSourceInfo *DI = D->getTypeSourceInfo();
863 if (DI->getType()->isInstantiationDependentType() ||
864 DI->getType()->isVariablyModifiedType()) {
865 DI = SemaRef.SubstType(DI, TemplateArgs,
866 D->getLocation(), D->getDeclName());
867 if (!DI) {
868 DI = D->getTypeSourceInfo();
869 Invalid = true;
870 } else if (DI->getType()->isFunctionType()) {
871 // C++ [temp.arg.type]p3:
872 // If a declaration acquires a function type through a type
873 // dependent on a template-parameter and this causes a
874 // declaration that does not use the syntactic form of a
875 // function declarator to have function type, the program is
876 // ill-formed.
877 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
878 << DI->getType();
879 Invalid = true;
880 }
881 } else {
882 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
883 }
884
885 Expr *BitWidth = D->getBitWidth();
886 if (Invalid)
887 BitWidth = nullptr;
888 else if (BitWidth) {
889 // The bit-width expression is a constant expression.
890 EnterExpressionEvaluationContext Unevaluated(
891 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
892
893 ExprResult InstantiatedBitWidth
894 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
895 if (InstantiatedBitWidth.isInvalid()) {
896 Invalid = true;
897 BitWidth = nullptr;
898 } else
899 BitWidth = InstantiatedBitWidth.getAs<Expr>();
900 }
901
902 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
903 DI->getType(), DI,
904 cast<RecordDecl>(Owner),
905 D->getLocation(),
906 D->isMutable(),
907 BitWidth,
908 D->getInClassInitStyle(),
909 D->getInnerLocStart(),
910 D->getAccess(),
911 nullptr);
912 if (!Field) {
913 cast<Decl>(Owner)->setInvalidDecl();
914 return nullptr;
915 }
916
917 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
918
919 if (Field->hasAttrs())
920 SemaRef.CheckAlignasUnderalignment(Field);
921
922 if (Invalid)
923 Field->setInvalidDecl();
924
925 if (!Field->getDeclName()) {
926 // Keep track of where this decl came from.
927 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
928 }
929 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
930 if (Parent->isAnonymousStructOrUnion() &&
931 Parent->getRedeclContext()->isFunctionOrMethod())
932 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
933 }
934
935 Field->setImplicit(D->isImplicit());
936 Field->setAccess(D->getAccess());
937 Owner->addDecl(Field);
938
939 return Field;
940}
941
942Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
943 bool Invalid = false;
944 TypeSourceInfo *DI = D->getTypeSourceInfo();
945
946 if (DI->getType()->isVariablyModifiedType()) {
947 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
948 << D;
949 Invalid = true;
950 } else if (DI->getType()->isInstantiationDependentType()) {
951 DI = SemaRef.SubstType(DI, TemplateArgs,
952 D->getLocation(), D->getDeclName());
953 if (!DI) {
954 DI = D->getTypeSourceInfo();
955 Invalid = true;
956 } else if (DI->getType()->isFunctionType()) {
957 // C++ [temp.arg.type]p3:
958 // If a declaration acquires a function type through a type
959 // dependent on a template-parameter and this causes a
960 // declaration that does not use the syntactic form of a
961 // function declarator to have function type, the program is
962 // ill-formed.
963 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
964 << DI->getType();
965 Invalid = true;
966 }
967 } else {
968 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
969 }
970
971 MSPropertyDecl *Property = MSPropertyDecl::Create(
972 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
973 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
974
975 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
976 StartingScope);
977
978 if (Invalid)
979 Property->setInvalidDecl();
980
981 Property->setAccess(D->getAccess());
982 Owner->addDecl(Property);
983
984 return Property;
985}
986
987Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
988 NamedDecl **NamedChain =
989 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
990
991 int i = 0;
992 for (auto *PI : D->chain()) {
993 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
994 TemplateArgs);
995 if (!Next)
996 return nullptr;
997
998 NamedChain[i++] = Next;
999 }
1000
1001 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1002 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1003 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1004 {NamedChain, D->getChainingSize()});
1005
1006 for (const auto *Attr : D->attrs())
1007 IndirectField->addAttr(Attr->clone(SemaRef.Context));
1008
1009 IndirectField->setImplicit(D->isImplicit());
1010 IndirectField->setAccess(D->getAccess());
1011 Owner->addDecl(IndirectField);
1012 return IndirectField;
1013}
1014
1015Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1016 // Handle friend type expressions by simply substituting template
1017 // parameters into the pattern type and checking the result.
1018 if (TypeSourceInfo *Ty = D->getFriendType()) {
1019 TypeSourceInfo *InstTy;
1020 // If this is an unsupported friend, don't bother substituting template
1021 // arguments into it. The actual type referred to won't be used by any
1022 // parts of Clang, and may not be valid for instantiating. Just use the
1023 // same info for the instantiated friend.
1024 if (D->isUnsupportedFriend()) {
1025 InstTy = Ty;
1026 } else {
1027 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1028 D->getLocation(), DeclarationName());
1029 }
1030 if (!InstTy)
1031 return nullptr;
1032
1033 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
1034 D->getFriendLoc(), InstTy);
1035 if (!FD)
1036 return nullptr;
1037
1038 FD->setAccess(AS_public);
1039 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1040 Owner->addDecl(FD);
1041 return FD;
1042 }
1043
1044 NamedDecl *ND = D->getFriendDecl();
1045 assert(ND && "friend decl must be a decl or a type!")((ND && "friend decl must be a decl or a type!") ? static_cast
<void> (0) : __assert_fail ("ND && \"friend decl must be a decl or a type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1045, __PRETTY_FUNCTION__))
;
1046
1047 // All of the Visit implementations for the various potential friend
1048 // declarations have to be carefully written to work for friend
1049 // objects, with the most important detail being that the target
1050 // decl should almost certainly not be placed in Owner.
1051 Decl *NewND = Visit(ND);
1052 if (!NewND) return nullptr;
1053
1054 FriendDecl *FD =
1055 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1056 cast<NamedDecl>(NewND), D->getFriendLoc());
1057 FD->setAccess(AS_public);
1058 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1059 Owner->addDecl(FD);
1060 return FD;
1061}
1062
1063Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1064 Expr *AssertExpr = D->getAssertExpr();
1065
1066 // The expression in a static assertion is a constant expression.
1067 EnterExpressionEvaluationContext Unevaluated(
1068 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1069
1070 ExprResult InstantiatedAssertExpr
1071 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1072 if (InstantiatedAssertExpr.isInvalid())
1073 return nullptr;
1074
1075 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
1076 InstantiatedAssertExpr.get(),
1077 D->getMessage(),
1078 D->getRParenLoc(),
1079 D->isFailed());
1080}
1081
1082Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1083 EnumDecl *PrevDecl = nullptr;
1084 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1085 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1086 PatternPrev,
1087 TemplateArgs);
1088 if (!Prev) return nullptr;
1089 PrevDecl = cast<EnumDecl>(Prev);
1090 }
1091
1092 EnumDecl *Enum =
1093 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1094 D->getLocation(), D->getIdentifier(), PrevDecl,
1095 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1096 if (D->isFixed()) {
1097 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1098 // If we have type source information for the underlying type, it means it
1099 // has been explicitly set by the user. Perform substitution on it before
1100 // moving on.
1101 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1102 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1103 DeclarationName());
1104 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1105 Enum->setIntegerType(SemaRef.Context.IntTy);
1106 else
1107 Enum->setIntegerTypeSourceInfo(NewTI);
1108 } else {
1109 assert(!D->getIntegerType()->isDependentType()((!D->getIntegerType()->isDependentType() && "Dependent type without type source info"
) ? static_cast<void> (0) : __assert_fail ("!D->getIntegerType()->isDependentType() && \"Dependent type without type source info\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1110, __PRETTY_FUNCTION__))
1110 && "Dependent type without type source info")((!D->getIntegerType()->isDependentType() && "Dependent type without type source info"
) ? static_cast<void> (0) : __assert_fail ("!D->getIntegerType()->isDependentType() && \"Dependent type without type source info\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1110, __PRETTY_FUNCTION__))
;
1111 Enum->setIntegerType(D->getIntegerType());
1112 }
1113 }
1114
1115 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1116
1117 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1118 Enum->setAccess(D->getAccess());
1119 // Forward the mangling number from the template to the instantiated decl.
1120 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
1121 // See if the old tag was defined along with a declarator.
1122 // If it did, mark the new tag as being associated with that declarator.
1123 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1124 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1125 // See if the old tag was defined along with a typedef.
1126 // If it did, mark the new tag as being associated with that typedef.
1127 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1128 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
1129 if (SubstQualifier(D, Enum)) return nullptr;
1130 Owner->addDecl(Enum);
1131
1132 EnumDecl *Def = D->getDefinition();
1133 if (Def && Def != D) {
1134 // If this is an out-of-line definition of an enum member template, check
1135 // that the underlying types match in the instantiation of both
1136 // declarations.
1137 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1138 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1139 QualType DefnUnderlying =
1140 SemaRef.SubstType(TI->getType(), TemplateArgs,
1141 UnderlyingLoc, DeclarationName());
1142 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1143 DefnUnderlying, /*IsFixed=*/true, Enum);
1144 }
1145 }
1146
1147 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1148 // specialization causes the implicit instantiation of the declarations, but
1149 // not the definitions of scoped member enumerations.
1150 //
1151 // DR1484 clarifies that enumeration definitions inside of a template
1152 // declaration aren't considered entities that can be separately instantiated
1153 // from the rest of the entity they are declared inside of.
1154 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1155 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
1156 InstantiateEnumDefinition(Enum, Def);
1157 }
1158
1159 return Enum;
1160}
1161
1162void TemplateDeclInstantiator::InstantiateEnumDefinition(
1163 EnumDecl *Enum, EnumDecl *Pattern) {
1164 Enum->startDefinition();
1165
1166 // Update the location to refer to the definition.
1167 Enum->setLocation(Pattern->getLocation());
1168
1169 SmallVector<Decl*, 4> Enumerators;
1170
1171 EnumConstantDecl *LastEnumConst = nullptr;
1172 for (auto *EC : Pattern->enumerators()) {
1173 // The specified value for the enumerator.
1174 ExprResult Value((Expr *)nullptr);
1175 if (Expr *UninstValue = EC->getInitExpr()) {
1176 // The enumerator's value expression is a constant expression.
1177 EnterExpressionEvaluationContext Unevaluated(
1178 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1179
1180 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1181 }
1182
1183 // Drop the initial value and continue.
1184 bool isInvalid = false;
1185 if (Value.isInvalid()) {
1186 Value = nullptr;
1187 isInvalid = true;
1188 }
1189
1190 EnumConstantDecl *EnumConst
1191 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1192 EC->getLocation(), EC->getIdentifier(),
1193 Value.get());
1194
1195 if (isInvalid) {
1196 if (EnumConst)
1197 EnumConst->setInvalidDecl();
1198 Enum->setInvalidDecl();
1199 }
1200
1201 if (EnumConst) {
1202 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1203
1204 EnumConst->setAccess(Enum->getAccess());
1205 Enum->addDecl(EnumConst);
1206 Enumerators.push_back(EnumConst);
1207 LastEnumConst = EnumConst;
1208
1209 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1210 !Enum->isScoped()) {
1211 // If the enumeration is within a function or method, record the enum
1212 // constant as a local.
1213 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1214 }
1215 }
1216 }
1217
1218 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1219 Enumerators, nullptr, ParsedAttributesView());
1220}
1221
1222Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1223 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.")::llvm::llvm_unreachable_internal("EnumConstantDecls can only occur within EnumDecls."
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1223)
;
1224}
1225
1226Decl *
1227TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1228 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.")::llvm::llvm_unreachable_internal("BuiltinTemplateDecls cannot be instantiated."
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1228)
;
1229}
1230
1231Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1232 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1233
1234 // Create a local instantiation scope for this class template, which
1235 // will contain the instantiations of the template parameters.
1236 LocalInstantiationScope Scope(SemaRef);
1237 TemplateParameterList *TempParams = D->getTemplateParameters();
1238 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1239 if (!InstParams)
1240 return nullptr;
1241
1242 CXXRecordDecl *Pattern = D->getTemplatedDecl();
1243
1244 // Instantiate the qualifier. We have to do this first in case
1245 // we're a friend declaration, because if we are then we need to put
1246 // the new declaration in the appropriate context.
1247 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1248 if (QualifierLoc) {
1249 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1250 TemplateArgs);
1251 if (!QualifierLoc)
1252 return nullptr;
1253 }
1254
1255 CXXRecordDecl *PrevDecl = nullptr;
1256 ClassTemplateDecl *PrevClassTemplate = nullptr;
1257
1258 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1259 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1260 if (!Found.empty()) {
1261 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1262 if (PrevClassTemplate)
1263 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1264 }
1265 }
1266
1267 // If this isn't a friend, then it's a member template, in which
1268 // case we just want to build the instantiation in the
1269 // specialization. If it is a friend, we want to build it in
1270 // the appropriate context.
1271 DeclContext *DC = Owner;
1272 if (isFriend) {
1273 if (QualifierLoc) {
1274 CXXScopeSpec SS;
1275 SS.Adopt(QualifierLoc);
1276 DC = SemaRef.computeDeclContext(SS);
1277 if (!DC) return nullptr;
1278 } else {
1279 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1280 Pattern->getDeclContext(),
1281 TemplateArgs);
1282 }
1283
1284 // Look for a previous declaration of the template in the owning
1285 // context.
1286 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1287 Sema::LookupOrdinaryName,
1288 SemaRef.forRedeclarationInCurContext());
1289 SemaRef.LookupQualifiedName(R, DC);
1290
1291 if (R.isSingleResult()) {
1292 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1293 if (PrevClassTemplate)
1294 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1295 }
1296
1297 if (!PrevClassTemplate && QualifierLoc) {
1298 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1299 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1300 << QualifierLoc.getSourceRange();
1301 return nullptr;
1302 }
1303
1304 bool AdoptedPreviousTemplateParams = false;
1305 if (PrevClassTemplate) {
1306 bool Complain = true;
1307
1308 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
1309 // template for struct std::tr1::__detail::_Map_base, where the
1310 // template parameters of the friend declaration don't match the
1311 // template parameters of the original declaration. In this one
1312 // case, we don't complain about the ill-formed friend
1313 // declaration.
1314 if (isFriend && Pattern->getIdentifier() &&
1315 Pattern->getIdentifier()->isStr("_Map_base") &&
1316 DC->isNamespace() &&
1317 cast<NamespaceDecl>(DC)->getIdentifier() &&
1318 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
1319 DeclContext *DCParent = DC->getParent();
1320 if (DCParent->isNamespace() &&
1321 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
1322 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
1323 if (cast<Decl>(DCParent)->isInStdNamespace())
1324 Complain = false;
1325 }
1326 }
1327
1328 TemplateParameterList *PrevParams
1329 = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters();
1330
1331 // Make sure the parameter lists match.
1332 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
1333 Complain,
1334 Sema::TPL_TemplateMatch)) {
1335 if (Complain)
1336 return nullptr;
1337
1338 AdoptedPreviousTemplateParams = true;
1339 InstParams = PrevParams;
1340 }
1341
1342 // Do some additional validation, then merge default arguments
1343 // from the existing declarations.
1344 if (!AdoptedPreviousTemplateParams &&
1345 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1346 Sema::TPC_ClassTemplate))
1347 return nullptr;
1348 }
1349 }
1350
1351 CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1352 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1353 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1354 /*DelayTypeCreation=*/true);
1355
1356 if (QualifierLoc)
1357 RecordInst->setQualifierInfo(QualifierLoc);
1358
1359 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1360 StartingScope);
1361
1362 ClassTemplateDecl *Inst
1363 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1364 D->getIdentifier(), InstParams, RecordInst);
1365 assert(!(isFriend && Owner->isDependentContext()))((!(isFriend && Owner->isDependentContext())) ? static_cast
<void> (0) : __assert_fail ("!(isFriend && Owner->isDependentContext())"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1365, __PRETTY_FUNCTION__))
;
1366 Inst->setPreviousDecl(PrevClassTemplate);
1367
1368 RecordInst->setDescribedClassTemplate(Inst);
1369
1370 if (isFriend) {
1371 if (PrevClassTemplate)
1372 Inst->setAccess(PrevClassTemplate->getAccess());
1373 else
1374 Inst->setAccess(D->getAccess());
1375
1376 Inst->setObjectOfFriendDecl();
1377 // TODO: do we want to track the instantiation progeny of this
1378 // friend target decl?
1379 } else {
1380 Inst->setAccess(D->getAccess());
1381 if (!PrevClassTemplate)
1382 Inst->setInstantiatedFromMemberTemplate(D);
1383 }
1384
1385 // Trigger creation of the type for the instantiation.
1386 SemaRef.Context.getInjectedClassNameType(RecordInst,
1387 Inst->getInjectedClassNameSpecialization());
1388
1389 // Finish handling of friends.
1390 if (isFriend) {
1391 DC->makeDeclVisibleInContext(Inst);
1392 Inst->setLexicalDeclContext(Owner);
1393 RecordInst->setLexicalDeclContext(Owner);
1394 return Inst;
1395 }
1396
1397 if (D->isOutOfLine()) {
1398 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1399 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1400 }
1401
1402 Owner->addDecl(Inst);
1403
1404 if (!PrevClassTemplate) {
1405 // Queue up any out-of-line partial specializations of this member
1406 // class template; the client will force their instantiation once
1407 // the enclosing class has been instantiated.
1408 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1409 D->getPartialSpecializations(PartialSpecs);
1410 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1411 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1412 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1413 }
1414
1415 return Inst;
1416}
1417
1418Decl *
1419TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1420 ClassTemplatePartialSpecializationDecl *D) {
1421 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1422
1423 // Lookup the already-instantiated declaration in the instantiation
1424 // of the class template and return that.
1425 DeclContext::lookup_result Found
1426 = Owner->lookup(ClassTemplate->getDeclName());
1427 if (Found.empty())
1428 return nullptr;
1429
1430 ClassTemplateDecl *InstClassTemplate
1431 = dyn_cast<ClassTemplateDecl>(Found.front());
1432 if (!InstClassTemplate)
1433 return nullptr;
1434
1435 if (ClassTemplatePartialSpecializationDecl *Result
1436 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1437 return Result;
1438
1439 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1440}
1441
1442Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1443 assert(D->getTemplatedDecl()->isStaticDataMember() &&((D->getTemplatedDecl()->isStaticDataMember() &&
"Only static data member templates are allowed.") ? static_cast
<void> (0) : __assert_fail ("D->getTemplatedDecl()->isStaticDataMember() && \"Only static data member templates are allowed.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1444, __PRETTY_FUNCTION__))
1444 "Only static data member templates are allowed.")((D->getTemplatedDecl()->isStaticDataMember() &&
"Only static data member templates are allowed.") ? static_cast
<void> (0) : __assert_fail ("D->getTemplatedDecl()->isStaticDataMember() && \"Only static data member templates are allowed.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1444, __PRETTY_FUNCTION__))
;
1445
1446 // Create a local instantiation scope for this variable template, which
1447 // will contain the instantiations of the template parameters.
1448 LocalInstantiationScope Scope(SemaRef);
1449 TemplateParameterList *TempParams = D->getTemplateParameters();
1450 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1451 if (!InstParams)
1452 return nullptr;
1453
1454 VarDecl *Pattern = D->getTemplatedDecl();
1455 VarTemplateDecl *PrevVarTemplate = nullptr;
1456
1457 if (getPreviousDeclForInstantiation(Pattern)) {
1458 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1459 if (!Found.empty())
1460 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1461 }
1462
1463 VarDecl *VarInst =
1464 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1465 /*InstantiatingVarTemplate=*/true));
1466 if (!VarInst) return nullptr;
1467
1468 DeclContext *DC = Owner;
1469
1470 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1471 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1472 VarInst);
1473 VarInst->setDescribedVarTemplate(Inst);
1474 Inst->setPreviousDecl(PrevVarTemplate);
1475
1476 Inst->setAccess(D->getAccess());
1477 if (!PrevVarTemplate)
1478 Inst->setInstantiatedFromMemberTemplate(D);
1479
1480 if (D->isOutOfLine()) {
1481 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1482 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1483 }
1484
1485 Owner->addDecl(Inst);
1486
1487 if (!PrevVarTemplate) {
1488 // Queue up any out-of-line partial specializations of this member
1489 // variable template; the client will force their instantiation once
1490 // the enclosing class has been instantiated.
1491 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1492 D->getPartialSpecializations(PartialSpecs);
1493 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1494 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1495 OutOfLineVarPartialSpecs.push_back(
1496 std::make_pair(Inst, PartialSpecs[I]));
1497 }
1498
1499 return Inst;
1500}
1501
1502Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1503 VarTemplatePartialSpecializationDecl *D) {
1504 assert(D->isStaticDataMember() &&((D->isStaticDataMember() && "Only static data member templates are allowed."
) ? static_cast<void> (0) : __assert_fail ("D->isStaticDataMember() && \"Only static data member templates are allowed.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1505, __PRETTY_FUNCTION__))
1505 "Only static data member templates are allowed.")((D->isStaticDataMember() && "Only static data member templates are allowed."
) ? static_cast<void> (0) : __assert_fail ("D->isStaticDataMember() && \"Only static data member templates are allowed.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1505, __PRETTY_FUNCTION__))
;
1506
1507 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1508
1509 // Lookup the already-instantiated declaration and return that.
1510 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1511 assert(!Found.empty() && "Instantiation found nothing?")((!Found.empty() && "Instantiation found nothing?") ?
static_cast<void> (0) : __assert_fail ("!Found.empty() && \"Instantiation found nothing?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1511, __PRETTY_FUNCTION__))
;
1512
1513 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1514 assert(InstVarTemplate && "Instantiation did not find a variable template?")((InstVarTemplate && "Instantiation did not find a variable template?"
) ? static_cast<void> (0) : __assert_fail ("InstVarTemplate && \"Instantiation did not find a variable template?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1514, __PRETTY_FUNCTION__))
;
1515
1516 if (VarTemplatePartialSpecializationDecl *Result =
1517 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1518 return Result;
1519
1520 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1521}
1522
1523Decl *
1524TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1525 // Create a local instantiation scope for this function template, which
1526 // will contain the instantiations of the template parameters and then get
1527 // merged with the local instantiation scope for the function template
1528 // itself.
1529 LocalInstantiationScope Scope(SemaRef);
1530
1531 TemplateParameterList *TempParams = D->getTemplateParameters();
1532 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1533 if (!InstParams)
1534 return nullptr;
1535
1536 FunctionDecl *Instantiated = nullptr;
1537 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1538 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1539 InstParams));
1540 else
1541 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1542 D->getTemplatedDecl(),
1543 InstParams));
1544
1545 if (!Instantiated)
1546 return nullptr;
1547
1548 // Link the instantiated function template declaration to the function
1549 // template from which it was instantiated.
1550 FunctionTemplateDecl *InstTemplate
1551 = Instantiated->getDescribedFunctionTemplate();
1552 InstTemplate->setAccess(D->getAccess());
1553 assert(InstTemplate &&((InstTemplate && "VisitFunctionDecl/CXXMethodDecl didn't create a template!"
) ? static_cast<void> (0) : __assert_fail ("InstTemplate && \"VisitFunctionDecl/CXXMethodDecl didn't create a template!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1554, __PRETTY_FUNCTION__))
1554 "VisitFunctionDecl/CXXMethodDecl didn't create a template!")((InstTemplate && "VisitFunctionDecl/CXXMethodDecl didn't create a template!"
) ? static_cast<void> (0) : __assert_fail ("InstTemplate && \"VisitFunctionDecl/CXXMethodDecl didn't create a template!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1554, __PRETTY_FUNCTION__))
;
1555
1556 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1557
1558 // Link the instantiation back to the pattern *unless* this is a
1559 // non-definition friend declaration.
1560 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1561 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1562 InstTemplate->setInstantiatedFromMemberTemplate(D);
1563
1564 // Make declarations visible in the appropriate context.
1565 if (!isFriend) {
1566 Owner->addDecl(InstTemplate);
1567 } else if (InstTemplate->getDeclContext()->isRecord() &&
1568 !getPreviousDeclForInstantiation(D)) {
1569 SemaRef.CheckFriendAccess(InstTemplate);
1570 }
1571
1572 return InstTemplate;
1573}
1574
1575Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1576 CXXRecordDecl *PrevDecl = nullptr;
1577 if (D->isInjectedClassName())
1578 PrevDecl = cast<CXXRecordDecl>(Owner);
1579 else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1580 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1581 PatternPrev,
1582 TemplateArgs);
1583 if (!Prev) return nullptr;
1584 PrevDecl = cast<CXXRecordDecl>(Prev);
1585 }
1586
1587 CXXRecordDecl *Record = CXXRecordDecl::Create(
1588 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
1589 D->getLocation(), D->getIdentifier(), PrevDecl);
1590
1591 // Substitute the nested name specifier, if any.
1592 if (SubstQualifier(D, Record))
1593 return nullptr;
1594
1595 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
1596 StartingScope);
1597
1598 Record->setImplicit(D->isImplicit());
1599 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1600 // the tag decls introduced by friend class declarations don't have an access
1601 // specifier. Remove once this area of the code gets sorted out.
1602 if (D->getAccess() != AS_none)
1603 Record->setAccess(D->getAccess());
1604 if (!D->isInjectedClassName())
1605 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1606
1607 // If the original function was part of a friend declaration,
1608 // inherit its namespace state.
1609 if (D->getFriendObjectKind())
1610 Record->setObjectOfFriendDecl();
1611
1612 // Make sure that anonymous structs and unions are recorded.
1613 if (D->isAnonymousStructOrUnion())
1614 Record->setAnonymousStructOrUnion(true);
1615
1616 if (D->isLocalClass())
1617 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1618
1619 // Forward the mangling number from the template to the instantiated decl.
1620 SemaRef.Context.setManglingNumber(Record,
1621 SemaRef.Context.getManglingNumber(D));
1622
1623 // See if the old tag was defined along with a declarator.
1624 // If it did, mark the new tag as being associated with that declarator.
1625 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1626 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1627
1628 // See if the old tag was defined along with a typedef.
1629 // If it did, mark the new tag as being associated with that typedef.
1630 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1631 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1632
1633 Owner->addDecl(Record);
1634
1635 // DR1484 clarifies that the members of a local class are instantiated as part
1636 // of the instantiation of their enclosing entity.
1637 if (D->isCompleteDefinition() && D->isLocalClass()) {
1638 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
1639
1640 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1641 TSK_ImplicitInstantiation,
1642 /*Complain=*/true);
1643
1644 // For nested local classes, we will instantiate the members when we
1645 // reach the end of the outermost (non-nested) local class.
1646 if (!D->isCXXClassMember())
1647 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1648 TSK_ImplicitInstantiation);
1649
1650 // This class may have local implicit instantiations that need to be
1651 // performed within this scope.
1652 LocalInstantiations.perform();
1653 }
1654
1655 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1656
1657 return Record;
1658}
1659
1660/// Adjust the given function type for an instantiation of the
1661/// given declaration, to cope with modifications to the function's type that
1662/// aren't reflected in the type-source information.
1663///
1664/// \param D The declaration we're instantiating.
1665/// \param TInfo The already-instantiated type.
1666static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1667 FunctionDecl *D,
1668 TypeSourceInfo *TInfo) {
1669 const FunctionProtoType *OrigFunc
1670 = D->getType()->castAs<FunctionProtoType>();
1671 const FunctionProtoType *NewFunc
1672 = TInfo->getType()->castAs<FunctionProtoType>();
1673 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1674 return TInfo->getType();
1675
1676 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1677 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1678 return Context.getFunctionType(NewFunc->getReturnType(),
1679 NewFunc->getParamTypes(), NewEPI);
1680}
1681
1682/// Normal class members are of more specific types and therefore
1683/// don't make it here. This function serves three purposes:
1684/// 1) instantiating function templates
1685/// 2) substituting friend declarations
1686/// 3) substituting deduction guide declarations for nested class templates
1687Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1688 TemplateParameterList *TemplateParams) {
1689 // Check whether there is already a function template specialization for
1690 // this declaration.
1691 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1692 if (FunctionTemplate && !TemplateParams) {
1693 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1694
1695 void *InsertPos = nullptr;
1696 FunctionDecl *SpecFunc
1697 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1698
1699 // If we already have a function template specialization, return it.
1700 if (SpecFunc)
1701 return SpecFunc;
1702 }
1703
1704 bool isFriend;
1705 if (FunctionTemplate)
1706 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1707 else
1708 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1709
1710 bool MergeWithParentScope = (TemplateParams != nullptr) ||
1711 Owner->isFunctionOrMethod() ||
1712 !(isa<Decl>(Owner) &&
1713 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1714 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1715
1716 ExplicitSpecifier InstantiatedExplicitSpecifier;
1717 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
1718 InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
1719 SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
1720 if (InstantiatedExplicitSpecifier.isInvalid())
1721 return nullptr;
1722 }
1723
1724 SmallVector<ParmVarDecl *, 4> Params;
1725 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1726 if (!TInfo)
1727 return nullptr;
1728 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1729
1730 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1731 if (QualifierLoc) {
1732 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1733 TemplateArgs);
1734 if (!QualifierLoc)
1735 return nullptr;
1736 }
1737
1738 // If we're instantiating a local function declaration, put the result
1739 // in the enclosing namespace; otherwise we need to find the instantiated
1740 // context.
1741 DeclContext *DC;
1742 if (D->isLocalExternDecl()) {
1743 DC = Owner;
1744 SemaRef.adjustContextForLocalExternDecl(DC);
1745 } else if (isFriend && QualifierLoc) {
1746 CXXScopeSpec SS;
1747 SS.Adopt(QualifierLoc);
1748 DC = SemaRef.computeDeclContext(SS);
1749 if (!DC) return nullptr;
1750 } else {
1751 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1752 TemplateArgs);
1753 }
1754
1755 DeclarationNameInfo NameInfo
1756 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1757
1758 FunctionDecl *Function;
1759 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
1760 Function = CXXDeductionGuideDecl::Create(
1761 SemaRef.Context, DC, D->getInnerLocStart(),
1762 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
1763 D->getSourceRange().getEnd());
1764 if (DGuide->isCopyDeductionCandidate())
1765 cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
1766 Function->setAccess(D->getAccess());
1767 } else {
1768 Function = FunctionDecl::Create(
1769 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
1770 D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(),
1771 D->hasWrittenPrototype(), D->isConstexpr());
1772 Function->setRangeEnd(D->getSourceRange().getEnd());
1773 }
1774
1775 if (D->isInlined())
1776 Function->setImplicitlyInline();
1777
1778 if (QualifierLoc)
1779 Function->setQualifierInfo(QualifierLoc);
1780
1781 if (D->isLocalExternDecl())
1782 Function->setLocalExternDecl();
1783
1784 DeclContext *LexicalDC = Owner;
1785 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
1786 assert(D->getDeclContext()->isFileContext())((D->getDeclContext()->isFileContext()) ? static_cast<
void> (0) : __assert_fail ("D->getDeclContext()->isFileContext()"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1786, __PRETTY_FUNCTION__))
;
1787 LexicalDC = D->getDeclContext();
1788 }
1789
1790 Function->setLexicalDeclContext(LexicalDC);
1791
1792 // Attach the parameters
1793 for (unsigned P = 0; P < Params.size(); ++P)
1794 if (Params[P])
1795 Params[P]->setOwningFunction(Function);
1796 Function->setParams(Params);
1797
1798 if (TemplateParams) {
1799 // Our resulting instantiation is actually a function template, since we
1800 // are substituting only the outer template parameters. For example, given
1801 //
1802 // template<typename T>
1803 // struct X {
1804 // template<typename U> friend void f(T, U);
1805 // };
1806 //
1807 // X<int> x;
1808 //
1809 // We are instantiating the friend function template "f" within X<int>,
1810 // which means substituting int for T, but leaving "f" as a friend function
1811 // template.
1812 // Build the function template itself.
1813 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1814 Function->getLocation(),
1815 Function->getDeclName(),
1816 TemplateParams, Function);
1817 Function->setDescribedFunctionTemplate(FunctionTemplate);
1818
1819 FunctionTemplate->setLexicalDeclContext(LexicalDC);
1820
1821 if (isFriend && D->isThisDeclarationADefinition()) {
1822 FunctionTemplate->setInstantiatedFromMemberTemplate(
1823 D->getDescribedFunctionTemplate());
1824 }
1825 } else if (FunctionTemplate) {
1826 // Record this function template specialization.
1827 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1828 Function->setFunctionTemplateSpecialization(FunctionTemplate,
1829 TemplateArgumentList::CreateCopy(SemaRef.Context,
1830 Innermost),
1831 /*InsertPos=*/nullptr);
1832 } else if (isFriend && D->isThisDeclarationADefinition()) {
1833 // Do not connect the friend to the template unless it's actually a
1834 // definition. We don't want non-template functions to be marked as being
1835 // template instantiations.
1836 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1837 }
1838
1839 if (isFriend)
1840 Function->setObjectOfFriendDecl();
1841
1842 if (InitFunctionInstantiation(Function, D))
1843 Function->setInvalidDecl();
1844
1845 bool IsExplicitSpecialization = false;
1846
1847 LookupResult Previous(
1848 SemaRef, Function->getDeclName(), SourceLocation(),
1849 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1850 : Sema::LookupOrdinaryName,
1851 D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
1852 : SemaRef.forRedeclarationInCurContext());
1853
1854 if (DependentFunctionTemplateSpecializationInfo *Info
1855 = D->getDependentSpecializationInfo()) {
1856 assert(isFriend && "non-friend has dependent specialization info?")((isFriend && "non-friend has dependent specialization info?"
) ? static_cast<void> (0) : __assert_fail ("isFriend && \"non-friend has dependent specialization info?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1856, __PRETTY_FUNCTION__))
;
1857
1858 // Instantiate the explicit template arguments.
1859 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1860 Info->getRAngleLoc());
1861 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1862 ExplicitArgs, TemplateArgs))
1863 return nullptr;
1864
1865 // Map the candidate templates to their instantiations.
1866 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1867 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1868 Info->getTemplate(I),
1869 TemplateArgs);
1870 if (!Temp) return nullptr;
1871
1872 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1873 }
1874
1875 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1876 &ExplicitArgs,
1877 Previous))
1878 Function->setInvalidDecl();
1879
1880 IsExplicitSpecialization = true;
1881 } else if (const ASTTemplateArgumentListInfo *Info =
1882 D->getTemplateSpecializationArgsAsWritten()) {
1883 // The name of this function was written as a template-id.
1884 SemaRef.LookupQualifiedName(Previous, DC);
1885
1886 // Instantiate the explicit template arguments.
1887 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1888 Info->getRAngleLoc());
1889 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1890 ExplicitArgs, TemplateArgs))
1891 return nullptr;
1892
1893 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1894 &ExplicitArgs,
1895 Previous))
1896 Function->setInvalidDecl();
1897
1898 IsExplicitSpecialization = true;
1899 } else if (TemplateParams || !FunctionTemplate) {
1900 // Look only into the namespace where the friend would be declared to
1901 // find a previous declaration. This is the innermost enclosing namespace,
1902 // as described in ActOnFriendFunctionDecl.
1903 SemaRef.LookupQualifiedName(Previous, DC);
1904
1905 // In C++, the previous declaration we find might be a tag type
1906 // (class or enum). In this case, the new declaration will hide the
1907 // tag type. Note that this does does not apply if we're declaring a
1908 // typedef (C++ [dcl.typedef]p4).
1909 if (Previous.isSingleTagDecl())
1910 Previous.clear();
1911 }
1912
1913 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
1914 IsExplicitSpecialization);
1915
1916 NamedDecl *PrincipalDecl = (TemplateParams
1917 ? cast<NamedDecl>(FunctionTemplate)
1918 : Function);
1919
1920 // If the original function was part of a friend declaration,
1921 // inherit its namespace state and add it to the owner.
1922 if (isFriend) {
1923 Function->setObjectOfFriendDecl();
1924 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
1925 FT->setObjectOfFriendDecl();
1926 DC->makeDeclVisibleInContext(PrincipalDecl);
1927
1928 bool QueuedInstantiation = false;
1929
1930 // C++11 [temp.friend]p4 (DR329):
1931 // When a function is defined in a friend function declaration in a class
1932 // template, the function is instantiated when the function is odr-used.
1933 // The same restrictions on multiple declarations and definitions that
1934 // apply to non-template function declarations and definitions also apply
1935 // to these implicit definitions.
1936 if (D->isThisDeclarationADefinition()) {
1937 SemaRef.CheckForFunctionRedefinition(Function);
1938 if (!Function->isInvalidDecl()) {
1939 for (auto R : Function->redecls()) {
1940 if (R == Function)
1941 continue;
1942
1943 // If some prior declaration of this function has been used, we need
1944 // to instantiate its definition.
1945 if (!QueuedInstantiation && R->isUsed(false)) {
1946 if (MemberSpecializationInfo *MSInfo =
1947 Function->getMemberSpecializationInfo()) {
1948 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1949 SourceLocation Loc = R->getLocation(); // FIXME
1950 MSInfo->setPointOfInstantiation(Loc);
1951 SemaRef.PendingLocalImplicitInstantiations.push_back(
1952 std::make_pair(Function, Loc));
1953 QueuedInstantiation = true;
1954 }
1955 }
1956 }
1957 }
1958 }
1959 }
1960
1961 // Check the template parameter list against the previous declaration. The
1962 // goal here is to pick up default arguments added since the friend was
1963 // declared; we know the template parameter lists match, since otherwise
1964 // we would not have picked this template as the previous declaration.
1965 if (TemplateParams && FunctionTemplate->getPreviousDecl()) {
1966 SemaRef.CheckTemplateParameterList(
1967 TemplateParams,
1968 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
1969 Function->isThisDeclarationADefinition()
1970 ? Sema::TPC_FriendFunctionTemplateDefinition
1971 : Sema::TPC_FriendFunctionTemplate);
1972 }
1973 }
1974
1975 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1976 DC->makeDeclVisibleInContext(PrincipalDecl);
1977
1978 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1979 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1980 PrincipalDecl->setNonMemberOperator();
1981
1982 assert(!D->isDefaulted() && "only methods should be defaulted")((!D->isDefaulted() && "only methods should be defaulted"
) ? static_cast<void> (0) : __assert_fail ("!D->isDefaulted() && \"only methods should be defaulted\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1982, __PRETTY_FUNCTION__))
;
1983 return Function;
1984}
1985
1986Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
1987 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
1988 Optional<const ASTTemplateArgumentListInfo *>
1989 ClassScopeSpecializationArgs) {
1990 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1991 if (FunctionTemplate && !TemplateParams) {
1992 // We are creating a function template specialization from a function
1993 // template. Check whether there is already a function template
1994 // specialization for this particular set of template arguments.
1995 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1996
1997 void *InsertPos = nullptr;
1998 FunctionDecl *SpecFunc
1999 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2000
2001 // If we already have a function template specialization, return it.
2002 if (SpecFunc)
2003 return SpecFunc;
2004 }
2005
2006 bool isFriend;
2007 if (FunctionTemplate)
2008 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2009 else
2010 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2011
2012 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2013 !(isa<Decl>(Owner) &&
2014 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2015 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2016
2017 // Instantiate enclosing template arguments for friends.
2018 SmallVector<TemplateParameterList *, 4> TempParamLists;
2019 unsigned NumTempParamLists = 0;
2020 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2021 TempParamLists.resize(NumTempParamLists);
2022 for (unsigned I = 0; I != NumTempParamLists; ++I) {
2023 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2024 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2025 if (!InstParams)
2026 return nullptr;
2027 TempParamLists[I] = InstParams;
2028 }
2029 }
2030
2031 ExplicitSpecifier InstantiatedExplicitSpecifier =
2032 instantiateExplicitSpecifier(SemaRef, TemplateArgs,
2033 ExplicitSpecifier::getFromDecl(D), D);
2034 if (InstantiatedExplicitSpecifier.isInvalid())
2035 return nullptr;
2036
2037 SmallVector<ParmVarDecl *, 4> Params;
2038 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2039 if (!TInfo)
2040 return nullptr;
2041 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2042
2043 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2044 if (QualifierLoc) {
2045 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2046 TemplateArgs);
2047 if (!QualifierLoc)
2048 return nullptr;
2049 }
2050
2051 DeclContext *DC = Owner;
2052 if (isFriend) {
2053 if (QualifierLoc) {
2054 CXXScopeSpec SS;
2055 SS.Adopt(QualifierLoc);
2056 DC = SemaRef.computeDeclContext(SS);
2057
2058 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2059 return nullptr;
2060 } else {
2061 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2062 D->getDeclContext(),
2063 TemplateArgs);
2064 }
2065 if (!DC) return nullptr;
2066 }
2067
2068 // Build the instantiated method declaration.
2069 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2070 CXXMethodDecl *Method = nullptr;
2071
2072 SourceLocation StartLoc = D->getInnerLocStart();
2073 DeclarationNameInfo NameInfo
2074 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2075 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2076 Method = CXXConstructorDecl::Create(
2077 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2078 InstantiatedExplicitSpecifier, Constructor->isInlineSpecified(), false,
2079 Constructor->isConstexpr());
2080 Method->setRangeEnd(Constructor->getEndLoc());
2081 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2082 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
2083 StartLoc, NameInfo, T, TInfo,
2084 Destructor->isInlineSpecified(),
2085 false);
2086 Method->setRangeEnd(Destructor->getEndLoc());
2087 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2088 Method = CXXConversionDecl::Create(
2089 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2090 Conversion->isInlineSpecified(), InstantiatedExplicitSpecifier,
2091 Conversion->isConstexpr(), Conversion->getEndLoc());
2092 } else {
2093 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2094 Method = CXXMethodDecl::Create(SemaRef.Context, Record, StartLoc, NameInfo,
2095 T, TInfo, SC, D->isInlineSpecified(),
2096 D->isConstexpr(), D->getEndLoc());
2097 }
2098
2099 if (D->isInlined())
2100 Method->setImplicitlyInline();
2101
2102 if (QualifierLoc)
2103 Method->setQualifierInfo(QualifierLoc);
2104
2105 if (TemplateParams) {
2106 // Our resulting instantiation is actually a function template, since we
2107 // are substituting only the outer template parameters. For example, given
2108 //
2109 // template<typename T>
2110 // struct X {
2111 // template<typename U> void f(T, U);
2112 // };
2113 //
2114 // X<int> x;
2115 //
2116 // We are instantiating the member template "f" within X<int>, which means
2117 // substituting int for T, but leaving "f" as a member function template.
2118 // Build the function template itself.
2119 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2120 Method->getLocation(),
2121 Method->getDeclName(),
2122 TemplateParams, Method);
2123 if (isFriend) {
2124 FunctionTemplate->setLexicalDeclContext(Owner);
2125 FunctionTemplate->setObjectOfFriendDecl();
2126 } else if (D->isOutOfLine())
2127 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2128 Method->setDescribedFunctionTemplate(FunctionTemplate);
2129 } else if (FunctionTemplate) {
2130 // Record this function template specialization.
2131 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2132 Method->setFunctionTemplateSpecialization(FunctionTemplate,
2133 TemplateArgumentList::CreateCopy(SemaRef.Context,
2134 Innermost),
2135 /*InsertPos=*/nullptr);
2136 } else if (!isFriend) {
2137 // Record that this is an instantiation of a member function.
2138 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2139 }
2140
2141 // If we are instantiating a member function defined
2142 // out-of-line, the instantiation will have the same lexical
2143 // context (which will be a namespace scope) as the template.
2144 if (isFriend) {
2145 if (NumTempParamLists)
2146 Method->setTemplateParameterListsInfo(
2147 SemaRef.Context,
2148 llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
2149
2150 Method->setLexicalDeclContext(Owner);
2151 Method->setObjectOfFriendDecl();
2152 } else if (D->isOutOfLine())
2153 Method->setLexicalDeclContext(D->getLexicalDeclContext());
2154
2155 // Attach the parameters
2156 for (unsigned P = 0; P < Params.size(); ++P)
2157 Params[P]->setOwningFunction(Method);
2158 Method->setParams(Params);
2159
2160 if (InitMethodInstantiation(Method, D))
2161 Method->setInvalidDecl();
2162
2163 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2164 Sema::ForExternalRedeclaration);
2165
2166 bool IsExplicitSpecialization = false;
2167
2168 // If the name of this function was written as a template-id, instantiate
2169 // the explicit template arguments.
2170 if (DependentFunctionTemplateSpecializationInfo *Info
2171 = D->getDependentSpecializationInfo()) {
2172 assert(isFriend && "non-friend has dependent specialization info?")((isFriend && "non-friend has dependent specialization info?"
) ? static_cast<void> (0) : __assert_fail ("isFriend && \"non-friend has dependent specialization info?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2172, __PRETTY_FUNCTION__))
;
2173
2174 // Instantiate the explicit template arguments.
2175 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2176 Info->getRAngleLoc());
2177 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2178 ExplicitArgs, TemplateArgs))
2179 return nullptr;
2180
2181 // Map the candidate templates to their instantiations.
2182 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2183 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2184 Info->getTemplate(I),
2185 TemplateArgs);
2186 if (!Temp) return nullptr;
2187
2188 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2189 }
2190
2191 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2192 &ExplicitArgs,
2193 Previous))
2194 Method->setInvalidDecl();
2195
2196 IsExplicitSpecialization = true;
2197 } else if (const ASTTemplateArgumentListInfo *Info =
2198 ClassScopeSpecializationArgs.getValueOr(
2199 D->getTemplateSpecializationArgsAsWritten())) {
2200 SemaRef.LookupQualifiedName(Previous, DC);
2201
2202 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2203 Info->getRAngleLoc());
2204 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2205 ExplicitArgs, TemplateArgs))
2206 return nullptr;
2207
2208 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2209 &ExplicitArgs,
2210 Previous))
2211 Method->setInvalidDecl();
2212
2213 IsExplicitSpecialization = true;
2214 } else if (ClassScopeSpecializationArgs) {
2215 // Class-scope explicit specialization written without explicit template
2216 // arguments.
2217 SemaRef.LookupQualifiedName(Previous, DC);
2218 if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
2219 Method->setInvalidDecl();
2220
2221 IsExplicitSpecialization = true;
2222 } else if (!FunctionTemplate || TemplateParams || isFriend) {
2223 SemaRef.LookupQualifiedName(Previous, Record);
2224
2225 // In C++, the previous declaration we find might be a tag type
2226 // (class or enum). In this case, the new declaration will hide the
2227 // tag type. Note that this does does not apply if we're declaring a
2228 // typedef (C++ [dcl.typedef]p4).
2229 if (Previous.isSingleTagDecl())
2230 Previous.clear();
2231 }
2232
2233 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2234 IsExplicitSpecialization);
2235
2236 if (D->isPure())
2237 SemaRef.CheckPureMethod(Method, SourceRange());
2238
2239 // Propagate access. For a non-friend declaration, the access is
2240 // whatever we're propagating from. For a friend, it should be the
2241 // previous declaration we just found.
2242 if (isFriend && Method->getPreviousDecl())
2243 Method->setAccess(Method->getPreviousDecl()->getAccess());
2244 else
2245 Method->setAccess(D->getAccess());
2246 if (FunctionTemplate)
2247 FunctionTemplate->setAccess(Method->getAccess());
2248
2249 SemaRef.CheckOverrideControl(Method);
2250
2251 // If a function is defined as defaulted or deleted, mark it as such now.
2252 if (D->isExplicitlyDefaulted())
2253 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
2254 if (D->isDeletedAsWritten())
2255 SemaRef.SetDeclDeleted(Method, Method->getLocation());
2256
2257 // If this is an explicit specialization, mark the implicitly-instantiated
2258 // template specialization as being an explicit specialization too.
2259 // FIXME: Is this necessary?
2260 if (IsExplicitSpecialization && !isFriend)
2261 SemaRef.CompleteMemberSpecialization(Method, Previous);
2262
2263 // If there's a function template, let our caller handle it.
2264 if (FunctionTemplate) {
2265 // do nothing
2266
2267 // Don't hide a (potentially) valid declaration with an invalid one.
2268 } else if (Method->isInvalidDecl() && !Previous.empty()) {
2269 // do nothing
2270
2271 // Otherwise, check access to friends and make them visible.
2272 } else if (isFriend) {
2273 // We only need to re-check access for methods which we didn't
2274 // manage to match during parsing.
2275 if (!D->getPreviousDecl())
2276 SemaRef.CheckFriendAccess(Method);
2277
2278 Record->makeDeclVisibleInContext(Method);
2279
2280 // Otherwise, add the declaration. We don't need to do this for
2281 // class-scope specializations because we'll have matched them with
2282 // the appropriate template.
2283 } else {
2284 Owner->addDecl(Method);
2285 }
2286
2287 // PR17480: Honor the used attribute to instantiate member function
2288 // definitions
2289 if (Method->hasAttr<UsedAttr>()) {
2290 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2291 SourceLocation Loc;
2292 if (const MemberSpecializationInfo *MSInfo =
2293 A->getMemberSpecializationInfo())
2294 Loc = MSInfo->getPointOfInstantiation();
2295 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2296 Loc = Spec->getPointOfInstantiation();
2297 SemaRef.MarkFunctionReferenced(Loc, Method);
2298 }
2299 }
2300
2301 return Method;
2302}
2303
2304Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2305 return VisitCXXMethodDecl(D);
2306}
2307
2308Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2309 return VisitCXXMethodDecl(D);
2310}
2311
2312Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2313 return VisitCXXMethodDecl(D);
2314}
2315
2316Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2317 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2318 /*ExpectParameterPack=*/ false);
2319}
2320
2321Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2322 TemplateTypeParmDecl *D) {
2323 // TODO: don't always clone when decls are refcounted.
2324 assert(D->getTypeForDecl()->isTemplateTypeParmType())((D->getTypeForDecl()->isTemplateTypeParmType()) ? static_cast
<void> (0) : __assert_fail ("D->getTypeForDecl()->isTemplateTypeParmType()"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2324, __PRETTY_FUNCTION__))
;
2325
2326 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
2327 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
2328 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2329 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack());
2330 Inst->setAccess(AS_public);
2331
2332 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2333 TypeSourceInfo *InstantiatedDefaultArg =
2334 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2335 D->getDefaultArgumentLoc(), D->getDeclName());
2336 if (InstantiatedDefaultArg)
2337 Inst->setDefaultArgument(InstantiatedDefaultArg);
2338 }
2339
2340 // Introduce this template parameter's instantiation into the instantiation
2341 // scope.
2342 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2343
2344 return Inst;
2345}
2346
2347Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2348 NonTypeTemplateParmDecl *D) {
2349 // Substitute into the type of the non-type template parameter.
2350 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2351 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2352 SmallVector<QualType, 4> ExpandedParameterPackTypes;
2353 bool IsExpandedParameterPack = false;
2354 TypeSourceInfo *DI;
2355 QualType T;
2356 bool Invalid = false;
2357
2358 if (D->isExpandedParameterPack()) {
2359 // The non-type template parameter pack is an already-expanded pack
2360 // expansion of types. Substitute into each of the expanded types.
2361 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2362 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2363 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2364 TypeSourceInfo *NewDI =
2365 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2366 D->getLocation(), D->getDeclName());
2367 if (!NewDI)
2368 return nullptr;
2369
2370 QualType NewT =
2371 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2372 if (NewT.isNull())
2373 return nullptr;
2374
2375 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2376 ExpandedParameterPackTypes.push_back(NewT);
2377 }
2378
2379 IsExpandedParameterPack = true;
2380 DI = D->getTypeSourceInfo();
2381 T = DI->getType();
2382 } else if (D->isPackExpansion()) {
2383 // The non-type template parameter pack's type is a pack expansion of types.
2384 // Determine whether we need to expand this parameter pack into separate
2385 // types.
2386 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
2387 TypeLoc Pattern = Expansion.getPatternLoc();
2388 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2389 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2390
2391 // Determine whether the set of unexpanded parameter packs can and should
2392 // be expanded.
2393 bool Expand = true;
2394 bool RetainExpansion = false;
2395 Optional<unsigned> OrigNumExpansions
2396 = Expansion.getTypePtr()->getNumExpansions();
2397 Optional<unsigned> NumExpansions = OrigNumExpansions;
2398 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2399 Pattern.getSourceRange(),
2400 Unexpanded,
2401 TemplateArgs,
2402 Expand, RetainExpansion,
2403 NumExpansions))
2404 return nullptr;
2405
2406 if (Expand) {
2407 for (unsigned I = 0; I != *NumExpansions; ++I) {
2408 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2409 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2410 D->getLocation(),
2411 D->getDeclName());
2412 if (!NewDI)
2413 return nullptr;
2414
2415 QualType NewT =
2416 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2417 if (NewT.isNull())
2418 return nullptr;
2419
2420 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2421 ExpandedParameterPackTypes.push_back(NewT);
2422 }
2423
2424 // Note that we have an expanded parameter pack. The "type" of this
2425 // expanded parameter pack is the original expansion type, but callers
2426 // will end up using the expanded parameter pack types for type-checking.
2427 IsExpandedParameterPack = true;
2428 DI = D->getTypeSourceInfo();
2429 T = DI->getType();
2430 } else {
2431 // We cannot fully expand the pack expansion now, so substitute into the
2432 // pattern and create a new pack expansion type.
2433 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2434 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2435 D->getLocation(),
2436 D->getDeclName());
2437 if (!NewPattern)
2438 return nullptr;
2439
2440 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
2441 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2442 NumExpansions);
2443 if (!DI)
2444 return nullptr;
2445
2446 T = DI->getType();
2447 }
2448 } else {
2449 // Simple case: substitution into a parameter that is not a parameter pack.
2450 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2451 D->getLocation(), D->getDeclName());
2452 if (!DI)
2453 return nullptr;
2454
2455 // Check that this type is acceptable for a non-type template parameter.
2456 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
2457 if (T.isNull()) {
2458 T = SemaRef.Context.IntTy;
2459 Invalid = true;
2460 }
2461 }
2462
2463 NonTypeTemplateParmDecl *Param;
2464 if (IsExpandedParameterPack)
2465 Param = NonTypeTemplateParmDecl::Create(
2466 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2467 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2468 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
2469 ExpandedParameterPackTypesAsWritten);
2470 else
2471 Param = NonTypeTemplateParmDecl::Create(
2472 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2473 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2474 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
2475
2476 Param->setAccess(AS_public);
2477 if (Invalid)
2478 Param->setInvalidDecl();
2479
2480 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2481 EnterExpressionEvaluationContext ConstantEvaluated(
2482 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2483 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2484 if (!Value.isInvalid())
2485 Param->setDefaultArgument(Value.get());
2486 }
2487
2488 // Introduce this template parameter's instantiation into the instantiation
2489 // scope.
2490 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2491 return Param;
2492}
2493
2494static void collectUnexpandedParameterPacks(
2495 Sema &S,
2496 TemplateParameterList *Params,
2497 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
2498 for (const auto &P : *Params) {
2499 if (P->isTemplateParameterPack())
2500 continue;
2501 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
2502 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2503 Unexpanded);
2504 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
2505 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2506 Unexpanded);
2507 }
2508}
2509
2510Decl *
2511TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2512 TemplateTemplateParmDecl *D) {
2513 // Instantiate the template parameter list of the template template parameter.
2514 TemplateParameterList *TempParams = D->getTemplateParameters();
2515 TemplateParameterList *InstParams;
2516 SmallVector<TemplateParameterList*, 8> ExpandedParams;
2517
2518 bool IsExpandedParameterPack = false;
2519
2520 if (D->isExpandedParameterPack()) {
2521 // The template template parameter pack is an already-expanded pack
2522 // expansion of template parameters. Substitute into each of the expanded
2523 // parameters.
2524 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2525 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2526 I != N; ++I) {
2527 LocalInstantiationScope Scope(SemaRef);
2528 TemplateParameterList *Expansion =
2529 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2530 if (!Expansion)
2531 return nullptr;
2532 ExpandedParams.push_back(Expansion);
2533 }
2534
2535 IsExpandedParameterPack = true;
2536 InstParams = TempParams;
2537 } else if (D->isPackExpansion()) {
2538 // The template template parameter pack expands to a pack of template
2539 // template parameters. Determine whether we need to expand this parameter
2540 // pack into separate parameters.
2541 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2542 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2543 Unexpanded);
2544
2545 // Determine whether the set of unexpanded parameter packs can and should
2546 // be expanded.
2547 bool Expand = true;
2548 bool RetainExpansion = false;
2549 Optional<unsigned> NumExpansions;
2550 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2551 TempParams->getSourceRange(),
2552 Unexpanded,
2553 TemplateArgs,
2554 Expand, RetainExpansion,
2555 NumExpansions))
2556 return nullptr;
2557
2558 if (Expand) {
2559 for (unsigned I = 0; I != *NumExpansions; ++I) {
2560 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2561 LocalInstantiationScope Scope(SemaRef);
2562 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2563 if (!Expansion)
2564 return nullptr;
2565 ExpandedParams.push_back(Expansion);
2566 }
2567
2568 // Note that we have an expanded parameter pack. The "type" of this
2569 // expanded parameter pack is the original expansion type, but callers
2570 // will end up using the expanded parameter pack types for type-checking.
2571 IsExpandedParameterPack = true;
2572 InstParams = TempParams;
2573 } else {
2574 // We cannot fully expand the pack expansion now, so just substitute
2575 // into the pattern.
2576 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2577
2578 LocalInstantiationScope Scope(SemaRef);
2579 InstParams = SubstTemplateParams(TempParams);
2580 if (!InstParams)
2581 return nullptr;
2582 }
2583 } else {
2584 // Perform the actual substitution of template parameters within a new,
2585 // local instantiation scope.
2586 LocalInstantiationScope Scope(SemaRef);
2587 InstParams = SubstTemplateParams(TempParams);
2588 if (!InstParams)
2589 return nullptr;
2590 }
2591
2592 // Build the template template parameter.
2593 TemplateTemplateParmDecl *Param;
2594 if (IsExpandedParameterPack)
2595 Param = TemplateTemplateParmDecl::Create(
2596 SemaRef.Context, Owner, D->getLocation(),
2597 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2598 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
2599 else
2600 Param = TemplateTemplateParmDecl::Create(
2601 SemaRef.Context, Owner, D->getLocation(),
2602 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2603 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
2604 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2605 NestedNameSpecifierLoc QualifierLoc =
2606 D->getDefaultArgument().getTemplateQualifierLoc();
2607 QualifierLoc =
2608 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2609 TemplateName TName = SemaRef.SubstTemplateName(
2610 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2611 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2612 if (!TName.isNull())
2613 Param->setDefaultArgument(
2614 SemaRef.Context,
2615 TemplateArgumentLoc(TemplateArgument(TName),
2616 D->getDefaultArgument().getTemplateQualifierLoc(),
2617 D->getDefaultArgument().getTemplateNameLoc()));
2618 }
2619 Param->setAccess(AS_public);
2620
2621 // Introduce this template parameter's instantiation into the instantiation
2622 // scope.
2623 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2624
2625 return Param;
2626}
2627
2628Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2629 // Using directives are never dependent (and never contain any types or
2630 // expressions), so they require no explicit instantiation work.
2631
2632 UsingDirectiveDecl *Inst
2633 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2634 D->getNamespaceKeyLocation(),
2635 D->getQualifierLoc(),
2636 D->getIdentLocation(),
2637 D->getNominatedNamespace(),
2638 D->getCommonAncestor());
2639
2640 // Add the using directive to its declaration context
2641 // only if this is not a function or method.
2642 if (!Owner->isFunctionOrMethod())
2643 Owner->addDecl(Inst);
2644
2645 return Inst;
2646}
2647
2648Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2649
2650 // The nested name specifier may be dependent, for example
2651 // template <typename T> struct t {
2652 // struct s1 { T f1(); };
2653 // struct s2 : s1 { using s1::f1; };
2654 // };
2655 // template struct t<int>;
2656 // Here, in using s1::f1, s1 refers to t<T>::s1;
2657 // we need to substitute for t<int>::s1.
2658 NestedNameSpecifierLoc QualifierLoc
2659 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2660 TemplateArgs);
2661 if (!QualifierLoc)
2662 return nullptr;
2663
2664 // For an inheriting constructor declaration, the name of the using
2665 // declaration is the name of a constructor in this class, not in the
2666 // base class.
2667 DeclarationNameInfo NameInfo = D->getNameInfo();
2668 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2669 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
2670 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
2671 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
2672
2673 // We only need to do redeclaration lookups if we're in a class
2674 // scope (in fact, it's not really even possible in non-class
2675 // scopes).
2676 bool CheckRedeclaration = Owner->isRecord();
2677
2678 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2679 Sema::ForVisibleRedeclaration);
2680
2681 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2682 D->getUsingLoc(),
2683 QualifierLoc,
2684 NameInfo,
2685 D->hasTypename());
2686
2687 CXXScopeSpec SS;
2688 SS.Adopt(QualifierLoc);
2689 if (CheckRedeclaration) {
2690 Prev.setHideTags(false);
2691 SemaRef.LookupQualifiedName(Prev, Owner);
2692
2693 // Check for invalid redeclarations.
2694 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2695 D->hasTypename(), SS,
2696 D->getLocation(), Prev))
2697 NewUD->setInvalidDecl();
2698
2699 }
2700
2701 if (!NewUD->isInvalidDecl() &&
2702 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(),
2703 SS, NameInfo, D->getLocation()))
2704 NewUD->setInvalidDecl();
2705
2706 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2707 NewUD->setAccess(D->getAccess());
2708 Owner->addDecl(NewUD);
2709
2710 // Don't process the shadow decls for an invalid decl.
2711 if (NewUD->isInvalidDecl())
2712 return NewUD;
2713
2714 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2715 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
2716
2717 bool isFunctionScope = Owner->isFunctionOrMethod();
2718
2719 // Process the shadow decls.
2720 for (auto *Shadow : D->shadows()) {
2721 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
2722 // reconstruct it in the case where it matters.
2723 NamedDecl *OldTarget = Shadow->getTargetDecl();
2724 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
2725 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
2726 OldTarget = BaseShadow;
2727
2728 NamedDecl *InstTarget =
2729 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2730 Shadow->getLocation(), OldTarget, TemplateArgs));
2731 if (!InstTarget)
2732 return nullptr;
2733
2734 UsingShadowDecl *PrevDecl = nullptr;
2735 if (CheckRedeclaration) {
2736 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2737 continue;
2738 } else if (UsingShadowDecl *OldPrev =
2739 getPreviousDeclForInstantiation(Shadow)) {
2740 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2741 Shadow->getLocation(), OldPrev, TemplateArgs));
2742 }
2743
2744 UsingShadowDecl *InstShadow =
2745 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2746 PrevDecl);
2747 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2748
2749 if (isFunctionScope)
2750 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2751 }
2752
2753 return NewUD;
2754}
2755
2756Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2757 // Ignore these; we handle them in bulk when processing the UsingDecl.
2758 return nullptr;
2759}
2760
2761Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
2762 ConstructorUsingShadowDecl *D) {
2763 // Ignore these; we handle them in bulk when processing the UsingDecl.
2764 return nullptr;
2765}
2766
2767template <typename T>
2768Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
2769 T *D, bool InstantiatingPackElement) {
2770 // If this is a pack expansion, expand it now.
2771 if (D->isPackExpansion() && !InstantiatingPackElement) {
2772 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2773 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
2774 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
2775
2776 // Determine whether the set of unexpanded parameter packs can and should
2777 // be expanded.
2778 bool Expand = true;
2779 bool RetainExpansion = false;
2780 Optional<unsigned> NumExpansions;
2781 if (SemaRef.CheckParameterPacksForExpansion(
2782 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
2783 Expand, RetainExpansion, NumExpansions))
2784 return nullptr;
2785
2786 // This declaration cannot appear within a function template signature,
2787 // so we can't have a partial argument list for a parameter pack.
2788 assert(!RetainExpansion &&((!RetainExpansion && "should never need to retain an expansion for UsingPackDecl"
) ? static_cast<void> (0) : __assert_fail ("!RetainExpansion && \"should never need to retain an expansion for UsingPackDecl\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2789, __PRETTY_FUNCTION__))
2789 "should never need to retain an expansion for UsingPackDecl")((!RetainExpansion && "should never need to retain an expansion for UsingPackDecl"
) ? static_cast<void> (0) : __assert_fail ("!RetainExpansion && \"should never need to retain an expansion for UsingPackDecl\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2789, __PRETTY_FUNCTION__))
;
2790
2791 if (!Expand) {
2792 // We cannot fully expand the pack expansion now, so substitute into the
2793 // pattern and create a new pack expansion.
2794 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2795 return instantiateUnresolvedUsingDecl(D, true);
2796 }
2797
2798 // Within a function, we don't have any normal way to check for conflicts
2799 // between shadow declarations from different using declarations in the
2800 // same pack expansion, but this is always ill-formed because all expansions
2801 // must produce (conflicting) enumerators.
2802 //
2803 // Sadly we can't just reject this in the template definition because it
2804 // could be valid if the pack is empty or has exactly one expansion.
2805 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
2806 SemaRef.Diag(D->getEllipsisLoc(),
2807 diag::err_using_decl_redeclaration_expansion);
2808 return nullptr;
2809 }
2810
2811 // Instantiate the slices of this pack and build a UsingPackDecl.
2812 SmallVector<NamedDecl*, 8> Expansions;
2813 for (unsigned I = 0; I != *NumExpansions; ++I) {
2814 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2815 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
2816 if (!Slice)
2817 return nullptr;
2818 // Note that we can still get unresolved using declarations here, if we
2819 // had arguments for all packs but the pattern also contained other
2820 // template arguments (this only happens during partial substitution, eg
2821 // into the body of a generic lambda in a function template).
2822 Expansions.push_back(cast<NamedDecl>(Slice));
2823 }
2824
2825 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2826 if (isDeclWithinFunction(D))
2827 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2828 return NewD;
2829 }
2830
2831 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
2832 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
2833
2834 NestedNameSpecifierLoc QualifierLoc
2835 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2836 TemplateArgs);
2837 if (!QualifierLoc)
2838 return nullptr;
2839
2840 CXXScopeSpec SS;
2841 SS.Adopt(QualifierLoc);
2842
2843 DeclarationNameInfo NameInfo
2844 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2845
2846 // Produce a pack expansion only if we're not instantiating a particular
2847 // slice of a pack expansion.
2848 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
2849 SemaRef.ArgumentPackSubstitutionIndex != -1;
2850 SourceLocation EllipsisLoc =
2851 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
2852
2853 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
2854 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
2855 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
2856 ParsedAttributesView(),
2857 /*IsInstantiation*/ true);
2858 if (UD)
2859 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
2860
2861 return UD;
2862}
2863
2864Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
2865 UnresolvedUsingTypenameDecl *D) {
2866 return instantiateUnresolvedUsingDecl(D);
2867}
2868
2869Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
2870 UnresolvedUsingValueDecl *D) {
2871 return instantiateUnresolvedUsingDecl(D);
2872}
2873
2874Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
2875 SmallVector<NamedDecl*, 8> Expansions;
2876 for (auto *UD : D->expansions()) {
2877 if (NamedDecl *NewUD =
2878 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
2879 Expansions.push_back(NewUD);
2880 else
2881 return nullptr;
2882 }
2883
2884 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2885 if (isDeclWithinFunction(D))
2886 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2887 return NewD;
2888}
2889
2890Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2891 ClassScopeFunctionSpecializationDecl *Decl) {
2892 CXXMethodDecl *OldFD = Decl->getSpecialization();
2893 return cast_or_null<CXXMethodDecl>(
2894 VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
2895}
2896
2897Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2898 OMPThreadPrivateDecl *D) {
2899 SmallVector<Expr *, 5> Vars;
2900 for (auto *I : D->varlists()) {
2901 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2902 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr")((isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr"
) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(Var) && \"threadprivate arg is not a DeclRefExpr\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2902, __PRETTY_FUNCTION__))
;
2903 Vars.push_back(Var);
2904 }
2905
2906 OMPThreadPrivateDecl *TD =
2907 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2908
2909 TD->setAccess(AS_public);
2910 Owner->addDecl(TD);
2911
2912 return TD;
2913}
2914
2915Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2916 SmallVector<Expr *, 5> Vars;
2917 for (auto *I : D->varlists()) {
2918 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2919 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr")((isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr"
) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(Var) && \"allocate arg is not a DeclRefExpr\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2919, __PRETTY_FUNCTION__))
;
2920 Vars.push_back(Var);
2921 }
2922 SmallVector<OMPClause *, 4> Clauses;
2923 // Copy map clauses from the original mapper.
2924 for (OMPClause *C : D->clauselists()) {
2925 auto *AC = cast<OMPAllocatorClause>(C);
2926 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
2927 if (!NewE.isUsable())
2928 continue;
2929 OMPClause *IC = SemaRef.ActOnOpenMPAllocatorClause(
2930 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
2931 Clauses.push_back(IC);
2932 }
2933
2934 Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
2935 D->getLocation(), Vars, Clauses, Owner);
2936 if (Res.get().isNull())
2937 return nullptr;
2938 return Res.get().getSingleDecl();
2939}
2940
2941Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
2942 llvm_unreachable(::llvm::llvm_unreachable_internal("Requires directive cannot be instantiated within a dependent context"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2943)
2943 "Requires directive cannot be instantiated within a dependent context")::llvm::llvm_unreachable_internal("Requires directive cannot be instantiated within a dependent context"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2943)
;
2944}
2945
2946Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
2947 OMPDeclareReductionDecl *D) {
2948 // Instantiate type and check if it is allowed.
2949 const bool RequiresInstantiation =
2950 D->getType()->isDependentType() ||
2951 D->getType()->isInstantiationDependentType() ||
2952 D->getType()->containsUnexpandedParameterPack();
2953 QualType SubstReductionType;
2954 if (RequiresInstantiation) {
2955 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
2956 D->getLocation(),
2957 ParsedType::make(SemaRef.SubstType(
2958 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
2959 } else {
2960 SubstReductionType = D->getType();
2961 }
2962 if (SubstReductionType.isNull())
2963 return nullptr;
2964 bool IsCorrect = !SubstReductionType.isNull();
2965 // Create instantiated copy.
2966 std::pair<QualType, SourceLocation> ReductionTypes[] = {
2967 std::make_pair(SubstReductionType, D->getLocation())};
2968 auto *PrevDeclInScope = D->getPrevDeclInScope();
2969 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
2970 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
2971 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
2972 ->get<Decl *>());
2973 }
2974 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
2975 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
2976 PrevDeclInScope);
2977 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
2978 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
2979 if (!RequiresInstantiation) {
2980 if (Expr *Combiner = D->getCombiner()) {
2981 NewDRD->setCombinerData(D->getCombinerIn(), D->getCombinerOut());
2982 NewDRD->setCombiner(Combiner);
2983 if (Expr *Init = D->getInitializer()) {
2984 NewDRD->setInitializerData(D->getInitOrig(), D->getInitPriv());
2985 NewDRD->setInitializer(Init, D->getInitializerKind());
2986 }
2987 }
2988 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
2989 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
2990 return NewDRD;
2991 }
2992 Expr *SubstCombiner = nullptr;
2993 Expr *SubstInitializer = nullptr;
2994 // Combiners instantiation sequence.
2995 if (D->getCombiner()) {
2996 SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
2997 /*S=*/nullptr, NewDRD);
2998 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
2999 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3000 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3001 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3002 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3003 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3004 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3005 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3006 ThisContext);
3007 SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get();
3008 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3009 // Initializers instantiation sequence.
3010 if (D->getInitializer()) {
3011 VarDecl *OmpPrivParm =
3012 SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
3013 /*S=*/nullptr, NewDRD);
3014 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3015 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3016 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3017 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3018 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3019 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3020 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
3021 SubstInitializer =
3022 SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get();
3023 } else {
3024 IsCorrect = IsCorrect && OmpPrivParm->hasInit();
3025 }
3026 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(
3027 NewDRD, SubstInitializer, OmpPrivParm);
3028 }
3029 IsCorrect =
3030 IsCorrect && SubstCombiner &&
3031 (!D->getInitializer() ||
3032 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
3033 SubstInitializer) ||
3034 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
3035 !SubstInitializer && !SubstInitializer));
3036 } else {
3037 IsCorrect = false;
3038 }
3039
3040 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD,
3041 IsCorrect);
3042
3043 return NewDRD;
3044}
3045
3046Decl *
3047TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3048 // Instantiate type and check if it is allowed.
3049 const bool RequiresInstantiation =
3050 D->getType()->isDependentType() ||
3051 D->getType()->isInstantiationDependentType() ||
3052 D->getType()->containsUnexpandedParameterPack();
3053 QualType SubstMapperTy;
3054 DeclarationName VN = D->getVarName();
3055 if (RequiresInstantiation) {
3056 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
3057 D->getLocation(),
3058 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3059 D->getLocation(), VN)));
3060 } else {
3061 SubstMapperTy = D->getType();
3062 }
3063 if (SubstMapperTy.isNull())
3064 return nullptr;
3065 // Create an instantiated copy of mapper.
3066 auto *PrevDeclInScope = D->getPrevDeclInScope();
3067 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3068 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3069 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3070 ->get<Decl *>());
3071 }
3072 OMPDeclareMapperDecl *NewDMD = SemaRef.ActOnOpenMPDeclareMapperDirectiveStart(
3073 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3074 VN, D->getAccess(), PrevDeclInScope);
3075 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3076 SmallVector<OMPClause *, 6> Clauses;
3077 bool IsCorrect = true;
3078 if (!RequiresInstantiation) {
3079 // Copy the mapper variable.
3080 NewDMD->setMapperVarRef(D->getMapperVarRef());
3081 // Copy map clauses from the original mapper.
3082 for (OMPClause *C : D->clauselists())
3083 Clauses.push_back(C);
3084 } else {
3085 // Instantiate the mapper variable.
3086 DeclarationNameInfo DirName;
3087 SemaRef.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, /*S=*/nullptr,
3088 (*D->clauselist_begin())->getBeginLoc());
3089 SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3090 NewDMD, /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3091 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3092 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3093 cast<DeclRefExpr>(NewDMD->getMapperVarRef())->getDecl());
3094 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3095 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3096 ThisContext);
3097 // Instantiate map clauses.
3098 for (OMPClause *C : D->clauselists()) {
3099 auto *OldC = cast<OMPMapClause>(C);
3100 SmallVector<Expr *, 4> NewVars;
3101 for (Expr *OE : OldC->varlists()) {
3102 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3103 if (!NE) {
3104 IsCorrect = false;
3105 break;
3106 }
3107 NewVars.push_back(NE);
3108 }
3109 if (!IsCorrect)
3110 break;
3111 NestedNameSpecifierLoc NewQualifierLoc =
3112 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3113 TemplateArgs);
3114 CXXScopeSpec SS;
3115 SS.Adopt(NewQualifierLoc);
3116 DeclarationNameInfo NewNameInfo = SemaRef.SubstDeclarationNameInfo(
3117 OldC->getMapperIdInfo(), TemplateArgs);
3118 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3119 OldC->getEndLoc());
3120 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
3121 OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS,
3122 NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(),
3123 OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs);
3124 Clauses.push_back(NewC);
3125 }
3126 SemaRef.EndOpenMPDSABlock(nullptr);
3127 }
3128 (void)SemaRef.ActOnOpenMPDeclareMapperDirectiveEnd(NewDMD, /*S=*/nullptr,
3129 Clauses);
3130 if (!IsCorrect)
3131 return nullptr;
3132 return NewDMD;
3133}
3134
3135Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3136 OMPCapturedExprDecl * /*D*/) {
3137 llvm_unreachable("Should not be met in templates")::llvm::llvm_unreachable_internal("Should not be met in templates"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3137)
;
3138}
3139
3140Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
3141 return VisitFunctionDecl(D, nullptr);
3142}
3143
3144Decl *
3145TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3146 Decl *Inst = VisitFunctionDecl(D, nullptr);
3147 if (Inst && !D->getDescribedFunctionTemplate())
3148 Owner->addDecl(Inst);
3149 return Inst;
3150}
3151
3152Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
3153 return VisitCXXMethodDecl(D, nullptr);
3154}
3155
3156Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3157 llvm_unreachable("There are only CXXRecordDecls in C++")::llvm::llvm_unreachable_internal("There are only CXXRecordDecls in C++"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3157)
;
3158}
3159
3160Decl *
3161TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3162 ClassTemplateSpecializationDecl *D) {
3163 // As a MS extension, we permit class-scope explicit specialization
3164 // of member class templates.
3165 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3166 assert(ClassTemplate->getDeclContext()->isRecord() &&((ClassTemplate->getDeclContext()->isRecord() &&
D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
&& "can only instantiate an explicit specialization "
"for a member class template") ? static_cast<void> (0)
: __assert_fail ("ClassTemplate->getDeclContext()->isRecord() && D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && \"can only instantiate an explicit specialization \" \"for a member class template\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3169, __PRETTY_FUNCTION__))
3167 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&((ClassTemplate->getDeclContext()->isRecord() &&
D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
&& "can only instantiate an explicit specialization "
"for a member class template") ? static_cast<void> (0)
: __assert_fail ("ClassTemplate->getDeclContext()->isRecord() && D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && \"can only instantiate an explicit specialization \" \"for a member class template\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3169, __PRETTY_FUNCTION__))
3168 "can only instantiate an explicit specialization "((ClassTemplate->getDeclContext()->isRecord() &&
D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
&& "can only instantiate an explicit specialization "
"for a member class template") ? static_cast<void> (0)
: __assert_fail ("ClassTemplate->getDeclContext()->isRecord() && D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && \"can only instantiate an explicit specialization \" \"for a member class template\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3169, __PRETTY_FUNCTION__))
3169 "for a member class template")((ClassTemplate->getDeclContext()->isRecord() &&
D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
&& "can only instantiate an explicit specialization "
"for a member class template") ? static_cast<void> (0)
: __assert_fail ("ClassTemplate->getDeclContext()->isRecord() && D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && \"can only instantiate an explicit specialization \" \"for a member class template\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3169, __PRETTY_FUNCTION__))
;
3170
3171 // Lookup the already-instantiated declaration in the instantiation
3172 // of the class template.
3173 ClassTemplateDecl *InstClassTemplate =
3174 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3175 D->getLocation(), ClassTemplate, TemplateArgs));
3176 if (!InstClassTemplate)
3177 return nullptr;
3178
3179 // Substitute into the template arguments of the class template explicit
3180 // specialization.
3181 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
3182 castAs<TemplateSpecializationTypeLoc>();
3183 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
3184 Loc.getRAngleLoc());
3185 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
3186 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
3187 ArgLocs.push_back(Loc.getArgLoc(I));
3188 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
3189 InstTemplateArgs, TemplateArgs))
3190 return nullptr;
3191
3192 // Check that the template argument list is well-formed for this
3193 // class template.
3194 SmallVector<TemplateArgument, 4> Converted;
3195 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
3196 D->getLocation(),
3197 InstTemplateArgs,
3198 false,
3199 Converted))
3200 return nullptr;
3201
3202 // Figure out where to insert this class template explicit specialization
3203 // in the member template's set of class template explicit specializations.
3204 void *InsertPos = nullptr;
3205 ClassTemplateSpecializationDecl *PrevDecl =
3206 InstClassTemplate->findSpecialization(Converted, InsertPos);
3207
3208 // Check whether we've already seen a conflicting instantiation of this
3209 // declaration (for instance, if there was a prior implicit instantiation).
3210 bool Ignored;
3211 if (PrevDecl &&
3212 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3213 D->getSpecializationKind(),
3214 PrevDecl,
3215 PrevDecl->getSpecializationKind(),
3216 PrevDecl->getPointOfInstantiation(),
3217 Ignored))
3218 return nullptr;
3219
3220 // If PrevDecl was a definition and D is also a definition, diagnose.
3221 // This happens in cases like:
3222 //
3223 // template<typename T, typename U>
3224 // struct Outer {
3225 // template<typename X> struct Inner;
3226 // template<> struct Inner<T> {};
3227 // template<> struct Inner<U> {};
3228 // };
3229 //
3230 // Outer<int, int> outer; // error: the explicit specializations of Inner
3231 // // have the same signature.
3232 if (PrevDecl && PrevDecl->getDefinition() &&
3233 D->isThisDeclarationADefinition()) {
3234 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3235 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3236 diag::note_previous_definition);
3237 return nullptr;
3238 }
3239
3240 // Create the class template partial specialization declaration.
3241 ClassTemplateSpecializationDecl *InstD =
3242 ClassTemplateSpecializationDecl::Create(
3243 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3244 D->getLocation(), InstClassTemplate, Converted, PrevDecl);
3245
3246 // Add this partial specialization to the set of class template partial
3247 // specializations.
3248 if (!PrevDecl)
3249 InstClassTemplate->AddSpecialization(InstD, InsertPos);
3250
3251 // Substitute the nested name specifier, if any.
3252 if (SubstQualifier(D, InstD))
3253 return nullptr;
3254
3255 // Build the canonical type that describes the converted template
3256 // arguments of the class template explicit specialization.
3257 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3258 TemplateName(InstClassTemplate), Converted,
3259 SemaRef.Context.getRecordType(InstD));
3260
3261 // Build the fully-sugared type for this class template
3262 // specialization as the user wrote in the specialization
3263 // itself. This means that we'll pretty-print the type retrieved
3264 // from the specialization's declaration the way that the user
3265 // actually wrote the specialization, rather than formatting the
3266 // name based on the "canonical" representation used to store the
3267 // template arguments in the specialization.
3268 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3269 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3270 CanonType);
3271
3272 InstD->setAccess(D->getAccess());
3273 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3274 InstD->setSpecializationKind(D->getSpecializationKind());
3275 InstD->setTypeAsWritten(WrittenTy);
3276 InstD->setExternLoc(D->getExternLoc());
3277 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3278
3279 Owner->addDecl(InstD);
3280
3281 // Instantiate the members of the class-scope explicit specialization eagerly.
3282 // We don't have support for lazy instantiation of an explicit specialization
3283 // yet, and MSVC eagerly instantiates in this case.
3284 // FIXME: This is wrong in standard C++.
3285 if (D->isThisDeclarationADefinition() &&
3286 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3287 TSK_ImplicitInstantiation,
3288 /*Complain=*/true))
3289 return nullptr;
3290
3291 return InstD;
3292}
3293
3294Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3295 VarTemplateSpecializationDecl *D) {
3296
3297 TemplateArgumentListInfo VarTemplateArgsInfo;
3298 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3299 assert(VarTemplate &&((VarTemplate && "A template specialization without specialized template?"
) ? static_cast<void> (0) : __assert_fail ("VarTemplate && \"A template specialization without specialized template?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3300, __PRETTY_FUNCTION__))
3300 "A template specialization without specialized template?")((VarTemplate && "A template specialization without specialized template?"
) ? static_cast<void> (0) : __assert_fail ("VarTemplate && \"A template specialization without specialized template?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3300, __PRETTY_FUNCTION__))
;
3301
3302 VarTemplateDecl *InstVarTemplate =
3303 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3304 D->getLocation(), VarTemplate, TemplateArgs));
3305 if (!InstVarTemplate)
3306 return nullptr;
3307
3308 // Substitute the current template arguments.
3309 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
3310 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
3311 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
3312
3313 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
3314 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
3315 return nullptr;
3316
3317 // Check that the template argument list is well-formed for this template.
3318 SmallVector<TemplateArgument, 4> Converted;
3319 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3320 VarTemplateArgsInfo, false, Converted))
3321 return nullptr;
3322
3323 // Check whether we've already seen a declaration of this specialization.
3324 void *InsertPos = nullptr;
3325 VarTemplateSpecializationDecl *PrevDecl =
3326 InstVarTemplate->findSpecialization(Converted, InsertPos);
3327
3328 // Check whether we've already seen a conflicting instantiation of this
3329 // declaration (for instance, if there was a prior implicit instantiation).
3330 bool Ignored;
3331 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
3332 D->getLocation(), D->getSpecializationKind(), PrevDecl,
3333 PrevDecl->getSpecializationKind(),
3334 PrevDecl->getPointOfInstantiation(), Ignored))
3335 return nullptr;
3336
3337 return VisitVarTemplateSpecializationDecl(
3338 InstVarTemplate, D, InsertPos, VarTemplateArgsInfo, Converted, PrevDecl);
3339}
3340
3341Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3342 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
3343 const TemplateArgumentListInfo &TemplateArgsInfo,
3344 ArrayRef<TemplateArgument> Converted,
3345 VarTemplateSpecializationDecl *PrevDecl) {
3346
3347 // Do substitution on the type of the declaration
3348 TypeSourceInfo *DI =
3349 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3350 D->getTypeSpecStartLoc(), D->getDeclName());
3351 if (!DI)
3352 return nullptr;
3353
3354 if (DI->getType()->isFunctionType()) {
3355 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3356 << D->isStaticDataMember() << DI->getType();
3357 return nullptr;
3358 }
3359
3360 // Build the instantiated declaration
3361 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3362 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3363 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
3364 Var->setTemplateArgsInfo(TemplateArgsInfo);
3365 if (InsertPos)
3366 VarTemplate->AddSpecialization(Var, InsertPos);
3367
3368 // Substitute the nested name specifier, if any.
3369 if (SubstQualifier(D, Var))
3370 return nullptr;
3371
3372 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
3373 StartingScope, false, PrevDecl);
3374
3375 return Var;
3376}
3377
3378Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3379 llvm_unreachable("@defs is not supported in Objective-C++")::llvm::llvm_unreachable_internal("@defs is not supported in Objective-C++"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3379)
;
3380}
3381
3382Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3383 // FIXME: We need to be able to instantiate FriendTemplateDecls.
3384 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3385 DiagnosticsEngine::Error,
3386 "cannot instantiate %0 yet");
3387 SemaRef.Diag(D->getLocation(), DiagID)
3388 << D->getDeclKindName();
3389
3390 return nullptr;
3391}
3392
3393Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
3394 llvm_unreachable("Unexpected decl")::llvm::llvm_unreachable_internal("Unexpected decl", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3394)
;
3395}
3396
3397Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
3398 const MultiLevelTemplateArgumentList &TemplateArgs) {
3399 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3400 if (D->isInvalidDecl())
3401 return nullptr;
3402
3403 return Instantiator.Visit(D);
3404}
3405
3406/// Instantiates a nested template parameter list in the current
3407/// instantiation context.
3408///
3409/// \param L The parameter list to instantiate
3410///
3411/// \returns NULL if there was an error
3412TemplateParameterList *
3413TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
3414 // Get errors for all the parameters before bailing out.
3415 bool Invalid = false;
3416
3417 unsigned N = L->size();
3418 typedef SmallVector<NamedDecl *, 8> ParamVector;
3419 ParamVector Params;
3420 Params.reserve(N);
3421 for (auto &P : *L) {
3422 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
3423 Params.push_back(D);
3424 Invalid = Invalid || !D || D->isInvalidDecl();
3425 }
3426
3427 // Clean up if we had an error.
3428 if (Invalid)
3429 return nullptr;
3430
3431 // Note: we substitute into associated constraints later
3432 Expr *const UninstantiatedRequiresClause = L->getRequiresClause();
3433
3434 TemplateParameterList *InstL
3435 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
3436 L->getLAngleLoc(), Params,
3437 L->getRAngleLoc(),
3438 UninstantiatedRequiresClause);
3439 return InstL;
3440}
3441
3442TemplateParameterList *
3443Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
3444 const MultiLevelTemplateArgumentList &TemplateArgs) {
3445 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3446 return Instantiator.SubstTemplateParams(Params);
3447}
3448
3449/// Instantiate the declaration of a class template partial
3450/// specialization.
3451///
3452/// \param ClassTemplate the (instantiated) class template that is partially
3453// specialized by the instantiation of \p PartialSpec.
3454///
3455/// \param PartialSpec the (uninstantiated) class template partial
3456/// specialization that we are instantiating.
3457///
3458/// \returns The instantiated partial specialization, if successful; otherwise,
3459/// NULL to indicate an error.
3460ClassTemplatePartialSpecializationDecl *
3461TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
3462 ClassTemplateDecl *ClassTemplate,
3463 ClassTemplatePartialSpecializationDecl *PartialSpec) {
3464 // Create a local instantiation scope for this class template partial
3465 // specialization, which will contain the instantiations of the template
3466 // parameters.
3467 LocalInstantiationScope Scope(SemaRef);
3468
3469 // Substitute into the template parameters of the class template partial
3470 // specialization.
3471 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3472 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3473 if (!InstParams)
3474 return nullptr;
3475
3476 // Substitute into the template arguments of the class template partial
3477 // specialization.
3478 const ASTTemplateArgumentListInfo *TemplArgInfo
3479 = PartialSpec->getTemplateArgsAsWritten();
3480 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3481 TemplArgInfo->RAngleLoc);
3482 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3483 TemplArgInfo->NumTemplateArgs,
3484 InstTemplateArgs, TemplateArgs))
3485 return nullptr;
3486
3487 // Check that the template argument list is well-formed for this
3488 // class template.
3489 SmallVector<TemplateArgument, 4> Converted;
3490 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
3491 PartialSpec->getLocation(),
3492 InstTemplateArgs,
3493 false,
3494 Converted))
3495 return nullptr;
3496
3497 // Check these arguments are valid for a template partial specialization.
3498 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3499 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
3500 Converted))
3501 return nullptr;
3502
3503 // Figure out where to insert this class template partial specialization
3504 // in the member template's set of class template partial specializations.
3505 void *InsertPos = nullptr;
3506 ClassTemplateSpecializationDecl *PrevDecl
3507 = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
3508
3509 // Build the canonical type that describes the converted template
3510 // arguments of the class template partial specialization.
3511 QualType CanonType
3512 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
3513 Converted);
3514
3515 // Build the fully-sugared type for this class template
3516 // specialization as the user wrote in the specialization
3517 // itself. This means that we'll pretty-print the type retrieved
3518 // from the specialization's declaration the way that the user
3519 // actually wrote the specialization, rather than formatting the
3520 // name based on the "canonical" representation used to store the
3521 // template arguments in the specialization.
3522 TypeSourceInfo *WrittenTy
3523 = SemaRef.Context.getTemplateSpecializationTypeInfo(
3524 TemplateName(ClassTemplate),
3525 PartialSpec->getLocation(),
3526 InstTemplateArgs,
3527 CanonType);
3528
3529 if (PrevDecl) {
3530 // We've already seen a partial specialization with the same template
3531 // parameters and template arguments. This can happen, for example, when
3532 // substituting the outer template arguments ends up causing two
3533 // class template partial specializations of a member class template
3534 // to have identical forms, e.g.,
3535 //
3536 // template<typename T, typename U>
3537 // struct Outer {
3538 // template<typename X, typename Y> struct Inner;
3539 // template<typename Y> struct Inner<T, Y>;
3540 // template<typename Y> struct Inner<U, Y>;
3541 // };
3542 //
3543 // Outer<int, int> outer; // error: the partial specializations of Inner
3544 // // have the same signature.
3545 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
3546 << WrittenTy->getType();
3547 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3548 << SemaRef.Context.getTypeDeclType(PrevDecl);
3549 return nullptr;
3550 }
3551
3552
3553 // Create the class template partial specialization declaration.
3554 ClassTemplatePartialSpecializationDecl *InstPartialSpec =
3555 ClassTemplatePartialSpecializationDecl::Create(
3556 SemaRef.Context, PartialSpec->getTagKind(), Owner,
3557 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
3558 ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
3559 // Substitute the nested name specifier, if any.
3560 if (SubstQualifier(PartialSpec, InstPartialSpec))
3561 return nullptr;
3562
3563 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3564 InstPartialSpec->setTypeAsWritten(WrittenTy);
3565
3566 // Check the completed partial specialization.
3567 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3568
3569 // Add this partial specialization to the set of class template partial
3570 // specializations.
3571 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
3572 /*InsertPos=*/nullptr);
3573 return InstPartialSpec;
3574}
3575
3576/// Instantiate the declaration of a variable template partial
3577/// specialization.
3578///
3579/// \param VarTemplate the (instantiated) variable template that is partially
3580/// specialized by the instantiation of \p PartialSpec.
3581///
3582/// \param PartialSpec the (uninstantiated) variable template partial
3583/// specialization that we are instantiating.
3584///
3585/// \returns The instantiated partial specialization, if successful; otherwise,
3586/// NULL to indicate an error.
3587VarTemplatePartialSpecializationDecl *
3588TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
3589 VarTemplateDecl *VarTemplate,
3590 VarTemplatePartialSpecializationDecl *PartialSpec) {
3591 // Create a local instantiation scope for this variable template partial
3592 // specialization, which will contain the instantiations of the template
3593 // parameters.
3594 LocalInstantiationScope Scope(SemaRef);
3595
3596 // Substitute into the template parameters of the variable template partial
3597 // specialization.
3598 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3599 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3600 if (!InstParams)
3601 return nullptr;
3602
3603 // Substitute into the template arguments of the variable template partial
3604 // specialization.
3605 const ASTTemplateArgumentListInfo *TemplArgInfo
3606 = PartialSpec->getTemplateArgsAsWritten();
3607 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3608 TemplArgInfo->RAngleLoc);
3609 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3610 TemplArgInfo->NumTemplateArgs,
3611 InstTemplateArgs, TemplateArgs))
3612 return nullptr;
3613
3614 // Check that the template argument list is well-formed for this
3615 // class template.
3616 SmallVector<TemplateArgument, 4> Converted;
3617 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
3618 InstTemplateArgs, false, Converted))
3619 return nullptr;
3620
3621 // Check these arguments are valid for a template partial specialization.
3622 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3623 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
3624 Converted))
3625 return nullptr;
3626
3627 // Figure out where to insert this variable template partial specialization
3628 // in the member template's set of variable template partial specializations.
3629 void *InsertPos = nullptr;
3630 VarTemplateSpecializationDecl *PrevDecl =
3631 VarTemplate->findPartialSpecialization(Converted, InsertPos);
3632
3633 // Build the canonical type that describes the converted template
3634 // arguments of the variable template partial specialization.
3635 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3636 TemplateName(VarTemplate), Converted);
3637
3638 // Build the fully-sugared type for this variable template
3639 // specialization as the user wrote in the specialization
3640 // itself. This means that we'll pretty-print the type retrieved
3641 // from the specialization's declaration the way that the user
3642 // actually wrote the specialization, rather than formatting the
3643 // name based on the "canonical" representation used to store the
3644 // template arguments in the specialization.
3645 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3646 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
3647 CanonType);
3648
3649 if (PrevDecl) {
3650 // We've already seen a partial specialization with the same template
3651 // parameters and template arguments. This can happen, for example, when
3652 // substituting the outer template arguments ends up causing two
3653 // variable template partial specializations of a member variable template
3654 // to have identical forms, e.g.,
3655 //
3656 // template<typename T, typename U>
3657 // struct Outer {
3658 // template<typename X, typename Y> pair<X,Y> p;
3659 // template<typename Y> pair<T, Y> p;
3660 // template<typename Y> pair<U, Y> p;
3661 // };
3662 //
3663 // Outer<int, int> outer; // error: the partial specializations of Inner
3664 // // have the same signature.
3665 SemaRef.Diag(PartialSpec->getLocation(),
3666 diag::err_var_partial_spec_redeclared)
3667 << WrittenTy->getType();
3668 SemaRef.Diag(PrevDecl->getLocation(),
3669 diag::note_var_prev_partial_spec_here);
3670 return nullptr;
3671 }
3672
3673 // Do substitution on the type of the declaration
3674 TypeSourceInfo *DI = SemaRef.SubstType(
3675 PartialSpec->getTypeSourceInfo(), TemplateArgs,
3676 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
3677 if (!DI)
3678 return nullptr;
3679
3680 if (DI->getType()->isFunctionType()) {
3681 SemaRef.Diag(PartialSpec->getLocation(),
3682 diag::err_variable_instantiates_to_function)
3683 << PartialSpec->isStaticDataMember() << DI->getType();
3684 return nullptr;
3685 }
3686
3687 // Create the variable template partial specialization declaration.
3688 VarTemplatePartialSpecializationDecl *InstPartialSpec =
3689 VarTemplatePartialSpecializationDecl::Create(
3690 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
3691 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
3692 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
3693
3694 // Substitute the nested name specifier, if any.
3695 if (SubstQualifier(PartialSpec, InstPartialSpec))
3696 return nullptr;
3697
3698 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3699 InstPartialSpec->setTypeAsWritten(WrittenTy);
3700
3701 // Check the completed partial specialization.
3702 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3703
3704 // Add this partial specialization to the set of variable template partial
3705 // specializations. The instantiation of the initializer is not necessary.
3706 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
3707
3708 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
3709 LateAttrs, Owner, StartingScope);
3710
3711 return InstPartialSpec;
3712}
3713
3714TypeSourceInfo*
3715TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
3716 SmallVectorImpl<ParmVarDecl *> &Params) {
3717 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
3718 assert(OldTInfo && "substituting function without type source info")((OldTInfo && "substituting function without type source info"
) ? static_cast<void> (0) : __assert_fail ("OldTInfo && \"substituting function without type source info\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3718, __PRETTY_FUNCTION__))
;
3719 assert(Params.empty() && "parameter vector is non-empty at start")((Params.empty() && "parameter vector is non-empty at start"
) ? static_cast<void> (0) : __assert_fail ("Params.empty() && \"parameter vector is non-empty at start\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3719, __PRETTY_FUNCTION__))
;
3720
3721 CXXRecordDecl *ThisContext = nullptr;
3722 Qualifiers ThisTypeQuals;
3723 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3724 ThisContext = cast<CXXRecordDecl>(Owner);
3725 ThisTypeQuals = Method->getMethodQualifiers();
3726 }
3727
3728 TypeSourceInfo *NewTInfo
3729 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
3730 D->getTypeSpecStartLoc(),
3731 D->getDeclName(),
3732 ThisContext, ThisTypeQuals);
3733 if (!NewTInfo)
3734 return nullptr;
3735
3736 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
3737 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
3738 if (NewTInfo != OldTInfo) {
3739 // Get parameters from the new type info.
3740 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
3741 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
3742 unsigned NewIdx = 0;
3743 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
3744 OldIdx != NumOldParams; ++OldIdx) {
3745 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
3746 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3747
3748 Optional<unsigned> NumArgumentsInExpansion;
3749 if (OldParam->isParameterPack())
3750 NumArgumentsInExpansion =
3751 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3752 TemplateArgs);
3753 if (!NumArgumentsInExpansion) {
3754 // Simple case: normal parameter, or a parameter pack that's
3755 // instantiated to a (still-dependent) parameter pack.
3756 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3757 Params.push_back(NewParam);
3758 Scope->InstantiatedLocal(OldParam, NewParam);
3759 } else {
3760 // Parameter pack expansion: make the instantiation an argument pack.
3761 Scope->MakeInstantiatedLocalArgPack(OldParam);
3762 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
3763 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3764 Params.push_back(NewParam);
3765 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3766 }
3767 }
3768 }
3769 } else {
3770 // The function type itself was not dependent and therefore no
3771 // substitution occurred. However, we still need to instantiate
3772 // the function parameters themselves.
3773 const FunctionProtoType *OldProto =
3774 cast<FunctionProtoType>(OldProtoLoc.getType());
3775 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3776 ++i) {
3777 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
3778 if (!OldParam) {
3779 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
3780 D, D->getLocation(), OldProto->getParamType(i)));
3781 continue;
3782 }
3783
3784 ParmVarDecl *Parm =
3785 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
3786 if (!Parm)
3787 return nullptr;
3788 Params.push_back(Parm);
3789 }
3790 }
3791 } else {
3792 // If the type of this function, after ignoring parentheses, is not
3793 // *directly* a function type, then we're instantiating a function that
3794 // was declared via a typedef or with attributes, e.g.,
3795 //
3796 // typedef int functype(int, int);
3797 // functype func;
3798 // int __cdecl meth(int, int);
3799 //
3800 // In this case, we'll just go instantiate the ParmVarDecls that we
3801 // synthesized in the method declaration.
3802 SmallVector<QualType, 4> ParamTypes;
3803 Sema::ExtParameterInfoBuilder ExtParamInfos;
3804 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
3805 TemplateArgs, ParamTypes, &Params,
3806 ExtParamInfos))
3807 return nullptr;
3808 }
3809
3810 return NewTInfo;
3811}
3812
3813/// Introduce the instantiated function parameters into the local
3814/// instantiation scope, and set the parameter names to those used
3815/// in the template.
3816static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
3817 const FunctionDecl *PatternDecl,
3818 LocalInstantiationScope &Scope,
3819 const MultiLevelTemplateArgumentList &TemplateArgs) {
3820 unsigned FParamIdx = 0;
3821 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3822 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3823 if (!PatternParam->isParameterPack()) {
3824 // Simple case: not a parameter pack.
3825 assert(FParamIdx < Function->getNumParams())((FParamIdx < Function->getNumParams()) ? static_cast<
void> (0) : __assert_fail ("FParamIdx < Function->getNumParams()"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3825, __PRETTY_FUNCTION__))
;
3826 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3827 FunctionParam->setDeclName(PatternParam->getDeclName());
3828 // If the parameter's type is not dependent, update it to match the type
3829 // in the pattern. They can differ in top-level cv-qualifiers, and we want
3830 // the pattern's type here. If the type is dependent, they can't differ,
3831 // per core issue 1668. Substitute into the type from the pattern, in case
3832 // it's instantiation-dependent.
3833 // FIXME: Updating the type to work around this is at best fragile.
3834 if (!PatternDecl->getType()->isDependentType()) {
3835 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3836 FunctionParam->getLocation(),
3837 FunctionParam->getDeclName());
3838 if (T.isNull())
3839 return true;
3840 FunctionParam->setType(T);
3841 }
3842
3843 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3844 ++FParamIdx;
3845 continue;
3846 }
3847
3848 // Expand the parameter pack.
3849 Scope.MakeInstantiatedLocalArgPack(PatternParam);
3850 Optional<unsigned> NumArgumentsInExpansion
3851 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
3852 if (NumArgumentsInExpansion) {
3853 QualType PatternType =
3854 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
3855 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
3856 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3857 FunctionParam->setDeclName(PatternParam->getDeclName());
3858 if (!PatternDecl->getType()->isDependentType()) {
3859 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3860 QualType T = S.SubstType(PatternType, TemplateArgs,
3861 FunctionParam->getLocation(),
3862 FunctionParam->getDeclName());
3863 if (T.isNull())
3864 return true;
3865 FunctionParam->setType(T);
3866 }
3867
3868 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3869 ++FParamIdx;
3870 }
3871 }
3872 }
3873
3874 return false;
3875}
3876
3877void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3878 FunctionDecl *Decl) {
3879 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3880 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
3881 return;
3882
3883 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3884 InstantiatingTemplate::ExceptionSpecification());
3885 if (Inst.isInvalid()) {
3886 // We hit the instantiation depth limit. Clear the exception specification
3887 // so that our callers don't have to cope with EST_Uninstantiated.
3888 UpdateExceptionSpec(Decl, EST_None);
3889 return;
3890 }
3891 if (Inst.isAlreadyInstantiating()) {
3892 // This exception specification indirectly depends on itself. Reject.
3893 // FIXME: Corresponding rule in the standard?
3894 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
3895 UpdateExceptionSpec(Decl, EST_None);
3896 return;
3897 }
3898
3899 // Enter the scope of this instantiation. We don't use
3900 // PushDeclContext because we don't have a scope.
3901 Sema::ContextRAII savedContext(*this, Decl);
3902 LocalInstantiationScope Scope(*this);
3903
3904 MultiLevelTemplateArgumentList TemplateArgs =
3905 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
3906
3907 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3908 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3909 TemplateArgs)) {
3910 UpdateExceptionSpec(Decl, EST_None);
3911 return;
3912 }
3913
3914 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3915 TemplateArgs);
3916}
3917
3918/// Initializes the common fields of an instantiation function
3919/// declaration (New) from the corresponding fields of its template (Tmpl).
3920///
3921/// \returns true if there was an error
3922bool
3923TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
3924 FunctionDecl *Tmpl) {
3925 if (Tmpl->isDeleted())
3926 New->setDeletedAsWritten();
3927
3928 New->setImplicit(Tmpl->isImplicit());
3929
3930 // Forward the mangling number from the template to the instantiated decl.
3931 SemaRef.Context.setManglingNumber(New,
3932 SemaRef.Context.getManglingNumber(Tmpl));
3933
3934 // If we are performing substituting explicitly-specified template arguments
3935 // or deduced template arguments into a function template and we reach this
3936 // point, we are now past the point where SFINAE applies and have committed
3937 // to keeping the new function template specialization. We therefore
3938 // convert the active template instantiation for the function template
3939 // into a template instantiation for this specific function template
3940 // specialization, which is not a SFINAE context, so that we diagnose any
3941 // further errors in the declaration itself.
3942 typedef Sema::CodeSynthesisContext ActiveInstType;
3943 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
3944 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3945 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
3946 if (FunctionTemplateDecl *FunTmpl
3947 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
3948 assert(FunTmpl->getTemplatedDecl() == Tmpl &&((FunTmpl->getTemplatedDecl() == Tmpl && "Deduction from the wrong function template?"
) ? static_cast<void> (0) : __assert_fail ("FunTmpl->getTemplatedDecl() == Tmpl && \"Deduction from the wrong function template?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3949, __PRETTY_FUNCTION__))
3949 "Deduction from the wrong function template?")((FunTmpl->getTemplatedDecl() == Tmpl && "Deduction from the wrong function template?"
) ? static_cast<void> (0) : __assert_fail ("FunTmpl->getTemplatedDecl() == Tmpl && \"Deduction from the wrong function template?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3949, __PRETTY_FUNCTION__))
;
3950 (void) FunTmpl;
3951 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
3952 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
3953 ActiveInst.Entity = New;
3954 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
3955 }
3956 }
3957
3958 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3959 assert(Proto && "Function template without prototype?")((Proto && "Function template without prototype?") ? static_cast
<void> (0) : __assert_fail ("Proto && \"Function template without prototype?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3959, __PRETTY_FUNCTION__))
;
3960
3961 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
3962 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3963
3964 // DR1330: In C++11, defer instantiation of a non-trivial
3965 // exception specification.
3966 // DR1484: Local classes and their members are instantiated along with the
3967 // containing function.
3968 if (SemaRef.getLangOpts().CPlusPlus11 &&
3969 EPI.ExceptionSpec.Type != EST_None &&
3970 EPI.ExceptionSpec.Type != EST_DynamicNone &&
3971 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
3972 !Tmpl->isLexicallyWithinFunctionOrMethod()) {
3973 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3974 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3975 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
3976 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3977 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
3978 NewEST = EST_Unevaluated;
3979
3980 // Mark the function has having an uninstantiated exception specification.
3981 const FunctionProtoType *NewProto
3982 = New->getType()->getAs<FunctionProtoType>();
3983 assert(NewProto && "Template instantiation without function prototype?")((NewProto && "Template instantiation without function prototype?"
) ? static_cast<void> (0) : __assert_fail ("NewProto && \"Template instantiation without function prototype?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3983, __PRETTY_FUNCTION__))
;
3984 EPI = NewProto->getExtProtoInfo();
3985 EPI.ExceptionSpec.Type = NewEST;
3986 EPI.ExceptionSpec.SourceDecl = New;
3987 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
3988 New->setType(SemaRef.Context.getFunctionType(
3989 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
3990 } else {
3991 Sema::ContextRAII SwitchContext(SemaRef, New);
3992 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
3993 }
3994 }
3995
3996 // Get the definition. Leaves the variable unchanged if undefined.
3997 const FunctionDecl *Definition = Tmpl;
3998 Tmpl->isDefined(Definition);
3999
4000 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4001 LateAttrs, StartingScope);
4002
4003 return false;
4004}
4005
4006/// Initializes common fields of an instantiated method
4007/// declaration (New) from the corresponding fields of its template
4008/// (Tmpl).
4009///
4010/// \returns true if there was an error
4011bool
4012TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
4013 CXXMethodDecl *Tmpl) {
4014 if (InitFunctionInstantiation(New, Tmpl))
4015 return true;
4016
4017 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4018 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4019
4020 New->setAccess(Tmpl->getAccess());
4021 if (Tmpl->isVirtualAsWritten())
4022 New->setVirtualAsWritten(true);
4023
4024 // FIXME: New needs a pointer to Tmpl
4025 return false;
4026}
4027
4028/// Instantiate (or find existing instantiation of) a function template with a
4029/// given set of template arguments.
4030///
4031/// Usually this should not be used, and template argument deduction should be
4032/// used in its place.
4033FunctionDecl *
4034Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
4035 const TemplateArgumentList *Args,
4036 SourceLocation Loc) {
4037 FunctionDecl *FD = FTD->getTemplatedDecl();
4038
4039 sema::TemplateDeductionInfo Info(Loc);
4040 InstantiatingTemplate Inst(
4041 *this, Loc, FTD, Args->asArray(),
4042 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
4043 if (Inst.isInvalid())
4044 return nullptr;
4045
4046 ContextRAII SavedContext(*this, FD);
4047 MultiLevelTemplateArgumentList MArgs(*Args);
4048
4049 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4050}
4051
4052/// In the MS ABI, we need to instantiate default arguments of dllexported
4053/// default constructors along with the constructor definition. This allows IR
4054/// gen to emit a constructor closure which calls the default constructor with
4055/// its default arguments.
4056static void InstantiateDefaultCtorDefaultArgs(Sema &S,
4057 CXXConstructorDecl *Ctor) {
4058 assert(S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&((S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Ctor->isDefaultConstructor()) ? static_cast<void> (
0) : __assert_fail ("S.Context.getTargetInfo().getCXXABI().isMicrosoft() && Ctor->isDefaultConstructor()"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4059, __PRETTY_FUNCTION__))
4059 Ctor->isDefaultConstructor())((S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Ctor->isDefaultConstructor()) ? static_cast<void> (
0) : __assert_fail ("S.Context.getTargetInfo().getCXXABI().isMicrosoft() && Ctor->isDefaultConstructor()"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4059, __PRETTY_FUNCTION__))
;
4060 unsigned NumParams = Ctor->getNumParams();
4061 if (NumParams == 0)
4062 return;
4063 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
4064 if (!Attr)
4065 return;
4066 for (unsigned I = 0; I != NumParams; ++I) {
4067 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
4068 Ctor->getParamDecl(I));
4069 S.DiscardCleanupsInEvaluationContext();
4070 }
4071}
4072
4073/// Instantiate the definition of the given function from its
4074/// template.
4075///
4076/// \param PointOfInstantiation the point at which the instantiation was
4077/// required. Note that this is not precisely a "point of instantiation"
4078/// for the function, but it's close.
4079///
4080/// \param Function the already-instantiated declaration of a
4081/// function template specialization or member function of a class template
4082/// specialization.
4083///
4084/// \param Recursive if true, recursively instantiates any functions that
4085/// are required by this instantiation.
4086///
4087/// \param DefinitionRequired if true, then we are performing an explicit
4088/// instantiation where the body of the function is required. Complain if
4089/// there is no such body.
4090void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4091 FunctionDecl *Function,
4092 bool Recursive,
4093 bool DefinitionRequired,
4094 bool AtEndOfTU) {
4095 if (Function->isInvalidDecl() || Function->isDefined() ||
2
Assuming the condition is false
3
Assuming the condition is false
4
Taking false branch
4096 isa<CXXDeductionGuideDecl>(Function))
4097 return;
4098
4099 // Never instantiate an explicit specialization except if it is a class scope
4100 // explicit specialization.
4101 TemplateSpecializationKind TSK =
4102 Function->getTemplateSpecializationKindForInstantiation();
4103 if (TSK == TSK_ExplicitSpecialization)
5
Assuming 'TSK' is not equal to TSK_ExplicitSpecialization
6
Taking false branch
4104 return;
4105
4106 // Find the function body that we'll be substituting.
4107 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
4108 assert(PatternDecl && "instantiating a non-template")((PatternDecl && "instantiating a non-template") ? static_cast
<void> (0) : __assert_fail ("PatternDecl && \"instantiating a non-template\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4108, __PRETTY_FUNCTION__))
;
7
Assuming 'PatternDecl' is non-null
8
'?' condition is true
4109
4110 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
4111 Stmt *Pattern = nullptr;
4112 if (PatternDef) {
9
Taking false branch
4113 Pattern = PatternDef->getBody(PatternDef);
4114 PatternDecl = PatternDef;
4115 if (PatternDef->willHaveBody())
4116 PatternDef = nullptr;
4117 }
4118
4119 // FIXME: We need to track the instantiation stack in order to know which
4120 // definitions should be visible within this instantiation.
4121 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
10
Assuming the condition is false
11
Taking false branch
4122 Function->getInstantiatedFromMemberFunction(),
4123 PatternDecl, PatternDef, TSK,
4124 /*Complain*/DefinitionRequired)) {
4125 if (DefinitionRequired)
4126 Function->setInvalidDecl();
4127 else if (TSK == TSK_ExplicitInstantiationDefinition) {
4128 // Try again at the end of the translation unit (at which point a
4129 // definition will be required).
4130 assert(!Recursive)((!Recursive) ? static_cast<void> (0) : __assert_fail (
"!Recursive", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4130, __PRETTY_FUNCTION__))
;
4131 Function->setInstantiationIsPending(true);
4132 PendingInstantiations.push_back(
4133 std::make_pair(Function, PointOfInstantiation));
4134 } else if (TSK == TSK_ImplicitInstantiation) {
4135 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4136 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4137 Diag(PointOfInstantiation, diag::warn_func_template_missing)
4138 << Function;
4139 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4140 if (getLangOpts().CPlusPlus11)
4141 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4142 << Function;
4143 }
4144 }
4145
4146 return;
4147 }
4148
4149 // Postpone late parsed template instantiations.
4150 if (PatternDecl->isLateTemplateParsed() &&
12
Assuming the condition is false
4151 !LateTemplateParser) {
4152 Function->setInstantiationIsPending(true);
4153 LateParsedInstantiations.push_back(
4154 std::make_pair(Function, PointOfInstantiation));
4155 return;
4156 }
4157
4158 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
4159 std::string Name;
4160 llvm::raw_string_ostream OS(Name);
4161 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
4162 /*Qualified=*/true);
4163 return Name;
4164 });
4165
4166 // If we're performing recursive template instantiation, create our own
4167 // queue of pending implicit instantiations that we will instantiate later,
4168 // while we're still within our own instantiation context.
4169 // This has to happen before LateTemplateParser below is called, so that
4170 // it marks vtables used in late parsed templates as used.
4171 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4172 /*Enabled=*/Recursive);
4173 LocalEagerInstantiationScope LocalInstantiations(*this);
4174
4175 // Call the LateTemplateParser callback if there is a need to late parse
4176 // a templated function definition.
4177 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
4178 LateTemplateParser) {
4179 // FIXME: Optimize to allow individual templates to be deserialized.
4180 if (PatternDecl->isFromASTFile())
4181 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
4182
4183 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
4184 assert(LPTIter != LateParsedTemplateMap.end() &&((LPTIter != LateParsedTemplateMap.end() && "missing LateParsedTemplate"
) ? static_cast<void> (0) : __assert_fail ("LPTIter != LateParsedTemplateMap.end() && \"missing LateParsedTemplate\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4185, __PRETTY_FUNCTION__))
4185 "missing LateParsedTemplate")((LPTIter != LateParsedTemplateMap.end() && "missing LateParsedTemplate"
) ? static_cast<void> (0) : __assert_fail ("LPTIter != LateParsedTemplateMap.end() && \"missing LateParsedTemplate\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4185, __PRETTY_FUNCTION__))
;
4186 LateTemplateParser(OpaqueParser, *LPTIter->second);
4187 Pattern = PatternDecl->getBody(PatternDecl);
4188 }
4189
4190 // Note, we should never try to instantiate a deleted function template.
4191 assert((Pattern || PatternDecl->isDefaulted() ||(((Pattern || PatternDecl->isDefaulted() || PatternDecl->
hasSkippedBody()) && "unexpected kind of function template definition"
) ? static_cast<void> (0) : __assert_fail ("(Pattern || PatternDecl->isDefaulted() || PatternDecl->hasSkippedBody()) && \"unexpected kind of function template definition\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4193, __PRETTY_FUNCTION__))
13
Assuming the condition is false
14
Assuming the condition is true
15
'?' condition is true
4192 PatternDecl->hasSkippedBody()) &&(((Pattern || PatternDecl->isDefaulted() || PatternDecl->
hasSkippedBody()) && "unexpected kind of function template definition"
) ? static_cast<void> (0) : __assert_fail ("(Pattern || PatternDecl->isDefaulted() || PatternDecl->hasSkippedBody()) && \"unexpected kind of function template definition\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4193, __PRETTY_FUNCTION__))
4193 "unexpected kind of function template definition")(((Pattern || PatternDecl->isDefaulted() || PatternDecl->
hasSkippedBody()) && "unexpected kind of function template definition"
) ? static_cast<void> (0) : __assert_fail ("(Pattern || PatternDecl->isDefaulted() || PatternDecl->hasSkippedBody()) && \"unexpected kind of function template definition\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4193, __PRETTY_FUNCTION__))
;
4194
4195 // C++1y [temp.explicit]p10:
4196 // Except for inline functions, declarations with types deduced from their
4197 // initializer or return value, and class template specializations, other
4198 // explicit instantiation declarations have the effect of suppressing the
4199 // implicit instantiation of the entity to which they refer.
4200 if (TSK == TSK_ExplicitInstantiationDeclaration &&
16
Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDeclaration
17
Taking false branch
4201 !PatternDecl->isInlined() &&
4202 !PatternDecl->getReturnType()->getContainedAutoType())
4203 return;
4204
4205 if (PatternDecl->isInlined()) {
18
Assuming the condition is false
19
Taking false branch
4206 // Function, and all later redeclarations of it (from imported modules,
4207 // for instance), are now implicitly inline.
4208 for (auto *D = Function->getMostRecentDecl(); /**/;
4209 D = D->getPreviousDecl()) {
4210 D->setImplicitlyInline();
4211 if (D == Function)
4212 break;
4213 }
4214 }
4215
4216 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
4217 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
20
Assuming the condition is false
21
Assuming the condition is false
22
Taking false branch
4218 return;
4219 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
4220 "instantiating function definition");
4221
4222 // The instantiation is visible here, even if it was first declared in an
4223 // unimported module.
4224 Function->setVisibleDespiteOwningModule();
4225
4226 // Copy the inner loc start from the pattern.
4227 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
4228
4229 EnterExpressionEvaluationContext EvalContext(
4230 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4231
4232 // Introduce a new scope where local variable instantiations will be
4233 // recorded, unless we're actually a member function within a local
4234 // class, in which case we need to merge our results with the parent
4235 // scope (of the enclosing function).
4236 bool MergeWithParentScope = false;
4237 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
23
Taking false branch
4238 MergeWithParentScope = Rec->isLocalClass();
4239
4240 LocalInstantiationScope Scope(*this, MergeWithParentScope);
4241
4242 if (PatternDecl->isDefaulted())
24
Taking false branch
4243 SetDeclDefaulted(Function, PatternDecl->getLocation());
4244 else {
4245 MultiLevelTemplateArgumentList TemplateArgs =
4246 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
4247
4248 // Substitute into the qualifier; we can get a substitution failure here
4249 // through evil use of alias templates.
4250 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
4251 // of the) lexical context of the pattern?
4252 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
4253
4254 ActOnStartOfFunctionDef(nullptr, Function);
4255
4256 // Enter the scope of this instantiation. We don't use
4257 // PushDeclContext because we don't have a scope.
4258 Sema::ContextRAII savedContext(*this, Function);
4259
4260 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
25
Assuming the condition is false
26
Taking false branch
4261 TemplateArgs))
4262 return;
4263
4264 StmtResult Body;
4265 if (PatternDecl->hasSkippedBody()) {
27
Taking true branch
4266 ActOnSkippedFunctionBody(Function);
4267 Body = nullptr;
4268 } else {
4269 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
4270 // If this is a constructor, instantiate the member initializers.
4271 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
4272 TemplateArgs);
4273
4274 // If this is an MS ABI dllexport default constructor, instantiate any
4275 // default arguments.
4276 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4277 Ctor->isDefaultConstructor()) {
4278 InstantiateDefaultCtorDefaultArgs(*this, Ctor);
4279 }
4280 }
4281
4282 // Instantiate the function body.
4283 Body = SubstStmt(Pattern, TemplateArgs);
4284
4285 if (Body.isInvalid())
4286 Function->setInvalidDecl();
4287 }
4288 // FIXME: finishing the function body while in an expression evaluation
4289 // context seems wrong. Investigate more.
4290 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
4291
4292 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
4293
4294 if (auto *Listener = getASTMutationListener())
28
Assuming 'Listener' is null
29
Taking false branch
4295 Listener->FunctionDefinitionInstantiated(Function);
4296
4297 savedContext.pop();
4298 }
4299
4300 DeclGroupRef DG(Function);
4301 Consumer.HandleTopLevelDecl(DG);
4302
4303 // This class may have local implicit instantiations that need to be
4304 // instantiation within this scope.
4305 LocalInstantiations.perform();
4306 Scope.Exit();
4307 GlobalInstantiations.perform();
30
Calling 'GlobalEagerInstantiationScope::perform'
4308}
4309
4310VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
4311 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
4312 const TemplateArgumentList &TemplateArgList,
4313 const TemplateArgumentListInfo &TemplateArgsInfo,
4314 SmallVectorImpl<TemplateArgument> &Converted,
4315 SourceLocation PointOfInstantiation, void *InsertPos,
4316 LateInstantiatedAttrVec *LateAttrs,
4317 LocalInstantiationScope *StartingScope) {
4318 if (FromVar->isInvalidDecl())
4319 return nullptr;
4320
4321 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
4322 if (Inst.isInvalid())
4323 return nullptr;
4324
4325 MultiLevelTemplateArgumentList TemplateArgLists;
4326 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
4327
4328 // Instantiate the first declaration of the variable template: for a partial
4329 // specialization of a static data member template, the first declaration may
4330 // or may not be the declaration in the class; if it's in the class, we want
4331 // to instantiate a member in the class (a declaration), and if it's outside,
4332 // we want to instantiate a definition.
4333 //
4334 // If we're instantiating an explicitly-specialized member template or member
4335 // partial specialization, don't do this. The member specialization completely
4336 // replaces the original declaration in this case.
4337 bool IsMemberSpec = false;
4338 if (VarTemplatePartialSpecializationDecl *PartialSpec =
4339 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
4340 IsMemberSpec = PartialSpec->isMemberSpecialization();
4341 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
4342 IsMemberSpec = FromTemplate->isMemberSpecialization();
4343 if (!IsMemberSpec)
4344 FromVar = FromVar->getFirstDecl();
4345
4346 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
4347 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
4348 MultiLevelList);
4349
4350 // TODO: Set LateAttrs and StartingScope ...
4351
4352 return cast_or_null<VarTemplateSpecializationDecl>(
4353 Instantiator.VisitVarTemplateSpecializationDecl(
4354 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
4355}
4356
4357/// Instantiates a variable template specialization by completing it
4358/// with appropriate type information and initializer.
4359VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
4360 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
4361 const MultiLevelTemplateArgumentList &TemplateArgs) {
4362 assert(PatternDecl->isThisDeclarationADefinition() &&((PatternDecl->isThisDeclarationADefinition() && "don't have a definition to instantiate from"
) ? static_cast<void> (0) : __assert_fail ("PatternDecl->isThisDeclarationADefinition() && \"don't have a definition to instantiate from\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4363, __PRETTY_FUNCTION__))
4363 "don't have a definition to instantiate from")((PatternDecl->isThisDeclarationADefinition() && "don't have a definition to instantiate from"
) ? static_cast<void> (0) : __assert_fail ("PatternDecl->isThisDeclarationADefinition() && \"don't have a definition to instantiate from\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4363, __PRETTY_FUNCTION__))
;
4364
4365 // Do substitution on the type of the declaration
4366 TypeSourceInfo *DI =
4367 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
4368 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
4369 if (!DI)
4370 return nullptr;
4371
4372 // Update the type of this variable template specialization.
4373 VarSpec->setType(DI->getType());
4374
4375 // Convert the declaration into a definition now.
4376 VarSpec->setCompleteDefinition();
4377
4378 // Instantiate the initializer.
4379 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
4380
4381 return VarSpec;
4382}
4383
4384/// BuildVariableInstantiation - Used after a new variable has been created.
4385/// Sets basic variable data and decides whether to postpone the
4386/// variable instantiation.
4387void Sema::BuildVariableInstantiation(
4388 VarDecl *NewVar, VarDecl *OldVar,
4389 const MultiLevelTemplateArgumentList &TemplateArgs,
4390 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
4391 LocalInstantiationScope *StartingScope,
4392 bool InstantiatingVarTemplate,
4393 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
4394 // Instantiating a partial specialization to produce a partial
4395 // specialization.
4396 bool InstantiatingVarTemplatePartialSpec =
4397 isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
4398 isa<VarTemplatePartialSpecializationDecl>(NewVar);
4399 // Instantiating from a variable template (or partial specialization) to
4400 // produce a variable template specialization.
4401 bool InstantiatingSpecFromTemplate =
4402 isa<VarTemplateSpecializationDecl>(NewVar) &&
4403 (OldVar->getDescribedVarTemplate() ||
4404 isa<VarTemplatePartialSpecializationDecl>(OldVar));
4405
4406 // If we are instantiating a local extern declaration, the
4407 // instantiation belongs lexically to the containing function.
4408 // If we are instantiating a static data member defined
4409 // out-of-line, the instantiation will have the same lexical
4410 // context (which will be a namespace scope) as the template.
4411 if (OldVar->isLocalExternDecl()) {
4412 NewVar->setLocalExternDecl();
4413 NewVar->setLexicalDeclContext(Owner);
4414 } else if (OldVar->isOutOfLine())
4415 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
4416 NewVar->setTSCSpec(OldVar->getTSCSpec());
4417 NewVar->setInitStyle(OldVar->getInitStyle());
4418 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
4419 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
4420 NewVar->setConstexpr(OldVar->isConstexpr());
4421 NewVar->setInitCapture(OldVar->isInitCapture());
4422 NewVar->setPreviousDeclInSameBlockScope(
4423 OldVar->isPreviousDeclInSameBlockScope());
4424 NewVar->setAccess(OldVar->getAccess());
4425
4426 if (!OldVar->isStaticDataMember()) {
4427 if (OldVar->isUsed(false))
4428 NewVar->setIsUsed();
4429 NewVar->setReferenced(OldVar->isReferenced());
4430 }
4431
4432 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
4433
4434 LookupResult Previous(
4435 *this, NewVar->getDeclName(), NewVar->getLocation(),
4436 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
4437 : Sema::LookupOrdinaryName,
4438 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
4439 : forRedeclarationInCurContext());
4440
4441 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
4442 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
4443 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
4444 // We have a previous declaration. Use that one, so we merge with the
4445 // right type.
4446 if (NamedDecl *NewPrev = FindInstantiatedDecl(
4447 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
4448 Previous.addDecl(NewPrev);
4449 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
4450 OldVar->hasLinkage()) {
4451 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
4452 } else if (PrevDeclForVarTemplateSpecialization) {
4453 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
4454 }
4455 CheckVariableDeclaration(NewVar, Previous);
4456
4457 if (!InstantiatingVarTemplate) {
4458 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
4459 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
4460 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
4461 }
4462
4463 if (!OldVar->isOutOfLine()) {
4464 if (NewVar->getDeclContext()->isFunctionOrMethod())
4465 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
4466 }
4467
4468 // Link instantiations of static data members back to the template from
4469 // which they were instantiated.
4470 //
4471 // Don't do this when instantiating a template (we link the template itself
4472 // back in that case) nor when instantiating a static data member template
4473 // (that's not a member specialization).
4474 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
4475 !InstantiatingSpecFromTemplate)
4476 NewVar->setInstantiationOfStaticDataMember(OldVar,
4477 TSK_ImplicitInstantiation);
4478
4479 // If the pattern is an (in-class) explicit specialization, then the result
4480 // is also an explicit specialization.
4481 if (VarTemplateSpecializationDecl *OldVTSD =
4482 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
4483 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
4484 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
4485 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
4486 TSK_ExplicitSpecialization);
4487 }
4488
4489 // Forward the mangling number from the template to the instantiated decl.
4490 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
4491 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
4492
4493 // Figure out whether to eagerly instantiate the initializer.
4494 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
4495 // We're producing a template. Don't instantiate the initializer yet.
4496 } else if (NewVar->getType()->isUndeducedType()) {
4497 // We need the type to complete the declaration of the variable.
4498 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4499 } else if (InstantiatingSpecFromTemplate ||
4500 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
4501 !NewVar->isThisDeclarationADefinition())) {
4502 // Delay instantiation of the initializer for variable template
4503 // specializations or inline static data members until a definition of the
4504 // variable is needed.
4505 } else {
4506 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4507 }
4508
4509 // Diagnose unused local variables with dependent types, where the diagnostic
4510 // will have been deferred.
4511 if (!NewVar->isInvalidDecl() &&
4512 NewVar->getDeclContext()->isFunctionOrMethod() &&
4513 OldVar->getType()->isDependentType())
4514 DiagnoseUnusedDecl(NewVar);
4515}
4516
4517/// Instantiate the initializer of a variable.
4518void Sema::InstantiateVariableInitializer(
4519 VarDecl *Var, VarDecl *OldVar,
4520 const MultiLevelTemplateArgumentList &TemplateArgs) {
4521 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4522 L->VariableDefinitionInstantiated(Var);
4523
4524 // We propagate the 'inline' flag with the initializer, because it
4525 // would otherwise imply that the variable is a definition for a
4526 // non-static data member.
4527 if (OldVar->isInlineSpecified())
4528 Var->setInlineSpecified();
4529 else if (OldVar->isInline())
4530 Var->setImplicitlyInline();
4531
4532 if (OldVar->getInit()) {
4533 EnterExpressionEvaluationContext Evaluated(
4534 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
4535
4536 // Instantiate the initializer.
4537 ExprResult Init;
4538
4539 {
4540 ContextRAII SwitchContext(*this, Var->getDeclContext());
4541 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
4542 OldVar->getInitStyle() == VarDecl::CallInit);
4543 }
4544
4545 if (!Init.isInvalid()) {
4546 Expr *InitExpr = Init.get();
4547
4548 if (Var->hasAttr<DLLImportAttr>() &&
4549 (!InitExpr ||
4550 !InitExpr->isConstantInitializer(getASTContext(), false))) {
4551 // Do not dynamically initialize dllimport variables.
4552 } else if (InitExpr) {
4553 bool DirectInit = OldVar->isDirectInit();
4554 AddInitializerToDecl(Var, InitExpr, DirectInit);
4555 } else
4556 ActOnUninitializedDecl(Var);
4557 } else {
4558 // FIXME: Not too happy about invalidating the declaration
4559 // because of a bogus initializer.
4560 Var->setInvalidDecl();
4561 }
4562 } else {
4563 // `inline` variables are a definition and declaration all in one; we won't
4564 // pick up an initializer from anywhere else.
4565 if (Var->isStaticDataMember() && !Var->isInline()) {
4566 if (!Var->isOutOfLine())
4567 return;
4568
4569 // If the declaration inside the class had an initializer, don't add
4570 // another one to the out-of-line definition.
4571 if (OldVar->getFirstDecl()->hasInit())
4572 return;
4573 }
4574
4575 // We'll add an initializer to a for-range declaration later.
4576 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
4577 return;
4578
4579 ActOnUninitializedDecl(Var);
4580 }
4581
4582 if (getLangOpts().CUDA)
4583 checkAllowedCUDAInitializer(Var);
4584}
4585
4586/// Instantiate the definition of the given variable from its
4587/// template.
4588///
4589/// \param PointOfInstantiation the point at which the instantiation was
4590/// required. Note that this is not precisely a "point of instantiation"
4591/// for the variable, but it's close.
4592///
4593/// \param Var the already-instantiated declaration of a templated variable.
4594///
4595/// \param Recursive if true, recursively instantiates any functions that
4596/// are required by this instantiation.
4597///
4598/// \param DefinitionRequired if true, then we are performing an explicit
4599/// instantiation where a definition of the variable is required. Complain
4600/// if there is no such definition.
4601void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
4602 VarDecl *Var, bool Recursive,
4603 bool DefinitionRequired, bool AtEndOfTU) {
4604 if (Var->isInvalidDecl())
48
Assuming the condition is false
49
Taking false branch
4605 return;
4606
4607 // Never instantiate an explicitly-specialized entity.
4608 TemplateSpecializationKind TSK =
4609 Var->getTemplateSpecializationKindForInstantiation();
4610 if (TSK == TSK_ExplicitSpecialization)
50
Assuming 'TSK' is not equal to TSK_ExplicitSpecialization
51
Taking false branch
4611 return;
4612
4613 // Find the pattern and the arguments to substitute into it.
4614 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
4615 assert(PatternDecl && "no pattern for templated variable")((PatternDecl && "no pattern for templated variable")
? static_cast<void> (0) : __assert_fail ("PatternDecl && \"no pattern for templated variable\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4615, __PRETTY_FUNCTION__))
;
52
Assuming 'PatternDecl' is non-null
53
'?' condition is true
4616 MultiLevelTemplateArgumentList TemplateArgs =
4617 getTemplateInstantiationArgs(Var);
4618
4619 VarTemplateSpecializationDecl *VarSpec =
4620 dyn_cast<VarTemplateSpecializationDecl>(Var);
4621 if (VarSpec) {
54
Assuming 'VarSpec' is null
55
Taking false branch
4622 // If this is a variable template specialization, make sure that it is
4623 // non-dependent.
4624 bool InstantiationDependent = false;
4625 assert(!TemplateSpecializationType::anyDependentTemplateArguments(((!TemplateSpecializationType::anyDependentTemplateArguments(
VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
"Only instantiate variable template specializations that are "
"not type-dependent") ? static_cast<void> (0) : __assert_fail
("!TemplateSpecializationType::anyDependentTemplateArguments( VarSpec->getTemplateArgsInfo(), InstantiationDependent) && \"Only instantiate variable template specializations that are \" \"not type-dependent\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4628, __PRETTY_FUNCTION__))
4626 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&((!TemplateSpecializationType::anyDependentTemplateArguments(
VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
"Only instantiate variable template specializations that are "
"not type-dependent") ? static_cast<void> (0) : __assert_fail
("!TemplateSpecializationType::anyDependentTemplateArguments( VarSpec->getTemplateArgsInfo(), InstantiationDependent) && \"Only instantiate variable template specializations that are \" \"not type-dependent\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4628, __PRETTY_FUNCTION__))
4627 "Only instantiate variable template specializations that are "((!TemplateSpecializationType::anyDependentTemplateArguments(
VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
"Only instantiate variable template specializations that are "
"not type-dependent") ? static_cast<void> (0) : __assert_fail
("!TemplateSpecializationType::anyDependentTemplateArguments( VarSpec->getTemplateArgsInfo(), InstantiationDependent) && \"Only instantiate variable template specializations that are \" \"not type-dependent\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4628, __PRETTY_FUNCTION__))
4628 "not type-dependent")((!TemplateSpecializationType::anyDependentTemplateArguments(
VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
"Only instantiate variable template specializations that are "
"not type-dependent") ? static_cast<void> (0) : __assert_fail
("!TemplateSpecializationType::anyDependentTemplateArguments( VarSpec->getTemplateArgsInfo(), InstantiationDependent) && \"Only instantiate variable template specializations that are \" \"not type-dependent\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4628, __PRETTY_FUNCTION__))
;
4629 (void)InstantiationDependent;
4630
4631 // If this is a static data member template, there might be an
4632 // uninstantiated initializer on the declaration. If so, instantiate
4633 // it now.
4634 //
4635 // FIXME: This largely duplicates what we would do below. The difference
4636 // is that along this path we may instantiate an initializer from an
4637 // in-class declaration of the template and instantiate the definition
4638 // from a separate out-of-class definition.
4639 if (PatternDecl->isStaticDataMember() &&
4640 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
4641 !Var->hasInit()) {
4642 // FIXME: Factor out the duplicated instantiation context setup/tear down
4643 // code here.
4644 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4645 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4646 return;
4647 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
4648 "instantiating variable initializer");
4649
4650 // The instantiation is visible here, even if it was first declared in an
4651 // unimported module.
4652 Var->setVisibleDespiteOwningModule();
4653
4654 // If we're performing recursive template instantiation, create our own
4655 // queue of pending implicit instantiations that we will instantiate
4656 // later, while we're still within our own instantiation context.
4657 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4658 /*Enabled=*/Recursive);
4659 LocalInstantiationScope Local(*this);
4660 LocalEagerInstantiationScope LocalInstantiations(*this);
4661
4662 // Enter the scope of this instantiation. We don't use
4663 // PushDeclContext because we don't have a scope.
4664 ContextRAII PreviousContext(*this, Var->getDeclContext());
4665 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
4666 PreviousContext.pop();
4667
4668 // This variable may have local implicit instantiations that need to be
4669 // instantiated within this scope.
4670 LocalInstantiations.perform();
4671 Local.Exit();
4672 GlobalInstantiations.perform();
4673 }
4674 } else {
4675 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&((Var->isStaticDataMember() && PatternDecl->isStaticDataMember
() && "not a static data member?") ? static_cast<void
> (0) : __assert_fail ("Var->isStaticDataMember() && PatternDecl->isStaticDataMember() && \"not a static data member?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4676, __PRETTY_FUNCTION__))
56
Assuming the condition is true
57
Assuming the condition is true
58
'?' condition is true
4676 "not a static data member?")((Var->isStaticDataMember() && PatternDecl->isStaticDataMember
() && "not a static data member?") ? static_cast<void
> (0) : __assert_fail ("Var->isStaticDataMember() && PatternDecl->isStaticDataMember() && \"not a static data member?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4676, __PRETTY_FUNCTION__))
;
4677 }
4678
4679 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
59
'Def' initialized here
4680
4681 // If we don't have a definition of the variable template, we won't perform
4682 // any instantiation. Rather, we rely on the user to instantiate this
4683 // definition (or provide a specialization for it) in another translation
4684 // unit.
4685 if (!Def && !DefinitionRequired) {
60
Assuming 'Def' is null
61
Assuming pointer value is null
62
Taking true branch
4686 if (TSK == TSK_ExplicitInstantiationDefinition) {
63
Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDefinition
64
Taking false branch
4687 PendingInstantiations.push_back(
4688 std::make_pair(Var, PointOfInstantiation));
4689 } else if (TSK == TSK_ImplicitInstantiation) {
65
Assuming 'TSK' is not equal to TSK_ImplicitInstantiation
66
Taking false branch
4690 // Warn about missing definition at the end of translation unit.
4691 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4692 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4693 Diag(PointOfInstantiation, diag::warn_var_template_missing)
4694 << Var;
4695 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4696 if (getLangOpts().CPlusPlus11)
4697 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
4698 }
4699 return;
4700 }
4701 }
4702
4703 // FIXME: We need to track the instantiation stack in order to know which
4704 // definitions should be visible within this instantiation.
4705 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
4706 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
67
Assuming the condition is false
68
Taking false branch
4707 /*InstantiatedFromMember*/false,
4708 PatternDecl, Def, TSK,
4709 /*Complain*/DefinitionRequired))
4710 return;
4711
4712 // C++11 [temp.explicit]p10:
4713 // Except for inline functions, const variables of literal types, variables
4714 // of reference types, [...] explicit instantiation declarations
4715 // have the effect of suppressing the implicit instantiation of the entity
4716 // to which they refer.
4717 if (TSK == TSK_ExplicitInstantiationDeclaration &&
69
Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDeclaration
4718 !Var->isUsableInConstantExpressions(getASTContext()))
4719 return;
4720
4721 // Make sure to pass the instantiated variable to the consumer at the end.
4722 struct PassToConsumerRAII {
4723 ASTConsumer &Consumer;
4724 VarDecl *Var;
4725
4726 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
4727 : Consumer(Consumer), Var(Var) { }
4728
4729 ~PassToConsumerRAII() {
4730 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
4731 }
4732 } PassToConsumerRAII(Consumer, Var);
4733
4734 // If we already have a definition, we're done.
4735 if (VarDecl *Def = Var->getDefinition()) {
70
Assuming 'Def' is null
71
Taking false branch
4736 // We may be explicitly instantiating something we've already implicitly
4737 // instantiated.
4738 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
4739 PointOfInstantiation);
4740 return;
4741 }
4742
4743 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4744 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
72
Assuming the condition is false
73
Assuming the condition is false
74
Taking false branch
4745 return;
4746 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
4747 "instantiating variable definition");
4748
4749 // If we're performing recursive template instantiation, create our own
4750 // queue of pending implicit instantiations that we will instantiate later,
4751 // while we're still within our own instantiation context.
4752 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4753 /*Enabled=*/Recursive);
4754
4755 // Enter the scope of this instantiation. We don't use
4756 // PushDeclContext because we don't have a scope.
4757 ContextRAII PreviousContext(*this, Var->getDeclContext());
4758 LocalInstantiationScope Local(*this);
4759
4760 LocalEagerInstantiationScope LocalInstantiations(*this);
4761
4762 VarDecl *OldVar = Var;
4763 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
75
Called C++ object pointer is null
4764 // We're instantiating an inline static data member whose definition was
4765 // provided inside the class.
4766 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4767 } else if (!VarSpec) {
4768 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
4769 TemplateArgs));
4770 } else if (Var->isStaticDataMember() &&
4771 Var->getLexicalDeclContext()->isRecord()) {
4772 // We need to instantiate the definition of a static data member template,
4773 // and all we have is the in-class declaration of it. Instantiate a separate
4774 // declaration of the definition.
4775 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
4776 TemplateArgs);
4777 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
4778 VarSpec->getSpecializedTemplate(), Def, nullptr,
4779 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
4780 if (Var) {
4781 llvm::PointerUnion<VarTemplateDecl *,
4782 VarTemplatePartialSpecializationDecl *> PatternPtr =
4783 VarSpec->getSpecializedTemplateOrPartial();
4784 if (VarTemplatePartialSpecializationDecl *Partial =
4785 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
4786 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
4787 Partial, &VarSpec->getTemplateInstantiationArgs());
4788
4789 // Merge the definition with the declaration.
4790 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
4791 LookupOrdinaryName, forRedeclarationInCurContext());
4792 R.addDecl(OldVar);
4793 MergeVarDecl(Var, R);
4794
4795 // Attach the initializer.
4796 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4797 }
4798 } else
4799 // Complete the existing variable's definition with an appropriately
4800 // substituted type and initializer.
4801 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
4802
4803 PreviousContext.pop();
4804
4805 if (Var) {
4806 PassToConsumerRAII.Var = Var;
4807 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
4808 OldVar->getPointOfInstantiation());
4809 }
4810
4811 // This variable may have local implicit instantiations that need to be
4812 // instantiated within this scope.
4813 LocalInstantiations.perform();
4814 Local.Exit();
4815 GlobalInstantiations.perform();
4816}
4817
4818void
4819Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
4820 const CXXConstructorDecl *Tmpl,
4821 const MultiLevelTemplateArgumentList &TemplateArgs) {
4822
4823 SmallVector<CXXCtorInitializer*, 4> NewInits;
4824 bool AnyErrors = Tmpl->isInvalidDecl();
4825
4826 // Instantiate all the initializers.
4827 for (const auto *Init : Tmpl->inits()) {
4828 // Only instantiate written initializers, let Sema re-construct implicit
4829 // ones.
4830 if (!Init->isWritten())
4831 continue;
4832
4833 SourceLocation EllipsisLoc;
4834
4835 if (Init->isPackExpansion()) {
4836 // This is a pack expansion. We should expand it now.
4837 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
4838 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4839 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
4840 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
4841 bool ShouldExpand = false;
4842 bool RetainExpansion = false;
4843 Optional<unsigned> NumExpansions;
4844 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
4845 BaseTL.getSourceRange(),
4846 Unexpanded,
4847 TemplateArgs, ShouldExpand,
4848 RetainExpansion,
4849 NumExpansions)) {
4850 AnyErrors = true;
4851 New->setInvalidDecl();
4852 continue;
4853 }
4854 assert(ShouldExpand && "Partial instantiation of base initializer?")((ShouldExpand && "Partial instantiation of base initializer?"
) ? static_cast<void> (0) : __assert_fail ("ShouldExpand && \"Partial instantiation of base initializer?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4854, __PRETTY_FUNCTION__))
;
4855
4856 // Loop over all of the arguments in the argument pack(s),
4857 for (unsigned I = 0; I != *NumExpansions; ++I) {
4858 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4859
4860 // Instantiate the initializer.
4861 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4862 /*CXXDirectInit=*/true);
4863 if (TempInit.isInvalid()) {
4864 AnyErrors = true;
4865 break;
4866 }
4867
4868 // Instantiate the base type.
4869 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
4870 TemplateArgs,
4871 Init->getSourceLocation(),
4872 New->getDeclName());
4873 if (!BaseTInfo) {
4874 AnyErrors = true;
4875 break;
4876 }
4877
4878 // Build the initializer.
4879 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
4880 BaseTInfo, TempInit.get(),
4881 New->getParent(),
4882 SourceLocation());
4883 if (NewInit.isInvalid()) {
4884 AnyErrors = true;
4885 break;
4886 }
4887
4888 NewInits.push_back(NewInit.get());
4889 }
4890
4891 continue;
4892 }
4893
4894 // Instantiate the initializer.
4895 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4896 /*CXXDirectInit=*/true);
4897 if (TempInit.isInvalid()) {
4898 AnyErrors = true;
4899 continue;
4900 }
4901
4902 MemInitResult NewInit;
4903 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4904 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4905 TemplateArgs,
4906 Init->getSourceLocation(),
4907 New->getDeclName());
4908 if (!TInfo) {
4909 AnyErrors = true;
4910 New->setInvalidDecl();
4911 continue;
4912 }
4913
4914 if (Init->isBaseInitializer())
4915 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
4916 New->getParent(), EllipsisLoc);
4917 else
4918 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
4919 cast<CXXRecordDecl>(CurContext->getParent()));
4920 } else if (Init->isMemberInitializer()) {
4921 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
4922 Init->getMemberLocation(),
4923 Init->getMember(),
4924 TemplateArgs));
4925 if (!Member) {
4926 AnyErrors = true;
4927 New->setInvalidDecl();
4928 continue;
4929 }
4930
4931 NewInit = BuildMemberInitializer(Member, TempInit.get(),
4932 Init->getSourceLocation());
4933 } else if (Init->isIndirectMemberInitializer()) {
4934 IndirectFieldDecl *IndirectMember =
4935 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
4936 Init->getMemberLocation(),
4937 Init->getIndirectMember(), TemplateArgs));
4938
4939 if (!IndirectMember) {
4940 AnyErrors = true;
4941 New->setInvalidDecl();
4942 continue;
4943 }
4944
4945 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
4946 Init->getSourceLocation());
4947 }
4948
4949 if (NewInit.isInvalid()) {
4950 AnyErrors = true;
4951 New->setInvalidDecl();
4952 } else {
4953 NewInits.push_back(NewInit.get());
4954 }
4955 }
4956
4957 // Assign all the initializers to the new constructor.
4958 ActOnMemInitializers(New,
4959 /*FIXME: ColonLoc */
4960 SourceLocation(),
4961 NewInits,
4962 AnyErrors);
4963}
4964
4965// TODO: this could be templated if the various decl types used the
4966// same method name.
4967static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4968 ClassTemplateDecl *Instance) {
4969 Pattern = Pattern->getCanonicalDecl();
4970
4971 do {
4972 Instance = Instance->getCanonicalDecl();
4973 if (Pattern == Instance) return true;
4974 Instance = Instance->getInstantiatedFromMemberTemplate();
4975 } while (Instance);
4976
4977 return false;
4978}
4979
4980static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4981 FunctionTemplateDecl *Instance) {
4982 Pattern = Pattern->getCanonicalDecl();
4983
4984 do {
4985 Instance = Instance->getCanonicalDecl();
4986 if (Pattern == Instance) return true;
4987 Instance = Instance->getInstantiatedFromMemberTemplate();
4988 } while (Instance);
4989
4990 return false;
4991}
4992
4993static bool
4994isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4995 ClassTemplatePartialSpecializationDecl *Instance) {
4996 Pattern
4997 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4998 do {
4999 Instance = cast<ClassTemplatePartialSpecializationDecl>(
5000 Instance->getCanonicalDecl());
5001 if (Pattern == Instance)
5002 return true;
5003 Instance = Instance->getInstantiatedFromMember();
5004 } while (Instance);
5005
5006 return false;
5007}
5008
5009static bool isInstantiationOf(CXXRecordDecl *Pattern,
5010 CXXRecordDecl *Instance) {
5011 Pattern = Pattern->getCanonicalDecl();
5012
5013 do {
5014 Instance = Instance->getCanonicalDecl();
5015 if (Pattern == Instance) return true;
5016 Instance = Instance->getInstantiatedFromMemberClass();
5017 } while (Instance);
5018
5019 return false;
5020}
5021
5022static bool isInstantiationOf(FunctionDecl *Pattern,
5023 FunctionDecl *Instance) {
5024 Pattern = Pattern->getCanonicalDecl();
5025
5026 do {
5027 Instance = Instance->getCanonicalDecl();
5028 if (Pattern == Instance) return true;
5029 Instance = Instance->getInstantiatedFromMemberFunction();
5030 } while (Instance);
5031
5032 return false;
5033}
5034
5035static bool isInstantiationOf(EnumDecl *Pattern,
5036 EnumDecl *Instance) {
5037 Pattern = Pattern->getCanonicalDecl();
5038
5039 do {
5040 Instance = Instance->getCanonicalDecl();
5041 if (Pattern == Instance) return true;
5042 Instance = Instance->getInstantiatedFromMemberEnum();
5043 } while (Instance);
5044
5045 return false;
5046}
5047
5048static bool isInstantiationOf(UsingShadowDecl *Pattern,
5049 UsingShadowDecl *Instance,
5050 ASTContext &C) {
5051 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
5052 Pattern);
5053}
5054
5055static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
5056 ASTContext &C) {
5057 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
5058}
5059
5060template<typename T>
5061static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
5062 ASTContext &Ctx) {
5063 // An unresolved using declaration can instantiate to an unresolved using
5064 // declaration, or to a using declaration or a using declaration pack.
5065 //
5066 // Multiple declarations can claim to be instantiated from an unresolved
5067 // using declaration if it's a pack expansion. We want the UsingPackDecl
5068 // in that case, not the individual UsingDecls within the pack.
5069 bool OtherIsPackExpansion;
5070 NamedDecl *OtherFrom;
5071 if (auto *OtherUUD = dyn_cast<T>(Other)) {
5072 OtherIsPackExpansion = OtherUUD->isPackExpansion();
5073 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
5074 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
5075 OtherIsPackExpansion = true;
5076 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
5077 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
5078 OtherIsPackExpansion = false;
5079 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
5080 } else {
5081 return false;
5082 }
5083 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
5084 declaresSameEntity(OtherFrom, Pattern);
5085}
5086
5087static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
5088 VarDecl *Instance) {
5089 assert(Instance->isStaticDataMember())((Instance->isStaticDataMember()) ? static_cast<void>
(0) : __assert_fail ("Instance->isStaticDataMember()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5089, __PRETTY_FUNCTION__))
;
5090
5091 Pattern = Pattern->getCanonicalDecl();
5092
5093 do {
5094 Instance = Instance->getCanonicalDecl();
5095 if (Pattern == Instance) return true;
5096 Instance = Instance->getInstantiatedFromStaticDataMember();
5097 } while (Instance);
5098
5099 return false;
5100}
5101
5102// Other is the prospective instantiation
5103// D is the prospective pattern
5104static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
5105 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
5106 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5107
5108 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
5109 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5110
5111 if (D->getKind() != Other->getKind())
5112 return false;
5113
5114 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
5115 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
5116
5117 if (auto *Function = dyn_cast<FunctionDecl>(Other))
5118 return isInstantiationOf(cast<FunctionDecl>(D), Function);
5119
5120 if (auto *Enum = dyn_cast<EnumDecl>(Other))
5121 return isInstantiationOf(cast<EnumDecl>(D), Enum);
5122
5123 if (auto *Var = dyn_cast<VarDecl>(Other))
5124 if (Var->isStaticDataMember())
5125 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
5126
5127 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
5128 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
5129
5130 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
5131 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
5132
5133 if (auto *PartialSpec =
5134 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
5135 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
5136 PartialSpec);
5137
5138 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
5139 if (!Field->getDeclName()) {
5140 // This is an unnamed field.
5141 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
5142 cast<FieldDecl>(D));
5143 }
5144 }
5145
5146 if (auto *Using = dyn_cast<UsingDecl>(Other))
5147 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
5148
5149 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
5150 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
5151
5152 return D->getDeclName() &&
5153 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
5154}
5155
5156template<typename ForwardIterator>
5157static NamedDecl *findInstantiationOf(ASTContext &Ctx,
5158 NamedDecl *D,
5159 ForwardIterator first,
5160 ForwardIterator last) {
5161 for (; first != last; ++first)
5162 if (isInstantiationOf(Ctx, D, *first))
5163 return cast<NamedDecl>(*first);
5164
5165 return nullptr;
5166}
5167
5168/// Finds the instantiation of the given declaration context
5169/// within the current instantiation.
5170///
5171/// \returns NULL if there was an error
5172DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
5173 const MultiLevelTemplateArgumentList &TemplateArgs) {
5174 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
5175 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
5176 return cast_or_null<DeclContext>(ID);
5177 } else return DC;
5178}
5179
5180/// Find the instantiation of the given declaration within the
5181/// current instantiation.
5182///
5183/// This routine is intended to be used when \p D is a declaration
5184/// referenced from within a template, that needs to mapped into the
5185/// corresponding declaration within an instantiation. For example,
5186/// given:
5187///
5188/// \code
5189/// template<typename T>
5190/// struct X {
5191/// enum Kind {
5192/// KnownValue = sizeof(T)
5193/// };
5194///
5195/// bool getKind() const { return KnownValue; }
5196/// };
5197///
5198/// template struct X<int>;
5199/// \endcode
5200///
5201/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
5202/// \p EnumConstantDecl for \p KnownValue (which refers to
5203/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
5204/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
5205/// this mapping from within the instantiation of <tt>X<int></tt>.
5206NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
5207 const MultiLevelTemplateArgumentList &TemplateArgs,
5208 bool FindingInstantiatedContext) {
5209 DeclContext *ParentDC = D->getDeclContext();
5210 // FIXME: Parmeters of pointer to functions (y below) that are themselves
5211 // parameters (p below) can have their ParentDC set to the translation-unit
5212 // - thus we can not consistently check if the ParentDC of such a parameter
5213 // is Dependent or/and a FunctionOrMethod.
5214 // For e.g. this code, during Template argument deduction tries to
5215 // find an instantiated decl for (T y) when the ParentDC for y is
5216 // the translation unit.
5217 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
5218 // float baz(float(*)()) { return 0.0; }
5219 // Foo(baz);
5220 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
5221 // it gets here, always has a FunctionOrMethod as its ParentDC??
5222 // For now:
5223 // - as long as we have a ParmVarDecl whose parent is non-dependent and
5224 // whose type is not instantiation dependent, do nothing to the decl
5225 // - otherwise find its instantiated decl.
5226 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
5227 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
5228 return D;
5229 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
5230 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
5231 ((ParentDC->isFunctionOrMethod() ||
5232 isa<OMPDeclareReductionDecl>(ParentDC) ||
5233 isa<OMPDeclareMapperDecl>(ParentDC)) &&
5234 ParentDC->isDependentContext()) ||
5235 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
5236 // D is a local of some kind. Look into the map of local
5237 // declarations to their instantiations.
5238 if (CurrentInstantiationScope) {
5239 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
5240 if (Decl *FD = Found->dyn_cast<Decl *>())
5241 return cast<NamedDecl>(FD);
5242
5243 int PackIdx = ArgumentPackSubstitutionIndex;
5244 assert(PackIdx != -1 &&((PackIdx != -1 && "found declaration pack but not pack expanding"
) ? static_cast<void> (0) : __assert_fail ("PackIdx != -1 && \"found declaration pack but not pack expanding\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5245, __PRETTY_FUNCTION__))
5245 "found declaration pack but not pack expanding")((PackIdx != -1 && "found declaration pack but not pack expanding"
) ? static_cast<void> (0) : __assert_fail ("PackIdx != -1 && \"found declaration pack but not pack expanding\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5245, __PRETTY_FUNCTION__))
;
5246 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
5247 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
5248 }
5249 }
5250
5251 // If we're performing a partial substitution during template argument
5252 // deduction, we may not have values for template parameters yet. They
5253 // just map to themselves.
5254 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
5255 isa<TemplateTemplateParmDecl>(D))
5256 return D;
5257
5258 if (D->isInvalidDecl())
5259 return nullptr;
5260
5261 // Normally this function only searches for already instantiated declaration
5262 // however we have to make an exclusion for local types used before
5263 // definition as in the code:
5264 //
5265 // template<typename T> void f1() {
5266 // void g1(struct x1);
5267 // struct x1 {};
5268 // }
5269 //
5270 // In this case instantiation of the type of 'g1' requires definition of
5271 // 'x1', which is defined later. Error recovery may produce an enum used
5272 // before definition. In these cases we need to instantiate relevant
5273 // declarations here.
5274 bool NeedInstantiate = false;
5275 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5276 NeedInstantiate = RD->isLocalClass();
5277 else
5278 NeedInstantiate = isa<EnumDecl>(D);
5279 if (NeedInstantiate) {
5280 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5281 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5282 return cast<TypeDecl>(Inst);
5283 }
5284
5285 // If we didn't find the decl, then we must have a label decl that hasn't
5286 // been found yet. Lazily instantiate it and return it now.
5287 assert(isa<LabelDecl>(D))((isa<LabelDecl>(D)) ? static_cast<void> (0) : __assert_fail
("isa<LabelDecl>(D)", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5287, __PRETTY_FUNCTION__))
;
5288
5289 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5290 assert(Inst && "Failed to instantiate label??")((Inst && "Failed to instantiate label??") ? static_cast
<void> (0) : __assert_fail ("Inst && \"Failed to instantiate label??\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5290, __PRETTY_FUNCTION__))
;
5291
5292 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5293 return cast<LabelDecl>(Inst);
5294 }
5295
5296 // For variable template specializations, update those that are still
5297 // type-dependent.
5298 if (VarTemplateSpecializationDecl *VarSpec =
5299 dyn_cast<VarTemplateSpecializationDecl>(D)) {
5300 bool InstantiationDependent = false;
5301 const TemplateArgumentListInfo &VarTemplateArgs =
5302 VarSpec->getTemplateArgsInfo();
5303 if (TemplateSpecializationType::anyDependentTemplateArguments(
5304 VarTemplateArgs, InstantiationDependent))
5305 D = cast<NamedDecl>(
5306 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
5307 return D;
5308 }
5309
5310 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
5311 if (!Record->isDependentContext())
5312 return D;
5313
5314 // Determine whether this record is the "templated" declaration describing
5315 // a class template or class template partial specialization.
5316 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
5317 if (ClassTemplate)
5318 ClassTemplate = ClassTemplate->getCanonicalDecl();
5319 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5320 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
5321 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
5322
5323 // Walk the current context to find either the record or an instantiation of
5324 // it.
5325 DeclContext *DC = CurContext;
5326 while (!DC->isFileContext()) {
5327 // If we're performing substitution while we're inside the template
5328 // definition, we'll find our own context. We're done.
5329 if (DC->Equals(Record))
5330 return Record;
5331
5332 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
5333 // Check whether we're in the process of instantiating a class template
5334 // specialization of the template we're mapping.
5335 if (ClassTemplateSpecializationDecl *InstSpec
5336 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
5337 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
5338 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
5339 return InstRecord;
5340 }
5341
5342 // Check whether we're in the process of instantiating a member class.
5343 if (isInstantiationOf(Record, InstRecord))
5344 return InstRecord;
5345 }
5346
5347 // Move to the outer template scope.
5348 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
5349 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
5350 DC = FD->getLexicalDeclContext();
5351 continue;
5352 }
5353 // An implicit deduction guide acts as if it's within the class template
5354 // specialization described by its name and first N template params.
5355 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
5356 if (Guide && Guide->isImplicit()) {
5357 TemplateDecl *TD = Guide->getDeducedTemplate();
5358 // Convert the arguments to an "as-written" list.
5359 TemplateArgumentListInfo Args(Loc, Loc);
5360 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
5361 TD->getTemplateParameters()->size())) {
5362 ArrayRef<TemplateArgument> Unpacked(Arg);
5363 if (Arg.getKind() == TemplateArgument::Pack)
5364 Unpacked = Arg.pack_elements();
5365 for (TemplateArgument UnpackedArg : Unpacked)
5366 Args.addArgument(
5367 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
5368 }
5369 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
5370 if (T.isNull())
5371 return nullptr;
5372 auto *SubstRecord = T->getAsCXXRecordDecl();
5373 assert(SubstRecord && "class template id not a class type?")((SubstRecord && "class template id not a class type?"
) ? static_cast<void> (0) : __assert_fail ("SubstRecord && \"class template id not a class type?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5373, __PRETTY_FUNCTION__))
;
5374 // Check that this template-id names the primary template and not a
5375 // partial or explicit specialization. (In the latter cases, it's
5376 // meaningless to attempt to find an instantiation of D within the
5377 // specialization.)
5378 // FIXME: The standard doesn't say what should happen here.
5379 if (FindingInstantiatedContext &&
5380 usesPartialOrExplicitSpecialization(
5381 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
5382 Diag(Loc, diag::err_specialization_not_primary_template)
5383 << T << (SubstRecord->getTemplateSpecializationKind() ==
5384 TSK_ExplicitSpecialization);
5385 return nullptr;
5386 }
5387 DC = SubstRecord;
5388 continue;
5389 }
5390 }
5391
5392 DC = DC->getParent();
5393 }
5394
5395 // Fall through to deal with other dependent record types (e.g.,
5396 // anonymous unions in class templates).
5397 }
5398
5399 if (!ParentDC->isDependentContext())
5400 return D;
5401
5402 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
5403 if (!ParentDC)
5404 return nullptr;
5405
5406 if (ParentDC != D->getDeclContext()) {
5407 // We performed some kind of instantiation in the parent context,
5408 // so now we need to look into the instantiated parent context to
5409 // find the instantiation of the declaration D.
5410
5411 // If our context used to be dependent, we may need to instantiate
5412 // it before performing lookup into that context.
5413 bool IsBeingInstantiated = false;
5414 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
5415 if (!Spec->isDependentContext()) {
5416 QualType T = Context.getTypeDeclType(Spec);
5417 const RecordType *Tag = T->getAs<RecordType>();
5418 assert(Tag && "type of non-dependent record is not a RecordType")((Tag && "type of non-dependent record is not a RecordType"
) ? static_cast<void> (0) : __assert_fail ("Tag && \"type of non-dependent record is not a RecordType\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5418, __PRETTY_FUNCTION__))
;
5419 if (Tag->isBeingDefined())
5420 IsBeingInstantiated = true;
5421 if (!Tag->isBeingDefined() &&
5422 RequireCompleteType(Loc, T, diag::err_incomplete_type))
5423 return nullptr;
5424
5425 ParentDC = Tag->getDecl();
5426 }
5427 }
5428
5429 NamedDecl *Result = nullptr;
5430 // FIXME: If the name is a dependent name, this lookup won't necessarily
5431 // find it. Does that ever matter?
5432 if (auto Name = D->getDeclName()) {
5433 DeclarationNameInfo NameInfo(Name, D->getLocation());
5434 Name = SubstDeclarationNameInfo(NameInfo, TemplateArgs).getName();
5435 if (!Name)
5436 return nullptr;
5437 DeclContext::lookup_result Found = ParentDC->lookup(Name);
5438 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
5439 } else {
5440 // Since we don't have a name for the entity we're looking for,
5441 // our only option is to walk through all of the declarations to
5442 // find that name. This will occur in a few cases:
5443 //
5444 // - anonymous struct/union within a template
5445 // - unnamed class/struct/union/enum within a template
5446 //
5447 // FIXME: Find a better way to find these instantiations!
5448 Result = findInstantiationOf(Context, D,
5449 ParentDC->decls_begin(),
5450 ParentDC->decls_end());
5451 }
5452
5453 if (!Result) {
5454 if (isa<UsingShadowDecl>(D)) {
5455 // UsingShadowDecls can instantiate to nothing because of using hiding.
5456 } else if (Diags.hasErrorOccurred()) {
5457 // We've already complained about something, so most likely this
5458 // declaration failed to instantiate. There's no point in complaining
5459 // further, since this is normal in invalid code.
5460 } else if (IsBeingInstantiated) {
5461 // The class in which this member exists is currently being
5462 // instantiated, and we haven't gotten around to instantiating this
5463 // member yet. This can happen when the code uses forward declarations
5464 // of member classes, and introduces ordering dependencies via
5465 // template instantiation.
5466 Diag(Loc, diag::err_member_not_yet_instantiated)
5467 << D->getDeclName()
5468 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
5469 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
5470 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
5471 // This enumeration constant was found when the template was defined,
5472 // but can't be found in the instantiation. This can happen if an
5473 // unscoped enumeration member is explicitly specialized.
5474 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
5475 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
5476 TemplateArgs));
5477 assert(Spec->getTemplateSpecializationKind() ==((Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
) ? static_cast<void> (0) : __assert_fail ("Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5478, __PRETTY_FUNCTION__))
5478 TSK_ExplicitSpecialization)((Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
) ? static_cast<void> (0) : __assert_fail ("Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5478, __PRETTY_FUNCTION__))
;
5479 Diag(Loc, diag::err_enumerator_does_not_exist)
5480 << D->getDeclName()
5481 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
5482 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
5483 << Context.getTypeDeclType(Spec);
5484 } else {
5485 // We should have found something, but didn't.
5486 llvm_unreachable("Unable to find instantiation of declaration!")::llvm::llvm_unreachable_internal("Unable to find instantiation of declaration!"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5486)
;
5487 }
5488 }
5489
5490 D = Result;
5491 }
5492
5493 return D;
5494}
5495
5496/// Performs template instantiation for all implicit template
5497/// instantiations we have seen until this point.
5498void Sema::PerformPendingInstantiations(bool LocalOnly) {
5499 while (!PendingLocalImplicitInstantiations.empty() ||
34
Assuming the condition is false
36
Loop condition is true. Entering loop body
5500 (!LocalOnly && !PendingInstantiations.empty())) {
35
Assuming the condition is true
5501 PendingImplicitInstantiation Inst;
5502
5503 if (PendingLocalImplicitInstantiations.empty()) {
37
Assuming the condition is false
38
Taking false branch
5504 Inst = PendingInstantiations.front();
5505 PendingInstantiations.pop_front();
5506 } else {
5507 Inst = PendingLocalImplicitInstantiations.front();
5508 PendingLocalImplicitInstantiations.pop_front();
5509 }
5510
5511 // Instantiate function definitions
5512 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
39
Taking false branch
5513 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
5514 TSK_ExplicitInstantiationDefinition;
5515 if (Function->isMultiVersion()) {
5516 getASTContext().forEachMultiversionedFunctionVersion(
5517 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
5518 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
1
Calling 'Sema::InstantiateFunctionDefinition'
5519 DefinitionRequired, true);
5520 if (CurFD->isDefined())
5521 CurFD->setInstantiationIsPending(false);
5522 });
5523 } else {
5524 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
5525 DefinitionRequired, true);
5526 if (Function->isDefined())
5527 Function->setInstantiationIsPending(false);
5528 }
5529 continue;
5530 }
5531
5532 // Instantiate variable definitions
5533 VarDecl *Var = cast<VarDecl>(Inst.first);
5534
5535 assert((Var->isStaticDataMember() ||(((Var->isStaticDataMember() || isa<VarTemplateSpecializationDecl
>(Var)) && "Not a static data member, nor a variable template"
" specialization?") ? static_cast<void> (0) : __assert_fail
("(Var->isStaticDataMember() || isa<VarTemplateSpecializationDecl>(Var)) && \"Not a static data member, nor a variable template\" \" specialization?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5538, __PRETTY_FUNCTION__))
40
Assuming the condition is true
41
'?' condition is true
5536 isa<VarTemplateSpecializationDecl>(Var)) &&(((Var->isStaticDataMember() || isa<VarTemplateSpecializationDecl
>(Var)) && "Not a static data member, nor a variable template"
" specialization?") ? static_cast<void> (0) : __assert_fail
("(Var->isStaticDataMember() || isa<VarTemplateSpecializationDecl>(Var)) && \"Not a static data member, nor a variable template\" \" specialization?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5538, __PRETTY_FUNCTION__))
5537 "Not a static data member, nor a variable template"(((Var->isStaticDataMember() || isa<VarTemplateSpecializationDecl
>(Var)) && "Not a static data member, nor a variable template"
" specialization?") ? static_cast<void> (0) : __assert_fail
("(Var->isStaticDataMember() || isa<VarTemplateSpecializationDecl>(Var)) && \"Not a static data member, nor a variable template\" \" specialization?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5538, __PRETTY_FUNCTION__))
5538 " specialization?")(((Var->isStaticDataMember() || isa<VarTemplateSpecializationDecl
>(Var)) && "Not a static data member, nor a variable template"
" specialization?") ? static_cast<void> (0) : __assert_fail
("(Var->isStaticDataMember() || isa<VarTemplateSpecializationDecl>(Var)) && \"Not a static data member, nor a variable template\" \" specialization?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5538, __PRETTY_FUNCTION__))
;
5539
5540 // Don't try to instantiate declarations if the most recent redeclaration
5541 // is invalid.
5542 if (Var->getMostRecentDecl()->isInvalidDecl())
42
Assuming the condition is false
43
Taking false branch
5543 continue;
5544
5545 // Check if the most recent declaration has changed the specialization kind
5546 // and removed the need for implicit instantiation.
5547 switch (Var->getMostRecentDecl()
44
Control jumps to 'case TSK_ImplicitInstantiation:' at line 5560
5548 ->getTemplateSpecializationKindForInstantiation()) {
5549 case TSK_Undeclared:
5550 llvm_unreachable("Cannot instantitiate an undeclared specialization.")::llvm::llvm_unreachable_internal("Cannot instantitiate an undeclared specialization."
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5550)
;
5551 case TSK_ExplicitInstantiationDeclaration:
5552 case TSK_ExplicitSpecialization:
5553 continue; // No longer need to instantiate this type.
5554 case TSK_ExplicitInstantiationDefinition:
5555 // We only need an instantiation if the pending instantiation *is* the
5556 // explicit instantiation.
5557 if (Var != Var->getMostRecentDecl())
5558 continue;
5559 break;
5560 case TSK_ImplicitInstantiation:
5561 break;
45
Execution continues on line 5564
5562 }
5563
5564 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5565 "instantiating variable definition");
5566 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
46
Assuming the condition is false
5567 TSK_ExplicitInstantiationDefinition;
5568
5569 // Instantiate static data member definitions or variable template
5570 // specializations.
5571 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
47
Calling 'Sema::InstantiateVariableDefinition'
5572 DefinitionRequired, true);
5573 }
5574}
5575
5576void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
5577 const MultiLevelTemplateArgumentList &TemplateArgs) {
5578 for (auto DD : Pattern->ddiags()) {
5579 switch (DD->getKind()) {
5580 case DependentDiagnostic::Access:
5581 HandleDependentAccessCheck(*DD, TemplateArgs);
5582 break;
5583 }
5584 }
5585}

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