Bug Summary

File:clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 626, column 40
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 SemaDeclCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/EvaluatedExprVisitor.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/AST/RecursiveASTVisitor.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/AST/TypeLoc.h"
26#include "clang/AST/TypeOrdering.h"
27#include "clang/Basic/AttributeCommonInfo.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/LiteralSupport.h"
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
39#include "clang/Sema/SemaInternal.h"
40#include "clang/Sema/Template.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/SmallString.h"
43#include "llvm/ADT/StringExtras.h"
44#include <map>
45#include <set>
46
47using namespace clang;
48
49//===----------------------------------------------------------------------===//
50// CheckDefaultArgumentVisitor
51//===----------------------------------------------------------------------===//
52
53namespace {
54 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
55 /// the default argument of a parameter to determine whether it
56 /// contains any ill-formed subexpressions. For example, this will
57 /// diagnose the use of local variables or parameters within the
58 /// default argument expression.
59 class CheckDefaultArgumentVisitor
60 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
61 Expr *DefaultArg;
62 Sema *S;
63
64 public:
65 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
66 : DefaultArg(defarg), S(s) {}
67
68 bool VisitExpr(Expr *Node);
69 bool VisitDeclRefExpr(DeclRefExpr *DRE);
70 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
71 bool VisitLambdaExpr(LambdaExpr *Lambda);
72 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
73 };
74
75 /// VisitExpr - Visit all of the children of this expression.
76 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
77 bool IsInvalid = false;
78 for (Stmt *SubStmt : Node->children())
79 IsInvalid |= Visit(SubStmt);
80 return IsInvalid;
81 }
82
83 /// VisitDeclRefExpr - Visit a reference to a declaration, to
84 /// determine whether this declaration can be used in the default
85 /// argument expression.
86 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
87 NamedDecl *Decl = DRE->getDecl();
88 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
89 // C++ [dcl.fct.default]p9
90 // Default arguments are evaluated each time the function is
91 // called. The order of evaluation of function arguments is
92 // unspecified. Consequently, parameters of a function shall not
93 // be used in default argument expressions, even if they are not
94 // evaluated. Parameters of a function declared before a default
95 // argument expression are in scope and can hide namespace and
96 // class member names.
97 return S->Diag(DRE->getBeginLoc(),
98 diag::err_param_default_argument_references_param)
99 << Param->getDeclName() << DefaultArg->getSourceRange();
100 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
101 // C++ [dcl.fct.default]p7
102 // Local variables shall not be used in default argument
103 // expressions.
104 if (VDecl->isLocalVarDecl())
105 return S->Diag(DRE->getBeginLoc(),
106 diag::err_param_default_argument_references_local)
107 << VDecl->getDeclName() << DefaultArg->getSourceRange();
108 }
109
110 return false;
111 }
112
113 /// VisitCXXThisExpr - Visit a C++ "this" expression.
114 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
115 // C++ [dcl.fct.default]p8:
116 // The keyword this shall not be used in a default argument of a
117 // member function.
118 return S->Diag(ThisE->getBeginLoc(),
119 diag::err_param_default_argument_references_this)
120 << ThisE->getSourceRange();
121 }
122
123 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
124 bool Invalid = false;
125 for (PseudoObjectExpr::semantics_iterator
126 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
127 Expr *E = *i;
128
129 // Look through bindings.
130 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
131 E = OVE->getSourceExpr();
132 assert(E && "pseudo-object binding without source expression?")((E && "pseudo-object binding without source expression?"
) ? static_cast<void> (0) : __assert_fail ("E && \"pseudo-object binding without source expression?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 132, __PRETTY_FUNCTION__))
;
133 }
134
135 Invalid |= Visit(E);
136 }
137 return Invalid;
138 }
139
140 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
141 // C++11 [expr.lambda.prim]p13:
142 // A lambda-expression appearing in a default argument shall not
143 // implicitly or explicitly capture any entity.
144 if (Lambda->capture_begin() == Lambda->capture_end())
145 return false;
146
147 return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
148 }
149}
150
151void
152Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
153 const CXXMethodDecl *Method) {
154 // If we have an MSAny spec already, don't bother.
155 if (!Method || ComputedEST == EST_MSAny)
156 return;
157
158 const FunctionProtoType *Proto
159 = Method->getType()->getAs<FunctionProtoType>();
160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
161 if (!Proto)
162 return;
163
164 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165
166 // If we have a throw-all spec at this point, ignore the function.
167 if (ComputedEST == EST_None)
168 return;
169
170 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
171 EST = EST_BasicNoexcept;
172
173 switch (EST) {
174 case EST_Unparsed:
175 case EST_Uninstantiated:
176 case EST_Unevaluated:
177 llvm_unreachable("should not see unresolved exception specs here")::llvm::llvm_unreachable_internal("should not see unresolved exception specs here"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 177)
;
178
179 // If this function can throw any exceptions, make a note of that.
180 case EST_MSAny:
181 case EST_None:
182 // FIXME: Whichever we see last of MSAny and None determines our result.
183 // We should make a consistent, order-independent choice here.
184 ClearExceptions();
185 ComputedEST = EST;
186 return;
187 case EST_NoexceptFalse:
188 ClearExceptions();
189 ComputedEST = EST_None;
190 return;
191 // FIXME: If the call to this decl is using any of its default arguments, we
192 // need to search them for potentially-throwing calls.
193 // If this function has a basic noexcept, it doesn't affect the outcome.
194 case EST_BasicNoexcept:
195 case EST_NoexceptTrue:
196 case EST_NoThrow:
197 return;
198 // If we're still at noexcept(true) and there's a throw() callee,
199 // change to that specification.
200 case EST_DynamicNone:
201 if (ComputedEST == EST_BasicNoexcept)
202 ComputedEST = EST_DynamicNone;
203 return;
204 case EST_DependentNoexcept:
205 llvm_unreachable(::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 206)
206 "should not generate implicit declarations for dependent cases")::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 206)
;
207 case EST_Dynamic:
208 break;
209 }
210 assert(EST == EST_Dynamic && "EST case not considered earlier.")((EST == EST_Dynamic && "EST case not considered earlier."
) ? static_cast<void> (0) : __assert_fail ("EST == EST_Dynamic && \"EST case not considered earlier.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 210, __PRETTY_FUNCTION__))
;
211 assert(ComputedEST != EST_None &&((ComputedEST != EST_None && "Shouldn't collect exceptions when throw-all is guaranteed."
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 212, __PRETTY_FUNCTION__))
212 "Shouldn't collect exceptions when throw-all is guaranteed.")((ComputedEST != EST_None && "Shouldn't collect exceptions when throw-all is guaranteed."
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 212, __PRETTY_FUNCTION__))
;
213 ComputedEST = EST_Dynamic;
214 // Record the exceptions in this function's exception specification.
215 for (const auto &E : Proto->exceptions())
216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
217 Exceptions.push_back(E);
218}
219
220void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
221 if (!S || ComputedEST == EST_MSAny)
222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
245 if (Self->canThrow(S))
246 ComputedEST = EST_None;
247}
248
249bool
250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
251 SourceLocation EqualLoc) {
252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
270 if (Result.isInvalid())
271 return true;
272 Arg = Result.getAs<Expr>();
273
274 CheckCompletedExpr(Arg, EqualLoc);
275 Arg = MaybeCreateExprWithCleanups(Arg);
276
277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
279
280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
292 return false;
293}
294
295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
298void
299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
302 return;
303
304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
305 UnparsedDefaultArgLocs.erase(Param);
306
307 // Default arguments are only permitted in C++
308 if (!getLangOpts().CPlusPlus) {
309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
311 Param->setInvalidDecl();
312 return;
313 }
314
315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
321 // C++11 [dcl.fct.default]p3
322 // A default argument expression [...] shall not be specified for a
323 // parameter pack.
324 if (Param->isParameterPack()) {
325 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
326 << DefaultArg->getSourceRange();
327 return;
328 }
329
330 // Check that the default argument is well-formed
331 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
332 if (DefaultArgChecker.Visit(DefaultArg)) {
333 Param->setInvalidDecl();
334 return;
335 }
336
337 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
338}
339
340/// ActOnParamUnparsedDefaultArgument - We've seen a default
341/// argument for a function parameter, but we can't parse it yet
342/// because we're inside a class definition. Note that this default
343/// argument will be parsed later.
344void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
345 SourceLocation EqualLoc,
346 SourceLocation ArgLoc) {
347 if (!param)
348 return;
349
350 ParmVarDecl *Param = cast<ParmVarDecl>(param);
351 Param->setUnparsedDefaultArg();
352 UnparsedDefaultArgLocs[Param] = ArgLoc;
353}
354
355/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
356/// the default argument for the parameter param failed.
357void Sema::ActOnParamDefaultArgumentError(Decl *param,
358 SourceLocation EqualLoc) {
359 if (!param)
360 return;
361
362 ParmVarDecl *Param = cast<ParmVarDecl>(param);
363 Param->setInvalidDecl();
364 UnparsedDefaultArgLocs.erase(Param);
365 Param->setDefaultArg(new(Context)
366 OpaqueValueExpr(EqualLoc,
367 Param->getType().getNonReferenceType(),
368 VK_RValue));
369}
370
371/// CheckExtraCXXDefaultArguments - Check for any extra default
372/// arguments in the declarator, which is not a function declaration
373/// or definition and therefore is not permitted to have default
374/// arguments. This routine should be invoked for every declarator
375/// that is not a function declaration or definition.
376void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
377 // C++ [dcl.fct.default]p3
378 // A default argument expression shall be specified only in the
379 // parameter-declaration-clause of a function declaration or in a
380 // template-parameter (14.1). It shall not be specified for a
381 // parameter pack. If it is specified in a
382 // parameter-declaration-clause, it shall not occur within a
383 // declarator or abstract-declarator of a parameter-declaration.
384 bool MightBeFunction = D.isFunctionDeclarationContext();
385 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
386 DeclaratorChunk &chunk = D.getTypeObject(i);
387 if (chunk.Kind == DeclaratorChunk::Function) {
388 if (MightBeFunction) {
389 // This is a function declaration. It can have default arguments, but
390 // keep looking in case its return type is a function type with default
391 // arguments.
392 MightBeFunction = false;
393 continue;
394 }
395 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
396 ++argIdx) {
397 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
398 if (Param->hasUnparsedDefaultArg()) {
399 std::unique_ptr<CachedTokens> Toks =
400 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
401 SourceRange SR;
402 if (Toks->size() > 1)
403 SR = SourceRange((*Toks)[1].getLocation(),
404 Toks->back().getLocation());
405 else
406 SR = UnparsedDefaultArgLocs[Param];
407 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
408 << SR;
409 } else if (Param->getDefaultArg()) {
410 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
411 << Param->getDefaultArg()->getSourceRange();
412 Param->setDefaultArg(nullptr);
413 }
414 }
415 } else if (chunk.Kind != DeclaratorChunk::Paren) {
416 MightBeFunction = false;
417 }
418 }
419}
420
421static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
422 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
423 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
424 if (!PVD->hasDefaultArg())
425 return false;
426 if (!PVD->hasInheritedDefaultArg())
427 return true;
428 }
429 return false;
430}
431
432/// MergeCXXFunctionDecl - Merge two declarations of the same C++
433/// function, once we already know that they have the same
434/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
435/// error, false otherwise.
436bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
437 Scope *S) {
438 bool Invalid = false;
439
440 // The declaration context corresponding to the scope is the semantic
441 // parent, unless this is a local function declaration, in which case
442 // it is that surrounding function.
443 DeclContext *ScopeDC = New->isLocalExternDecl()
1
Assuming the condition is false
2
'?' condition is false
444 ? New->getLexicalDeclContext()
445 : New->getDeclContext();
446
447 // Find the previous declaration for the purpose of default arguments.
448 FunctionDecl *PrevForDefaultArgs = Old;
449 for (/**/; PrevForDefaultArgs;
3
Assuming pointer value is null
4
Loop condition is false. Execution continues on line 497
450 // Don't bother looking back past the latest decl if this is a local
451 // extern declaration; nothing else could work.
452 PrevForDefaultArgs = New->isLocalExternDecl()
453 ? nullptr
454 : PrevForDefaultArgs->getPreviousDecl()) {
455 // Ignore hidden declarations.
456 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
457 continue;
458
459 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
460 !New->isCXXClassMember()) {
461 // Ignore default arguments of old decl if they are not in
462 // the same scope and this is not an out-of-line definition of
463 // a member function.
464 continue;
465 }
466
467 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
468 // If only one of these is a local function declaration, then they are
469 // declared in different scopes, even though isDeclInScope may think
470 // they're in the same scope. (If both are local, the scope check is
471 // sufficient, and if neither is local, then they are in the same scope.)
472 continue;
473 }
474
475 // We found the right previous declaration.
476 break;
477 }
478
479 // C++ [dcl.fct.default]p4:
480 // For non-template functions, default arguments can be added in
481 // later declarations of a function in the same
482 // scope. Declarations in different scopes have completely
483 // distinct sets of default arguments. That is, declarations in
484 // inner scopes do not acquire default arguments from
485 // declarations in outer scopes, and vice versa. In a given
486 // function declaration, all parameters subsequent to a
487 // parameter with a default argument shall have default
488 // arguments supplied in this or previous declarations. A
489 // default argument shall not be redefined by a later
490 // declaration (not even to the same value).
491 //
492 // C++ [dcl.fct.default]p6:
493 // Except for member functions of class templates, the default arguments
494 // in a member function definition that appears outside of the class
495 // definition are added to the set of default arguments provided by the
496 // member function declaration in the class definition.
497 for (unsigned p = 0, NumParams = PrevForDefaultArgs
4.1
'PrevForDefaultArgs' is null
5
'?' condition is false
6
Loop condition is false. Execution continues on line 625
498 ? PrevForDefaultArgs->getNumParams() 499 : 0; 500 p < NumParams; ++p) { 501 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 502 ParmVarDecl *NewParam = New->getParamDecl(p); 503 504 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 505 bool NewParamHasDfl = NewParam->hasDefaultArg(); 506 507 if (OldParamHasDfl && NewParamHasDfl) { 508 unsigned DiagDefaultParamID = 509 diag::err_param_default_argument_redefinition; 510 511 // MSVC accepts that default parameters be redefined for member functions 512 // of template class. The new default parameter's value is ignored. 513 Invalid = true; 514 if (getLangOpts().MicrosoftExt) { 515 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 516 if (MD && MD->getParent()->getDescribedClassTemplate()) { 517 // Merge the old default argument into the new parameter. 518 NewParam->setHasInheritedDefaultArg(); 519 if (OldParam->hasUninstantiatedDefaultArg()) 520 NewParam->setUninstantiatedDefaultArg( 521 OldParam->getUninstantiatedDefaultArg()); 522 else 523 NewParam->setDefaultArg(OldParam->getInit()); 524 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 525 Invalid = false; 526 } 527 } 528 529 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 530 // hint here. Alternatively, we could walk the type-source information 531 // for NewParam to find the last source location in the type... but it 532 // isn't worth the effort right now. This is the kind of test case that 533 // is hard to get right: 534 // int f(int); 535 // void g(int (*fp)(int) = f); 536 // void g(int (*fp)(int) = &f); 537 Diag(NewParam->getLocation(), DiagDefaultParamID) 538 << NewParam->getDefaultArgRange(); 539 540 // Look for the function declaration where the default argument was 541 // actually written, which may be a declaration prior to Old. 542 for (auto Older = PrevForDefaultArgs; 543 OldParam->hasInheritedDefaultArg(); /**/) { 544 Older = Older->getPreviousDecl(); 545 OldParam = Older->getParamDecl(p); 546 } 547 548 Diag(OldParam->getLocation(), diag::note_previous_definition) 549 << OldParam->getDefaultArgRange(); 550 } else if (OldParamHasDfl) { 551 // Merge the old default argument into the new parameter unless the new 552 // function is a friend declaration in a template class. In the latter 553 // case the default arguments will be inherited when the friend 554 // declaration will be instantiated. 555 if (New->getFriendObjectKind() == Decl::FOK_None || 556 !New->getLexicalDeclContext()->isDependentContext()) { 557 // It's important to use getInit() here; getDefaultArg() 558 // strips off any top-level ExprWithCleanups. 559 NewParam->setHasInheritedDefaultArg(); 560 if (OldParam->hasUnparsedDefaultArg()) 561 NewParam->setUnparsedDefaultArg(); 562 else if (OldParam->hasUninstantiatedDefaultArg()) 563 NewParam->setUninstantiatedDefaultArg( 564 OldParam->getUninstantiatedDefaultArg()); 565 else 566 NewParam->setDefaultArg(OldParam->getInit()); 567 } 568 } else if (NewParamHasDfl) { 569 if (New->getDescribedFunctionTemplate()) { 570 // Paragraph 4, quoted above, only applies to non-template functions. 571 Diag(NewParam->getLocation(), 572 diag::err_param_default_argument_template_redecl) 573 << NewParam->getDefaultArgRange(); 574 Diag(PrevForDefaultArgs->getLocation(), 575 diag::note_template_prev_declaration) 576 << false; 577 } else if (New->getTemplateSpecializationKind() 578 != TSK_ImplicitInstantiation && 579 New->getTemplateSpecializationKind() != TSK_Undeclared) { 580 // C++ [temp.expr.spec]p21: 581 // Default function arguments shall not be specified in a declaration 582 // or a definition for one of the following explicit specializations: 583 // - the explicit specialization of a function template; 584 // - the explicit specialization of a member function template; 585 // - the explicit specialization of a member function of a class 586 // template where the class template specialization to which the 587 // member function specialization belongs is implicitly 588 // instantiated. 589 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 590 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 591 << New->getDeclName() 592 << NewParam->getDefaultArgRange(); 593 } else if (New->getDeclContext()->isDependentContext()) { 594 // C++ [dcl.fct.default]p6 (DR217): 595 // Default arguments for a member function of a class template shall 596 // be specified on the initial declaration of the member function 597 // within the class template. 598 // 599 // Reading the tea leaves a bit in DR217 and its reference to DR205 600 // leads me to the conclusion that one cannot add default function 601 // arguments for an out-of-line definition of a member function of a 602 // dependent type. 603 int WhichKind = 2; 604 if (CXXRecordDecl *Record 605 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 606 if (Record->getDescribedClassTemplate()) 607 WhichKind = 0; 608 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 609 WhichKind = 1; 610 else 611 WhichKind = 2; 612 } 613 614 Diag(NewParam->getLocation(), 615 diag::err_param_default_argument_member_template_redecl) 616 << WhichKind 617 << NewParam->getDefaultArgRange(); 618 } 619 } 620 } 621 622 // DR1344: If a default argument is added outside a class definition and that 623 // default argument makes the function a special member function, the program 624 // is ill-formed. This can only happen for constructors. 625 if (isa<CXXConstructorDecl>(New) &&
7
Assuming 'New' is a 'CXXConstructorDecl'
626 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
8
Called C++ object pointer is null
627 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 628 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 629 if (NewSM != OldSM) { 630 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 631 assert(NewParam->hasDefaultArg())((NewParam->hasDefaultArg()) ? static_cast<void> (0)
: __assert_fail ("NewParam->hasDefaultArg()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 631, __PRETTY_FUNCTION__))
; 632 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 633 << NewParam->getDefaultArgRange() << NewSM; 634 Diag(Old->getLocation(), diag::note_previous_declaration); 635 } 636 } 637 638 const FunctionDecl *Def; 639 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 640 // template has a constexpr specifier then all its declarations shall 641 // contain the constexpr specifier. 642 if (New->getConstexprKind() != Old->getConstexprKind()) { 643 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 644 << New << New->getConstexprKind() << Old->getConstexprKind(); 645 Diag(Old->getLocation(), diag::note_previous_declaration); 646 Invalid = true; 647 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 648 Old->isDefined(Def) && 649 // If a friend function is inlined but does not have 'inline' 650 // specifier, it is a definition. Do not report attribute conflict 651 // in this case, redefinition will be diagnosed later. 652 (New->isInlineSpecified() || 653 New->getFriendObjectKind() == Decl::FOK_None)) { 654 // C++11 [dcl.fcn.spec]p4: 655 // If the definition of a function appears in a translation unit before its 656 // first declaration as inline, the program is ill-formed. 657 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 658 Diag(Def->getLocation(), diag::note_previous_definition); 659 Invalid = true; 660 } 661 662 // C++17 [temp.deduct.guide]p3: 663 // Two deduction guide declarations in the same translation unit 664 // for the same class template shall not have equivalent 665 // parameter-declaration-clauses. 666 if (isa<CXXDeductionGuideDecl>(New) && 667 !New->isFunctionTemplateSpecialization()) { 668 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 669 Diag(Old->getLocation(), diag::note_previous_declaration); 670 } 671 672 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 673 // argument expression, that declaration shall be a definition and shall be 674 // the only declaration of the function or function template in the 675 // translation unit. 676 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 677 functionDeclHasDefaultArgument(Old)) { 678 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 679 Diag(Old->getLocation(), diag::note_previous_declaration); 680 Invalid = true; 681 } 682 683 return Invalid; 684} 685 686NamedDecl * 687Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 688 MultiTemplateParamsArg TemplateParamLists) { 689 assert(D.isDecompositionDeclarator())((D.isDecompositionDeclarator()) ? static_cast<void> (0
) : __assert_fail ("D.isDecompositionDeclarator()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 689, __PRETTY_FUNCTION__))
; 690 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 691 692 // The syntax only allows a decomposition declarator as a simple-declaration, 693 // a for-range-declaration, or a condition in Clang, but we parse it in more 694 // cases than that. 695 if (!D.mayHaveDecompositionDeclarator()) { 696 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 697 << Decomp.getSourceRange(); 698 return nullptr; 699 } 700 701 if (!TemplateParamLists.empty()) { 702 // FIXME: There's no rule against this, but there are also no rules that 703 // would actually make it usable, so we reject it for now. 704 Diag(TemplateParamLists.front()->getTemplateLoc(), 705 diag::err_decomp_decl_template); 706 return nullptr; 707 } 708 709 Diag(Decomp.getLSquareLoc(), 710 !getLangOpts().CPlusPlus17 711 ? diag::ext_decomp_decl 712 : D.getContext() == DeclaratorContext::ConditionContext 713 ? diag::ext_decomp_decl_cond 714 : diag::warn_cxx14_compat_decomp_decl) 715 << Decomp.getSourceRange(); 716 717 // The semantic context is always just the current context. 718 DeclContext *const DC = CurContext; 719 720 // C++17 [dcl.dcl]/8: 721 // The decl-specifier-seq shall contain only the type-specifier auto 722 // and cv-qualifiers. 723 // C++2a [dcl.dcl]/8: 724 // If decl-specifier-seq contains any decl-specifier other than static, 725 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 726 auto &DS = D.getDeclSpec(); 727 { 728 SmallVector<StringRef, 8> BadSpecifiers; 729 SmallVector<SourceLocation, 8> BadSpecifierLocs; 730 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 731 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 732 if (auto SCS = DS.getStorageClassSpec()) { 733 if (SCS == DeclSpec::SCS_static) { 734 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 735 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 736 } else { 737 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 738 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 739 } 740 } 741 if (auto TSCS = DS.getThreadStorageClassSpec()) { 742 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 743 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 744 } 745 if (DS.hasConstexprSpecifier()) { 746 BadSpecifiers.push_back( 747 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 748 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 749 } 750 if (DS.isInlineSpecified()) { 751 BadSpecifiers.push_back("inline"); 752 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 753 } 754 if (!BadSpecifiers.empty()) { 755 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 756 Err << (int)BadSpecifiers.size() 757 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 758 // Don't add FixItHints to remove the specifiers; we do still respect 759 // them when building the underlying variable. 760 for (auto Loc : BadSpecifierLocs) 761 Err << SourceRange(Loc, Loc); 762 } else if (!CPlusPlus20Specifiers.empty()) { 763 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 764 getLangOpts().CPlusPlus2a 765 ? diag::warn_cxx17_compat_decomp_decl_spec 766 : diag::ext_decomp_decl_spec); 767 Warn << (int)CPlusPlus20Specifiers.size() 768 << llvm::join(CPlusPlus20Specifiers.begin(), 769 CPlusPlus20Specifiers.end(), " "); 770 for (auto Loc : CPlusPlus20SpecifierLocs) 771 Warn << SourceRange(Loc, Loc); 772 } 773 // We can't recover from it being declared as a typedef. 774 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 775 return nullptr; 776 } 777 778 // C++2a [dcl.struct.bind]p1: 779 // A cv that includes volatile is deprecated 780 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 781 getLangOpts().CPlusPlus2a) 782 Diag(DS.getVolatileSpecLoc(), 783 diag::warn_deprecated_volatile_structured_binding); 784 785 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 786 QualType R = TInfo->getType(); 787 788 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 789 UPPC_DeclarationType)) 790 D.setInvalidType(); 791 792 // The syntax only allows a single ref-qualifier prior to the decomposition 793 // declarator. No other declarator chunks are permitted. Also check the type 794 // specifier here. 795 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 796 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 797 (D.getNumTypeObjects() == 1 && 798 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 799 Diag(Decomp.getLSquareLoc(), 800 (D.hasGroupingParens() || 801 (D.getNumTypeObjects() && 802 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 803 ? diag::err_decomp_decl_parens 804 : diag::err_decomp_decl_type) 805 << R; 806 807 // In most cases, there's no actual problem with an explicitly-specified 808 // type, but a function type won't work here, and ActOnVariableDeclarator 809 // shouldn't be called for such a type. 810 if (R->isFunctionType()) 811 D.setInvalidType(); 812 } 813 814 // Build the BindingDecls. 815 SmallVector<BindingDecl*, 8> Bindings; 816 817 // Build the BindingDecls. 818 for (auto &B : D.getDecompositionDeclarator().bindings()) { 819 // Check for name conflicts. 820 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 821 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 822 ForVisibleRedeclaration); 823 LookupName(Previous, S, 824 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 825 826 // It's not permitted to shadow a template parameter name. 827 if (Previous.isSingleResult() && 828 Previous.getFoundDecl()->isTemplateParameter()) { 829 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 830 Previous.getFoundDecl()); 831 Previous.clear(); 832 } 833 834 bool ConsiderLinkage = DC->isFunctionOrMethod() && 835 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 836 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 837 /*AllowInlineNamespace*/false); 838 if (!Previous.empty()) { 839 auto *Old = Previous.getRepresentativeDecl(); 840 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 841 Diag(Old->getLocation(), diag::note_previous_definition); 842 } 843 844 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 845 PushOnScopeChains(BD, S, true); 846 Bindings.push_back(BD); 847 ParsingInitForAutoVars.insert(BD); 848 } 849 850 // There are no prior lookup results for the variable itself, because it 851 // is unnamed. 852 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 853 Decomp.getLSquareLoc()); 854 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 855 ForVisibleRedeclaration); 856 857 // Build the variable that holds the non-decomposed object. 858 bool AddToScope = true; 859 NamedDecl *New = 860 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 861 MultiTemplateParamsArg(), AddToScope, Bindings); 862 if (AddToScope) { 863 S->AddDecl(New); 864 CurContext->addHiddenDecl(New); 865 } 866 867 if (isInOpenMPDeclareTargetContext()) 868 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 869 870 return New; 871} 872 873static bool checkSimpleDecomposition( 874 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 875 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 876 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 877 if ((int64_t)Bindings.size() != NumElems) { 878 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 879 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 880 << (NumElems < Bindings.size()); 881 return true; 882 } 883 884 unsigned I = 0; 885 for (auto *B : Bindings) { 886 SourceLocation Loc = B->getLocation(); 887 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 888 if (E.isInvalid()) 889 return true; 890 E = GetInit(Loc, E.get(), I++); 891 if (E.isInvalid()) 892 return true; 893 B->setBinding(ElemType, E.get()); 894 } 895 896 return false; 897} 898 899static bool checkArrayLikeDecomposition(Sema &S, 900 ArrayRef<BindingDecl *> Bindings, 901 ValueDecl *Src, QualType DecompType, 902 const llvm::APSInt &NumElems, 903 QualType ElemType) { 904 return checkSimpleDecomposition( 905 S, Bindings, Src, DecompType, NumElems, ElemType, 906 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 907 ExprResult E = S.ActOnIntegerConstant(Loc, I); 908 if (E.isInvalid()) 909 return ExprError(); 910 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 911 }); 912} 913 914static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 915 ValueDecl *Src, QualType DecompType, 916 const ConstantArrayType *CAT) { 917 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 918 llvm::APSInt(CAT->getSize()), 919 CAT->getElementType()); 920} 921 922static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 923 ValueDecl *Src, QualType DecompType, 924 const VectorType *VT) { 925 return checkArrayLikeDecomposition( 926 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 927 S.Context.getQualifiedType(VT->getElementType(), 928 DecompType.getQualifiers())); 929} 930 931static bool checkComplexDecomposition(Sema &S, 932 ArrayRef<BindingDecl *> Bindings, 933 ValueDecl *Src, QualType DecompType, 934 const ComplexType *CT) { 935 return checkSimpleDecomposition( 936 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 937 S.Context.getQualifiedType(CT->getElementType(), 938 DecompType.getQualifiers()), 939 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 940 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 941 }); 942} 943 944static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 945 TemplateArgumentListInfo &Args) { 946 SmallString<128> SS; 947 llvm::raw_svector_ostream OS(SS); 948 bool First = true; 949 for (auto &Arg : Args.arguments()) { 950 if (!First) 951 OS << ", "; 952 Arg.getArgument().print(PrintingPolicy, OS); 953 First = false; 954 } 955 return std::string(OS.str()); 956} 957 958static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 959 SourceLocation Loc, StringRef Trait, 960 TemplateArgumentListInfo &Args, 961 unsigned DiagID) { 962 auto DiagnoseMissing = [&] { 963 if (DiagID) 964 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 965 Args); 966 return true; 967 }; 968 969 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 970 NamespaceDecl *Std = S.getStdNamespace(); 971 if (!Std) 972 return DiagnoseMissing(); 973 974 // Look up the trait itself, within namespace std. We can diagnose various 975 // problems with this lookup even if we've been asked to not diagnose a 976 // missing specialization, because this can only fail if the user has been 977 // declaring their own names in namespace std or we don't support the 978 // standard library implementation in use. 979 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 980 Loc, Sema::LookupOrdinaryName); 981 if (!S.LookupQualifiedName(Result, Std)) 982 return DiagnoseMissing(); 983 if (Result.isAmbiguous()) 984 return true; 985 986 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 987 if (!TraitTD) { 988 Result.suppressDiagnostics(); 989 NamedDecl *Found = *Result.begin(); 990 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 991 S.Diag(Found->getLocation(), diag::note_declared_at); 992 return true; 993 } 994 995 // Build the template-id. 996 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 997 if (TraitTy.isNull()) 998 return true; 999 if (!S.isCompleteType(Loc, TraitTy)) { 1000 if (DiagID) 1001 S.RequireCompleteType( 1002 Loc, TraitTy, DiagID, 1003 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 1004 return true; 1005 } 1006 1007 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1008 assert(RD && "specialization of class template is not a class?")((RD && "specialization of class template is not a class?"
) ? static_cast<void> (0) : __assert_fail ("RD && \"specialization of class template is not a class?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 1008, __PRETTY_FUNCTION__))
; 1009 1010 // Look up the member of the trait type. 1011 S.LookupQualifiedName(TraitMemberLookup, RD); 1012 return TraitMemberLookup.isAmbiguous(); 1013} 1014 1015static TemplateArgumentLoc 1016getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1017 uint64_t I) { 1018 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1019 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1020} 1021 1022static TemplateArgumentLoc 1023getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1024 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1025} 1026 1027namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1028 1029static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1030 llvm::APSInt &Size) { 1031 EnterExpressionEvaluationContext ContextRAII( 1032 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1033 1034 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1035 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1036 1037 // Form template argument list for tuple_size<T>. 1038 TemplateArgumentListInfo Args(Loc, Loc); 1039 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1040 1041 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1042 // it's not tuple-like. 1043 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1044 R.empty()) 1045 return IsTupleLike::NotTupleLike; 1046 1047 // If we get this far, we've committed to the tuple interpretation, but 1048 // we can still fail if there actually isn't a usable ::value. 1049 1050 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1051 LookupResult &R; 1052 TemplateArgumentListInfo &Args; 1053 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1054 : R(R), Args(Args) {} 1055 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1056 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1057 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1058 } 1059 } Diagnoser(R, Args); 1060 1061 ExprResult E = 1062 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1063 if (E.isInvalid()) 1064 return IsTupleLike::Error; 1065 1066 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1067 if (E.isInvalid()) 1068 return IsTupleLike::Error; 1069 1070 return IsTupleLike::TupleLike; 1071} 1072 1073/// \return std::tuple_element<I, T>::type. 1074static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1075 unsigned I, QualType T) { 1076 // Form template argument list for tuple_element<I, T>. 1077 TemplateArgumentListInfo Args(Loc, Loc); 1078 Args.addArgument( 1079 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1080 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1081 1082 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1083 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1084 if (lookupStdTypeTraitMember( 1085 S, R, Loc, "tuple_element", Args, 1086 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1087 return QualType(); 1088 1089 auto *TD = R.getAsSingle<TypeDecl>(); 1090 if (!TD) { 1091 R.suppressDiagnostics(); 1092 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1093 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1094 if (!R.empty()) 1095 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1096 return QualType(); 1097 } 1098 1099 return S.Context.getTypeDeclType(TD); 1100} 1101 1102namespace { 1103struct BindingDiagnosticTrap { 1104 Sema &S; 1105 DiagnosticErrorTrap Trap; 1106 BindingDecl *BD; 1107 1108 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1109 : S(S), Trap(S.Diags), BD(BD) {} 1110 ~BindingDiagnosticTrap() { 1111 if (Trap.hasErrorOccurred()) 1112 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1113 } 1114}; 1115} 1116 1117static bool checkTupleLikeDecomposition(Sema &S, 1118 ArrayRef<BindingDecl *> Bindings, 1119 VarDecl *Src, QualType DecompType, 1120 const llvm::APSInt &TupleSize) { 1121 if ((int64_t)Bindings.size() != TupleSize) { 1122 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1123 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1124 << (TupleSize < Bindings.size()); 1125 return true; 1126 } 1127 1128 if (Bindings.empty()) 1129 return false; 1130 1131 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1132 1133 // [dcl.decomp]p3: 1134 // The unqualified-id get is looked up in the scope of E by class member 1135 // access lookup ... 1136 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1137 bool UseMemberGet = false; 1138 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1139 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1140 S.LookupQualifiedName(MemberGet, RD); 1141 if (MemberGet.isAmbiguous()) 1142 return true; 1143 // ... and if that finds at least one declaration that is a function 1144 // template whose first template parameter is a non-type parameter ... 1145 for (NamedDecl *D : MemberGet) { 1146 if (FunctionTemplateDecl *FTD = 1147 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1148 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1149 if (TPL->size() != 0 && 1150 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1151 // ... the initializer is e.get<i>(). 1152 UseMemberGet = true; 1153 break; 1154 } 1155 } 1156 } 1157 } 1158 1159 unsigned I = 0; 1160 for (auto *B : Bindings) { 1161 BindingDiagnosticTrap Trap(S, B); 1162 SourceLocation Loc = B->getLocation(); 1163 1164 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1165 if (E.isInvalid()) 1166 return true; 1167 1168 // e is an lvalue if the type of the entity is an lvalue reference and 1169 // an xvalue otherwise 1170 if (!Src->getType()->isLValueReferenceType()) 1171 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1172 E.get(), nullptr, VK_XValue); 1173 1174 TemplateArgumentListInfo Args(Loc, Loc); 1175 Args.addArgument( 1176 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1177 1178 if (UseMemberGet) { 1179 // if [lookup of member get] finds at least one declaration, the 1180 // initializer is e.get<i-1>(). 1181 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1182 CXXScopeSpec(), SourceLocation(), nullptr, 1183 MemberGet, &Args, nullptr); 1184 if (E.isInvalid()) 1185 return true; 1186 1187 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1188 } else { 1189 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1190 // in the associated namespaces. 1191 Expr *Get = UnresolvedLookupExpr::Create( 1192 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1193 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1194 UnresolvedSetIterator(), UnresolvedSetIterator()); 1195 1196 Expr *Arg = E.get(); 1197 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1198 } 1199 if (E.isInvalid()) 1200 return true; 1201 Expr *Init = E.get(); 1202 1203 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1204 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1205 if (T.isNull()) 1206 return true; 1207 1208 // each vi is a variable of type "reference to T" initialized with the 1209 // initializer, where the reference is an lvalue reference if the 1210 // initializer is an lvalue and an rvalue reference otherwise 1211 QualType RefType = 1212 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1213 if (RefType.isNull()) 1214 return true; 1215 auto *RefVD = VarDecl::Create( 1216 S.Context, Src->getDeclContext(), Loc, Loc, 1217 B->getDeclName().getAsIdentifierInfo(), RefType, 1218 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1219 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1220 RefVD->setTSCSpec(Src->getTSCSpec()); 1221 RefVD->setImplicit(); 1222 if (Src->isInlineSpecified()) 1223 RefVD->setInlineSpecified(); 1224 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1225 1226 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1227 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1228 InitializationSequence Seq(S, Entity, Kind, Init); 1229 E = Seq.Perform(S, Entity, Kind, Init); 1230 if (E.isInvalid()) 1231 return true; 1232 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1233 if (E.isInvalid()) 1234 return true; 1235 RefVD->setInit(E.get()); 1236 if (!E.get()->isValueDependent()) 1237 RefVD->checkInitIsICE(); 1238 1239 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1240 DeclarationNameInfo(B->getDeclName(), Loc), 1241 RefVD); 1242 if (E.isInvalid()) 1243 return true; 1244 1245 B->setBinding(T, E.get()); 1246 I++; 1247 } 1248 1249 return false; 1250} 1251 1252/// Find the base class to decompose in a built-in decomposition of a class type. 1253/// This base class search is, unfortunately, not quite like any other that we 1254/// perform anywhere else in C++. 1255static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1256 const CXXRecordDecl *RD, 1257 CXXCastPath &BasePath) { 1258 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1259 CXXBasePath &Path) { 1260 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1261 }; 1262 1263 const CXXRecordDecl *ClassWithFields = nullptr; 1264 AccessSpecifier AS = AS_public; 1265 if (RD->hasDirectFields()) 1266 // [dcl.decomp]p4: 1267 // Otherwise, all of E's non-static data members shall be public direct 1268 // members of E ... 1269 ClassWithFields = RD; 1270 else { 1271 // ... or of ... 1272 CXXBasePaths Paths; 1273 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1274 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1275 // If no classes have fields, just decompose RD itself. (This will work 1276 // if and only if zero bindings were provided.) 1277 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1278 } 1279 1280 CXXBasePath *BestPath = nullptr; 1281 for (auto &P : Paths) { 1282 if (!BestPath) 1283 BestPath = &P; 1284 else if (!S.Context.hasSameType(P.back().Base->getType(), 1285 BestPath->back().Base->getType())) { 1286 // ... the same ... 1287 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1288 << false << RD << BestPath->back().Base->getType() 1289 << P.back().Base->getType(); 1290 return DeclAccessPair(); 1291 } else if (P.Access < BestPath->Access) { 1292 BestPath = &P; 1293 } 1294 } 1295 1296 // ... unambiguous ... 1297 QualType BaseType = BestPath->back().Base->getType(); 1298 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1299 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1300 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1301 return DeclAccessPair(); 1302 } 1303 1304 // ... [accessible, implied by other rules] base class of E. 1305 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1306 *BestPath, diag::err_decomp_decl_inaccessible_base); 1307 AS = BestPath->Access; 1308 1309 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1310 S.BuildBasePathArray(Paths, BasePath); 1311 } 1312 1313 // The above search did not check whether the selected class itself has base 1314 // classes with fields, so check that now. 1315 CXXBasePaths Paths; 1316 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1317 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1318 << (ClassWithFields == RD) << RD << ClassWithFields 1319 << Paths.front().back().Base->getType(); 1320 return DeclAccessPair(); 1321 } 1322 1323 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1324} 1325 1326static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1327 ValueDecl *Src, QualType DecompType, 1328 const CXXRecordDecl *OrigRD) { 1329 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1330 diag::err_incomplete_type)) 1331 return true; 1332 1333 CXXCastPath BasePath; 1334 DeclAccessPair BasePair = 1335 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1336 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1337 if (!RD) 1338 return true; 1339 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1340 DecompType.getQualifiers()); 1341 1342 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1343 unsigned NumFields = 1344 std::count_if(RD->field_begin(), RD->field_end(), 1345 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1346 assert(Bindings.size() != NumFields)((Bindings.size() != NumFields) ? static_cast<void> (0)
: __assert_fail ("Bindings.size() != NumFields", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 1346, __PRETTY_FUNCTION__))
; 1347 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1348 << DecompType << (unsigned)Bindings.size() << NumFields 1349 << (NumFields < Bindings.size()); 1350 return true; 1351 }; 1352 1353 // all of E's non-static data members shall be [...] well-formed 1354 // when named as e.name in the context of the structured binding, 1355 // E shall not have an anonymous union member, ... 1356 unsigned I = 0; 1357 for (auto *FD : RD->fields()) { 1358 if (FD->isUnnamedBitfield()) 1359 continue; 1360 1361 if (FD->isAnonymousStructOrUnion()) { 1362 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1363 << DecompType << FD->getType()->isUnionType(); 1364 S.Diag(FD->getLocation(), diag::note_declared_at); 1365 return true; 1366 } 1367 1368 // We have a real field to bind. 1369 if (I >= Bindings.size()) 1370 return DiagnoseBadNumberOfBindings(); 1371 auto *B = Bindings[I++]; 1372 SourceLocation Loc = B->getLocation(); 1373 1374 // The field must be accessible in the context of the structured binding. 1375 // We already checked that the base class is accessible. 1376 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1377 // const_cast here. 1378 S.CheckStructuredBindingMemberAccess( 1379 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1380 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1381 BasePair.getAccess(), FD->getAccess()))); 1382 1383 // Initialize the binding to Src.FD. 1384 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1385 if (E.isInvalid()) 1386 return true; 1387 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1388 VK_LValue, &BasePath); 1389 if (E.isInvalid()) 1390 return true; 1391 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1392 CXXScopeSpec(), FD, 1393 DeclAccessPair::make(FD, FD->getAccess()), 1394 DeclarationNameInfo(FD->getDeclName(), Loc)); 1395 if (E.isInvalid()) 1396 return true; 1397 1398 // If the type of the member is T, the referenced type is cv T, where cv is 1399 // the cv-qualification of the decomposition expression. 1400 // 1401 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1402 // 'const' to the type of the field. 1403 Qualifiers Q = DecompType.getQualifiers(); 1404 if (FD->isMutable()) 1405 Q.removeConst(); 1406 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1407 } 1408 1409 if (I != Bindings.size()) 1410 return DiagnoseBadNumberOfBindings(); 1411 1412 return false; 1413} 1414 1415void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1416 QualType DecompType = DD->getType(); 1417 1418 // If the type of the decomposition is dependent, then so is the type of 1419 // each binding. 1420 if (DecompType->isDependentType()) { 1421 for (auto *B : DD->bindings()) 1422 B->setType(Context.DependentTy); 1423 return; 1424 } 1425 1426 DecompType = DecompType.getNonReferenceType(); 1427 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1428 1429 // C++1z [dcl.decomp]/2: 1430 // If E is an array type [...] 1431 // As an extension, we also support decomposition of built-in complex and 1432 // vector types. 1433 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1434 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1435 DD->setInvalidDecl(); 1436 return; 1437 } 1438 if (auto *VT = DecompType->getAs<VectorType>()) { 1439 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1440 DD->setInvalidDecl(); 1441 return; 1442 } 1443 if (auto *CT = DecompType->getAs<ComplexType>()) { 1444 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1445 DD->setInvalidDecl(); 1446 return; 1447 } 1448 1449 // C++1z [dcl.decomp]/3: 1450 // if the expression std::tuple_size<E>::value is a well-formed integral 1451 // constant expression, [...] 1452 llvm::APSInt TupleSize(32); 1453 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1454 case IsTupleLike::Error: 1455 DD->setInvalidDecl(); 1456 return; 1457 1458 case IsTupleLike::TupleLike: 1459 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1460 DD->setInvalidDecl(); 1461 return; 1462 1463 case IsTupleLike::NotTupleLike: 1464 break; 1465 } 1466 1467 // C++1z [dcl.dcl]/8: 1468 // [E shall be of array or non-union class type] 1469 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1470 if (!RD || RD->isUnion()) { 1471 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1472 << DD << !RD << DecompType; 1473 DD->setInvalidDecl(); 1474 return; 1475 } 1476 1477 // C++1z [dcl.decomp]/4: 1478 // all of E's non-static data members shall be [...] direct members of 1479 // E or of the same unambiguous public base class of E, ... 1480 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1481 DD->setInvalidDecl(); 1482} 1483 1484/// Merge the exception specifications of two variable declarations. 1485/// 1486/// This is called when there's a redeclaration of a VarDecl. The function 1487/// checks if the redeclaration might have an exception specification and 1488/// validates compatibility and merges the specs if necessary. 1489void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1490 // Shortcut if exceptions are disabled. 1491 if (!getLangOpts().CXXExceptions) 1492 return; 1493 1494 assert(Context.hasSameType(New->getType(), Old->getType()) &&((Context.hasSameType(New->getType(), Old->getType()) &&
"Should only be called if types are otherwise the same.") ? static_cast
<void> (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 1495, __PRETTY_FUNCTION__))
1495 "Should only be called if types are otherwise the same.")((Context.hasSameType(New->getType(), Old->getType()) &&
"Should only be called if types are otherwise the same.") ? static_cast
<void> (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 1495, __PRETTY_FUNCTION__))
; 1496 1497 QualType NewType = New->getType(); 1498 QualType OldType = Old->getType(); 1499 1500 // We're only interested in pointers and references to functions, as well 1501 // as pointers to member functions. 1502 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1503 NewType = R->getPointeeType(); 1504 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1505 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1506 NewType = P->getPointeeType(); 1507 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1508 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1509 NewType = M->getPointeeType(); 1510 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1511 } 1512 1513 if (!NewType->isFunctionProtoType()) 1514 return; 1515 1516 // There's lots of special cases for functions. For function pointers, system 1517 // libraries are hopefully not as broken so that we don't need these 1518 // workarounds. 1519 if (CheckEquivalentExceptionSpec( 1520 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1521 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1522 New->setInvalidDecl(); 1523 } 1524} 1525 1526/// CheckCXXDefaultArguments - Verify that the default arguments for a 1527/// function declaration are well-formed according to C++ 1528/// [dcl.fct.default]. 1529void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1530 unsigned NumParams = FD->getNumParams(); 1531 unsigned p; 1532 1533 // Find first parameter with a default argument 1534 for (p = 0; p < NumParams; ++p) { 1535 ParmVarDecl *Param = FD->getParamDecl(p); 1536 if (Param->hasDefaultArg()) 1537 break; 1538 } 1539 1540 // C++11 [dcl.fct.default]p4: 1541 // In a given function declaration, each parameter subsequent to a parameter 1542 // with a default argument shall have a default argument supplied in this or 1543 // a previous declaration or shall be a function parameter pack. A default 1544 // argument shall not be redefined by a later declaration (not even to the 1545 // same value). 1546 unsigned LastMissingDefaultArg = 0; 1547 for (; p < NumParams; ++p) { 1548 ParmVarDecl *Param = FD->getParamDecl(p); 1549 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1550 if (Param->isInvalidDecl()) 1551 /* We already complained about this parameter. */; 1552 else if (Param->getIdentifier()) 1553 Diag(Param->getLocation(), 1554 diag::err_param_default_argument_missing_name) 1555 << Param->getIdentifier(); 1556 else 1557 Diag(Param->getLocation(), 1558 diag::err_param_default_argument_missing); 1559 1560 LastMissingDefaultArg = p; 1561 } 1562 } 1563 1564 if (LastMissingDefaultArg > 0) { 1565 // Some default arguments were missing. Clear out all of the 1566 // default arguments up to (and including) the last missing 1567 // default argument, so that we leave the function parameters 1568 // in a semantically valid state. 1569 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1570 ParmVarDecl *Param = FD->getParamDecl(p); 1571 if (Param->hasDefaultArg()) { 1572 Param->setDefaultArg(nullptr); 1573 } 1574 } 1575 } 1576} 1577 1578/// Check that the given type is a literal type. Issue a diagnostic if not, 1579/// if Kind is Diagnose. 1580/// \return \c true if a problem has been found (and optionally diagnosed). 1581template <typename... Ts> 1582static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1583 SourceLocation Loc, QualType T, unsigned DiagID, 1584 Ts &&...DiagArgs) { 1585 if (T->isDependentType()) 1586 return false; 1587 1588 switch (Kind) { 1589 case Sema::CheckConstexprKind::Diagnose: 1590 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1591 std::forward<Ts>(DiagArgs)...); 1592 1593 case Sema::CheckConstexprKind::CheckValid: 1594 return !T->isLiteralType(SemaRef.Context); 1595 } 1596 1597 llvm_unreachable("unknown CheckConstexprKind")::llvm::llvm_unreachable_internal("unknown CheckConstexprKind"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 1597)
; 1598} 1599 1600/// Determine whether a destructor cannot be constexpr due to 1601static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1602 const CXXDestructorDecl *DD, 1603 Sema::CheckConstexprKind Kind) { 1604 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1605 const CXXRecordDecl *RD = 1606 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1607 if (!RD || RD->hasConstexprDestructor()) 1608 return true; 1609 1610 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1611 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1612 << DD->getConstexprKind() << !FD 1613 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1614 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1615 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1616 } 1617 return false; 1618 }; 1619 1620 const CXXRecordDecl *RD = DD->getParent(); 1621 for (const CXXBaseSpecifier &B : RD->bases()) 1622 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1623 return false; 1624 for (const FieldDecl *FD : RD->fields()) 1625 if (!Check(FD->getLocation(), FD->getType(), FD)) 1626 return false; 1627 return true; 1628} 1629 1630/// Check whether a function's parameter types are all literal types. If so, 1631/// return true. If not, produce a suitable diagnostic and return false. 1632static bool CheckConstexprParameterTypes(Sema &SemaRef, 1633 const FunctionDecl *FD, 1634 Sema::CheckConstexprKind Kind) { 1635 unsigned ArgIndex = 0; 1636 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1637 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1638 e = FT->param_type_end(); 1639 i != e; ++i, ++ArgIndex) { 1640 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1641 SourceLocation ParamLoc = PD->getLocation(); 1642 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1643 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1644 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1645 FD->isConsteval())) 1646 return false; 1647 } 1648 return true; 1649} 1650 1651/// Check whether a function's return type is a literal type. If so, return 1652/// true. If not, produce a suitable diagnostic and return false. 1653static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1654 Sema::CheckConstexprKind Kind) { 1655 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1656 diag::err_constexpr_non_literal_return, 1657 FD->isConsteval())) 1658 return false; 1659 return true; 1660} 1661 1662/// Get diagnostic %select index for tag kind for 1663/// record diagnostic message. 1664/// WARNING: Indexes apply to particular diagnostics only! 1665/// 1666/// \returns diagnostic %select index. 1667static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1668 switch (Tag) { 1669 case TTK_Struct: return 0; 1670 case TTK_Interface: return 1; 1671 case TTK_Class: return 2; 1672 default: llvm_unreachable("Invalid tag kind for record diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for record diagnostic!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 1672)
; 1673 } 1674} 1675 1676static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1677 Stmt *Body, 1678 Sema::CheckConstexprKind Kind); 1679 1680// Check whether a function declaration satisfies the requirements of a 1681// constexpr function definition or a constexpr constructor definition. If so, 1682// return true. If not, produce appropriate diagnostics (unless asked not to by 1683// Kind) and return false. 1684// 1685// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1686bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1687 CheckConstexprKind Kind) { 1688 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1689 if (MD && MD->isInstance()) { 1690 // C++11 [dcl.constexpr]p4: 1691 // The definition of a constexpr constructor shall satisfy the following 1692 // constraints: 1693 // - the class shall not have any virtual base classes; 1694 // 1695 // FIXME: This only applies to constructors and destructors, not arbitrary 1696 // member functions. 1697 const CXXRecordDecl *RD = MD->getParent(); 1698 if (RD->getNumVBases()) { 1699 if (Kind == CheckConstexprKind::CheckValid) 1700 return false; 1701 1702 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1703 << isa<CXXConstructorDecl>(NewFD) 1704 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1705 for (const auto &I : RD->vbases()) 1706 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1707 << I.getSourceRange(); 1708 return false; 1709 } 1710 } 1711 1712 if (!isa<CXXConstructorDecl>(NewFD)) { 1713 // C++11 [dcl.constexpr]p3: 1714 // The definition of a constexpr function shall satisfy the following 1715 // constraints: 1716 // - it shall not be virtual; (removed in C++20) 1717 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1718 if (Method && Method->isVirtual()) { 1719 if (getLangOpts().CPlusPlus2a) { 1720 if (Kind == CheckConstexprKind::Diagnose) 1721 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1722 } else { 1723 if (Kind == CheckConstexprKind::CheckValid) 1724 return false; 1725 1726 Method = Method->getCanonicalDecl(); 1727 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1728 1729 // If it's not obvious why this function is virtual, find an overridden 1730 // function which uses the 'virtual' keyword. 1731 const CXXMethodDecl *WrittenVirtual = Method; 1732 while (!WrittenVirtual->isVirtualAsWritten()) 1733 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1734 if (WrittenVirtual != Method) 1735 Diag(WrittenVirtual->getLocation(), 1736 diag::note_overridden_virtual_function); 1737 return false; 1738 } 1739 } 1740 1741 // - its return type shall be a literal type; 1742 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1743 return false; 1744 } 1745 1746 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1747 // A destructor can be constexpr only if the defaulted destructor could be; 1748 // we don't need to check the members and bases if we already know they all 1749 // have constexpr destructors. 1750 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1751 if (Kind == CheckConstexprKind::CheckValid) 1752 return false; 1753 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1754 return false; 1755 } 1756 } 1757 1758 // - each of its parameter types shall be a literal type; 1759 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1760 return false; 1761 1762 Stmt *Body = NewFD->getBody(); 1763 assert(Body &&((Body && "CheckConstexprFunctionDefinition called on function with no body"
) ? static_cast<void> (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 1764, __PRETTY_FUNCTION__))
1764 "CheckConstexprFunctionDefinition called on function with no body")((Body && "CheckConstexprFunctionDefinition called on function with no body"
) ? static_cast<void> (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 1764, __PRETTY_FUNCTION__))
; 1765 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1766} 1767 1768/// Check the given declaration statement is legal within a constexpr function 1769/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1770/// 1771/// \return true if the body is OK (maybe only as an extension), false if we 1772/// have diagnosed a problem. 1773static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1774 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1775 Sema::CheckConstexprKind Kind) { 1776 // C++11 [dcl.constexpr]p3 and p4: 1777 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1778 // contain only 1779 for (const auto *DclIt : DS->decls()) { 1780 switch (DclIt->getKind()) { 1781 case Decl::StaticAssert: 1782 case Decl::Using: 1783 case Decl::UsingShadow: 1784 case Decl::UsingDirective: 1785 case Decl::UnresolvedUsingTypename: 1786 case Decl::UnresolvedUsingValue: 1787 // - static_assert-declarations 1788 // - using-declarations, 1789 // - using-directives, 1790 continue; 1791 1792 case Decl::Typedef: 1793 case Decl::TypeAlias: { 1794 // - typedef declarations and alias-declarations that do not define 1795 // classes or enumerations, 1796 const auto *TN = cast<TypedefNameDecl>(DclIt); 1797 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1798 // Don't allow variably-modified types in constexpr functions. 1799 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1800 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1801 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1802 << TL.getSourceRange() << TL.getType() 1803 << isa<CXXConstructorDecl>(Dcl); 1804 } 1805 return false; 1806 } 1807 continue; 1808 } 1809 1810 case Decl::Enum: 1811 case Decl::CXXRecord: 1812 // C++1y allows types to be defined, not just declared. 1813 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1814 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1815 SemaRef.Diag(DS->getBeginLoc(), 1816 SemaRef.getLangOpts().CPlusPlus14 1817 ? diag::warn_cxx11_compat_constexpr_type_definition 1818 : diag::ext_constexpr_type_definition) 1819 << isa<CXXConstructorDecl>(Dcl); 1820 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1821 return false; 1822 } 1823 } 1824 continue; 1825 1826 case Decl::EnumConstant: 1827 case Decl::IndirectField: 1828 case Decl::ParmVar: 1829 // These can only appear with other declarations which are banned in 1830 // C++11 and permitted in C++1y, so ignore them. 1831 continue; 1832 1833 case Decl::Var: 1834 case Decl::Decomposition: { 1835 // C++1y [dcl.constexpr]p3 allows anything except: 1836 // a definition of a variable of non-literal type or of static or 1837 // thread storage duration or [before C++2a] for which no 1838 // initialization is performed. 1839 const auto *VD = cast<VarDecl>(DclIt); 1840 if (VD->isThisDeclarationADefinition()) { 1841 if (VD->isStaticLocal()) { 1842 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1843 SemaRef.Diag(VD->getLocation(), 1844 diag::err_constexpr_local_var_static) 1845 << isa<CXXConstructorDecl>(Dcl) 1846 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1847 } 1848 return false; 1849 } 1850 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1851 diag::err_constexpr_local_var_non_literal_type, 1852 isa<CXXConstructorDecl>(Dcl))) 1853 return false; 1854 if (!VD->getType()->isDependentType() && 1855 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1856 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1857 SemaRef.Diag( 1858 VD->getLocation(), 1859 SemaRef.getLangOpts().CPlusPlus2a 1860 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1861 : diag::ext_constexpr_local_var_no_init) 1862 << isa<CXXConstructorDecl>(Dcl); 1863 } else if (!SemaRef.getLangOpts().CPlusPlus2a) { 1864 return false; 1865 } 1866 continue; 1867 } 1868 } 1869 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1870 SemaRef.Diag(VD->getLocation(), 1871 SemaRef.getLangOpts().CPlusPlus14 1872 ? diag::warn_cxx11_compat_constexpr_local_var 1873 : diag::ext_constexpr_local_var) 1874 << isa<CXXConstructorDecl>(Dcl); 1875 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1876 return false; 1877 } 1878 continue; 1879 } 1880 1881 case Decl::NamespaceAlias: 1882 case Decl::Function: 1883 // These are disallowed in C++11 and permitted in C++1y. Allow them 1884 // everywhere as an extension. 1885 if (!Cxx1yLoc.isValid()) 1886 Cxx1yLoc = DS->getBeginLoc(); 1887 continue; 1888 1889 default: 1890 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1891 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1892 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1893 } 1894 return false; 1895 } 1896 } 1897 1898 return true; 1899} 1900 1901/// Check that the given field is initialized within a constexpr constructor. 1902/// 1903/// \param Dcl The constexpr constructor being checked. 1904/// \param Field The field being checked. This may be a member of an anonymous 1905/// struct or union nested within the class being checked. 1906/// \param Inits All declarations, including anonymous struct/union members and 1907/// indirect members, for which any initialization was provided. 1908/// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1909/// multiple notes for different members to the same error. 1910/// \param Kind Whether we're diagnosing a constructor as written or determining 1911/// whether the formal requirements are satisfied. 1912/// \return \c false if we're checking for validity and the constructor does 1913/// not satisfy the requirements on a constexpr constructor. 1914static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1915 const FunctionDecl *Dcl, 1916 FieldDecl *Field, 1917 llvm::SmallSet<Decl*, 16> &Inits, 1918 bool &Diagnosed, 1919 Sema::CheckConstexprKind Kind) { 1920 // In C++20 onwards, there's nothing to check for validity. 1921 if (Kind == Sema::CheckConstexprKind::CheckValid && 1922 SemaRef.getLangOpts().CPlusPlus2a) 1923 return true; 1924 1925 if (Field->isInvalidDecl()) 1926 return true; 1927 1928 if (Field->isUnnamedBitfield()) 1929 return true; 1930 1931 // Anonymous unions with no variant members and empty anonymous structs do not 1932 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1933 // indirect fields don't need initializing. 1934 if (Field->isAnonymousStructOrUnion() && 1935 (Field->getType()->isUnionType() 1936 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1937 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1938 return true; 1939 1940 if (!Inits.count(Field)) { 1941 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1942 if (!Diagnosed) { 1943 SemaRef.Diag(Dcl->getLocation(), 1944 SemaRef.getLangOpts().CPlusPlus2a 1945 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1946 : diag::ext_constexpr_ctor_missing_init); 1947 Diagnosed = true; 1948 } 1949 SemaRef.Diag(Field->getLocation(), 1950 diag::note_constexpr_ctor_missing_init); 1951 } else if (!SemaRef.getLangOpts().CPlusPlus2a) { 1952 return false; 1953 } 1954 } else if (Field->isAnonymousStructOrUnion()) { 1955 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1956 for (auto *I : RD->fields()) 1957 // If an anonymous union contains an anonymous struct of which any member 1958 // is initialized, all members must be initialized. 1959 if (!RD->isUnion() || Inits.count(I)) 1960 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 1961 Kind)) 1962 return false; 1963 } 1964 return true; 1965} 1966 1967/// Check the provided statement is allowed in a constexpr function 1968/// definition. 1969static bool 1970CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1971 SmallVectorImpl<SourceLocation> &ReturnStmts, 1972 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 1973 Sema::CheckConstexprKind Kind) { 1974 // - its function-body shall be [...] a compound-statement that contains only 1975 switch (S->getStmtClass()) { 1976 case Stmt::NullStmtClass: 1977 // - null statements, 1978 return true; 1979 1980 case Stmt::DeclStmtClass: 1981 // - static_assert-declarations 1982 // - using-declarations, 1983 // - using-directives, 1984 // - typedef declarations and alias-declarations that do not define 1985 // classes or enumerations, 1986 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 1987 return false; 1988 return true; 1989 1990 case Stmt::ReturnStmtClass: 1991 // - and exactly one return statement; 1992 if (isa<CXXConstructorDecl>(Dcl)) { 1993 // C++1y allows return statements in constexpr constructors. 1994 if (!Cxx1yLoc.isValid()) 1995 Cxx1yLoc = S->getBeginLoc(); 1996 return true; 1997 } 1998 1999 ReturnStmts.push_back(S->getBeginLoc()); 2000 return true; 2001 2002 case Stmt::CompoundStmtClass: { 2003 // C++1y allows compound-statements. 2004 if (!Cxx1yLoc.isValid()) 2005 Cxx1yLoc = S->getBeginLoc(); 2006 2007 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2008 for (auto *BodyIt : CompStmt->body()) { 2009 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2010 Cxx1yLoc, Cxx2aLoc, Kind)) 2011 return false; 2012 } 2013 return true; 2014 } 2015 2016 case Stmt::AttributedStmtClass: 2017 if (!Cxx1yLoc.isValid()) 2018 Cxx1yLoc = S->getBeginLoc(); 2019 return true; 2020 2021 case Stmt::IfStmtClass: { 2022 // C++1y allows if-statements. 2023 if (!Cxx1yLoc.isValid()) 2024 Cxx1yLoc = S->getBeginLoc(); 2025 2026 IfStmt *If = cast<IfStmt>(S); 2027 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2028 Cxx1yLoc, Cxx2aLoc, Kind)) 2029 return false; 2030 if (If->getElse() && 2031 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2032 Cxx1yLoc, Cxx2aLoc, Kind)) 2033 return false; 2034 return true; 2035 } 2036 2037 case Stmt::WhileStmtClass: 2038 case Stmt::DoStmtClass: 2039 case Stmt::ForStmtClass: 2040 case Stmt::CXXForRangeStmtClass: 2041 case Stmt::ContinueStmtClass: 2042 // C++1y allows all of these. We don't allow them as extensions in C++11, 2043 // because they don't make sense without variable mutation. 2044 if (!SemaRef.getLangOpts().CPlusPlus14) 2045 break; 2046 if (!Cxx1yLoc.isValid()) 2047 Cxx1yLoc = S->getBeginLoc(); 2048 for (Stmt *SubStmt : S->children()) 2049 if (SubStmt && 2050 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2051 Cxx1yLoc, Cxx2aLoc, Kind)) 2052 return false; 2053 return true; 2054 2055 case Stmt::SwitchStmtClass: 2056 case Stmt::CaseStmtClass: 2057 case Stmt::DefaultStmtClass: 2058 case Stmt::BreakStmtClass: 2059 // C++1y allows switch-statements, and since they don't need variable 2060 // mutation, we can reasonably allow them in C++11 as an extension. 2061 if (!Cxx1yLoc.isValid()) 2062 Cxx1yLoc = S->getBeginLoc(); 2063 for (Stmt *SubStmt : S->children()) 2064 if (SubStmt && 2065 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2066 Cxx1yLoc, Cxx2aLoc, Kind)) 2067 return false; 2068 return true; 2069 2070 case Stmt::GCCAsmStmtClass: 2071 case Stmt::MSAsmStmtClass: 2072 // C++2a allows inline assembly statements. 2073 case Stmt::CXXTryStmtClass: 2074 if (Cxx2aLoc.isInvalid()) 2075 Cxx2aLoc = S->getBeginLoc(); 2076 for (Stmt *SubStmt : S->children()) { 2077 if (SubStmt && 2078 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2079 Cxx1yLoc, Cxx2aLoc, Kind)) 2080 return false; 2081 } 2082 return true; 2083 2084 case Stmt::CXXCatchStmtClass: 2085 // Do not bother checking the language mode (already covered by the 2086 // try block check). 2087 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2088 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2089 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2090 return false; 2091 return true; 2092 2093 default: 2094 if (!isa<Expr>(S)) 2095 break; 2096 2097 // C++1y allows expression-statements. 2098 if (!Cxx1yLoc.isValid()) 2099 Cxx1yLoc = S->getBeginLoc(); 2100 return true; 2101 } 2102 2103 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2104 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2105 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2106 } 2107 return false; 2108} 2109 2110/// Check the body for the given constexpr function declaration only contains 2111/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2112/// 2113/// \return true if the body is OK, false if we have found or diagnosed a 2114/// problem. 2115static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2116 Stmt *Body, 2117 Sema::CheckConstexprKind Kind) { 2118 SmallVector<SourceLocation, 4> ReturnStmts; 2119 2120 if (isa<CXXTryStmt>(Body)) { 2121 // C++11 [dcl.constexpr]p3: 2122 // The definition of a constexpr function shall satisfy the following 2123 // constraints: [...] 2124 // - its function-body shall be = delete, = default, or a 2125 // compound-statement 2126 // 2127 // C++11 [dcl.constexpr]p4: 2128 // In the definition of a constexpr constructor, [...] 2129 // - its function-body shall not be a function-try-block; 2130 // 2131 // This restriction is lifted in C++2a, as long as inner statements also 2132 // apply the general constexpr rules. 2133 switch (Kind) { 2134 case Sema::CheckConstexprKind::CheckValid: 2135 if (!SemaRef.getLangOpts().CPlusPlus2a) 2136 return false; 2137 break; 2138 2139 case Sema::CheckConstexprKind::Diagnose: 2140 SemaRef.Diag(Body->getBeginLoc(), 2141 !SemaRef.getLangOpts().CPlusPlus2a 2142 ? diag::ext_constexpr_function_try_block_cxx2a 2143 : diag::warn_cxx17_compat_constexpr_function_try_block) 2144 << isa<CXXConstructorDecl>(Dcl); 2145 break; 2146 } 2147 } 2148 2149 // - its function-body shall be [...] a compound-statement that contains only 2150 // [... list of cases ...] 2151 // 2152 // Note that walking the children here is enough to properly check for 2153 // CompoundStmt and CXXTryStmt body. 2154 SourceLocation Cxx1yLoc, Cxx2aLoc; 2155 for (Stmt *SubStmt : Body->children()) { 2156 if (SubStmt && 2157 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2158 Cxx1yLoc, Cxx2aLoc, Kind)) 2159 return false; 2160 } 2161 2162 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2163 // If this is only valid as an extension, report that we don't satisfy the 2164 // constraints of the current language. 2165 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) || 2166 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2167 return false; 2168 } else if (Cxx2aLoc.isValid()) { 2169 SemaRef.Diag(Cxx2aLoc, 2170 SemaRef.getLangOpts().CPlusPlus2a 2171 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2172 : diag::ext_constexpr_body_invalid_stmt_cxx2a) 2173 << isa<CXXConstructorDecl>(Dcl); 2174 } else if (Cxx1yLoc.isValid()) { 2175 SemaRef.Diag(Cxx1yLoc, 2176 SemaRef.getLangOpts().CPlusPlus14 2177 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2178 : diag::ext_constexpr_body_invalid_stmt) 2179 << isa<CXXConstructorDecl>(Dcl); 2180 } 2181 2182 if (const CXXConstructorDecl *Constructor 2183 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2184 const CXXRecordDecl *RD = Constructor->getParent(); 2185 // DR1359: 2186 // - every non-variant non-static data member and base class sub-object 2187 // shall be initialized; 2188 // DR1460: 2189 // - if the class is a union having variant members, exactly one of them 2190 // shall be initialized; 2191 if (RD->isUnion()) { 2192 if (Constructor->getNumCtorInitializers() == 0 && 2193 RD->hasVariantMembers()) { 2194 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2195 SemaRef.Diag( 2196 Dcl->getLocation(), 2197 SemaRef.getLangOpts().CPlusPlus2a 2198 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2199 : diag::ext_constexpr_union_ctor_no_init); 2200 } else if (!SemaRef.getLangOpts().CPlusPlus2a) { 2201 return false; 2202 } 2203 } 2204 } else if (!Constructor->isDependentContext() && 2205 !Constructor->isDelegatingConstructor()) { 2206 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases")((RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"
) ? static_cast<void> (0) : __assert_fail ("RD->getNumVBases() == 0 && \"constexpr ctor with virtual bases\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 2206, __PRETTY_FUNCTION__))
; 2207 2208 // Skip detailed checking if we have enough initializers, and we would 2209 // allow at most one initializer per member. 2210 bool AnyAnonStructUnionMembers = false; 2211 unsigned Fields = 0; 2212 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2213 E = RD->field_end(); I != E; ++I, ++Fields) { 2214 if (I->isAnonymousStructOrUnion()) { 2215 AnyAnonStructUnionMembers = true; 2216 break; 2217 } 2218 } 2219 // DR1460: 2220 // - if the class is a union-like class, but is not a union, for each of 2221 // its anonymous union members having variant members, exactly one of 2222 // them shall be initialized; 2223 if (AnyAnonStructUnionMembers || 2224 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2225 // Check initialization of non-static data members. Base classes are 2226 // always initialized so do not need to be checked. Dependent bases 2227 // might not have initializers in the member initializer list. 2228 llvm::SmallSet<Decl*, 16> Inits; 2229 for (const auto *I: Constructor->inits()) { 2230 if (FieldDecl *FD = I->getMember()) 2231 Inits.insert(FD); 2232 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2233 Inits.insert(ID->chain_begin(), ID->chain_end()); 2234 } 2235 2236 bool Diagnosed = false; 2237 for (auto *I : RD->fields()) 2238 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2239 Kind)) 2240 return false; 2241 } 2242 } 2243 } else { 2244 if (ReturnStmts.empty()) { 2245 // C++1y doesn't require constexpr functions to contain a 'return' 2246 // statement. We still do, unless the return type might be void, because 2247 // otherwise if there's no return statement, the function cannot 2248 // be used in a core constant expression. 2249 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2250 (Dcl->getReturnType()->isVoidType() || 2251 Dcl->getReturnType()->isDependentType()); 2252 switch (Kind) { 2253 case Sema::CheckConstexprKind::Diagnose: 2254 SemaRef.Diag(Dcl->getLocation(), 2255 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2256 : diag::err_constexpr_body_no_return) 2257 << Dcl->isConsteval(); 2258 if (!OK) 2259 return false; 2260 break; 2261 2262 case Sema::CheckConstexprKind::CheckValid: 2263 // The formal requirements don't include this rule in C++14, even 2264 // though the "must be able to produce a constant expression" rules 2265 // still imply it in some cases. 2266 if (!SemaRef.getLangOpts().CPlusPlus14) 2267 return false; 2268 break; 2269 } 2270 } else if (ReturnStmts.size() > 1) { 2271 switch (Kind) { 2272 case Sema::CheckConstexprKind::Diagnose: 2273 SemaRef.Diag( 2274 ReturnStmts.back(), 2275 SemaRef.getLangOpts().CPlusPlus14 2276 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2277 : diag::ext_constexpr_body_multiple_return); 2278 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2279 SemaRef.Diag(ReturnStmts[I], 2280 diag::note_constexpr_body_previous_return); 2281 break; 2282 2283 case Sema::CheckConstexprKind::CheckValid: 2284 if (!SemaRef.getLangOpts().CPlusPlus14) 2285 return false; 2286 break; 2287 } 2288 } 2289 } 2290 2291 // C++11 [dcl.constexpr]p5: 2292 // if no function argument values exist such that the function invocation 2293 // substitution would produce a constant expression, the program is 2294 // ill-formed; no diagnostic required. 2295 // C++11 [dcl.constexpr]p3: 2296 // - every constructor call and implicit conversion used in initializing the 2297 // return value shall be one of those allowed in a constant expression. 2298 // C++11 [dcl.constexpr]p4: 2299 // - every constructor involved in initializing non-static data members and 2300 // base class sub-objects shall be a constexpr constructor. 2301 // 2302 // Note that this rule is distinct from the "requirements for a constexpr 2303 // function", so is not checked in CheckValid mode. 2304 SmallVector<PartialDiagnosticAt, 8> Diags; 2305 if (Kind == Sema::CheckConstexprKind::Diagnose && 2306 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2307 SemaRef.Diag(Dcl->getLocation(), 2308 diag::ext_constexpr_function_never_constant_expr) 2309 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2310 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2311 SemaRef.Diag(Diags[I].first, Diags[I].second); 2312 // Don't return false here: we allow this for compatibility in 2313 // system headers. 2314 } 2315 2316 return true; 2317} 2318 2319/// Get the class that is directly named by the current context. This is the 2320/// class for which an unqualified-id in this scope could name a constructor 2321/// or destructor. 2322/// 2323/// If the scope specifier denotes a class, this will be that class. 2324/// If the scope specifier is empty, this will be the class whose 2325/// member-specification we are currently within. Otherwise, there 2326/// is no such class. 2327CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2328 assert(getLangOpts().CPlusPlus && "No class names in C!")((getLangOpts().CPlusPlus && "No class names in C!") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 2328, __PRETTY_FUNCTION__))
; 2329 2330 if (SS && SS->isInvalid()) 2331 return nullptr; 2332 2333 if (SS && SS->isNotEmpty()) { 2334 DeclContext *DC = computeDeclContext(*SS, true); 2335 return dyn_cast_or_null<CXXRecordDecl>(DC); 2336 } 2337 2338 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2339} 2340 2341/// isCurrentClassName - Determine whether the identifier II is the 2342/// name of the class type currently being defined. In the case of 2343/// nested classes, this will only return true if II is the name of 2344/// the innermost class. 2345bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2346 const CXXScopeSpec *SS) { 2347 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2348 return CurDecl && &II == CurDecl->getIdentifier(); 2349} 2350 2351/// Determine whether the identifier II is a typo for the name of 2352/// the class type currently being defined. If so, update it to the identifier 2353/// that should have been used. 2354bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2355 assert(getLangOpts().CPlusPlus && "No class names in C!")((getLangOpts().CPlusPlus && "No class names in C!") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 2355, __PRETTY_FUNCTION__))
; 2356 2357 if (!getLangOpts().SpellChecking) 2358 return false; 2359 2360 CXXRecordDecl *CurDecl; 2361 if (SS && SS->isSet() && !SS->isInvalid()) { 2362 DeclContext *DC = computeDeclContext(*SS, true); 2363 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2364 } else 2365 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2366 2367 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2368 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2369 < II->getLength()) { 2370 II = CurDecl->getIdentifier(); 2371 return true; 2372 } 2373 2374 return false; 2375} 2376 2377/// Determine whether the given class is a base class of the given 2378/// class, including looking at dependent bases. 2379static bool findCircularInheritance(const CXXRecordDecl *Class, 2380 const CXXRecordDecl *Current) { 2381 SmallVector<const CXXRecordDecl*, 8> Queue; 2382 2383 Class = Class->getCanonicalDecl(); 2384 while (true) { 2385 for (const auto &I : Current->bases()) { 2386 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2387 if (!Base) 2388 continue; 2389 2390 Base = Base->getDefinition(); 2391 if (!Base) 2392 continue; 2393 2394 if (Base->getCanonicalDecl() == Class) 2395 return true; 2396 2397 Queue.push_back(Base); 2398 } 2399 2400 if (Queue.empty()) 2401 return false; 2402 2403 Current = Queue.pop_back_val(); 2404 } 2405 2406 return false; 2407} 2408 2409/// Check the validity of a C++ base class specifier. 2410/// 2411/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2412/// and returns NULL otherwise. 2413CXXBaseSpecifier * 2414Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2415 SourceRange SpecifierRange, 2416 bool Virtual, AccessSpecifier Access, 2417 TypeSourceInfo *TInfo, 2418 SourceLocation EllipsisLoc) { 2419 QualType BaseType = TInfo->getType(); 2420 2421 // C++ [class.union]p1: 2422 // A union shall not have base classes. 2423 if (Class->isUnion()) { 2424 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2425 << SpecifierRange; 2426 return nullptr; 2427 } 2428 2429 if (EllipsisLoc.isValid() && 2430 !TInfo->getType()->containsUnexpandedParameterPack()) { 2431 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2432 << TInfo->getTypeLoc().getSourceRange(); 2433 EllipsisLoc = SourceLocation(); 2434 } 2435 2436 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2437 2438 if (BaseType->isDependentType()) { 2439 // Make sure that we don't have circular inheritance among our dependent 2440 // bases. For non-dependent bases, the check for completeness below handles 2441 // this. 2442 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2443 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2444 ((BaseDecl = BaseDecl->getDefinition()) && 2445 findCircularInheritance(Class, BaseDecl))) { 2446 Diag(BaseLoc, diag::err_circular_inheritance) 2447 << BaseType << Context.getTypeDeclType(Class); 2448 2449 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2450 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2451 << BaseType; 2452 2453 return nullptr; 2454 } 2455 } 2456 2457 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2458 Class->getTagKind() == TTK_Class, 2459 Access, TInfo, EllipsisLoc); 2460 } 2461 2462 // Base specifiers must be record types. 2463 if (!BaseType->isRecordType()) { 2464 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2465 return nullptr; 2466 } 2467 2468 // C++ [class.union]p1: 2469 // A union shall not be used as a base class. 2470 if (BaseType->isUnionType()) { 2471 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2472 return nullptr; 2473 } 2474 2475 // For the MS ABI, propagate DLL attributes to base class templates. 2476 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2477 if (Attr *ClassAttr = getDLLAttr(Class)) { 2478 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2479 BaseType->getAsCXXRecordDecl())) { 2480 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2481 BaseLoc); 2482 } 2483 } 2484 } 2485 2486 // C++ [class.derived]p2: 2487 // The class-name in a base-specifier shall not be an incompletely 2488 // defined class. 2489 if (RequireCompleteType(BaseLoc, BaseType, 2490 diag::err_incomplete_base_class, SpecifierRange)) { 2491 Class->setInvalidDecl(); 2492 return nullptr; 2493 } 2494 2495 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2496 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2497 assert(BaseDecl && "Record type has no declaration")((BaseDecl && "Record type has no declaration") ? static_cast
<void> (0) : __assert_fail ("BaseDecl && \"Record type has no declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 2497, __PRETTY_FUNCTION__))
; 2498 BaseDecl = BaseDecl->getDefinition(); 2499 assert(BaseDecl && "Base type is not incomplete, but has no definition")((BaseDecl && "Base type is not incomplete, but has no definition"
) ? static_cast<void> (0) : __assert_fail ("BaseDecl && \"Base type is not incomplete, but has no definition\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 2499, __PRETTY_FUNCTION__))
; 2500 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2501 assert(CXXBaseDecl && "Base type is not a C++ type")((CXXBaseDecl && "Base type is not a C++ type") ? static_cast
<void> (0) : __assert_fail ("CXXBaseDecl && \"Base type is not a C++ type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 2501, __PRETTY_FUNCTION__))
; 2502 2503 // Microsoft docs say: 2504 // "If a base-class has a code_seg attribute, derived classes must have the 2505 // same attribute." 2506 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2507 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2508 if ((DerivedCSA || BaseCSA) && 2509 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2510 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2511 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2512 << CXXBaseDecl; 2513 return nullptr; 2514 } 2515 2516 // A class which contains a flexible array member is not suitable for use as a 2517 // base class: 2518 // - If the layout determines that a base comes before another base, 2519 // the flexible array member would index into the subsequent base. 2520 // - If the layout determines that base comes before the derived class, 2521 // the flexible array member would index into the derived class. 2522 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2523 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2524 << CXXBaseDecl->getDeclName(); 2525 return nullptr; 2526 } 2527 2528 // C++ [class]p3: 2529 // If a class is marked final and it appears as a base-type-specifier in 2530 // base-clause, the program is ill-formed. 2531 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2532 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2533 << CXXBaseDecl->getDeclName() 2534 << FA->isSpelledAsSealed(); 2535 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2536 << CXXBaseDecl->getDeclName() << FA->getRange(); 2537 return nullptr; 2538 } 2539 2540 if (BaseDecl->isInvalidDecl()) 2541 Class->setInvalidDecl(); 2542 2543 // Create the base specifier. 2544 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2545 Class->getTagKind() == TTK_Class, 2546 Access, TInfo, EllipsisLoc); 2547} 2548 2549/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2550/// one entry in the base class list of a class specifier, for 2551/// example: 2552/// class foo : public bar, virtual private baz { 2553/// 'public bar' and 'virtual private baz' are each base-specifiers. 2554BaseResult 2555Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2556 ParsedAttributes &Attributes, 2557 bool Virtual, AccessSpecifier Access, 2558 ParsedType basetype, SourceLocation BaseLoc, 2559 SourceLocation EllipsisLoc) { 2560 if (!classdecl) 2561 return true; 2562 2563 AdjustDeclIfTemplate(classdecl); 2564 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2565 if (!Class) 2566 return true; 2567 2568 // We haven't yet attached the base specifiers. 2569 Class->setIsParsingBaseSpecifiers(); 2570 2571 // We do not support any C++11 attributes on base-specifiers yet. 2572 // Diagnose any attributes we see. 2573 for (const ParsedAttr &AL : Attributes) { 2574 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2575 continue; 2576 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2577 ? (unsigned)diag::warn_unknown_attribute_ignored 2578 : (unsigned)diag::err_base_specifier_attribute) 2579 << AL; 2580 } 2581 2582 TypeSourceInfo *TInfo = nullptr; 2583 GetTypeFromParser(basetype, &TInfo); 2584 2585 if (EllipsisLoc.isInvalid() && 2586 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2587 UPPC_BaseType)) 2588 return true; 2589 2590 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2591 Virtual, Access, TInfo, 2592 EllipsisLoc)) 2593 return BaseSpec; 2594 else 2595 Class->setInvalidDecl(); 2596 2597 return true; 2598} 2599 2600/// Use small set to collect indirect bases. As this is only used 2601/// locally, there's no need to abstract the small size parameter. 2602typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2603 2604/// Recursively add the bases of Type. Don't add Type itself. 2605static void 2606NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2607 const QualType &Type) 2608{ 2609 // Even though the incoming type is a base, it might not be 2610 // a class -- it could be a template parm, for instance. 2611 if (auto Rec = Type->getAs<RecordType>()) { 2612 auto Decl = Rec->getAsCXXRecordDecl(); 2613 2614 // Iterate over its bases. 2615 for (const auto &BaseSpec : Decl->bases()) { 2616 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2617 .getUnqualifiedType(); 2618 if (Set.insert(Base).second) 2619 // If we've not already seen it, recurse. 2620 NoteIndirectBases(Context, Set, Base); 2621 } 2622 } 2623} 2624 2625/// Performs the actual work of attaching the given base class 2626/// specifiers to a C++ class. 2627bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2628 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2629 if (Bases.empty()) 2630 return false; 2631 2632 // Used to keep track of which base types we have already seen, so 2633 // that we can properly diagnose redundant direct base types. Note 2634 // that the key is always the unqualified canonical type of the base 2635 // class. 2636 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2637 2638 // Used to track indirect bases so we can see if a direct base is 2639 // ambiguous. 2640 IndirectBaseSet IndirectBaseTypes; 2641 2642 // Copy non-redundant base specifiers into permanent storage. 2643 unsigned NumGoodBases = 0; 2644 bool Invalid = false; 2645 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2646 QualType NewBaseType 2647 = Context.getCanonicalType(Bases[idx]->getType()); 2648 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2649 2650 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2651 if (KnownBase) { 2652 // C++ [class.mi]p3: 2653 // A class shall not be specified as a direct base class of a 2654 // derived class more than once. 2655 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2656 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2657 2658 // Delete the duplicate base class specifier; we're going to 2659 // overwrite its pointer later. 2660 Context.Deallocate(Bases[idx]); 2661 2662 Invalid = true; 2663 } else { 2664 // Okay, add this new base class. 2665 KnownBase = Bases[idx]; 2666 Bases[NumGoodBases++] = Bases[idx]; 2667 2668 // Note this base's direct & indirect bases, if there could be ambiguity. 2669 if (Bases.size() > 1) 2670 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2671 2672 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2673 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2674 if (Class->isInterface() && 2675 (!RD->isInterfaceLike() || 2676 KnownBase->getAccessSpecifier() != AS_public)) { 2677 // The Microsoft extension __interface does not permit bases that 2678 // are not themselves public interfaces. 2679 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2680 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2681 << RD->getSourceRange(); 2682 Invalid = true; 2683 } 2684 if (RD->hasAttr<WeakAttr>()) 2685 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2686 } 2687 } 2688 } 2689 2690 // Attach the remaining base class specifiers to the derived class. 2691 Class->setBases(Bases.data(), NumGoodBases); 2692 2693 // Check that the only base classes that are duplicate are virtual. 2694 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2695 // Check whether this direct base is inaccessible due to ambiguity. 2696 QualType BaseType = Bases[idx]->getType(); 2697 2698 // Skip all dependent types in templates being used as base specifiers. 2699 // Checks below assume that the base specifier is a CXXRecord. 2700 if (BaseType->isDependentType()) 2701 continue; 2702 2703 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2704 .getUnqualifiedType(); 2705 2706 if (IndirectBaseTypes.count(CanonicalBase)) { 2707 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2708 /*DetectVirtual=*/true); 2709 bool found 2710 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2711 assert(found)((found) ? static_cast<void> (0) : __assert_fail ("found"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 2711, __PRETTY_FUNCTION__))
; 2712 (void)found; 2713 2714 if (Paths.isAmbiguous(CanonicalBase)) 2715 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2716 << BaseType << getAmbiguousPathsDisplayString(Paths) 2717 << Bases[idx]->getSourceRange(); 2718 else 2719 assert(Bases[idx]->isVirtual())((Bases[idx]->isVirtual()) ? static_cast<void> (0) :
__assert_fail ("Bases[idx]->isVirtual()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 2719, __PRETTY_FUNCTION__))
; 2720 } 2721 2722 // Delete the base class specifier, since its data has been copied 2723 // into the CXXRecordDecl. 2724 Context.Deallocate(Bases[idx]); 2725 } 2726 2727 return Invalid; 2728} 2729 2730/// ActOnBaseSpecifiers - Attach the given base specifiers to the 2731/// class, after checking whether there are any duplicate base 2732/// classes. 2733void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2734 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2735 if (!ClassDecl || Bases.empty()) 2736 return; 2737 2738 AdjustDeclIfTemplate(ClassDecl); 2739 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2740} 2741 2742/// Determine whether the type \p Derived is a C++ class that is 2743/// derived from the type \p Base. 2744bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2745 if (!getLangOpts().CPlusPlus) 2746 return false; 2747 2748 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2749 if (!DerivedRD) 2750 return false; 2751 2752 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2753 if (!BaseRD) 2754 return false; 2755 2756 // If either the base or the derived type is invalid, don't try to 2757 // check whether one is derived from the other. 2758 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2759 return false; 2760 2761 // FIXME: In a modules build, do we need the entire path to be visible for us 2762 // to be able to use the inheritance relationship? 2763 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2764 return false; 2765 2766 return DerivedRD->isDerivedFrom(BaseRD); 2767} 2768 2769/// Determine whether the type \p Derived is a C++ class that is 2770/// derived from the type \p Base. 2771bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2772 CXXBasePaths &Paths) { 2773 if (!getLangOpts().CPlusPlus) 2774 return false; 2775 2776 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2777 if (!DerivedRD) 2778 return false; 2779 2780 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2781 if (!BaseRD) 2782 return false; 2783 2784 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2785 return false; 2786 2787 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2788} 2789 2790static void BuildBasePathArray(const CXXBasePath &Path, 2791 CXXCastPath &BasePathArray) { 2792 // We first go backward and check if we have a virtual base. 2793 // FIXME: It would be better if CXXBasePath had the base specifier for 2794 // the nearest virtual base. 2795 unsigned Start = 0; 2796 for (unsigned I = Path.size(); I != 0; --I) { 2797 if (Path[I - 1].Base->isVirtual()) { 2798 Start = I - 1; 2799 break; 2800 } 2801 } 2802 2803 // Now add all bases. 2804 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2805 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2806} 2807 2808 2809void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2810 CXXCastPath &BasePathArray) { 2811 assert(BasePathArray.empty() && "Base path array must be empty!")((BasePathArray.empty() && "Base path array must be empty!"
) ? static_cast<void> (0) : __assert_fail ("BasePathArray.empty() && \"Base path array must be empty!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 2811, __PRETTY_FUNCTION__))
; 2812 assert(Paths.isRecordingPaths() && "Must record paths!")((Paths.isRecordingPaths() && "Must record paths!") ?
static_cast<void> (0) : __assert_fail ("Paths.isRecordingPaths() && \"Must record paths!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 2812, __PRETTY_FUNCTION__))
; 2813 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2814} 2815/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2816/// conversion (where Derived and Base are class types) is 2817/// well-formed, meaning that the conversion is unambiguous (and 2818/// that all of the base classes are accessible). Returns true 2819/// and emits a diagnostic if the code is ill-formed, returns false 2820/// otherwise. Loc is the location where this routine should point to 2821/// if there is an error, and Range is the source range to highlight 2822/// if there is an error. 2823/// 2824/// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2825/// diagnostic for the respective type of error will be suppressed, but the 2826/// check for ill-formed code will still be performed. 2827bool 2828Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2829 unsigned InaccessibleBaseID, 2830 unsigned AmbigiousBaseConvID, 2831 SourceLocation Loc, SourceRange Range, 2832 DeclarationName Name, 2833 CXXCastPath *BasePath, 2834 bool IgnoreAccess) { 2835 // First, determine whether the path from Derived to Base is 2836 // ambiguous. This is slightly more expensive than checking whether 2837 // the Derived to Base conversion exists, because here we need to 2838 // explore multiple paths to determine if there is an ambiguity. 2839 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2840 /*DetectVirtual=*/false); 2841 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2842 if (!DerivationOkay) 2843 return true; 2844 2845 const CXXBasePath *Path = nullptr; 2846 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2847 Path = &Paths.front(); 2848 2849 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2850 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2851 // user to access such bases. 2852 if (!Path && getLangOpts().MSVCCompat) { 2853 for (const CXXBasePath &PossiblePath : Paths) { 2854 if (PossiblePath.size() == 1) { 2855 Path = &PossiblePath; 2856 if (AmbigiousBaseConvID) 2857 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2858 << Base << Derived << Range; 2859 break; 2860 } 2861 } 2862 } 2863 2864 if (Path) { 2865 if (!IgnoreAccess) { 2866 // Check that the base class can be accessed. 2867 switch ( 2868 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2869 case AR_inaccessible: 2870 return true; 2871 case AR_accessible: 2872 case AR_dependent: 2873 case AR_delayed: 2874 break; 2875 } 2876 } 2877 2878 // Build a base path if necessary. 2879 if (BasePath) 2880 ::BuildBasePathArray(*Path, *BasePath); 2881 return false; 2882 } 2883 2884 if (AmbigiousBaseConvID) { 2885 // We know that the derived-to-base conversion is ambiguous, and 2886 // we're going to produce a diagnostic. Perform the derived-to-base 2887 // search just one more time to compute all of the possible paths so 2888 // that we can print them out. This is more expensive than any of 2889 // the previous derived-to-base checks we've done, but at this point 2890 // performance isn't as much of an issue. 2891 Paths.clear(); 2892 Paths.setRecordingPaths(true); 2893 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2894 assert(StillOkay && "Can only be used with a derived-to-base conversion")((StillOkay && "Can only be used with a derived-to-base conversion"
) ? static_cast<void> (0) : __assert_fail ("StillOkay && \"Can only be used with a derived-to-base conversion\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 2894, __PRETTY_FUNCTION__))
; 2895 (void)StillOkay; 2896 2897 // Build up a textual representation of the ambiguous paths, e.g., 2898 // D -> B -> A, that will be used to illustrate the ambiguous 2899 // conversions in the diagnostic. We only print one of the paths 2900 // to each base class subobject. 2901 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2902 2903 Diag(Loc, AmbigiousBaseConvID) 2904 << Derived << Base << PathDisplayStr << Range << Name; 2905 } 2906 return true; 2907} 2908 2909bool 2910Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2911 SourceLocation Loc, SourceRange Range, 2912 CXXCastPath *BasePath, 2913 bool IgnoreAccess) { 2914 return CheckDerivedToBaseConversion( 2915 Derived, Base, diag::err_upcast_to_inaccessible_base, 2916 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2917 BasePath, IgnoreAccess); 2918} 2919 2920 2921/// Builds a string representing ambiguous paths from a 2922/// specific derived class to different subobjects of the same base 2923/// class. 2924/// 2925/// This function builds a string that can be used in error messages 2926/// to show the different paths that one can take through the 2927/// inheritance hierarchy to go from the derived class to different 2928/// subobjects of a base class. The result looks something like this: 2929/// @code 2930/// struct D -> struct B -> struct A 2931/// struct D -> struct C -> struct A 2932/// @endcode 2933std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2934 std::string PathDisplayStr; 2935 std::set<unsigned> DisplayedPaths; 2936 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2937 Path != Paths.end(); ++Path) { 2938 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2939 // We haven't displayed a path to this particular base 2940 // class subobject yet. 2941 PathDisplayStr += "\n "; 2942 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2943 for (CXXBasePath::const_iterator Element = Path->begin(); 2944 Element != Path->end(); ++Element) 2945 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2946 } 2947 } 2948 2949 return PathDisplayStr; 2950} 2951 2952//===----------------------------------------------------------------------===// 2953// C++ class member Handling 2954//===----------------------------------------------------------------------===// 2955 2956/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2957bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2958 SourceLocation ColonLoc, 2959 const ParsedAttributesView &Attrs) { 2960 assert(Access != AS_none && "Invalid kind for syntactic access specifier!")((Access != AS_none && "Invalid kind for syntactic access specifier!"
) ? static_cast<void> (0) : __assert_fail ("Access != AS_none && \"Invalid kind for syntactic access specifier!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 2960, __PRETTY_FUNCTION__))
; 2961 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2962 ASLoc, ColonLoc); 2963 CurContext->addHiddenDecl(ASDecl); 2964 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2965} 2966 2967/// CheckOverrideControl - Check C++11 override control semantics. 2968void Sema::CheckOverrideControl(NamedDecl *D) { 2969 if (D->isInvalidDecl()) 2970 return; 2971 2972 // We only care about "override" and "final" declarations. 2973 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2974 return; 2975 2976 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2977 2978 // We can't check dependent instance methods. 2979 if (MD && MD->isInstance() && 2980 (MD->getParent()->hasAnyDependentBases() || 2981 MD->getType()->isDependentType())) 2982 return; 2983 2984 if (MD && !MD->isVirtual()) { 2985 // If we have a non-virtual method, check if if hides a virtual method. 2986 // (In that case, it's most likely the method has the wrong type.) 2987 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2988 FindHiddenVirtualMethods(MD, OverloadedMethods); 2989 2990 if (!OverloadedMethods.empty()) { 2991 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2992 Diag(OA->getLocation(), 2993 diag::override_keyword_hides_virtual_member_function) 2994 << "override" << (OverloadedMethods.size() > 1); 2995 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2996 Diag(FA->getLocation(), 2997 diag::override_keyword_hides_virtual_member_function) 2998 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2999 << (OverloadedMethods.size() > 1); 3000 } 3001 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3002 MD->setInvalidDecl(); 3003 return; 3004 } 3005 // Fall through into the general case diagnostic. 3006 // FIXME: We might want to attempt typo correction here. 3007 } 3008 3009 if (!MD || !MD->isVirtual()) { 3010 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3011 Diag(OA->getLocation(), 3012 diag::override_keyword_only_allowed_on_virtual_member_functions) 3013 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3014 D->dropAttr<OverrideAttr>(); 3015 } 3016 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3017 Diag(FA->getLocation(), 3018 diag::override_keyword_only_allowed_on_virtual_member_functions) 3019 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3020 << FixItHint::CreateRemoval(FA->getLocation()); 3021 D->dropAttr<FinalAttr>(); 3022 } 3023 return; 3024 } 3025 3026 // C++11 [class.virtual]p5: 3027 // If a function is marked with the virt-specifier override and 3028 // does not override a member function of a base class, the program is 3029 // ill-formed. 3030 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3031 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3032 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3033 << MD->getDeclName(); 3034} 3035 3036void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 3037 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3038 return; 3039 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3040 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3041 return; 3042 3043 SourceLocation Loc = MD->getLocation(); 3044 SourceLocation SpellingLoc = Loc; 3045 if (getSourceManager().isMacroArgExpansion(Loc)) 3046 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3047 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3048 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3049 return; 3050 3051 if (MD->size_overridden_methods() > 0) { 3052 unsigned DiagID = isa<CXXDestructorDecl>(MD) 3053 ? diag::warn_destructor_marked_not_override_overriding 3054 : diag::warn_function_marked_not_override_overriding; 3055 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3056 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3057 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3058 } 3059} 3060 3061/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3062/// function overrides a virtual member function marked 'final', according to 3063/// C++11 [class.virtual]p4. 3064bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3065 const CXXMethodDecl *Old) { 3066 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3067 if (!FA) 3068 return false; 3069 3070 Diag(New->getLocation(), diag::err_final_function_overridden) 3071 << New->getDeclName() 3072 << FA->isSpelledAsSealed(); 3073 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3074 return true; 3075} 3076 3077static bool InitializationHasSideEffects(const FieldDecl &FD) { 3078 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3079 // FIXME: Destruction of ObjC lifetime types has side-effects. 3080 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3081 return !RD->isCompleteDefinition() || 3082 !RD->hasTrivialDefaultConstructor() || 3083 !RD->hasTrivialDestructor(); 3084 return false; 3085} 3086 3087static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3088 ParsedAttributesView::const_iterator Itr = 3089 llvm::find_if(list, [](const ParsedAttr &AL) { 3090 return AL.isDeclspecPropertyAttribute(); 3091 }); 3092 if (Itr != list.end()) 3093 return &*Itr; 3094 return nullptr; 3095} 3096 3097// Check if there is a field shadowing. 3098void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3099 DeclarationName FieldName, 3100 const CXXRecordDecl *RD, 3101 bool DeclIsField) { 3102 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3103 return; 3104 3105 // To record a shadowed field in a base 3106 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3107 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3108 CXXBasePath &Path) { 3109 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3110 // Record an ambiguous path directly 3111 if (Bases.find(Base) != Bases.end()) 3112 return true; 3113 for (const auto Field : Base->lookup(FieldName)) { 3114 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3115 Field->getAccess() != AS_private) { 3116 assert(Field->getAccess() != AS_none)((Field->getAccess() != AS_none) ? static_cast<void>
(0) : __assert_fail ("Field->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 3116, __PRETTY_FUNCTION__))
; 3117 assert(Bases.find(Base) == Bases.end())((Bases.find(Base) == Bases.end()) ? static_cast<void> (
0) : __assert_fail ("Bases.find(Base) == Bases.end()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 3117, __PRETTY_FUNCTION__))
; 3118 Bases[Base] = Field; 3119 return true; 3120 } 3121 } 3122 return false; 3123 }; 3124 3125 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3126 /*DetectVirtual=*/true); 3127 if (!RD->lookupInBases(FieldShadowed, Paths)) 3128 return; 3129 3130 for (const auto &P : Paths) { 3131 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3132 auto It = Bases.find(Base); 3133 // Skip duplicated bases 3134 if (It == Bases.end()) 3135 continue; 3136 auto BaseField = It->second; 3137 assert(BaseField->getAccess() != AS_private)((BaseField->getAccess() != AS_private) ? static_cast<void
> (0) : __assert_fail ("BaseField->getAccess() != AS_private"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 3137, __PRETTY_FUNCTION__))
; 3138 if (AS_none != 3139 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3140 Diag(Loc, diag::warn_shadow_field) 3141 << FieldName << RD << Base << DeclIsField; 3142 Diag(BaseField->getLocation(), diag::note_shadow_field); 3143 Bases.erase(It); 3144 } 3145 } 3146} 3147 3148/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3149/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3150/// bitfield width if there is one, 'InitExpr' specifies the initializer if 3151/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3152/// present (but parsing it has been deferred). 3153NamedDecl * 3154Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3155 MultiTemplateParamsArg TemplateParameterLists, 3156 Expr *BW, const VirtSpecifiers &VS, 3157 InClassInitStyle InitStyle) { 3158 const DeclSpec &DS = D.getDeclSpec(); 3159 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3160 DeclarationName Name = NameInfo.getName(); 3161 SourceLocation Loc = NameInfo.getLoc(); 3162 3163 // For anonymous bitfields, the location should point to the type. 3164 if (Loc.isInvalid()) 3165 Loc = D.getBeginLoc(); 3166 3167 Expr *BitWidth = static_cast<Expr*>(BW); 3168 3169 assert(isa<CXXRecordDecl>(CurContext))((isa<CXXRecordDecl>(CurContext)) ? static_cast<void
> (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 3169, __PRETTY_FUNCTION__))
; 3170 assert(!DS.isFriendSpecified())((!DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail
("!DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 3170, __PRETTY_FUNCTION__))
; 3171 3172 bool isFunc = D.isDeclarationOfFunction(); 3173 const ParsedAttr *MSPropertyAttr = 3174 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3175 3176 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3177 // The Microsoft extension __interface only permits public member functions 3178 // and prohibits constructors, destructors, operators, non-public member 3179 // functions, static methods and data members. 3180 unsigned InvalidDecl; 3181 bool ShowDeclName = true; 3182 if (!isFunc && 3183 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3184 InvalidDecl = 0; 3185 else if (!isFunc) 3186 InvalidDecl = 1; 3187 else if (AS != AS_public) 3188 InvalidDecl = 2; 3189 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3190 InvalidDecl = 3; 3191 else switch (Name.getNameKind()) { 3192 case DeclarationName::CXXConstructorName: 3193 InvalidDecl = 4; 3194 ShowDeclName = false; 3195 break; 3196 3197 case DeclarationName::CXXDestructorName: 3198 InvalidDecl = 5; 3199 ShowDeclName = false; 3200 break; 3201 3202 case DeclarationName::CXXOperatorName: 3203 case DeclarationName::CXXConversionFunctionName: 3204 InvalidDecl = 6; 3205 break; 3206 3207 default: 3208 InvalidDecl = 0; 3209 break; 3210 } 3211 3212 if (InvalidDecl) { 3213 if (ShowDeclName) 3214 Diag(Loc, diag::err_invalid_member_in_interface) 3215 << (InvalidDecl-1) << Name; 3216 else 3217 Diag(Loc, diag::err_invalid_member_in_interface) 3218 << (InvalidDecl-1) << ""; 3219 return nullptr; 3220 } 3221 } 3222 3223 // C++ 9.2p6: A member shall not be declared to have automatic storage 3224 // duration (auto, register) or with the extern storage-class-specifier. 3225 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3226 // data members and cannot be applied to names declared const or static, 3227 // and cannot be applied to reference members. 3228 switch (DS.getStorageClassSpec()) { 3229 case DeclSpec::SCS_unspecified: 3230 case DeclSpec::SCS_typedef: 3231 case DeclSpec::SCS_static: 3232 break; 3233 case DeclSpec::SCS_mutable: 3234 if (isFunc) { 3235 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3236 3237 // FIXME: It would be nicer if the keyword was ignored only for this 3238 // declarator. Otherwise we could get follow-up errors. 3239 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3240 } 3241 break; 3242 default: 3243 Diag(DS.getStorageClassSpecLoc(), 3244 diag::err_storageclass_invalid_for_member); 3245 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3246 break; 3247 } 3248 3249 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3250 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3251 !isFunc); 3252 3253 if (DS.hasConstexprSpecifier() && isInstField) { 3254 SemaDiagnosticBuilder B = 3255 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3256 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3257 if (InitStyle == ICIS_NoInit) { 3258 B << 0 << 0; 3259 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3260 B << FixItHint::CreateRemoval(ConstexprLoc); 3261 else { 3262 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3263 D.getMutableDeclSpec().ClearConstexprSpec(); 3264 const char *PrevSpec; 3265 unsigned DiagID; 3266 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3267 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3268 (void)Failed; 3269 assert(!Failed && "Making a constexpr member const shouldn't fail")((!Failed && "Making a constexpr member const shouldn't fail"
) ? static_cast<void> (0) : __assert_fail ("!Failed && \"Making a constexpr member const shouldn't fail\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 3269, __PRETTY_FUNCTION__))
; 3270 } 3271 } else { 3272 B << 1; 3273 const char *PrevSpec; 3274 unsigned DiagID; 3275 if (D.getMutableDeclSpec().SetStorageClassSpec( 3276 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3277 Context.getPrintingPolicy())) { 3278 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&((DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
"This is the only DeclSpec that should fail to be applied") ?
static_cast<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 3279, __PRETTY_FUNCTION__))
3279 "This is the only DeclSpec that should fail to be applied")((DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
"This is the only DeclSpec that should fail to be applied") ?
static_cast<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 3279, __PRETTY_FUNCTION__))
; 3280 B << 1; 3281 } else { 3282 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3283 isInstField = false; 3284 } 3285 } 3286 } 3287 3288 NamedDecl *Member; 3289 if (isInstField) { 3290 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3291 3292 // Data members must have identifiers for names. 3293 if (!Name.isIdentifier()) { 3294 Diag(Loc, diag::err_bad_variable_name) 3295 << Name; 3296 return nullptr; 3297 } 3298 3299 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3300 3301 // Member field could not be with "template" keyword. 3302 // So TemplateParameterLists should be empty in this case. 3303 if (TemplateParameterLists.size()) { 3304 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3305 if (TemplateParams->size()) { 3306 // There is no such thing as a member field template. 3307 Diag(D.getIdentifierLoc(), diag::err_template_member) 3308 << II 3309 << SourceRange(TemplateParams->getTemplateLoc(), 3310 TemplateParams->getRAngleLoc()); 3311 } else { 3312 // There is an extraneous 'template<>' for this member. 3313 Diag(TemplateParams->getTemplateLoc(), 3314 diag::err_template_member_noparams) 3315 << II 3316 << SourceRange(TemplateParams->getTemplateLoc(), 3317 TemplateParams->getRAngleLoc()); 3318 } 3319 return nullptr; 3320 } 3321 3322 if (SS.isSet() && !SS.isInvalid()) { 3323 // The user provided a superfluous scope specifier inside a class 3324 // definition: 3325 // 3326 // class X { 3327 // int X::member; 3328 // }; 3329 if (DeclContext *DC = computeDeclContext(SS, false)) 3330 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3331 D.getName().getKind() == 3332 UnqualifiedIdKind::IK_TemplateId); 3333 else 3334 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3335 << Name << SS.getRange(); 3336 3337 SS.clear(); 3338 } 3339 3340 if (MSPropertyAttr) { 3341 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3342 BitWidth, InitStyle, AS, *MSPropertyAttr); 3343 if (!Member) 3344 return nullptr; 3345 isInstField = false; 3346 } else { 3347 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3348 BitWidth, InitStyle, AS); 3349 if (!Member) 3350 return nullptr; 3351 } 3352 3353 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3354 } else { 3355 Member = HandleDeclarator(S, D, TemplateParameterLists); 3356 if (!Member) 3357 return nullptr; 3358 3359 // Non-instance-fields can't have a bitfield. 3360 if (BitWidth) { 3361 if (Member->isInvalidDecl()) { 3362 // don't emit another diagnostic. 3363 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3364 // C++ 9.6p3: A bit-field shall not be a static member. 3365 // "static member 'A' cannot be a bit-field" 3366 Diag(Loc, diag::err_static_not_bitfield) 3367 << Name << BitWidth->getSourceRange(); 3368 } else if (isa<TypedefDecl>(Member)) { 3369 // "typedef member 'x' cannot be a bit-field" 3370 Diag(Loc, diag::err_typedef_not_bitfield) 3371 << Name << BitWidth->getSourceRange(); 3372 } else { 3373 // A function typedef ("typedef int f(); f a;"). 3374 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3375 Diag(Loc, diag::err_not_integral_type_bitfield) 3376 << Name << cast<ValueDecl>(Member)->getType() 3377 << BitWidth->getSourceRange(); 3378 } 3379 3380 BitWidth = nullptr; 3381 Member->setInvalidDecl(); 3382 } 3383 3384 NamedDecl *NonTemplateMember = Member; 3385 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3386 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3387 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3388 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3389 3390 Member->setAccess(AS); 3391 3392 // If we have declared a member function template or static data member 3393 // template, set the access of the templated declaration as well. 3394 if (NonTemplateMember != Member) 3395 NonTemplateMember->setAccess(AS); 3396 3397 // C++ [temp.deduct.guide]p3: 3398 // A deduction guide [...] for a member class template [shall be 3399 // declared] with the same access [as the template]. 3400 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3401 auto *TD = DG->getDeducedTemplate(); 3402 // Access specifiers are only meaningful if both the template and the 3403 // deduction guide are from the same scope. 3404 if (AS != TD->getAccess() && 3405 TD->getDeclContext()->getRedeclContext()->Equals( 3406 DG->getDeclContext()->getRedeclContext())) { 3407 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3408 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3409 << TD->getAccess(); 3410 const AccessSpecDecl *LastAccessSpec = nullptr; 3411 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3412 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3413 LastAccessSpec = AccessSpec; 3414 } 3415 assert(LastAccessSpec && "differing access with no access specifier")((LastAccessSpec && "differing access with no access specifier"
) ? static_cast<void> (0) : __assert_fail ("LastAccessSpec && \"differing access with no access specifier\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 3415, __PRETTY_FUNCTION__))
; 3416 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3417 << AS; 3418 } 3419 } 3420 } 3421 3422 if (VS.isOverrideSpecified()) 3423 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3424 AttributeCommonInfo::AS_Keyword)); 3425 if (VS.isFinalSpecified()) 3426 Member->addAttr(FinalAttr::Create( 3427 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3428 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3429 3430 if (VS.getLastLocation().isValid()) { 3431 // Update the end location of a method that has a virt-specifiers. 3432 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3433 MD->setRangeEnd(VS.getLastLocation()); 3434 } 3435 3436 CheckOverrideControl(Member); 3437 3438 assert((Name || isInstField) && "No identifier for non-field ?")(((Name || isInstField) && "No identifier for non-field ?"
) ? static_cast<void> (0) : __assert_fail ("(Name || isInstField) && \"No identifier for non-field ?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 3438, __PRETTY_FUNCTION__))
; 3439 3440 if (isInstField) { 3441 FieldDecl *FD = cast<FieldDecl>(Member); 3442 FieldCollector->Add(FD); 3443 3444 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3445 // Remember all explicit private FieldDecls that have a name, no side 3446 // effects and are not part of a dependent type declaration. 3447 if (!FD->isImplicit() && FD->getDeclName() && 3448 FD->getAccess() == AS_private && 3449 !FD->hasAttr<UnusedAttr>() && 3450 !FD->getParent()->isDependentContext() && 3451 !InitializationHasSideEffects(*FD)) 3452 UnusedPrivateFields.insert(FD); 3453 } 3454 } 3455 3456 return Member; 3457} 3458 3459namespace { 3460 class UninitializedFieldVisitor 3461 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3462 Sema &S; 3463 // List of Decls to generate a warning on. Also remove Decls that become 3464 // initialized. 3465 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3466 // List of base classes of the record. Classes are removed after their 3467 // initializers. 3468 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3469 // Vector of decls to be removed from the Decl set prior to visiting the 3470 // nodes. These Decls may have been initialized in the prior initializer. 3471 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3472 // If non-null, add a note to the warning pointing back to the constructor. 3473 const CXXConstructorDecl *Constructor; 3474 // Variables to hold state when processing an initializer list. When 3475 // InitList is true, special case initialization of FieldDecls matching 3476 // InitListFieldDecl. 3477 bool InitList; 3478 FieldDecl *InitListFieldDecl; 3479 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3480 3481 public: 3482 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3483 UninitializedFieldVisitor(Sema &S, 3484 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3485 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3486 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3487 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3488 3489 // Returns true if the use of ME is not an uninitialized use. 3490 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3491 bool CheckReferenceOnly) { 3492 llvm::SmallVector<FieldDecl*, 4> Fields; 3493 bool ReferenceField = false; 3494 while (ME) { 3495 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3496 if (!FD) 3497 return false; 3498 Fields.push_back(FD); 3499 if (FD->getType()->isReferenceType()) 3500 ReferenceField = true; 3501 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3502 } 3503 3504 // Binding a reference to an uninitialized field is not an 3505 // uninitialized use. 3506 if (CheckReferenceOnly && !ReferenceField) 3507 return true; 3508 3509 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3510 // Discard the first field since it is the field decl that is being 3511 // initialized. 3512 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3513 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3514 } 3515 3516 for (auto UsedIter = UsedFieldIndex.begin(), 3517 UsedEnd = UsedFieldIndex.end(), 3518 OrigIter = InitFieldIndex.begin(), 3519 OrigEnd = InitFieldIndex.end(); 3520 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3521 if (*UsedIter < *OrigIter) 3522 return true; 3523 if (*UsedIter > *OrigIter) 3524 break; 3525 } 3526 3527 return false; 3528 } 3529 3530 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3531 bool AddressOf) { 3532 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3533 return; 3534 3535 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3536 // or union. 3537 MemberExpr *FieldME = ME; 3538 3539 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3540 3541 Expr *Base = ME; 3542 while (MemberExpr *SubME = 3543 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3544 3545 if (isa<VarDecl>(SubME->getMemberDecl())) 3546 return; 3547 3548 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3549 if (!FD->isAnonymousStructOrUnion()) 3550 FieldME = SubME; 3551 3552 if (!FieldME->getType().isPODType(S.Context)) 3553 AllPODFields = false; 3554 3555 Base = SubME->getBase(); 3556 } 3557 3558 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3559 return; 3560 3561 if (AddressOf && AllPODFields) 3562 return; 3563 3564 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3565 3566 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3567 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3568 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3569 } 3570 3571 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3572 QualType T = BaseCast->getType(); 3573 if (T->isPointerType() && 3574 BaseClasses.count(T->getPointeeType())) { 3575 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3576 << T->getPointeeType() << FoundVD; 3577 } 3578 } 3579 } 3580 3581 if (!Decls.count(FoundVD)) 3582 return; 3583 3584 const bool IsReference = FoundVD->getType()->isReferenceType(); 3585 3586 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3587 // Special checking for initializer lists. 3588 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3589 return; 3590 } 3591 } else { 3592 // Prevent double warnings on use of unbounded references. 3593 if (CheckReferenceOnly && !IsReference) 3594 return; 3595 } 3596 3597 unsigned diag = IsReference 3598 ? diag::warn_reference_field_is_uninit 3599 : diag::warn_field_is_uninit; 3600 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3601 if (Constructor) 3602 S.Diag(Constructor->getLocation(), 3603 diag::note_uninit_in_this_constructor) 3604 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3605 3606 } 3607 3608 void HandleValue(Expr *E, bool AddressOf) { 3609 E = E->IgnoreParens(); 3610 3611 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3612 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3613 AddressOf /*AddressOf*/); 3614 return; 3615 } 3616 3617 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3618 Visit(CO->getCond()); 3619 HandleValue(CO->getTrueExpr(), AddressOf); 3620 HandleValue(CO->getFalseExpr(), AddressOf); 3621 return; 3622 } 3623 3624 if (BinaryConditionalOperator *BCO = 3625 dyn_cast<BinaryConditionalOperator>(E)) { 3626 Visit(BCO->getCond()); 3627 HandleValue(BCO->getFalseExpr(), AddressOf); 3628 return; 3629 } 3630 3631 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3632 HandleValue(OVE->getSourceExpr(), AddressOf); 3633 return; 3634 } 3635 3636 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3637 switch (BO->getOpcode()) { 3638 default: 3639 break; 3640 case(BO_PtrMemD): 3641 case(BO_PtrMemI): 3642 HandleValue(BO->getLHS(), AddressOf); 3643 Visit(BO->getRHS()); 3644 return; 3645 case(BO_Comma): 3646 Visit(BO->getLHS()); 3647 HandleValue(BO->getRHS(), AddressOf); 3648 return; 3649 } 3650 } 3651 3652 Visit(E); 3653 } 3654 3655 void CheckInitListExpr(InitListExpr *ILE) { 3656 InitFieldIndex.push_back(0); 3657 for (auto Child : ILE->children()) { 3658 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3659 CheckInitListExpr(SubList); 3660 } else { 3661 Visit(Child); 3662 } 3663 ++InitFieldIndex.back(); 3664 } 3665 InitFieldIndex.pop_back(); 3666 } 3667 3668 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3669 FieldDecl *Field, const Type *BaseClass) { 3670 // Remove Decls that may have been initialized in the previous 3671 // initializer. 3672 for (ValueDecl* VD : DeclsToRemove) 3673 Decls.erase(VD); 3674 DeclsToRemove.clear(); 3675 3676 Constructor = FieldConstructor; 3677 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3678 3679 if (ILE && Field) { 3680 InitList = true; 3681 InitListFieldDecl = Field; 3682 InitFieldIndex.clear(); 3683 CheckInitListExpr(ILE); 3684 } else { 3685 InitList = false; 3686 Visit(E); 3687 } 3688 3689 if (Field) 3690 Decls.erase(Field); 3691 if (BaseClass) 3692 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3693 } 3694 3695 void VisitMemberExpr(MemberExpr *ME) { 3696 // All uses of unbounded reference fields will warn. 3697 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3698 } 3699 3700 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3701 if (E->getCastKind() == CK_LValueToRValue) { 3702 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3703 return; 3704 } 3705 3706 Inherited::VisitImplicitCastExpr(E); 3707 } 3708 3709 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3710 if (E->getConstructor()->isCopyConstructor()) { 3711 Expr *ArgExpr = E->getArg(0); 3712 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3713 if (ILE->getNumInits() == 1) 3714 ArgExpr = ILE->getInit(0); 3715 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3716 if (ICE->getCastKind() == CK_NoOp) 3717 ArgExpr = ICE->getSubExpr(); 3718 HandleValue(ArgExpr, false /*AddressOf*/); 3719 return; 3720 } 3721 Inherited::VisitCXXConstructExpr(E); 3722 } 3723 3724 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3725 Expr *Callee = E->getCallee(); 3726 if (isa<MemberExpr>(Callee)) { 3727 HandleValue(Callee, false /*AddressOf*/); 3728 for (auto Arg : E->arguments()) 3729 Visit(Arg); 3730 return; 3731 } 3732 3733 Inherited::VisitCXXMemberCallExpr(E); 3734 } 3735 3736 void VisitCallExpr(CallExpr *E) { 3737 // Treat std::move as a use. 3738 if (E->isCallToStdMove()) { 3739 HandleValue(E->getArg(0), /*AddressOf=*/false); 3740 return; 3741 } 3742 3743 Inherited::VisitCallExpr(E); 3744 } 3745 3746 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3747 Expr *Callee = E->getCallee(); 3748 3749 if (isa<UnresolvedLookupExpr>(Callee)) 3750 return Inherited::VisitCXXOperatorCallExpr(E); 3751 3752 Visit(Callee); 3753 for (auto Arg : E->arguments()) 3754 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3755 } 3756 3757 void VisitBinaryOperator(BinaryOperator *E) { 3758 // If a field assignment is detected, remove the field from the 3759 // uninitiailized field set. 3760 if (E->getOpcode() == BO_Assign) 3761 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3762 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3763 if (!FD->getType()->isReferenceType()) 3764 DeclsToRemove.push_back(FD); 3765 3766 if (E->isCompoundAssignmentOp()) { 3767 HandleValue(E->getLHS(), false /*AddressOf*/); 3768 Visit(E->getRHS()); 3769 return; 3770 } 3771 3772 Inherited::VisitBinaryOperator(E); 3773 } 3774 3775 void VisitUnaryOperator(UnaryOperator *E) { 3776 if (E->isIncrementDecrementOp()) { 3777 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3778 return; 3779 } 3780 if (E->getOpcode() == UO_AddrOf) { 3781 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3782 HandleValue(ME->getBase(), true /*AddressOf*/); 3783 return; 3784 } 3785 } 3786 3787 Inherited::VisitUnaryOperator(E); 3788 } 3789 }; 3790 3791 // Diagnose value-uses of fields to initialize themselves, e.g. 3792 // foo(foo) 3793 // where foo is not also a parameter to the constructor. 3794 // Also diagnose across field uninitialized use such as 3795 // x(y), y(x) 3796 // TODO: implement -Wuninitialized and fold this into that framework. 3797 static void DiagnoseUninitializedFields( 3798 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3799 3800 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3801 Constructor->getLocation())) { 3802 return; 3803 } 3804 3805 if (Constructor->isInvalidDecl()) 3806 return; 3807 3808 const CXXRecordDecl *RD = Constructor->getParent(); 3809 3810 if (RD->isDependentContext()) 3811 return; 3812 3813 // Holds fields that are uninitialized. 3814 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3815 3816 // At the beginning, all fields are uninitialized. 3817 for (auto *I : RD->decls()) { 3818 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3819 UninitializedFields.insert(FD); 3820 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3821 UninitializedFields.insert(IFD->getAnonField()); 3822 } 3823 } 3824 3825 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3826 for (auto I : RD->bases()) 3827 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3828 3829 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3830 return; 3831 3832 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3833 UninitializedFields, 3834 UninitializedBaseClasses); 3835 3836 for (const auto *FieldInit : Constructor->inits()) { 3837 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3838 break; 3839 3840 Expr *InitExpr = FieldInit->getInit(); 3841 if (!InitExpr) 3842 continue; 3843 3844 if (CXXDefaultInitExpr *Default = 3845 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3846 InitExpr = Default->getExpr(); 3847 if (!InitExpr) 3848 continue; 3849 // In class initializers will point to the constructor. 3850 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3851 FieldInit->getAnyMember(), 3852 FieldInit->getBaseClass()); 3853 } else { 3854 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3855 FieldInit->getAnyMember(), 3856 FieldInit->getBaseClass()); 3857 } 3858 } 3859 } 3860} // namespace 3861 3862/// Enter a new C++ default initializer scope. After calling this, the 3863/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3864/// parsing or instantiating the initializer failed. 3865void Sema::ActOnStartCXXInClassMemberInitializer() { 3866 // Create a synthetic function scope to represent the call to the constructor 3867 // that notionally surrounds a use of this initializer. 3868 PushFunctionScope(); 3869} 3870 3871void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3872 if (!D.isFunctionDeclarator()) 3873 return; 3874 auto &FTI = D.getFunctionTypeInfo(); 3875 if (!FTI.Params) 3876 return; 3877 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3878 FTI.NumParams)) { 3879 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3880 if (ParamDecl->getDeclName()) 3881 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3882 } 3883} 3884 3885ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3886 if (ConstraintExpr.isInvalid()) 3887 return ExprError(); 3888 return CorrectDelayedTyposInExpr(ConstraintExpr); 3889} 3890 3891/// This is invoked after parsing an in-class initializer for a 3892/// non-static C++ class member, and after instantiating an in-class initializer 3893/// in a class template. Such actions are deferred until the class is complete. 3894void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3895 SourceLocation InitLoc, 3896 Expr *InitExpr) { 3897 // Pop the notional constructor scope we created earlier. 3898 PopFunctionScopeInfo(nullptr, D); 3899 3900 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3901 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&(((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle
() != ICIS_NoInit) && "must set init style when field is created"
) ? static_cast<void> (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 3902, __PRETTY_FUNCTION__))
3902 "must set init style when field is created")(((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle
() != ICIS_NoInit) && "must set init style when field is created"
) ? static_cast<void> (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 3902, __PRETTY_FUNCTION__))
; 3903 3904 if (!InitExpr) { 3905 D->setInvalidDecl(); 3906 if (FD) 3907 FD->removeInClassInitializer(); 3908 return; 3909 } 3910 3911 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3912 FD->setInvalidDecl(); 3913 FD->removeInClassInitializer(); 3914 return; 3915 } 3916 3917 ExprResult Init = InitExpr; 3918 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3919 InitializedEntity Entity = 3920 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3921 InitializationKind Kind = 3922 FD->getInClassInitStyle() == ICIS_ListInit 3923 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3924 InitExpr->getBeginLoc(), 3925 InitExpr->getEndLoc()) 3926 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3927 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3928 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3929 if (Init.isInvalid()) { 3930 FD->setInvalidDecl(); 3931 return; 3932 } 3933 } 3934 3935 // C++11 [class.base.init]p7: 3936 // The initialization of each base and member constitutes a 3937 // full-expression. 3938 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 3939 if (Init.isInvalid()) { 3940 FD->setInvalidDecl(); 3941 return; 3942 } 3943 3944 InitExpr = Init.get(); 3945 3946 FD->setInClassInitializer(InitExpr); 3947} 3948 3949/// Find the direct and/or virtual base specifiers that 3950/// correspond to the given base type, for use in base initialization 3951/// within a constructor. 3952static bool FindBaseInitializer(Sema &SemaRef, 3953 CXXRecordDecl *ClassDecl, 3954 QualType BaseType, 3955 const CXXBaseSpecifier *&DirectBaseSpec, 3956 const CXXBaseSpecifier *&VirtualBaseSpec) { 3957 // First, check for a direct base class. 3958 DirectBaseSpec = nullptr; 3959 for (const auto &Base : ClassDecl->bases()) { 3960 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3961 // We found a direct base of this type. That's what we're 3962 // initializing. 3963 DirectBaseSpec = &Base; 3964 break; 3965 } 3966 } 3967 3968 // Check for a virtual base class. 3969 // FIXME: We might be able to short-circuit this if we know in advance that 3970 // there are no virtual bases. 3971 VirtualBaseSpec = nullptr; 3972 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3973 // We haven't found a base yet; search the class hierarchy for a 3974 // virtual base class. 3975 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3976 /*DetectVirtual=*/false); 3977 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3978 SemaRef.Context.getTypeDeclType(ClassDecl), 3979 BaseType, Paths)) { 3980 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3981 Path != Paths.end(); ++Path) { 3982 if (Path->back().Base->isVirtual()) { 3983 VirtualBaseSpec = Path->back().Base; 3984 break; 3985 } 3986 } 3987 } 3988 } 3989 3990 return DirectBaseSpec || VirtualBaseSpec; 3991} 3992 3993/// Handle a C++ member initializer using braced-init-list syntax. 3994MemInitResult 3995Sema::ActOnMemInitializer(Decl *ConstructorD, 3996 Scope *S, 3997 CXXScopeSpec &SS, 3998 IdentifierInfo *MemberOrBase, 3999 ParsedType TemplateTypeTy, 4000 const DeclSpec &DS, 4001 SourceLocation IdLoc, 4002 Expr *InitList, 4003 SourceLocation EllipsisLoc) { 4004 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4005 DS, IdLoc, InitList, 4006 EllipsisLoc); 4007} 4008 4009/// Handle a C++ member initializer using parentheses syntax. 4010MemInitResult 4011Sema::ActOnMemInitializer(Decl *ConstructorD, 4012 Scope *S, 4013 CXXScopeSpec &SS, 4014 IdentifierInfo *MemberOrBase, 4015 ParsedType TemplateTypeTy, 4016 const DeclSpec &DS, 4017 SourceLocation IdLoc, 4018 SourceLocation LParenLoc, 4019 ArrayRef<Expr *> Args, 4020 SourceLocation RParenLoc, 4021 SourceLocation EllipsisLoc) { 4022 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4023 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4024 DS, IdLoc, List, EllipsisLoc); 4025} 4026 4027namespace { 4028 4029// Callback to only accept typo corrections that can be a valid C++ member 4030// intializer: either a non-static field member or a base class. 4031class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4032public: 4033 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4034 : ClassDecl(ClassDecl) {} 4035 4036 bool ValidateCandidate(const TypoCorrection &candidate) override { 4037 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4038 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4039 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4040 return isa<TypeDecl>(ND); 4041 } 4042 return false; 4043 } 4044 4045 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4046 return std::make_unique<MemInitializerValidatorCCC>(*this); 4047 } 4048 4049private: 4050 CXXRecordDecl *ClassDecl; 4051}; 4052 4053} 4054 4055ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4056 CXXScopeSpec &SS, 4057 ParsedType TemplateTypeTy, 4058 IdentifierInfo *MemberOrBase) { 4059 if (SS.getScopeRep() || TemplateTypeTy) 4060 return nullptr; 4061 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 4062 if (Result.empty()) 4063 return nullptr; 4064 ValueDecl *Member; 4065 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 4066 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 4067 return Member; 4068 return nullptr; 4069} 4070 4071/// Handle a C++ member initializer. 4072MemInitResult 4073Sema::BuildMemInitializer(Decl *ConstructorD, 4074 Scope *S, 4075 CXXScopeSpec &SS, 4076 IdentifierInfo *MemberOrBase, 4077 ParsedType TemplateTypeTy, 4078 const DeclSpec &DS, 4079 SourceLocation IdLoc, 4080 Expr *Init, 4081 SourceLocation EllipsisLoc) { 4082 ExprResult Res = CorrectDelayedTyposInExpr(Init); 4083 if (!Res.isUsable()) 4084 return true; 4085 Init = Res.get(); 4086 4087 if (!ConstructorD) 4088 return true; 4089 4090 AdjustDeclIfTemplate(ConstructorD); 4091 4092 CXXConstructorDecl *Constructor 4093 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4094 if (!Constructor) { 4095 // The user wrote a constructor initializer on a function that is 4096 // not a C++ constructor. Ignore the error for now, because we may 4097 // have more member initializers coming; we'll diagnose it just 4098 // once in ActOnMemInitializers. 4099 return true; 4100 } 4101 4102 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4103 4104 // C++ [class.base.init]p2: 4105 // Names in a mem-initializer-id are looked up in the scope of the 4106 // constructor's class and, if not found in that scope, are looked 4107 // up in the scope containing the constructor's definition. 4108 // [Note: if the constructor's class contains a member with the 4109 // same name as a direct or virtual base class of the class, a 4110 // mem-initializer-id naming the member or base class and composed 4111 // of a single identifier refers to the class member. A 4112 // mem-initializer-id for the hidden base class may be specified 4113 // using a qualified name. ] 4114 4115 // Look for a member, first. 4116 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4117 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4118 if (EllipsisLoc.isValid()) 4119 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4120 << MemberOrBase 4121 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4122 4123 return BuildMemberInitializer(Member, Init, IdLoc); 4124 } 4125 // It didn't name a member, so see if it names a class. 4126 QualType BaseType; 4127 TypeSourceInfo *TInfo = nullptr; 4128 4129 if (TemplateTypeTy) { 4130 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4131 if (BaseType.isNull()) 4132 return true; 4133 } else if (DS.getTypeSpecType() == TST_decltype) { 4134 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4135 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4136 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4137 return true; 4138 } else { 4139 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4140 LookupParsedName(R, S, &SS); 4141 4142 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4143 if (!TyD) { 4144 if (R.isAmbiguous()) return true; 4145 4146 // We don't want access-control diagnostics here. 4147 R.suppressDiagnostics(); 4148 4149 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4150 bool NotUnknownSpecialization = false; 4151 DeclContext *DC = computeDeclContext(SS, false); 4152 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4153 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4154 4155 if (!NotUnknownSpecialization) { 4156 // When the scope specifier can refer to a member of an unknown 4157 // specialization, we take it as a type name. 4158 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4159 SS.getWithLocInContext(Context), 4160 *MemberOrBase, IdLoc); 4161 if (BaseType.isNull()) 4162 return true; 4163 4164 TInfo = Context.CreateTypeSourceInfo(BaseType); 4165 DependentNameTypeLoc TL = 4166 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4167 if (!TL.isNull()) { 4168 TL.setNameLoc(IdLoc); 4169 TL.setElaboratedKeywordLoc(SourceLocation()); 4170 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4171 } 4172 4173 R.clear(); 4174 R.setLookupName(MemberOrBase); 4175 } 4176 } 4177 4178 // If no results were found, try to correct typos. 4179 TypoCorrection Corr; 4180 MemInitializerValidatorCCC CCC(ClassDecl); 4181 if (R.empty() && BaseType.isNull() && 4182 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4183 CCC, CTK_ErrorRecovery, ClassDecl))) { 4184 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4185 // We have found a non-static data member with a similar 4186 // name to what was typed; complain and initialize that 4187 // member. 4188 diagnoseTypo(Corr, 4189 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4190 << MemberOrBase << true); 4191 return BuildMemberInitializer(Member, Init, IdLoc); 4192 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4193 const CXXBaseSpecifier *DirectBaseSpec; 4194 const CXXBaseSpecifier *VirtualBaseSpec; 4195 if (FindBaseInitializer(*this, ClassDecl, 4196 Context.getTypeDeclType(Type), 4197 DirectBaseSpec, VirtualBaseSpec)) { 4198 // We have found a direct or virtual base class with a 4199 // similar name to what was typed; complain and initialize 4200 // that base class. 4201 diagnoseTypo(Corr, 4202 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4203 << MemberOrBase << false, 4204 PDiag() /*Suppress note, we provide our own.*/); 4205 4206 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4207 : VirtualBaseSpec; 4208 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4209 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4210 4211 TyD = Type; 4212 } 4213 } 4214 } 4215 4216 if (!TyD && BaseType.isNull()) { 4217 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4218 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4219 return true; 4220 } 4221 } 4222 4223 if (BaseType.isNull()) { 4224 BaseType = Context.getTypeDeclType(TyD); 4225 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4226 if (SS.isSet()) { 4227 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4228 BaseType); 4229 TInfo = Context.CreateTypeSourceInfo(BaseType); 4230 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4231 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4232 TL.setElaboratedKeywordLoc(SourceLocation()); 4233 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4234 } 4235 } 4236 } 4237 4238 if (!TInfo) 4239 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4240 4241 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4242} 4243 4244MemInitResult 4245Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4246 SourceLocation IdLoc) { 4247 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4248 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4249 assert((DirectMember || IndirectMember) &&(((DirectMember || IndirectMember) && "Member must be a FieldDecl or IndirectFieldDecl"
) ? static_cast<void> (0) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 4250, __PRETTY_FUNCTION__))
4250 "Member must be a FieldDecl or IndirectFieldDecl")(((DirectMember || IndirectMember) && "Member must be a FieldDecl or IndirectFieldDecl"
) ? static_cast<void> (0) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 4250, __PRETTY_FUNCTION__))
; 4251 4252 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4253 return true; 4254 4255 if (Member->isInvalidDecl()) 4256 return true; 4257 4258 MultiExprArg Args; 4259 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4260 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4261 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4262 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4263 } else { 4264 // Template instantiation doesn't reconstruct ParenListExprs for us. 4265 Args = Init; 4266 } 4267 4268 SourceRange InitRange = Init->getSourceRange(); 4269 4270 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4271 // Can't check initialization for a member of dependent type or when 4272 // any of the arguments are type-dependent expressions. 4273 DiscardCleanupsInEvaluationContext(); 4274 } else { 4275 bool InitList = false; 4276 if (isa<InitListExpr>(Init)) { 4277 InitList = true; 4278 Args = Init; 4279 } 4280 4281 // Initialize the member. 4282 InitializedEntity MemberEntity = 4283 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4284 : InitializedEntity::InitializeMember(IndirectMember, 4285 nullptr); 4286 InitializationKind Kind = 4287 InitList ? InitializationKind::CreateDirectList( 4288 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4289 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4290 InitRange.getEnd()); 4291 4292 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4293 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4294 nullptr); 4295 if (MemberInit.isInvalid()) 4296 return true; 4297 4298 // C++11 [class.base.init]p7: 4299 // The initialization of each base and member constitutes a 4300 // full-expression. 4301 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4302 /*DiscardedValue*/ false); 4303 if (MemberInit.isInvalid()) 4304 return true; 4305 4306 Init = MemberInit.get(); 4307 } 4308 4309 if (DirectMember) { 4310 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4311 InitRange.getBegin(), Init, 4312 InitRange.getEnd()); 4313 } else { 4314 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4315 InitRange.getBegin(), Init, 4316 InitRange.getEnd()); 4317 } 4318} 4319 4320MemInitResult 4321Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4322 CXXRecordDecl *ClassDecl) { 4323 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4324 if (!LangOpts.CPlusPlus11) 4325 return Diag(NameLoc, diag::err_delegating_ctor) 4326 << TInfo->getTypeLoc().getLocalSourceRange(); 4327 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4328 4329 bool InitList = true; 4330 MultiExprArg Args = Init; 4331 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4332 InitList = false; 4333 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4334 } 4335 4336 SourceRange InitRange = Init->getSourceRange(); 4337 // Initialize the object. 4338 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4339 QualType(ClassDecl->getTypeForDecl(), 0)); 4340 InitializationKind Kind = 4341 InitList ? InitializationKind::CreateDirectList( 4342 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4343 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4344 InitRange.getEnd()); 4345 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4346 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4347 Args, nullptr); 4348 if (DelegationInit.isInvalid()) 4349 return true; 4350 4351 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&((cast<CXXConstructExpr>(DelegationInit.get())->getConstructor
() && "Delegating constructor with no target?") ? static_cast
<void> (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 4352, __PRETTY_FUNCTION__))
4352 "Delegating constructor with no target?")((cast<CXXConstructExpr>(DelegationInit.get())->getConstructor
() && "Delegating constructor with no target?") ? static_cast
<void> (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 4352, __PRETTY_FUNCTION__))
; 4353 4354 // C++11 [class.base.init]p7: 4355 // The initialization of each base and member constitutes a 4356 // full-expression. 4357 DelegationInit = ActOnFinishFullExpr( 4358 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4359 if (DelegationInit.isInvalid()) 4360 return true; 4361 4362 // If we are in a dependent context, template instantiation will 4363 // perform this type-checking again. Just save the arguments that we 4364 // received in a ParenListExpr. 4365 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4366 // of the information that we have about the base 4367 // initializer. However, deconstructing the ASTs is a dicey process, 4368 // and this approach is far more likely to get the corner cases right. 4369 if (CurContext->isDependentContext()) 4370 DelegationInit = Init; 4371 4372 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4373 DelegationInit.getAs<Expr>(), 4374 InitRange.getEnd()); 4375} 4376 4377MemInitResult 4378Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4379 Expr *Init, CXXRecordDecl *ClassDecl, 4380 SourceLocation EllipsisLoc) { 4381 SourceLocation BaseLoc 4382 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4383 4384 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4385 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4386 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4387 4388 // C++ [class.base.init]p2: 4389 // [...] Unless the mem-initializer-id names a nonstatic data 4390 // member of the constructor's class or a direct or virtual base 4391 // of that class, the mem-initializer is ill-formed. A 4392 // mem-initializer-list can initialize a base class using any 4393 // name that denotes that base class type. 4394 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4395 4396 SourceRange InitRange = Init->getSourceRange(); 4397 if (EllipsisLoc.isValid()) { 4398 // This is a pack expansion. 4399 if (!BaseType->containsUnexpandedParameterPack()) { 4400 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4401 << SourceRange(BaseLoc, InitRange.getEnd()); 4402 4403 EllipsisLoc = SourceLocation(); 4404 } 4405 } else { 4406 // Check for any unexpanded parameter packs. 4407 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4408 return true; 4409 4410 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4411 return true; 4412 } 4413 4414 // Check for direct and virtual base classes. 4415 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4416 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4417 if (!Dependent) { 4418 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4419 BaseType)) 4420 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4421 4422 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4423 VirtualBaseSpec); 4424 4425 // C++ [base.class.init]p2: 4426 // Unless the mem-initializer-id names a nonstatic data member of the 4427 // constructor's class or a direct or virtual base of that class, the 4428 // mem-initializer is ill-formed. 4429 if (!DirectBaseSpec && !VirtualBaseSpec) { 4430 // If the class has any dependent bases, then it's possible that 4431 // one of those types will resolve to the same type as 4432 // BaseType. Therefore, just treat this as a dependent base 4433 // class initialization. FIXME: Should we try to check the 4434 // initialization anyway? It seems odd. 4435 if (ClassDecl->hasAnyDependentBases()) 4436 Dependent = true; 4437 else 4438 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4439 << BaseType << Context.getTypeDeclType(ClassDecl) 4440 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4441 } 4442 } 4443 4444 if (Dependent) { 4445 DiscardCleanupsInEvaluationContext(); 4446 4447 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4448 /*IsVirtual=*/false, 4449 InitRange.getBegin(), Init, 4450 InitRange.getEnd(), EllipsisLoc); 4451 } 4452 4453 // C++ [base.class.init]p2: 4454 // If a mem-initializer-id is ambiguous because it designates both 4455 // a direct non-virtual base class and an inherited virtual base 4456 // class, the mem-initializer is ill-formed. 4457 if (DirectBaseSpec && VirtualBaseSpec) 4458 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4459 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4460 4461 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4462 if (!BaseSpec) 4463 BaseSpec = VirtualBaseSpec; 4464 4465 // Initialize the base. 4466 bool InitList = true; 4467 MultiExprArg Args = Init; 4468 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4469 InitList = false; 4470 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4471 } 4472 4473 InitializedEntity BaseEntity = 4474 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4475 InitializationKind Kind = 4476 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4477 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4478 InitRange.getEnd()); 4479 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4480 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4481 if (BaseInit.isInvalid()) 4482 return true; 4483 4484 // C++11 [class.base.init]p7: 4485 // The initialization of each base and member constitutes a 4486 // full-expression. 4487 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4488 /*DiscardedValue*/ false); 4489 if (BaseInit.isInvalid()) 4490 return true; 4491 4492 // If we are in a dependent context, template instantiation will 4493 // perform this type-checking again. Just save the arguments that we 4494 // received in a ParenListExpr. 4495 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4496 // of the information that we have about the base 4497 // initializer. However, deconstructing the ASTs is a dicey process, 4498 // and this approach is far more likely to get the corner cases right. 4499 if (CurContext->isDependentContext()) 4500 BaseInit = Init; 4501 4502 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4503 BaseSpec->isVirtual(), 4504 InitRange.getBegin(), 4505 BaseInit.getAs<Expr>(), 4506 InitRange.getEnd(), EllipsisLoc); 4507} 4508 4509// Create a static_cast\<T&&>(expr). 4510static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4511 if (T.isNull()) T = E->getType(); 4512 QualType TargetType = SemaRef.BuildReferenceType( 4513 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4514 SourceLocation ExprLoc = E->getBeginLoc(); 4515 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4516 TargetType, ExprLoc); 4517 4518 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4519 SourceRange(ExprLoc, ExprLoc), 4520 E->getSourceRange()).get(); 4521} 4522 4523/// ImplicitInitializerKind - How an implicit base or member initializer should 4524/// initialize its base or member. 4525enum ImplicitInitializerKind { 4526 IIK_Default, 4527 IIK_Copy, 4528 IIK_Move, 4529 IIK_Inherit 4530}; 4531 4532static bool 4533BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4534 ImplicitInitializerKind ImplicitInitKind, 4535 CXXBaseSpecifier *BaseSpec, 4536 bool IsInheritedVirtualBase, 4537 CXXCtorInitializer *&CXXBaseInit) { 4538 InitializedEntity InitEntity 4539 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4540 IsInheritedVirtualBase); 4541 4542 ExprResult BaseInit; 4543 4544 switch (ImplicitInitKind) { 4545 case IIK_Inherit: 4546 case IIK_Default: { 4547 InitializationKind InitKind 4548 = InitializationKind::CreateDefault(Constructor->getLocation()); 4549 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4550 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4551 break; 4552 } 4553 4554 case IIK_Move: 4555 case IIK_Copy: { 4556 bool Moving = ImplicitInitKind == IIK_Move; 4557 ParmVarDecl *Param = Constructor->getParamDecl(0); 4558 QualType ParamType = Param->getType().getNonReferenceType(); 4559 4560 Expr *CopyCtorArg = 4561 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4562 SourceLocation(), Param, false, 4563 Constructor->getLocation(), ParamType, 4564 VK_LValue, nullptr); 4565 4566 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4567 4568 // Cast to the base class to avoid ambiguities. 4569 QualType ArgTy = 4570 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4571 ParamType.getQualifiers()); 4572 4573 if (Moving) { 4574 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4575 } 4576 4577 CXXCastPath BasePath; 4578 BasePath.push_back(BaseSpec); 4579 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4580 CK_UncheckedDerivedToBase, 4581 Moving ? VK_XValue : VK_LValue, 4582 &BasePath).get(); 4583 4584 InitializationKind InitKind 4585 = InitializationKind::CreateDirect(Constructor->getLocation(), 4586 SourceLocation(), SourceLocation()); 4587 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4588 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4589 break; 4590 } 4591 } 4592 4593 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4594 if (BaseInit.isInvalid()) 4595 return true; 4596 4597 CXXBaseInit = 4598 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4599 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4600 SourceLocation()), 4601 BaseSpec->isVirtual(), 4602 SourceLocation(), 4603 BaseInit.getAs<Expr>(), 4604 SourceLocation(), 4605 SourceLocation()); 4606 4607 return false; 4608} 4609 4610static bool RefersToRValueRef(Expr *MemRef) { 4611 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4612 return Referenced->getType()->isRValueReferenceType(); 4613} 4614 4615static bool 4616BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4617 ImplicitInitializerKind ImplicitInitKind, 4618 FieldDecl *Field, IndirectFieldDecl *Indirect, 4619 CXXCtorInitializer *&CXXMemberInit) { 4620 if (Field->isInvalidDecl()) 4621 return true; 4622 4623 SourceLocation Loc = Constructor->getLocation(); 4624 4625 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4626 bool Moving = ImplicitInitKind == IIK_Move; 4627 ParmVarDecl *Param = Constructor->getParamDecl(0); 4628 QualType ParamType = Param->getType().getNonReferenceType(); 4629 4630 // Suppress copying zero-width bitfields. 4631 if (Field->isZeroLengthBitField(SemaRef.Context)) 4632 return false; 4633 4634 Expr *MemberExprBase = 4635 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4636 SourceLocation(), Param, false, 4637 Loc, ParamType, VK_LValue, nullptr); 4638 4639 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4640 4641 if (Moving) { 4642 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4643 } 4644 4645 // Build a reference to this field within the parameter. 4646 CXXScopeSpec SS; 4647 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4648 Sema::LookupMemberName); 4649 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4650 : cast<ValueDecl>(Field), AS_public); 4651 MemberLookup.resolveKind(); 4652 ExprResult CtorArg 4653 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4654 ParamType, Loc, 4655 /*IsArrow=*/false, 4656 SS, 4657 /*TemplateKWLoc=*/SourceLocation(), 4658 /*FirstQualifierInScope=*/nullptr, 4659 MemberLookup, 4660 /*TemplateArgs=*/nullptr, 4661 /*S*/nullptr); 4662 if (CtorArg.isInvalid()) 4663 return true; 4664 4665 // C++11 [class.copy]p15: 4666 // - if a member m has rvalue reference type T&&, it is direct-initialized 4667 // with static_cast<T&&>(x.m); 4668 if (RefersToRValueRef(CtorArg.get())) { 4669 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4670 } 4671 4672 InitializedEntity Entity = 4673 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4674 /*Implicit*/ true) 4675 : InitializedEntity::InitializeMember(Field, nullptr, 4676 /*Implicit*/ true); 4677 4678 // Direct-initialize to use the copy constructor. 4679 InitializationKind InitKind = 4680 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4681 4682 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4683 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4684 ExprResult MemberInit = 4685 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4686 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4687 if (MemberInit.isInvalid()) 4688 return true; 4689 4690 if (Indirect) 4691 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4692 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4693 else 4694 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4695 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4696 return false; 4697 } 4698 4699 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&(((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit
) && "Unhandled implicit init kind!") ? static_cast<
void> (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 4700, __PRETTY_FUNCTION__))
4700 "Unhandled implicit init kind!")(((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit
) && "Unhandled implicit init kind!") ? static_cast<
void> (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 4700, __PRETTY_FUNCTION__))
; 4701 4702 QualType FieldBaseElementType = 4703 SemaRef.Context.getBaseElementType(Field->getType()); 4704 4705 if (FieldBaseElementType->isRecordType()) { 4706 InitializedEntity InitEntity = 4707 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4708 /*Implicit*/ true) 4709 : InitializedEntity::InitializeMember(Field, nullptr, 4710 /*Implicit*/ true); 4711 InitializationKind InitKind = 4712 InitializationKind::CreateDefault(Loc); 4713 4714 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4715 ExprResult MemberInit = 4716 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4717 4718 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4719 if (MemberInit.isInvalid()) 4720 return true; 4721 4722 if (Indirect) 4723 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4724 Indirect, Loc, 4725 Loc, 4726 MemberInit.get(), 4727 Loc); 4728 else 4729 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4730 Field, Loc, Loc, 4731 MemberInit.get(), 4732 Loc); 4733 return false; 4734 } 4735 4736 if (!Field->getParent()->isUnion()) { 4737 if (FieldBaseElementType->isReferenceType()) { 4738 SemaRef.Diag(Constructor->getLocation(), 4739 diag::err_uninitialized_member_in_ctor) 4740 << (int)Constructor->isImplicit() 4741 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4742 << 0 << Field->getDeclName(); 4743 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4744 return true; 4745 } 4746 4747 if (FieldBaseElementType.isConstQualified()) { 4748 SemaRef.Diag(Constructor->getLocation(), 4749 diag::err_uninitialized_member_in_ctor) 4750 << (int)Constructor->isImplicit() 4751 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4752 << 1 << Field->getDeclName(); 4753 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4754 return true; 4755 } 4756 } 4757 4758 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4759 // ARC and Weak: 4760 // Default-initialize Objective-C pointers to NULL. 4761 CXXMemberInit 4762 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4763 Loc, Loc, 4764 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4765 Loc); 4766 return false; 4767 } 4768 4769 // Nothing to initialize. 4770 CXXMemberInit = nullptr; 4771 return false; 4772} 4773 4774namespace { 4775struct BaseAndFieldInfo { 4776 Sema &S; 4777 CXXConstructorDecl *Ctor; 4778 bool AnyErrorsInInits; 4779 ImplicitInitializerKind IIK; 4780 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4781 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4782 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4783 4784 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4785 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4786 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4787 if (Ctor->getInheritedConstructor()) 4788 IIK = IIK_Inherit; 4789 else if (Generated && Ctor->isCopyConstructor()) 4790 IIK = IIK_Copy; 4791 else if (Generated && Ctor->isMoveConstructor()) 4792 IIK = IIK_Move; 4793 else 4794 IIK = IIK_Default; 4795 } 4796 4797 bool isImplicitCopyOrMove() const { 4798 switch (IIK) { 4799 case IIK_Copy: 4800 case IIK_Move: 4801 return true; 4802 4803 case IIK_Default: 4804 case IIK_Inherit: 4805 return false; 4806 } 4807 4808 llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 4808)
; 4809 } 4810 4811 bool addFieldInitializer(CXXCtorInitializer *Init) { 4812 AllToInit.push_back(Init); 4813 4814 // Check whether this initializer makes the field "used". 4815 if (Init->getInit()->HasSideEffects(S.Context)) 4816 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4817 4818 return false; 4819 } 4820 4821 bool isInactiveUnionMember(FieldDecl *Field) { 4822 RecordDecl *Record = Field->getParent(); 4823 if (!Record->isUnion()) 4824 return false; 4825 4826 if (FieldDecl *Active = 4827 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4828 return Active != Field->getCanonicalDecl(); 4829 4830 // In an implicit copy or move constructor, ignore any in-class initializer. 4831 if (isImplicitCopyOrMove()) 4832 return true; 4833 4834 // If there's no explicit initialization, the field is active only if it 4835 // has an in-class initializer... 4836 if (Field->hasInClassInitializer()) 4837 return false; 4838 // ... or it's an anonymous struct or union whose class has an in-class 4839 // initializer. 4840 if (!Field->isAnonymousStructOrUnion()) 4841 return true; 4842 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4843 return !FieldRD->hasInClassInitializer(); 4844 } 4845 4846 /// Determine whether the given field is, or is within, a union member 4847 /// that is inactive (because there was an initializer given for a different 4848 /// member of the union, or because the union was not initialized at all). 4849 bool isWithinInactiveUnionMember(FieldDecl *Field, 4850 IndirectFieldDecl *Indirect) { 4851 if (!Indirect) 4852 return isInactiveUnionMember(Field); 4853 4854 for (auto *C : Indirect->chain()) { 4855 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4856 if (Field && isInactiveUnionMember(Field)) 4857 return true; 4858 } 4859 return false; 4860 } 4861}; 4862} 4863 4864/// Determine whether the given type is an incomplete or zero-lenfgth 4865/// array type. 4866static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4867 if (T->isIncompleteArrayType()) 4868 return true; 4869 4870 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4871 if (!ArrayT->getSize()) 4872 return true; 4873 4874 T = ArrayT->getElementType(); 4875 } 4876 4877 return false; 4878} 4879 4880static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4881 FieldDecl *Field, 4882 IndirectFieldDecl *Indirect = nullptr) { 4883 if (Field->isInvalidDecl()) 4884 return false; 4885 4886 // Overwhelmingly common case: we have a direct initializer for this field. 4887 if (CXXCtorInitializer *Init = 4888 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4889 return Info.addFieldInitializer(Init); 4890 4891 // C++11 [class.base.init]p8: 4892 // if the entity is a non-static data member that has a 4893 // brace-or-equal-initializer and either 4894 // -- the constructor's class is a union and no other variant member of that 4895 // union is designated by a mem-initializer-id or 4896 // -- the constructor's class is not a union, and, if the entity is a member 4897 // of an anonymous union, no other member of that union is designated by 4898 // a mem-initializer-id, 4899 // the entity is initialized as specified in [dcl.init]. 4900 // 4901 // We also apply the same rules to handle anonymous structs within anonymous 4902 // unions. 4903 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4904 return false; 4905 4906 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4907 ExprResult DIE = 4908 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4909 if (DIE.isInvalid()) 4910 return true; 4911 4912 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4913 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4914 4915 CXXCtorInitializer *Init; 4916 if (Indirect) 4917 Init = new (SemaRef.Context) 4918 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4919 SourceLocation(), DIE.get(), SourceLocation()); 4920 else 4921 Init = new (SemaRef.Context) 4922 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4923 SourceLocation(), DIE.get(), SourceLocation()); 4924 return Info.addFieldInitializer(Init); 4925 } 4926 4927 // Don't initialize incomplete or zero-length arrays. 4928 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4929 return false; 4930 4931 // Don't try to build an implicit initializer if there were semantic 4932 // errors in any of the initializers (and therefore we might be 4933 // missing some that the user actually wrote). 4934 if (Info.AnyErrorsInInits) 4935 return false; 4936 4937 CXXCtorInitializer *Init = nullptr; 4938 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4939 Indirect, Init)) 4940 return true; 4941 4942 if (!Init) 4943 return false; 4944 4945 return Info.addFieldInitializer(Init); 4946} 4947 4948bool 4949Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4950 CXXCtorInitializer *Initializer) { 4951 assert(Initializer->isDelegatingInitializer())((Initializer->isDelegatingInitializer()) ? static_cast<
void> (0) : __assert_fail ("Initializer->isDelegatingInitializer()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 4951, __PRETTY_FUNCTION__))
; 4952 Constructor->setNumCtorInitializers(1); 4953 CXXCtorInitializer **initializer = 4954 new (Context) CXXCtorInitializer*[1]; 4955 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4956 Constructor->setCtorInitializers(initializer); 4957 4958 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4959 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4960 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4961 } 4962 4963 DelegatingCtorDecls.push_back(Constructor); 4964 4965 DiagnoseUninitializedFields(*this, Constructor); 4966 4967 return false; 4968} 4969 4970bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4971 ArrayRef<CXXCtorInitializer *> Initializers) { 4972 if (Constructor->isDependentContext()) { 4973 // Just store the initializers as written, they will be checked during 4974 // instantiation. 4975 if (!Initializers.empty()) { 4976 Constructor->setNumCtorInitializers(Initializers.size()); 4977 CXXCtorInitializer **baseOrMemberInitializers = 4978 new (Context) CXXCtorInitializer*[Initializers.size()]; 4979 memcpy(baseOrMemberInitializers, Initializers.data(), 4980 Initializers.size() * sizeof(CXXCtorInitializer*)); 4981 Constructor->setCtorInitializers(baseOrMemberInitializers); 4982 } 4983 4984 // Let template instantiation know whether we had errors. 4985 if (AnyErrors) 4986 Constructor->setInvalidDecl(); 4987 4988 return false; 4989 } 4990 4991 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4992 4993 // We need to build the initializer AST according to order of construction 4994 // and not what user specified in the Initializers list. 4995 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4996 if (!ClassDecl) 4997 return true; 4998 4999 bool HadError = false; 5000 5001 for (unsigned i = 0; i < Initializers.size(); i++) { 5002 CXXCtorInitializer *Member = Initializers[i]; 5003 5004 if (Member->isBaseInitializer()) 5005 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5006 else { 5007 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5008 5009 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5010 for (auto *C : F->chain()) { 5011 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5012 if (FD && FD->getParent()->isUnion()) 5013 Info.ActiveUnionMember.insert(std::make_pair( 5014 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5015 } 5016 } else if (FieldDecl *FD = Member->getMember()) { 5017 if (FD->getParent()->isUnion()) 5018 Info.ActiveUnionMember.insert(std::make_pair( 5019 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5020 } 5021 } 5022 } 5023 5024 // Keep track of the direct virtual bases. 5025 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5026 for (auto &I : ClassDecl->bases()) { 5027 if (I.isVirtual()) 5028 DirectVBases.insert(&I); 5029 } 5030 5031 // Push virtual bases before others. 5032 for (auto &VBase : ClassDecl->vbases()) { 5033 if (CXXCtorInitializer *Value 5034 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5035 // [class.base.init]p7, per DR257: 5036 // A mem-initializer where the mem-initializer-id names a virtual base 5037 // class is ignored during execution of a constructor of any class that 5038 // is not the most derived class. 5039 if (ClassDecl->isAbstract()) { 5040 // FIXME: Provide a fixit to remove the base specifier. This requires 5041 // tracking the location of the associated comma for a base specifier. 5042 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5043 << VBase.getType() << ClassDecl; 5044 DiagnoseAbstractType(ClassDecl); 5045 } 5046 5047 Info.AllToInit.push_back(Value); 5048 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5049 // [class.base.init]p8, per DR257: 5050 // If a given [...] base class is not named by a mem-initializer-id 5051 // [...] and the entity is not a virtual base class of an abstract 5052 // class, then [...] the entity is default-initialized. 5053 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5054 CXXCtorInitializer *CXXBaseInit; 5055 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5056 &VBase, IsInheritedVirtualBase, 5057 CXXBaseInit)) { 5058 HadError = true; 5059 continue; 5060 } 5061 5062 Info.AllToInit.push_back(CXXBaseInit); 5063 } 5064 } 5065 5066 // Non-virtual bases. 5067 for (auto &Base : ClassDecl->bases()) { 5068 // Virtuals are in the virtual base list and already constructed. 5069 if (Base.isVirtual()) 5070 continue; 5071 5072 if (CXXCtorInitializer *Value 5073 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5074 Info.AllToInit.push_back(Value); 5075 } else if (!AnyErrors) { 5076 CXXCtorInitializer *CXXBaseInit; 5077 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5078 &Base, /*IsInheritedVirtualBase=*/false, 5079 CXXBaseInit)) { 5080 HadError = true; 5081 continue; 5082 } 5083 5084 Info.AllToInit.push_back(CXXBaseInit); 5085 } 5086 } 5087 5088 // Fields. 5089 for (auto *Mem : ClassDecl->decls()) { 5090 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5091 // C++ [class.bit]p2: 5092 // A declaration for a bit-field that omits the identifier declares an 5093 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5094 // initialized. 5095 if (F->isUnnamedBitfield()) 5096 continue; 5097 5098 // If we're not generating the implicit copy/move constructor, then we'll 5099 // handle anonymous struct/union fields based on their individual 5100 // indirect fields. 5101 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5102 continue; 5103 5104 if (CollectFieldInitializer(*this, Info, F)) 5105 HadError = true; 5106 continue; 5107 } 5108 5109 // Beyond this point, we only consider default initialization. 5110 if (Info.isImplicitCopyOrMove()) 5111 continue; 5112 5113 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5114 if (F->getType()->isIncompleteArrayType()) { 5115 assert(ClassDecl->hasFlexibleArrayMember() &&((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 5116, __PRETTY_FUNCTION__))
5116 "Incomplete array type is not valid")((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 5116, __PRETTY_FUNCTION__))
; 5117 continue; 5118 } 5119 5120 // Initialize each field of an anonymous struct individually. 5121 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5122 HadError = true; 5123 5124 continue; 5125 } 5126 } 5127 5128 unsigned NumInitializers = Info.AllToInit.size(); 5129 if (NumInitializers > 0) { 5130 Constructor->setNumCtorInitializers(NumInitializers); 5131 CXXCtorInitializer **baseOrMemberInitializers = 5132 new (Context) CXXCtorInitializer*[NumInitializers]; 5133 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5134 NumInitializers * sizeof(CXXCtorInitializer*)); 5135 Constructor->setCtorInitializers(baseOrMemberInitializers); 5136 5137 // Constructors implicitly reference the base and member 5138 // destructors. 5139 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5140 Constructor->getParent()); 5141 } 5142 5143 return HadError; 5144} 5145 5146static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5147 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5148 const RecordDecl *RD = RT->getDecl(); 5149 if (RD->isAnonymousStructOrUnion()) { 5150 for (auto *Field : RD->fields()) 5151 PopulateKeysForFields(Field, IdealInits); 5152 return; 5153 } 5154 } 5155 IdealInits.push_back(Field->getCanonicalDecl()); 5156} 5157 5158static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5159 return Context.getCanonicalType(BaseType).getTypePtr(); 5160} 5161 5162static const void *GetKeyForMember(ASTContext &Context, 5163 CXXCtorInitializer *Member) { 5164 if (!Member->isAnyMemberInitializer()) 5165 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5166 5167 return Member->getAnyMember()->getCanonicalDecl(); 5168} 5169 5170static void DiagnoseBaseOrMemInitializerOrder( 5171 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5172 ArrayRef<CXXCtorInitializer *> Inits) { 5173 if (Constructor->getDeclContext()->isDependentContext()) 5174 return; 5175 5176 // Don't check initializers order unless the warning is enabled at the 5177 // location of at least one initializer. 5178 bool ShouldCheckOrder = false; 5179 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5180 CXXCtorInitializer *Init = Inits[InitIndex]; 5181 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5182 Init->getSourceLocation())) { 5183 ShouldCheckOrder = true; 5184 break; 5185 } 5186 } 5187 if (!ShouldCheckOrder) 5188 return; 5189 5190 // Build the list of bases and members in the order that they'll 5191 // actually be initialized. The explicit initializers should be in 5192 // this same order but may be missing things. 5193 SmallVector<const void*, 32> IdealInitKeys; 5194 5195 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5196 5197 // 1. Virtual bases. 5198 for (const auto &VBase : ClassDecl->vbases()) 5199 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5200 5201 // 2. Non-virtual bases. 5202 for (const auto &Base : ClassDecl->bases()) { 5203 if (Base.isVirtual()) 5204 continue; 5205 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5206 } 5207 5208 // 3. Direct fields. 5209 for (auto *Field : ClassDecl->fields()) { 5210 if (Field->isUnnamedBitfield()) 5211 continue; 5212 5213 PopulateKeysForFields(Field, IdealInitKeys); 5214 } 5215 5216 unsigned NumIdealInits = IdealInitKeys.size(); 5217 unsigned IdealIndex = 0; 5218 5219 CXXCtorInitializer *PrevInit = nullptr; 5220 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5221 CXXCtorInitializer *Init = Inits[InitIndex]; 5222 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5223 5224 // Scan forward to try to find this initializer in the idealized 5225 // initializers list. 5226 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5227 if (InitKey == IdealInitKeys[IdealIndex]) 5228 break; 5229 5230 // If we didn't find this initializer, it must be because we 5231 // scanned past it on a previous iteration. That can only 5232 // happen if we're out of order; emit a warning. 5233 if (IdealIndex == NumIdealInits && PrevInit) { 5234 Sema::SemaDiagnosticBuilder D = 5235 SemaRef.Diag(PrevInit->getSourceLocation(), 5236 diag::warn_initializer_out_of_order); 5237 5238 if (PrevInit->isAnyMemberInitializer()) 5239 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5240 else 5241 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5242 5243 if (Init->isAnyMemberInitializer()) 5244 D << 0 << Init->getAnyMember()->getDeclName(); 5245 else 5246 D << 1 << Init->getTypeSourceInfo()->getType(); 5247 5248 // Move back to the initializer's location in the ideal list. 5249 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5250 if (InitKey == IdealInitKeys[IdealIndex]) 5251 break; 5252 5253 assert(IdealIndex < NumIdealInits &&((IdealIndex < NumIdealInits && "initializer not found in initializer list"
) ? static_cast<void> (0) : __assert_fail ("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 5254, __PRETTY_FUNCTION__))
5254 "initializer not found in initializer list")((IdealIndex < NumIdealInits && "initializer not found in initializer list"
) ? static_cast<void> (0) : __assert_fail ("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 5254, __PRETTY_FUNCTION__))
; 5255 } 5256 5257 PrevInit = Init; 5258 } 5259} 5260 5261namespace { 5262bool CheckRedundantInit(Sema &S, 5263 CXXCtorInitializer *Init, 5264 CXXCtorInitializer *&PrevInit) { 5265 if (!PrevInit) { 5266 PrevInit = Init; 5267 return false; 5268 } 5269 5270 if (FieldDecl *Field = Init->getAnyMember()) 5271 S.Diag(Init->getSourceLocation(), 5272 diag::err_multiple_mem_initialization) 5273 << Field->getDeclName() 5274 << Init->getSourceRange(); 5275 else { 5276 const Type *BaseClass = Init->getBaseClass(); 5277 assert(BaseClass && "neither field nor base")((BaseClass && "neither field nor base") ? static_cast
<void> (0) : __assert_fail ("BaseClass && \"neither field nor base\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 5277, __PRETTY_FUNCTION__))
; 5278 S.Diag(Init->getSourceLocation(), 5279 diag::err_multiple_base_initialization) 5280 << QualType(BaseClass, 0) 5281 << Init->getSourceRange(); 5282 } 5283 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5284 << 0 << PrevInit->getSourceRange(); 5285 5286 return true; 5287} 5288 5289typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5290typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5291 5292bool CheckRedundantUnionInit(Sema &S, 5293 CXXCtorInitializer *Init, 5294 RedundantUnionMap &Unions) { 5295 FieldDecl *Field = Init->getAnyMember(); 5296 RecordDecl *Parent = Field->getParent(); 5297 NamedDecl *Child = Field; 5298 5299 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5300 if (Parent->isUnion()) { 5301 UnionEntry &En = Unions[Parent]; 5302 if (En.first && En.first != Child) { 5303 S.Diag(Init->getSourceLocation(), 5304 diag::err_multiple_mem_union_initialization) 5305 << Field->getDeclName() 5306 << Init->getSourceRange(); 5307 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5308 << 0 << En.second->getSourceRange(); 5309 return true; 5310 } 5311 if (!En.first) { 5312 En.first = Child; 5313 En.second = Init; 5314 } 5315 if (!Parent->isAnonymousStructOrUnion()) 5316 return false; 5317 } 5318 5319 Child = Parent; 5320 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5321 } 5322 5323 return false; 5324} 5325} 5326 5327/// ActOnMemInitializers - Handle the member initializers for a constructor. 5328void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5329 SourceLocation ColonLoc, 5330 ArrayRef<CXXCtorInitializer*> MemInits, 5331 bool AnyErrors) { 5332 if (!ConstructorDecl) 5333 return; 5334 5335 AdjustDeclIfTemplate(ConstructorDecl); 5336 5337 CXXConstructorDecl *Constructor 5338 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5339 5340 if (!Constructor) { 5341 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5342 return; 5343 } 5344 5345 // Mapping for the duplicate initializers check. 5346 // For member initializers, this is keyed with a FieldDecl*. 5347 // For base initializers, this is keyed with a Type*. 5348 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5349 5350 // Mapping for the inconsistent anonymous-union initializers check. 5351 RedundantUnionMap MemberUnions; 5352 5353 bool HadError = false; 5354 for (unsigned i = 0; i < MemInits.size(); i++) { 5355 CXXCtorInitializer *Init = MemInits[i]; 5356 5357 // Set the source order index. 5358 Init->setSourceOrder(i); 5359 5360 if (Init->isAnyMemberInitializer()) { 5361 const void *Key = GetKeyForMember(Context, Init); 5362 if (CheckRedundantInit(*this, Init, Members[Key]) || 5363 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5364 HadError = true; 5365 } else if (Init->isBaseInitializer()) { 5366 const void *Key = GetKeyForMember(Context, Init); 5367 if (CheckRedundantInit(*this, Init, Members[Key])) 5368 HadError = true; 5369 } else { 5370 assert(Init->isDelegatingInitializer())((Init->isDelegatingInitializer()) ? static_cast<void>
(0) : __assert_fail ("Init->isDelegatingInitializer()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 5370, __PRETTY_FUNCTION__))
; 5371 // This must be the only initializer 5372 if (MemInits.size() != 1) { 5373 Diag(Init->getSourceLocation(), 5374 diag::err_delegating_initializer_alone) 5375 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5376 // We will treat this as being the only initializer. 5377 } 5378 SetDelegatingInitializer(Constructor, MemInits[i]); 5379 // Return immediately as the initializer is set. 5380 return; 5381 } 5382 } 5383 5384 if (HadError) 5385 return; 5386 5387 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5388 5389 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5390 5391 DiagnoseUninitializedFields(*this, Constructor); 5392} 5393 5394void 5395Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5396 CXXRecordDecl *ClassDecl) { 5397 // Ignore dependent contexts. Also ignore unions, since their members never 5398 // have destructors implicitly called. 5399 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5400 return; 5401 5402 // FIXME: all the access-control diagnostics are positioned on the 5403 // field/base declaration. That's probably good; that said, the 5404 // user might reasonably want to know why the destructor is being 5405 // emitted, and we currently don't say. 5406 5407 // Non-static data members. 5408 for (auto *Field : ClassDecl->fields()) { 5409 if (Field->isInvalidDecl()) 5410 continue; 5411 5412 // Don't destroy incomplete or zero-length arrays. 5413 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5414 continue; 5415 5416 QualType FieldType = Context.getBaseElementType(Field->getType()); 5417 5418 const RecordType* RT = FieldType->getAs<RecordType>(); 5419 if (!RT) 5420 continue; 5421 5422 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5423 if (FieldClassDecl->isInvalidDecl()) 5424 continue; 5425 if (FieldClassDecl->hasIrrelevantDestructor()) 5426 continue; 5427 // The destructor for an implicit anonymous union member is never invoked. 5428 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5429 continue; 5430 5431 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5432 assert(Dtor && "No dtor found for FieldClassDecl!")((Dtor && "No dtor found for FieldClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for FieldClassDecl!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 5432, __PRETTY_FUNCTION__))
; 5433 CheckDestructorAccess(Field->getLocation(), Dtor, 5434 PDiag(diag::err_access_dtor_field) 5435 << Field->getDeclName() 5436 << FieldType); 5437 5438 MarkFunctionReferenced(Location, Dtor); 5439 DiagnoseUseOfDecl(Dtor, Location); 5440 } 5441 5442 // We only potentially invoke the destructors of potentially constructed 5443 // subobjects. 5444 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5445 5446 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5447 5448 // Bases. 5449 for (const auto &Base : ClassDecl->bases()) { 5450 // Bases are always records in a well-formed non-dependent class. 5451 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5452 5453 // Remember direct virtual bases. 5454 if (Base.isVirtual()) { 5455 if (!VisitVirtualBases) 5456 continue; 5457 DirectVirtualBases.insert(RT); 5458 } 5459 5460 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5461 // If our base class is invalid, we probably can't get its dtor anyway. 5462 if (BaseClassDecl->isInvalidDecl()) 5463 continue; 5464 if (BaseClassDecl->hasIrrelevantDestructor()) 5465 continue; 5466 5467 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5468 assert(Dtor && "No dtor found for BaseClassDecl!")((Dtor && "No dtor found for BaseClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 5468, __PRETTY_FUNCTION__))
; 5469 5470 // FIXME: caret should be on the start of the class name 5471 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5472 PDiag(diag::err_access_dtor_base) 5473 << Base.getType() << Base.getSourceRange(), 5474 Context.getTypeDeclType(ClassDecl)); 5475 5476 MarkFunctionReferenced(Location, Dtor); 5477 DiagnoseUseOfDecl(Dtor, Location); 5478 } 5479 5480 if (!VisitVirtualBases) 5481 return; 5482 5483 // Virtual bases. 5484 for (const auto &VBase : ClassDecl->vbases()) { 5485 // Bases are always records in a well-formed non-dependent class. 5486 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5487 5488 // Ignore direct virtual bases. 5489 if (DirectVirtualBases.count(RT)) 5490 continue; 5491 5492 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5493 // If our base class is invalid, we probably can't get its dtor anyway. 5494 if (BaseClassDecl->isInvalidDecl()) 5495 continue; 5496 if (BaseClassDecl->hasIrrelevantDestructor()) 5497 continue; 5498 5499 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5500 assert(Dtor && "No dtor found for BaseClassDecl!")((Dtor && "No dtor found for BaseClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 5500, __PRETTY_FUNCTION__))
; 5501 if (CheckDestructorAccess( 5502 ClassDecl->getLocation(), Dtor, 5503 PDiag(diag::err_access_dtor_vbase) 5504 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5505 Context.getTypeDeclType(ClassDecl)) == 5506 AR_accessible) { 5507 CheckDerivedToBaseConversion( 5508 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5509 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5510 SourceRange(), DeclarationName(), nullptr); 5511 } 5512 5513 MarkFunctionReferenced(Location, Dtor); 5514 DiagnoseUseOfDecl(Dtor, Location); 5515 } 5516} 5517 5518void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5519 if (!CDtorDecl) 5520 return; 5521 5522 if (CXXConstructorDecl *Constructor 5523 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5524 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5525 DiagnoseUninitializedFields(*this, Constructor); 5526 } 5527} 5528 5529bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5530 if (!getLangOpts().CPlusPlus) 5531 return false; 5532 5533 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5534 if (!RD) 5535 return false; 5536 5537 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5538 // class template specialization here, but doing so breaks a lot of code. 5539 5540 // We can't answer whether something is abstract until it has a 5541 // definition. If it's currently being defined, we'll walk back 5542 // over all the declarations when we have a full definition. 5543 const CXXRecordDecl *Def = RD->getDefinition(); 5544 if (!Def || Def->isBeingDefined()) 5545 return false; 5546 5547 return RD->isAbstract(); 5548} 5549 5550bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5551 TypeDiagnoser &Diagnoser) { 5552 if (!isAbstractType(Loc, T)) 5553 return false; 5554 5555 T = Context.getBaseElementType(T); 5556 Diagnoser.diagnose(*this, Loc, T); 5557 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5558 return true; 5559} 5560 5561void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5562 // Check if we've already emitted the list of pure virtual functions 5563 // for this class. 5564 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5565 return; 5566 5567 // If the diagnostic is suppressed, don't emit the notes. We're only 5568 // going to emit them once, so try to attach them to a diagnostic we're 5569 // actually going to show. 5570 if (Diags.isLastDiagnosticIgnored()) 5571 return; 5572 5573 CXXFinalOverriderMap FinalOverriders; 5574 RD->getFinalOverriders(FinalOverriders); 5575 5576 // Keep a set of seen pure methods so we won't diagnose the same method 5577 // more than once. 5578 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5579 5580 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5581 MEnd = FinalOverriders.end(); 5582 M != MEnd; 5583 ++M) { 5584 for (OverridingMethods::iterator SO = M->second.begin(), 5585 SOEnd = M->second.end(); 5586 SO != SOEnd; ++SO) { 5587 // C++ [class.abstract]p4: 5588 // A class is abstract if it contains or inherits at least one 5589 // pure virtual function for which the final overrider is pure 5590 // virtual. 5591 5592 // 5593 if (SO->second.size() != 1) 5594 continue; 5595 5596 if (!SO->second.front().Method->isPure()) 5597 continue; 5598 5599 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5600 continue; 5601 5602 Diag(SO->second.front().Method->getLocation(), 5603 diag::note_pure_virtual_function) 5604 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5605 } 5606 } 5607 5608 if (!PureVirtualClassDiagSet) 5609 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5610 PureVirtualClassDiagSet->insert(RD); 5611} 5612 5613namespace { 5614struct AbstractUsageInfo { 5615 Sema &S; 5616 CXXRecordDecl *Record; 5617 CanQualType AbstractType; 5618 bool Invalid; 5619 5620 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5621 : S(S), Record(Record), 5622 AbstractType(S.Context.getCanonicalType( 5623 S.Context.getTypeDeclType(Record))), 5624 Invalid(false) {} 5625 5626 void DiagnoseAbstractType() { 5627 if (Invalid) return; 5628 S.DiagnoseAbstractType(Record); 5629 Invalid = true; 5630 } 5631 5632 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5633}; 5634 5635struct CheckAbstractUsage { 5636 AbstractUsageInfo &Info; 5637 const NamedDecl *Ctx; 5638 5639 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5640 : Info(Info), Ctx(Ctx) {} 5641 5642 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5643 switch (TL.getTypeLocClass()) { 5644#define ABSTRACT_TYPELOC(CLASS, PARENT) 5645#define TYPELOC(CLASS, PARENT) \ 5646 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5647#include "clang/AST/TypeLocNodes.def" 5648 } 5649 } 5650 5651 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5652 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5653 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5654 if (!TL.getParam(I)) 5655 continue; 5656 5657 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5658 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5659 } 5660 } 5661 5662 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5663 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5664 } 5665 5666 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5667 // Visit the type parameters from a permissive context. 5668 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5669 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5670 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5671 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5672 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5673 // TODO: other template argument types? 5674 } 5675 } 5676 5677 // Visit pointee types from a permissive context. 5678#define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc
(), Sema::AbstractNone); }
\
5679 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5680 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5681 } 5682 CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5683 CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5684 CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5685 CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5686 CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5687 5688 /// Handle all the types we haven't given a more specific 5689 /// implementation for above. 5690 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5691 // Every other kind of type that we haven't called out already 5692 // that has an inner type is either (1) sugar or (2) contains that 5693 // inner type in some way as a subobject. 5694 if (TypeLoc Next = TL.getNextTypeLoc()) 5695 return Visit(Next, Sel); 5696 5697 // If there's no inner type and we're in a permissive context, 5698 // don't diagnose. 5699 if (Sel == Sema::AbstractNone) return; 5700 5701 // Check whether the type matches the abstract type. 5702 QualType T = TL.getType(); 5703 if (T->isArrayType()) { 5704 Sel = Sema::AbstractArrayType; 5705 T = Info.S.Context.getBaseElementType(T); 5706 } 5707 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5708 if (CT != Info.AbstractType) return; 5709 5710 // It matched; do some magic. 5711 if (Sel == Sema::AbstractArrayType) { 5712 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5713 << T << TL.getSourceRange(); 5714 } else { 5715 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5716 << Sel << T << TL.getSourceRange(); 5717 } 5718 Info.DiagnoseAbstractType(); 5719 } 5720}; 5721 5722void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5723 Sema::AbstractDiagSelID Sel) { 5724 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5725} 5726 5727} 5728 5729/// Check for invalid uses of an abstract type in a method declaration. 5730static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5731 CXXMethodDecl *MD) { 5732 // No need to do the check on definitions, which require that 5733 // the return/param types be complete. 5734 if (MD->doesThisDeclarationHaveABody()) 5735 return; 5736 5737 // For safety's sake, just ignore it if we don't have type source 5738 // information. This should never happen for non-implicit methods, 5739 // but... 5740 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5741 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5742} 5743 5744/// Check for invalid uses of an abstract type within a class definition. 5745static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5746 CXXRecordDecl *RD) { 5747 for (auto *D : RD->decls()) { 5748 if (D->isImplicit()) continue; 5749 5750 // Methods and method templates. 5751 if (isa<CXXMethodDecl>(D)) { 5752 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5753 } else if (isa<FunctionTemplateDecl>(D)) { 5754 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5755 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5756 5757 // Fields and static variables. 5758 } else if (isa<FieldDecl>(D)) { 5759 FieldDecl *FD = cast<FieldDecl>(D); 5760 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5761 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5762 } else if (isa<VarDecl>(D)) { 5763 VarDecl *VD = cast<VarDecl>(D); 5764 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5765 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5766 5767 // Nested classes and class templates. 5768 } else if (isa<CXXRecordDecl>(D)) { 5769 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5770 } else if (isa<ClassTemplateDecl>(D)) { 5771 CheckAbstractClassUsage(Info, 5772 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5773 } 5774 } 5775} 5776 5777static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5778 Attr *ClassAttr = getDLLAttr(Class); 5779 if (!ClassAttr) 5780 return; 5781 5782 assert(ClassAttr->getKind() == attr::DLLExport)((ClassAttr->getKind() == attr::DLLExport) ? static_cast<
void> (0) : __assert_fail ("ClassAttr->getKind() == attr::DLLExport"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 5782, __PRETTY_FUNCTION__))
; 5783 5784 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5785 5786 if (TSK == TSK_ExplicitInstantiationDeclaration) 5787 // Don't go any further if this is just an explicit instantiation 5788 // declaration. 5789 return; 5790 5791 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5792 S.MarkVTableUsed(Class->getLocation(), Class, true); 5793 5794 for (Decl *Member : Class->decls()) { 5795 // Defined static variables that are members of an exported base 5796 // class must be marked export too. 5797 auto *VD = dyn_cast<VarDecl>(Member); 5798 if (VD && Member->getAttr<DLLExportAttr>() && 5799 VD->getStorageClass() == SC_Static && 5800 TSK == TSK_ImplicitInstantiation) 5801 S.MarkVariableReferenced(VD->getLocation(), VD); 5802 5803 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5804 if (!MD) 5805 continue; 5806 5807 if (Member->getAttr<DLLExportAttr>()) { 5808 if (MD->isUserProvided()) { 5809 // Instantiate non-default class member functions ... 5810 5811 // .. except for certain kinds of template specializations. 5812 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5813 continue; 5814 5815 S.MarkFunctionReferenced(Class->getLocation(), MD); 5816 5817 // The function will be passed to the consumer when its definition is 5818 // encountered. 5819 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5820 MD->isCopyAssignmentOperator() || 5821 MD->isMoveAssignmentOperator()) { 5822 // Synthesize and instantiate non-trivial implicit methods, explicitly 5823 // defaulted methods, and the copy and move assignment operators. The 5824 // latter are exported even if they are trivial, because the address of 5825 // an operator can be taken and should compare equal across libraries. 5826 DiagnosticErrorTrap Trap(S.Diags); 5827 S.MarkFunctionReferenced(Class->getLocation(), MD); 5828 if (Trap.hasErrorOccurred()) { 5829 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5830 << Class << !S.getLangOpts().CPlusPlus11; 5831 break; 5832 } 5833 5834 // There is no later point when we will see the definition of this 5835 // function, so pass it to the consumer now. 5836 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5837 } 5838 } 5839 } 5840} 5841 5842static void checkForMultipleExportedDefaultConstructors(Sema &S, 5843 CXXRecordDecl *Class) { 5844 // Only the MS ABI has default constructor closures, so we don't need to do 5845 // this semantic checking anywhere else. 5846 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5847 return; 5848 5849 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5850 for (Decl *Member : Class->decls()) { 5851 // Look for exported default constructors. 5852 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5853 if (!CD || !CD->isDefaultConstructor()) 5854 continue; 5855 auto *Attr = CD->getAttr<DLLExportAttr>(); 5856 if (!Attr) 5857 continue; 5858 5859 // If the class is non-dependent, mark the default arguments as ODR-used so 5860 // that we can properly codegen the constructor closure. 5861 if (!Class->isDependentContext()) { 5862 for (ParmVarDecl *PD : CD->parameters()) { 5863 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5864 S.DiscardCleanupsInEvaluationContext(); 5865 } 5866 } 5867 5868 if (LastExportedDefaultCtor) { 5869 S.Diag(LastExportedDefaultCtor->getLocation(), 5870 diag::err_attribute_dll_ambiguous_default_ctor) 5871 << Class; 5872 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5873 << CD->getDeclName(); 5874 return; 5875 } 5876 LastExportedDefaultCtor = CD; 5877 } 5878} 5879 5880void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 5881 // Mark any compiler-generated routines with the implicit code_seg attribute. 5882 for (auto *Method : Class->methods()) { 5883 if (Method->isUserProvided()) 5884 continue; 5885 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 5886 Method->addAttr(A); 5887 } 5888} 5889 5890/// Check class-level dllimport/dllexport attribute. 5891void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5892 Attr *ClassAttr = getDLLAttr(Class); 5893 5894 // MSVC inherits DLL attributes to partial class template specializations. 5895 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5896 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5897 if (Attr *TemplateAttr = 5898 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5899 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5900 A->setInherited(true); 5901 ClassAttr = A; 5902 } 5903 } 5904 } 5905 5906 if (!ClassAttr) 5907 return; 5908 5909 if (!Class->isExternallyVisible()) { 5910 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5911 << Class << ClassAttr; 5912 return; 5913 } 5914 5915 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5916 !ClassAttr->isInherited()) { 5917 // Diagnose dll attributes on members of class with dll attribute. 5918 for (Decl *Member : Class->decls()) { 5919 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5920 continue; 5921 InheritableAttr *MemberAttr = getDLLAttr(Member); 5922 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5923 continue; 5924 5925 Diag(MemberAttr->getLocation(), 5926 diag::err_attribute_dll_member_of_dll_class) 5927 << MemberAttr << ClassAttr; 5928 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5929 Member->setInvalidDecl(); 5930 } 5931 } 5932 5933 if (Class->getDescribedClassTemplate()) 5934 // Don't inherit dll attribute until the template is instantiated. 5935 return; 5936 5937 // The class is either imported or exported. 5938 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5939 5940 // Check if this was a dllimport attribute propagated from a derived class to 5941 // a base class template specialization. We don't apply these attributes to 5942 // static data members. 5943 const bool PropagatedImport = 5944 !ClassExported && 5945 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 5946 5947 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5948 5949 // Ignore explicit dllexport on explicit class template instantiation 5950 // declarations, except in MinGW mode. 5951 if (ClassExported && !ClassAttr->isInherited() && 5952 TSK == TSK_ExplicitInstantiationDeclaration && 5953 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 5954 Class->dropAttr<DLLExportAttr>(); 5955 return; 5956 } 5957 5958 // Force declaration of implicit members so they can inherit the attribute. 5959 ForceDeclarationOfImplicitMembers(Class); 5960 5961 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5962 // seem to be true in practice? 5963 5964 for (Decl *Member : Class->decls()) { 5965 VarDecl *VD = dyn_cast<VarDecl>(Member); 5966 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5967 5968 // Only methods and static fields inherit the attributes. 5969 if (!VD && !MD) 5970 continue; 5971 5972 if (MD) { 5973 // Don't process deleted methods. 5974 if (MD->isDeleted()) 5975 continue; 5976 5977 if (MD->isInlined()) { 5978 // MinGW does not import or export inline methods. But do it for 5979 // template instantiations. 5980 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5981 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() && 5982 TSK != TSK_ExplicitInstantiationDeclaration && 5983 TSK != TSK_ExplicitInstantiationDefinition) 5984 continue; 5985 5986 // MSVC versions before 2015 don't export the move assignment operators 5987 // and move constructor, so don't attempt to import/export them if 5988 // we have a definition. 5989 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5990 if ((MD->isMoveAssignmentOperator() || 5991 (Ctor && Ctor->isMoveConstructor())) && 5992 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5993 continue; 5994 5995 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5996 // operator is exported anyway. 5997 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5998 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5999 continue; 6000 } 6001 } 6002 6003 // Don't apply dllimport attributes to static data members of class template 6004 // instantiations when the attribute is propagated from a derived class. 6005 if (VD && PropagatedImport) 6006 continue; 6007 6008 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6009 continue; 6010 6011 if (!getDLLAttr(Member)) { 6012 InheritableAttr *NewAttr = nullptr; 6013 6014 // Do not export/import inline function when -fno-dllexport-inlines is 6015 // passed. But add attribute for later local static var check. 6016 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6017 TSK != TSK_ExplicitInstantiationDeclaration && 6018 TSK != TSK_ExplicitInstantiationDefinition) { 6019 if (ClassExported) { 6020 NewAttr = ::new (getASTContext()) 6021 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6022 } else { 6023 NewAttr = ::new (getASTContext()) 6024 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6025 } 6026 } else { 6027 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6028 } 6029 6030 NewAttr->setInherited(true); 6031 Member->addAttr(NewAttr); 6032 6033 if (MD) { 6034 // Propagate DLLAttr to friend re-declarations of MD that have already 6035 // been constructed. 6036 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6037 FD = FD->getPreviousDecl()) { 6038 if (FD->getFriendObjectKind() == Decl::FOK_None) 6039 continue; 6040 assert(!getDLLAttr(FD) &&((!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr"
) ? static_cast<void> (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 6041, __PRETTY_FUNCTION__))
6041 "friend re-decl should not already have a DLLAttr")((!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr"
) ? static_cast<void> (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDeclCXX.cpp"
, 6041, __PRETTY_FUNCTION__))
; 6042 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6043 NewAttr->setInherited(true); 6044 FD->addAttr(NewAttr); 6045 } 6046 } 6047 } 6048 } 6049 6050 if (ClassExported) 6051 DelayedDllExportClasses.push_back(Class); 6052} 6053 6054/// Perform propagation of DLL attributes from a derived class to a 6055/// templated base class for MS compatibility. 6056void Sema::propagateDLLAttrToBaseClassTemplate( 6057 CXXRecordDecl *Class, Attr *ClassAttr, 6058 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6059 if (getDLLAttr( 6060 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6061 // If the base class template has a DLL attribute, don't try to change it. 6062 return; 6063 } 6064 6065 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6066 if (!getDLLAttr(BaseTemplateSpec) && 6067 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6068 TSK == TSK_ImplicitInstantiation)) { 6069 // The template hasn't been instantiated yet (or it has, but only as an 6070 // explicit instantiation declaration or implicit instantiation, which means 6071 // we haven't codegenned any members yet), so propagate the attribute. 6072 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6073 NewAttr->setInherited(true); 6074 BaseTemplateSpec->addAttr(NewAttr); 6075 6076 // If this was an import, mark that we propagated it from a derived class to 6077 // a base class template specialization. 6078 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6079 ImportAttr->setPropagatedToBaseTemplate(); 6080 6081 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6082 // needs to be run again to work see the new attribute. Otherwise this will 6083 // get run whenever the template is instantiated. 6084 if (TSK != TSK_Undeclared) 6085 checkClassLevelDLLAttribute(BaseTemplateSpec); 6086 6087 return; 6088 } 6089 6090 if (getDLLAttr(BaseTemplateSpec)) { 6091 // The template has already been specialized or instantiated with an 6092 // attribute, explicitly or through propagation. We should not try to change 6093 // it. 6094 return; 6095 } 6096 6097 // The template was previously instantiated or explicitly specialized without 6098 // a dll attribute, It's too late for us to add an attribute, so warn that 6099 // this is unsupported. 6100 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6101 << BaseTemplateSpec->isExplicitSpecialization(); 6102 Diag(ClassAttr->getLocation(), diag::note_attribute); 6103 if (BaseTemplateSpec->isExplicitSpecialization()) { 6104 Diag(BaseTemplateSpec->getLocation(), 6105 diag::note_template_class_explicit_specialization_was_here) 6106 << BaseTemplateSpec; 6107 }