Bug Summary

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