Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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